/**
* JavaScript document for Datepicker widget
* Author: Alan Mitchell
* Last Modified: 2005-07-20

  TODO
  Highlight selected date in associated input field when calendar opens

*/

function addEvent(e,eventType,eventListener,useCapture)
{
	if (e.addEventListener) e.addEventListener(eventType, eventListener, useCapture);
	else if (e.attachEvent) e.attachEvent("on"+eventType, eventListener);
}


/* BASIC DATE  STARTER-SET */
/* Today's date */
var date = new Date();
var curr_dy = date.getDate(); 
var curr_mn = date.getMonth();
var curr_yr = date.getFullYear();
var DOMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var lDOMonth = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
var moty = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var detect = navigator.userAgent.toLowerCase();


addEvent(window, 'load', Calendar_init);
/**
* Constructor
*********************************
*** To be called on page load ***
*********************************
* Finds inputs with class datepicker and adds activation image + event handlers
* Assumes input is wrapped in p tags - or some kind of wrapper (td/div/etc)
* Appends calendar pop-up code to end of BODY
*/
function Calendar_init()
{
	//alert('init');
	// find all select elements with class datepicker
	// ! should turn this into a getElementsByClassName() method !
	aSelects = document.getElementsByTagName('INPUT');
	// loop
    for(i=0; i<aSelects.length; i++) {
        if(aSelects[i].className.indexOf("datepicker") >= 0) {
			// add img with js controls
			aSelects[i].style.width = 'auto';
			aSelects[i].size = '10';
			oHref = document.createElement('A');
			oHref.href = '#';
			oHref.className = 'datepicker';
			oHref.onclick = function () {
				showCal('','',this.previousSibling,5,true,8);
				return false;
			}
			// create icon
			oIcon = document.createElement('IMG');
			oIcon.src = 'js/calendar.gif';
			oIcon.alt = 'Select...';
			oIcon.width = 16;
			oIcon.height = 16;
			oIcon.className = 'datepicker';
			oIcon.valign = "absmiddle";
			// apend to a tag
			oHref.appendChild(oIcon);
			// apend to parent P tag
			aSelects[i].parentNode.appendChild(oHref);
			insertAfter(aSelects[i].parentNode, oHref, aSelects[i]);
        }
    }

	// apend calendar code to end of page
	aBodys = document.getElementsByTagName('BODY');
	oDiv = document.createElement('DIV');
	oDiv.id = 'calDiv';
	oDiv.style.display = 'none'; // bug! can't be in css for some reason
	oDiv.innerHTML = '<div id="calWrap"><div id="calTopBar">close <span onclick="hideCal()" id="calClose">x</span></div>'+
		'<table width="100%" id="calNav">'+
		'<tr><td id="calNavPY"></td><td id="calNavPM"></td><td id="calNavMY" width="100"></td><td id="calNavNM"></td><td id="calNavNY"></td></tr>'+
		'</table>'+
		'<table  id="calTbl" width="100%" cellspacing="0">'+
		'<thead><tr style="background-color:#eaeaea"><td>Sun</td><td>Mon</td><td>Tue</td><td>Wed</td><td>Thu</td><td>Fri</td><td>Sat</td></tr></thead>'+
		'<tbody></tbody>'+
		'</table></div>';
	aBodys[0].appendChild(oDiv);
	
	// add iframe for ie so datepicker can be shown above all other elements, even select's
	if(!(detect.indexOf("opera") + 1) && (detect.indexOf("msie") + 1)) {
		initIframe(oDiv);
	}
}

/**
* Main function for calling calendar pop-up
* @param m int month to show
* @param y int year to show
* @param f obj input field to associate with
* @param dateSpan int see below
* @param wknd boolean show weekends
* @param dateSpan int (see below)
* @param format int (see dateFormats())
*/
function showCal(m,y,f,dateSpan,wknd,format){
	/* 
	dateSpan - date that should have links; does not include weekends
	0 = no dates
	1 = all past dates up to and including today
	2 = all future dates starting with today
	3 = all future dates NOT including today ( for GTC Dates )
	4 = all past dates NOT including today ( for start / from dates )
	5 = all dates
	*/
	var pos = getAbsPos(f);

calField = f; calSpan = dateSpan; calFormat = format; calWknd = wknd;
	if (m == '' && y == ''){m = curr_mn; y = curr_yr;}
	buildCalendar(m,y);
	oCalDiv = document.getElementById('calDiv');
	oCalDiv.style.display = '';
    oCalDiv.style.position = "absolute";
	oCalDiv.style.left = (pos.X) + "px";
	oCalDiv.style.top = (pos.Y+f.offsetHeight)-1 + "px";
}

