// Rights reserved, Synkron A/S
	
// DATE PICKER JS

var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

//var dpDayArray = new Array('Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa');
//var dpMonthArray = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
  
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = ".";		// common values would be "/" or "."
var defaultDateFormat = "dmy"	// valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;


// global var containing postback field info
var dpFieldInfo;

// offset day determines which day to start with in a row in the datepicker (0=sunday, 1=monday, 2=tuesday, 3=wednesday, etc.)
var offsetDay = 1;

/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate"> 
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.
*/
function displayDatePicker(bUseNever, dateFieldName, dayFieldName, monthFieldName, yearFieldName, hourFieldName, minuteFieldName, url, postBack) {
	dpFieldInfo = new Object();
	dpFieldInfo.postBack = postBack;
	dpFieldInfo.dateFieldName = dateFieldName;
	dpFieldInfo.dayFieldName = dayFieldName;
	dpFieldInfo.monthFieldName = monthFieldName;
	dpFieldInfo.yearFieldName = yearFieldName;
	dpFieldInfo.bUseNever = bUseNever;
	dpFieldInfo.url = url;
	if(hourFieldName!=null && hourFieldName!='' && minuteFieldName!=null && minuteFieldName!='') {
		dpFieldInfo.hourFieldName = hourFieldName;
		dpFieldInfo.minuteFieldName = minuteFieldName;
	}
	else {
		dpFieldInfo.hourFieldName = null;
		dpFieldInfo.minuteFieldName = null;
	}

/*	var sDebug = "dpFieldInfo:\n" + dpFieldInfo.dateFieldName + "\n" + dpFieldInfo.dayFieldName + "\n" + dpFieldInfo.monthFieldName + "\n" + 	dpFieldInfo.yearFieldName + "\n" + 	dpFieldInfo.hourFieldName + "\n" + 	dpFieldInfo.minuteFieldName + "\n" + dpFieldInfo.url;
	
	alert(sDebug);
*/	
	var targetDateField = document.getElementsByName(dateFieldName).item(0);
	//var targetDateField = document.getElementById(dateFieldName);
	
	// display beneath the date field we're updating
	displayBelowThisObject = targetDateField;

	var x = displayBelowThisObject.offsetLeft;
	var y = displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight;

	// deal with elements inside tables and such
	var parent = displayBelowThisObject;
	while (parent.offsetParent) {
		parent = parent.offsetParent;
		x += parent.offsetLeft;
		y += parent.offsetTop;
	}
	
	drawDatePicker(targetDateField, x, y);
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
function drawDatePicker(targetDateField, x, y)
{
//	alert("drawDatePicker: "+targetDateField.name);
	var dt;
	var currentdate = targetDateField.value;
	var timestring = "00:00";
	if(currentdate==dpNeverText) {
		// current selection is "never" - set datepicker to "today"
		dt = new Date();
	}
	else {
		if(currentdate.indexOf(":")>=0) {
			timestring = currentdate.substr(currentdate.indexOf(":")-2, 5);
			currentdate = currentdate.substr(0, currentdate.length - 6);
	//		alert("getFieldDate time='"+timestring+"', date='"+currentdate+"'");
		}
		dt = getFieldDate(currentdate);
	}

	// the datepicker table will be drawn inside of a <div> with an ID defined by the
	// global datePickerDivID variable. If such a div doesn't yet exist on the HTML
	// document we're working with, add one.
	if (!document.getElementById(datePickerDivID)) {
		// don't use innerHTML to update the body, because it can cause global variables
		// that are currently pointing to objects on the page to have bad references
		//document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
		var newNode = document.createElement("div");
		newNode.setAttribute("id", datePickerDivID);
		newNode.setAttribute("class", "dpDiv");
		newNode.setAttribute("style", "visibility: hidden;");
		document.body.appendChild(newNode);
	}
  
	// move the datepicker div to the proper x,y coordinate and toggle the visiblity
	var pickerDiv = document.getElementById(datePickerDivID);
	pickerDiv.style.position = "absolute";
	pickerDiv.style.left = x + "px";
	pickerDiv.style.top = y + "px";
	//  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
	pickerDiv.style.visibility = "visible";
	pickerDiv.style.zIndex = 10000;

	// draw the datepicker table
	refreshDatePicker(dt.getFullYear(), dt.getMonth(), dt.getDate());

	if(dpFieldInfo.hourFieldName!=null) {
		document.getElementById(targetDateField.name+"_time").value = timestring;
	}

	try {
		document.getElementById(datePickerDivID).onkeydown = dpOnKeyDown;
		document.getElementById(datePickerDivID).setActive();
	}
	catch (ex) {}
}

function dpOnKeyDown(e) {
	if(e==null) {
		e = event;
	}
	var bHandled = false;
	if(e.keyCode==13) {
		if(dpSelectedDay!=null) {
			updateDateField(dpSelectedDay);
		}
		bHandled = true;
	}
	if(e.keyCode==27) {
		hideDatePicker();
		bHandled = true;
	}
	
	if(bHandled==true) {
		e.cancelBubble = true;
		e.returnValue = false;
	}
}

/**
This is the function that actually draws the datepicker calendar.
*/
var dpSelectedDay;
function refreshDatePicker(year, month, day)
{
	dpSelectedDay = null;
	// if no arguments are passed, use today's date; otherwise, month and year
	// are required (if a day is passed, it will be highlighted later)
	var thisDay = new Date();

	if ((month >= 0) && (year > 0)) {
		thisDay = new Date(year, month, 1);
	}
	else {
		day = thisDay.getDate();
		thisDay.setDate(1);
	}
  
  
	// start generating the code for the calendar table
	var html = "<table cols=7 class='dpTable' cellpadding=0 cellspacing=0>";

	// add top menu bar
	//alert("url: "+dpFieldInfo.url);
	html += "<tr><td colspan=7 class='dpTitleTD'>"+
			"<div class='dpTopBar'>"+
				"<div class='dpTitle'>" + dpTitle + "</div>"+
				"<div class='dpCloseButton'><a href='javascript:hideDatePicker();'><img src='"+dpFieldInfo.url+"/dp_close.gif' border='0'></a></div>"+
			"</div>"+
			"</td></tr>";
			

	// add time input field if used
/*	if(dpFieldInfo.hourFieldName!=null) {
		var timestring = "00:00";
		if(document.getElementById(dpFieldInfo.dateFieldName+"_time")!=null) {
			timestring = document.getElementById(dpFieldInfo.dateFieldName+"_time").value;
		}
		html += "<tr><td colspan=7>"+
				"<div class='dpTimeCaption'>"+
					dpTimeCaption +
				"</div>"+
				"<div class='dpTime'>"+
					dpTimeText + " " + 
					"<input type='text' value='" + timestring + "' class='dpTimeInput' id='" + dpFieldInfo.dateFieldName + "_time'>" + 
				"</div>"+
//				"<table class='dpHeaderTable'><tr>" + 
//					"<td colspan=7 class='dpTimeTD'>" + dpTimeText + " " + 
//					"<input type='text' value='" + timestring + "' class='dpTimeInput' id='" + dpFieldInfo.dateFieldName + "_time'>" + 
//					"</td>"+
//				"</tr></table>"+
				"</td></tr>";
				
	}*/
  
	// this is the menu bar that displays the month and the buttons to
	// go back to a previous month or forward to the next month
	html += "<tr>" +
			"<td colspan=7 align='center'>"+
			"<div class='dpMonthSelector'>"+
				"<div class='dpLastYear'>" + getButtonCode(thisDay, -12, "") + "</div>"+
				"<div class='dpLastMonth'>" + getButtonCode(thisDay, -1, "") + "</div>"+
				"<div class='dpCurrentMonth'>" + dpMonthArray[thisDay.getMonth()] + " " + thisDay.getFullYear() + "</div>"+
				"<div class='dpNextMonth'>" + getButtonCode(thisDay, 1, "") + "</div>"+
				"<div class='dpNextYear'>" + getButtonCode(thisDay, 12, "") + "</div>"+
			"</div>"+
//			"<table class='dpHeaderTable'><tr>" +
//				"<td class='dpButtonTD'>" + getButtonCode(thisDay, -1, "") + " " + getButtonCode(thisDay, -12, "") + "</td>" +
//				"<td class='dpCurrMonthTD'>" + dpMonthArray[thisDay.getMonth()] + " " + thisDay.getFullYear() + "</td>" +
//				"<td class='dpButtonTD'>" + getButtonCode(thisDay, 12, "") + " " + getButtonCode(thisDay, 1, "") + "</td>" +
//			"</tr></table>" +
			"</td></tr>";
  
	// this is the row that indicates which day of the week we're on
	html += "<tr class='dpDayTR'>";

	for(i = offsetDay; i < dpDayArray.length; i++) {
		html += "<td class='dpDayTD'>" + dpDayArray[i] + "</td>";
	}
	for(i = 0; i < offsetDay; i++) {
		html += "<td class='dpDayTD'>" + dpDayArray[i] + "</td>";
	}
	html += "</tr>";

	// now we'll start populating the table with days of the month
	html += "<tr>";

	// first, the leading blanks
	var lastBlank = (thisDay.getDay()==0 ? 7 : thisDay.getDay());
	for (i = offsetDay; i < lastBlank; i++) {
		html += "<td class='dpTD'></td>";
	}
	    
	// now, the days of the month
	do {
		dayNum = thisDay.getDate();
		TD_onmouseover = " onmouseover=\"this.className='dpDayHighlightTD';\" onmouseout=\"this.className='dpTD';\" ";
		TD_onclick = " onclick=\"updateDateField('" + thisDay + "');\">";
		
		if (dayNum == day) {
			dpSelectedDay = new Date(thisDay);
			html += "<td class='dpDayHighlightTD'" + TD_onclick + dayNum + "</td>";
		}
		else {
			html += "<td class='dpTD'" + TD_onmouseover + TD_onclick + dayNum + "</td>";
		}
			
		// start a new row?
		if (thisDay.getDay() == ((6+offsetDay)%7)) {
			html += "</tr><tr>";
		}
		
		// increment the day
		thisDay.setDate(thisDay.getDate() + 1);
	} while (thisDay.getDate() > 1)
/*
	// fill in any trailing blanks
	if (thisDay.getDay() > 0) {
		for (i = 6; i > thisDay.getDay(); i--)
		html += "<td class='dpTD'></td>";
	}*/
	html += "</tr>";
	thisDay = new Date();
	// add "today" button
	html += "<tr>" +
			"<td colspan=7 align='center'>"+
			"<div class='dpBottomButtonContainer'>"+
			"<div class='dpTodayButtonWrapper'>"+
			"<input type='button' class='dpTodayButton' value='" + dpTodayText + "' onMouseOver=this.style.background='#ffc970' onMouseOut=this.style.background='#ffffff' onclick=\"updateDateField('" + thisDay + "');\" >"+
			"</div>";
	if(dpFieldInfo.bUseNever==true) {
		thisDay = new Date(2100, 0, 1);

		html +=	"&nbsp;<div class='dpTodayButtonWrapper'>"+
				"<input type='button' class='dpTodayButton' value='" + dpNeverText + "' onMouseOver=this.style.background='#ffc970' onMouseOut=this.style.background='#ffffff' onclick=\"updateDateField('" + thisDay + "');\" >"+
				"</div>";
			
	}
			
	html += "</div>"+
			"</td>"+
			"</tr>";

	// and finally, close the table
	html += "</table>";
  
	document.getElementById(datePickerDivID).innerHTML = html;
	// add an "iFrame shim" to allow the datepicker to display above selection lists
	adjustiFrame();


//	document.getElementById(datePickerDivID).onkeydown = dpOnKeyDown;
//	document.getElementById(datePickerDivID).setActive();
}


/**
Convenience function for writing the code for the buttons that bring us back or forward
a month.
*/
function getButtonCode(dateVal, adjust, label)
{
	var newMonth = (dateVal.getMonth() + adjust) % 12;
	var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
	if (newMonth < 0) {
		newMonth += 12;
		newYear += -1;
	}
		
	switch(adjust) {
		case -1:
			return "<a class='dpButtonPrevMonth' href='javascript:refreshDatePicker(" + newYear + ", " + newMonth + ");'>" + label + "</a>";
			break;
		case 1:
			return "<a class='dpButtonNextMonth' href='javascript:refreshDatePicker(" + newYear + ", " + newMonth + ");'>" + label + "</a>";
			break;
		case -12:
			return "<a class='dpButtonPrevYear' href='javascript:refreshDatePicker(" + newYear + ", " + newMonth + ");'>" + label + "</a>";
			break;
		case 12:
			return "<a class='dpButtonNextYear' href='javascript:refreshDatePicker(" + newYear + ", " + newMonth + ");'>" + label + "</a>";
			break;
	}
}

/**
Convert a string to a JavaScript Date object.
*/
function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
  
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
//      alert("1");
      dateVal = new Date(y, m, d);
    } else {
//      alert("2: "+dateString);
      dateVal = new Date(dateString);
//      alert("2-1: "+dateVal);
    }
  } catch(e) {
 //     alert("3");
    dateVal = new Date();
  }
  
  return dateVal;
}


