
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";

var dayArrayShort = new Array('Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su');
var monthArrayLong = 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 dateSeparator = "-";        // common values would be "/" or "."
var dateFormat = "ymd"    // valid values are "mdy", "dmy", and "ymd"

function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep) {
	var targetDateField = $(dateFieldName);
	if ( !targetDateField.id ) {
		targetDateField.id = ('rnd_'+(Math.random()/Math.random())).replace(/\./g, '');
	}

	if ( !displayBelowThisObject ) {
		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);
}

function drawDatePicker(targetDateField, x, y) {
	var dt = getFieldDate(targetDateField.value);

	if ( !$(datePickerDivID) ) {
		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 = $(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.display = (pickerDiv.style.display == "block" ? "none" : "block");
	pickerDiv.style.zIndex = 10000;
	// draw the datepicker table
	refreshDatePicker( targetDateField, dt.getFullYear(), dt.getMonth(), dt.getDate() );
}

function refreshDatePicker(dateField, year, month, day) {
	dateField = $(dateField);
	// 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 ( 0 <= month && 0 < year ) {
		thisDay = new Date(year, month, 1);
	} else {
		day = thisDay.getDate();
		thisDay.setDate(1);
	}

	// start generating the code for the calendar table
	var html = '<table border="0" cellpadding="2" cellspacing="1">';

	// this is the title bar, which displays the month and the buttons to
	// go back to a previous month or forward to the next month
	html += '<thead><tr class="header">';
	html += '<th>' + getButtonCode(dateField, thisDay, -1, "&lt;") + '</th>';
	html += '<th colspan="5" class="title">' + monthArrayLong[ thisDay.getMonth()] + " " + thisDay.getFullYear() + '</th>';
	html += '<th>' + getButtonCode(dateField, thisDay, 1, "&gt;") + '</th>';
	html += '</tr>';

	// this is the row that indicates which day of the week we're on
	html += '<tr class="weekdays">';
	for(i = 0; i < dayArrayShort.length; i++) {
		html += '<th>' + dayArrayShort[i] + '</th>';
	}
	html += '</tr></thead>';

	// add buttons
	html += '<tfoot><tr class="footer">';
	html += '<th colspan="3"><input type="button" class="button" onclick="refreshDatePicker(\'' + dateField.id + '\');" value="today" /></th>';
	html += '<th><input type="button" class="button" onclick="updateDateField();" value="x" /></th>';
	html += '<th colspan="3"><input type="button" class="button" onclick="updateDateField(\'' + dateField.id + '\', null);" value="empty" /></th>';
	html += '</tr></tfoot>';

	// now we'll start populating the table with days of the month
	html += '<tbody><tr>';

	// first, the leading blanks
	var blanks = thisDay.getDay()-1;
	if ( 0 > blanks ) {
		blanks = 6;
	}
	for (i = 0; i < blanks; i++) {
		html += '<th></th>';
	}

	// now, the days of the month
	do {
		var dayNum = thisDay.getDate();
		var weekDayNum = thisDay.getDay();
		html += '<td' + ( dayNum == day ? ' class="today"' : '' ) + ' onclick="updateDateField(\'' + dateField.id + '\', \''+getDateString(thisDay) + '\');">' + dayNum + '</td>';

		// increment the day
		thisDay.setDate(dayNum + 1);

		// if this is a SUNDAY, start a new row
		if ( 0 == weekDayNum && 1 < thisDay.getDate() ) {
			html += '</tr><tr>';
		}
	} while (thisDay.getDate() > 1)

	html += '</tr></tbody>';

	// and finally, close the table
	html += '</table>';

	$(datePickerDivID).innerHTML = html;
	// add an "iFrame shim" to allow the datepicker to display above selection lists
	adjustiFrame();
}

function getButtonCode(dateField, 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;
	}
	return '<input type="button" class="button" onclick="refreshDatePicker(\'' + dateField.id + '\', ' + newYear + ', ' + newMonth + ');" value="' + label + '" />';
}

function getDateString(dateVal) {
	var dayString = "00" + dateVal.getDate();
	dayString = dayString.substring(dayString.length - 2);
	var monthString = "00" + (dateVal.getMonth()+1);
	monthString = monthString.substring(monthString.length - 2);
	return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
}

function getFieldDate(dateString) {
	var dateVal;
	var dArray;
	try {
		dArray = splitDateString(dateString);
		if (dArray) {
			var d = parseInt(dArray[2], 10);
			var m = parseInt(dArray[1], 10) - 1;
			var y = parseInt(dArray[0], 10);
			dateVal = new Date(y, m, d);
		} else if (dateString) {
			dateVal = new Date(dateString);
		} else {
			dateVal = new Date();
		}
	} catch(e) {
		dateVal = new Date();
	}
	return dateVal;
}

function splitDateString(dateString) {
	return 0 < dateString.indexOf("-") ? dateString.split("-") : false;
}

function updateDateField(dateFieldName, dateString) {
	var targetDateField = $(dateFieldName);

	if ( dateString || null === dateString) {
		targetDateField.value = dateString ? dateString : '';
	}
	var pickerDiv = $(datePickerDivID);
//	pickerDiv.style.visibility = "hidden";
	pickerDiv.style.display = "none";
	adjustiFrame();
//	targetDateField.focus();
	// after the datepicker has closed, optionally run a user-defined function called
	// datePickerClosed, passing the field that was just updated as a parameter
	// (note that this will only run if the user actually selected a date from the datepicker)
	if ((dateString) && (typeof(datePickerClosed) == "function")) {
		datePickerClosed(targetDateField);
	}
}

function adjustiFrame() {
	var pickerDiv, iframeDiv;
	// we know that Opera doesn't like something about this, so if we
	// think we're using Opera, don't even try
	var is_opera = (navigator.userAgent.toLowerCase().indexOf("opera") != -1);
	if (is_opera) { return; }

	// put a try/catch block around the whole thing, just in case
	try {
		if ( !$(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='' scrolling='no' frameborder='0'>";
			var newNode = document.createElement("iFrame");
			newNode.setAttribute("id", iFrameDivID);
			newNode.setAttribute("src", "");
			newNode.setAttribute("scrolling", "no");
			newNode.setAttribute ("frameborder", "0");
			document.body.appendChild(newNode);
		}
		if ( !pickerDiv ) {
			pickerDiv = $(datePickerDivID);
		}
		if ( !iframeDiv ) {
			iframeDiv = $(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 ;
			iframeDiv.style.display		= pickerDiv.style.display;
		} catch(e) {}
	} catch (ee) {}
}