function hideCal()
{
	document.getElementById('calDiv').style.display='none';
}

function Calendar_get_daysofmonth(monthNo, p_year) {
	if ((p_year % 4) == 0) {
		if ((p_year % 100) == 0 && (p_year % 400) != 0)
			return DOMonth[monthNo];
		return lDOMonth[monthNo];
	} else
		return DOMonth[monthNo];
}

// -- globals used with calendar and date functions
var calField; var calSpan; var calFormat; var calWknd = false;
/* ^^^^^^ end BASIC DATE  STARTER-SET ^^^^^^ */

function getNextMonth(m,y,incr){
	var ret_arr = new Array();
	ret_arr[0] = m + incr; ret_arr[1] = y;
	if (ret_arr[0] == 12){ ret_arr[0]=0; ret_arr[1]=ret_arr[1]+1; }
	if (ret_arr[0] == -1){ ret_arr[0]=11; ret_arr[1]=ret_arr[1]-1; }
	return ret_arr;
}
function figureDOTW(m,d,y){
	var tDate = new Date(); tDate.setDate(d); tDate.setMonth(m); tDate.setFullYear(y); return tDate.getDay();
}

function scramKids(n){ // this is a basic removeChild loop for removing all childNodes from node n
	var numKids = n.childNodes.length;
	for (i=0;i<numKids;i++) { n.removeChild(n.childNodes[0]); }
}		

function buildCalendar(m,y){
// -- requires: Basic Date Starter-Set, getNextMonth(), figureDOTW(), scramKids()
	m = parseFloat(m); y = parseFloat(y); 
	var dayNo = figureDOTW(m,1,y);
	var monthNo = Calendar_get_daysofmonth(m,y);
	var rowNum = Math.ceil((monthNo+dayNo)/7);
	var dayCount = 1;
	var calTB = document.getElementById('calTbl').getElementsByTagName('tbody')[0];
	var calNav = document.getElementById('calNav');
	scramKids(calTB);
	for (i=0;i<6;i++){ // row loop
		var calTR = document.createElement('tr');
		var calTDtext;
		var cellContent;
		for (j=0; j < 7; j++){ // cells in row loop, days in the week
			var calTD = document.createElement('td');
			if (j == 0 || j == 6 ) // weekends
				calTD.style.backgroundColor = '#cFcecc';
			if ((i==0 && j < dayNo) || dayCount > monthNo) // cells before the first of the month or after the last day
				cellContent = document.createElement('br');
			else  {
				var dyA = document.createElement('a');
				dyA.setAttribute('href','javascript:placeDate('+m+','+dayCount+','+y+')');
				
				calTDtext = document.createTextNode(dayCount.toString());
				cellContent = calTDtext;
				if (dayCount == curr_dy && m == curr_mn && y == curr_yr){
						//calTD.style.backgroundColor = '#f60';
						calTD.className='today';
				}else{
						calTD.className='';
				}
				if ((j!=0 && j!=6) || calWknd == true){ // if the day is a weekday or weekends allowed
					if (dayCount == curr_dy && m == curr_mn && y == curr_yr && calSpan != 3 && calSpan != 0 && calSpan != 4){
						dyA.appendChild(calTDtext); cellContent = dyA;
					}
					if (calSpan == 1 || calSpan == 4){
						if (y < curr_yr || (m < curr_mn && y == curr_yr) || (m == curr_mn && y == curr_yr && dayCount < curr_dy))
							{
							dyA.appendChild(calTDtext); cellContent = dyA;
							}
					} 
					if (calSpan == 2 || calSpan == 3){
						if (y > curr_yr || (m > curr_mn && y == curr_yr) || (m == curr_mn && y == curr_yr && dayCount > curr_dy))
							{dyA.appendChild(calTDtext); cellContent = dyA;}
					}
					if (calSpan == 5){
						dyA.appendChild(calTDtext); cellContent = dyA;
					}
				}
				else { /* else if it's a weekend */ }
				dayCount++;
			}
			calTD.appendChild(cellContent);
			calTD.setAttribute('width','14%');
			calTR.appendChild(calTD);
		}
		 calTB.appendChild(calTR);
	}
	var nMonth = getNextMonth(m,y,+1);
	var pMonth = getNextMonth(m,y,-1);
	document.getElementById('calNavPY').innerHTML = '<a href="javascript:void(0)" title="prev year" onclick="buildCalendar('+m+','+(y-1)+')">&laquo;</a>';
	document.getElementById('calNavPM').innerHTML = '<a href="javascript:void(0)" title="prev month" onclick="buildCalendar('+pMonth[0]+','+pMonth[1]+')">&lsaquo;</a>';
	document.getElementById('calNavMY').innerHTML = moty[m] +' '+y;
	document.getElementById('calNavNY').innerHTML = '<a href="javascript:void(0)" title="next year" onclick="buildCalendar('+m+','+(y+1)+')">&raquo;</a>';
	document.getElementById('calNavNM').innerHTML = '<a href="javascript:void(0)" title="next month" onclick="buildCalendar('+nMonth[0]+','+nMonth[1]+')">&rsaquo;</a>';
}