/**
Try to split a date string into an array of elements, using common date separators.
If the date is split, an array is returned; otherwise, we just return false.
*/
function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
  
  return dArray;
}

function makeTimeString(timeString) {
//	alert("makeTimeString("+timeString+")");
	var dArray = null;
	if (timeString.indexOf(":") >= 0)
		dArray = timeString.split(":");
	else if (timeString.indexOf(",") >= 0)
		dArray = timeString.split(",");
	else if (timeString.indexOf(".") >= 0)
		dArray = timeString.split(".");
	else if (timeString.indexOf("-") >= 0)
		dArray = timeString.split("-");
	else if (timeString.indexOf("_") >= 0)
		dArray = timeString.split("_");
		
	// enable entering only whole hours (e.g. entering "15" will be seen as "15:00")
	if(dArray==null) {
	    if(isNaN(timeString)==false) {
	        dArray = new Array(parseInt(timeString), 0);
	    }
    }

	if(dArray==null) {
		alert(dpTimeFormatError);
		return null;
	}
	if(dArray.length!=2) {
		alert(dpTimeFormatError);
		return null;
	}
	var hours = dArray[0];
	var minutes = dArray[1];

	if(isNaN(hours) || hours<0 || hours>23) {
		alert(dpHoursError);
		return null;
	}
	if(isNaN(minutes) || minutes<0 || minutes>59) {
		alert(dpMinutesError);
		return null;
	}

	minutes = "00"+minutes;
	minutes = minutes.substr(minutes.length-2, 2);
	hours = "00"+hours;
	hours = hours.substr(hours.length-2, 2);
	
	return (hours+":"+minutes);
}


//function updateDateField(dateString)
//{
function updateDateField(dateString)
{
	var selectedDate = new Date(dateString);
//	dateString = getDateString(selectedDate)
	
	var dayString = "00" + selectedDate.getDate();
	var monthString = "00" + (selectedDate.getMonth()+1);
	var yearString = selectedDate.getFullYear();
	dayString = dayString.substring(dayString.length - 2);
	monthString = monthString.substring(monthString.length - 2);
	
	switch (dateFormat) {
		case "ymd" :
			dateString = yearString + dateSeparator + monthString + dateSeparator + dayString;
		case "mdy" :
			dateString = monthString + dateSeparator + dayString + dateSeparator + yearString;
		case "dmy" :
		default :
			dateString = dayString + dateSeparator + monthString + dateSeparator + yearString;
	}
	
	var dateFieldName = dpFieldInfo.dateFieldName;

	var time = "";
	var hourString;
	var minuteString;
//	var secondString = "00";
	
	if(dpFieldInfo.hourFieldName!=null) {
		time = makeTimeString(document.getElementById(dateFieldName+"_time").value);
		if(time==null) {
			return;
		}
		var aTime = time.split(":");
		hourString = "00" + aTime[0];
		minuteString = "00" + aTime[1];
		hourString = hourString.substring(hourString.length - 2);
		minuteString = minuteString.substring(minuteString.length - 2);

//		time = " " + time;
	}
	
	dateString = dateString + " " + time;
	
	if(selectedDate.getFullYear()==2100) {
		dateString = dpNeverText;
	}

//	alert("day="+dayString+", month="+monthString+", year="+yearString+", hour="+hourString+", minute="+minuteString);	
	
	var targetDateField = document.getElementsByName(dateFieldName).item(0);
	targetDateField.value = dateString;

	// update hidden fields
	var targetDayField = document.getElementsByName(dpFieldInfo.dayFieldName).item(0);
	targetDayField.value = dayString;
	var targetMonthField = document.getElementsByName(dpFieldInfo.monthFieldName).item(0);
	targetMonthField.value = monthString;
	var targetYearField = document.getElementsByName(dpFieldInfo.yearFieldName).item(0);
	targetYearField.value = yearString;
	if(dpFieldInfo.hourFieldName!=null) {
		var targetHourField = document.getElementsByName(dpFieldInfo.hourFieldName).item(0);
		targetHourField.value = hourString;
		var targetMinuteField = document.getElementsByName(dpFieldInfo.minuteFieldName).item(0);
		targetMinuteField.value = minuteString;
	}	

	hideDatePicker();
	if(dpFieldInfo.postBack == 'true')
	{
		document.forms[0].submit();
	}
}