function placeDate(m,d,y){ 
	eval(calField).value = dateFormats(m,d,y,calFormat);
	document.getElementById('calDiv').style.display = 'none';
}

function dateFormats(m,d,y,calFormat){
	d = d.toString();
	m = m+1; m = m.toString();
	y = y.toString(); 
	var sy = y;
// -- convert to 2 digit numbers
	if (m.length == 1){m = '0'+ m;}
	if (d.length == 1){d = '0'+ d;}
	if (y.length == 4)
	 sy = y.substring(2,4);
	var format;
	switch (calFormat){
		case 0 : format = m + d + sy; break; 			//  mmddyy
		case 1 : format = m + d + y; break; 			//  mmddyyyy
		case 2 : format = m +'/'+ d +'/'+ y; break; 	//  mm/dd/yyyy
		case 3 : format = m +'/'+ d +'/'+ sy; break; 	//  mm/dd/yy
		case 4 : format = y + m; break; 				//  yyyymm
		case 5 : format = d + m + sy; break;			//  ddmmyy
		case 6 : format = d +'/'+ m +'/'+ sy; break; 	//  dd/mm/yy
		case 7 : format = d + m + y; break;				//  ddmmyyyy
		case 8 : format = d +'/'+ m +'/'+ y; break; 	//  dd/mm/yyyy
		default: format = m + d + y; break; 			//  mmddyyyy
	}
	return format;
}

function getAbsPos(obj)
{
	var x = 0;
	var y = 0;
	while(obj.offsetParent)
	{
		y += obj.offsetTop;
		x += obj.offsetLeft;
		obj = obj.offsetParent;
	}
	var rtn = {X:x,Y:y}
	return rtn;
}

function insertAfter(parent, node, referenceNode) {
	parent.insertBefore(node, referenceNode.nextSibling);
}

// ------------------------------------------------------------------ //
// Internet Explorer hack requires an empty iFrame.  We need to add   //
// one right underneath the div -> it will make the zindex work       //
// ------------------------------------------------------------------ //

function initIframe(ctrl) {
	//textWidth = textfield.offsetWidth;
	//textHeight = textfield.offsetHeight;
    hackFrame = document.createElement("iframe");
   // hackFrame.setAttribute("src", "/includes/datepicker.htm");
	hackFrame.setAttribute("scrolling", "0");
	hackFrame.setAttribute("tabindex", "-1");
	hackFrame.style.position = "absolute";
	hackFrame.style.zIndex = 274; 
	hackFrame.style.width = 200 + "px";
	hackFrame.style.height = 142 + "px";
	hackFrame.style.top = 0 + "px";
	hackFrame.style.left = 0 + "px";

	var calWrap = document.getElementById('calWrap');
	calWrap.style.position = "absolute";
	calWrap.style.zIndex = 275;
	calWrap.style.width = 200 + "px";
	calWrap.style.height = 142 + "px";
	calWrap.style.top = 0 + "px";
	calWrap.style.left = 0 + "px";
	//calWrap.style.backgroundColor = 'white';
	
	ctrl.insertBefore(hackFrame, document.getElementById(calTopBar));
}