function hideDatePicker() {
	document.getElementById(datePickerDivID).style.visibility = "hidden";
	adjustiFrame();
}

/**
Use an "iFrame shim" to deal with problems where the datepicker shows up behind
selection list elements, if they're below the datepicker. The problem and solution are
described at:
*/
function adjustiFrame(pickerDiv, iFrameDiv)
{
  if (!document.getElementById(iFrameDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<iframe id='" + iFrameDivID + "' src='javascript:false;' scrolling='no' frameborder='0'>";
    var newNode = document.createElement("iFrame");
    newNode.setAttribute("id", iFrameDivID);
    newNode.setAttribute("src", "javascript:false;");
    newNode.setAttribute("scrolling", "no");
    newNode.setAttribute("frameborder", "0");
    document.body.appendChild(newNode);
  }
  
  if (!pickerDiv)
    pickerDiv = document.getElementById(datePickerDivID);
  if (!iFrameDiv)
    iFrameDiv = document.getElementById(iFrameDivID);
  
  try {
    iFrameDiv.style.position = "absolute";
    iFrameDiv.style.width = pickerDiv.offsetWidth;
    iFrameDiv.style.height = pickerDiv.offsetHeight;
    iFrameDiv.style.top = pickerDiv.style.top;
    iFrameDiv.style.left = pickerDiv.style.left;
    iFrameDiv.style.zIndex = pickerDiv.style.zIndex - 1;
    iFrameDiv.style.visibility = pickerDiv.style.visibility;
  } catch(e) {
  }
}

