/*
USAGE:
- place javascript include of this file in html head element
- on input controls, use class="datepicker2" to restrict dates of all datepickers to >= today; "datepicker" to not restrict
- **Important: in the page, if you put a calendar graphic beside *one* date picker input, use a graphic for *every* input or the arrays will be out of synch
- set graphic class = "datepicker"
- inputs and calendar graphics must have a unique id
- include calendar.css stylesheet
- add button-close-grey-sm.gif to images folder
- 
*/

// test for dependencies and load the scripts if missing
if (document.all) {
	// mask selects in forms if this is ie
	if (typeof(ieSelectMask)==='undefined'){jsInclude('includes/js/ieSelectMask.js');}
}
if (typeof(findPosX)==='undefined'){jsInclude('includes/js/findPosition.js');}

// if your target object has background, border, or padding the mask will be visible or incorrectly sized
// if you need these attributes apply them to a wrapper div inside your css layer.

function ieSelectMask (obj) {
	if (document.all) {
		var mask;
		if (!document.getElementById(obj.id+'Mask')) {
			mask = document.createElement('iframe');
			mask.id = obj.id+'Mask';
			mask.setAttribute("src","javascript:false;");
		}
		else {
			mask = document.getElementById(obj.id+'Mask');
		}
		obj.insertBefore(mask,obj.childNodes[0]);
		mask.style.position = 'absolute';
		mask.style.top = '0px';
		mask.style.left = '0px';
		mask.style.height = obj.offsetHeight+'px';
		mask.style.width = obj.offsetWidth+'px';
		mask.style.border = '0px none';
		mask.style.zIndex = -1;
	}
};


// on document load attach onclick event to inputs with class="datepicker"
attachEventListener(window, "load", function() {
	attachCalPickers();
});

function attachEventListener(targetObject, eventType, functionToAttach, useCapture) {
  if (targetObject.addEventListener) {
    targetObject.addEventListener(eventType, functionToAttach, useCapture);
    return true;
  } else if (targetObject.attachEvent) {
    var r = targetObject.attachEvent("on" + eventType, functionToAttach);
    return r;
  } 
};

// set a variable that determines whether dates chosen are restricted to >= today
var calRestrict = false;
var calToday = new Date();
calToday = new Date(calToday.getFullYear(),calToday.getMonth(),calToday.getDate(),0,0,0,0);

function attachCalPickers () {
	// attach event listener to datepicker inputs
	var inputs = document.getElementsByTagName('input');
	var pickerGraphics = document.getElementsByTagName('a');
	
	var pickerInputArray = new Array();
	var pickerGraphicsArray = new Array();
	// build new arrays that correlate each input to it's graphic link
	var counter = 0;
	for (i=0; i<inputs.length; i++) 
	{
		
		if (inputs[i].type == 'text' && inputs[i].className.indexOf('datepicker')+1 > 0) 
		{
		    // add to new array
		    pickerInputArray[counter] = inputs[i];
		    counter++;

		}
    }
    
    counter = 0;
    for (i=0; i<pickerGraphics.length; i++) 
	{
		if (pickerGraphics[i].className == "datepicker") 
		{
		    // add to new array
		    pickerGraphicsArray[counter] = pickerGraphics[i];
		    counter++;
		}
    }
	createCalPicker();
	initCalPicker();
	for (i=0; i<pickerInputArray.length; i++) 
	{
		pickerInputArray[i].onfocus = function () 
		{
			showCalPicker(this);
		}
		pickerInputArray[i].onclick = function () 
		{
			showCalPicker(this);
		}
		var targetControl = document.getElementById(pickerInputArray[i]);
		pickerGraphicsArray[i].href = "javascript:passTarget('" + pickerInputArray[i].id + "')";

		if (pickerInputArray[i].className == 'datepicker2') 
		{
			calRestrict = true;
		}
	}
}

function passTarget(objectID)
{
    var targetControl = document.getElementById(objectID);
    showCalPicker(targetControl);
}

function createCalPicker(calPickerId) {
	pickerHtml = document.createElement('div');
	pickerHtml.id = 'spnCalendar';
	pickerHtml.style.position = 'absolute';
	pickerHtml.style.display = 'none';
	pickerHtml.style.zIndex = 999;
	
	//set what dates can be chosen on the calendar
	var tempHtml = '<input type="hidden" id="dateInputId" value="null" /> <input type="hidden" id="calPickDay" /><div class="simpleRow" id="calPickerControls"><img src="../img/datepicker/button-close-grey-sm.gif" alt="Close Button" width="9" height="9" onclick="hideCalPicker(\'\');" /> <select id="calPickMonth" onchange="rebuildCalPicker(thisDay,\'\');" style="width: 60px;"><option value="1">January</option><option value="2">February</option><option value="3">March</option><option value="4">April</option><option value="5">May</option><option value="6">June</option><option value="7">July</option><option value="8">August</option><option value="9">September</option><option value="10">October</option><option value="11">November</option><option value="12">December</option></select> <select id="calPickYear" onchange="rebuildCalPicker(thisDay,\'\');">';
	var d = new Date();
    var curr_year = d.getFullYear();
    //set years that can be chosen: 2005 to 4 years after current year
    for ( var i = 2005; i < (curr_year + 5); i++ )
    {
        tempHtml += ('<option value="' + i + '">' + i + '</option>');
    } 
    tempHtml += '</select></div><div id="calendarBody"></div>';	
	
	pickerHtml.innerHTML = tempHtml;
	if (document.getElementById('pageWrapper')) {
		document.getElementById('pageWrapper').appendChild(pickerHtml);
	} else {
		document.getElementsByTagName('body')[0].appendChild(pickerHtml);
	}
}

function initCalPicker (date) {
	var yearSelect = document.getElementById('calPickYear');
	var tempHtml = '';
	if (!date || date=='NaN') {date = new Date();}
	if (typeof(date) == 'string') {date = textToDate(date);}
	//alert(date);
	document.getElementById('calPickDay').value = date.getDate();
	document.getElementById('calPickMonth').value = date.getMonth()+1;
	if (calRestrict && testOptions('calPickYear')) {
		yearSelect.options.length = 0;
		for (i=0; i<5; i++) {
			yearSelect[i] = new Option(date.getFullYear()+i,date.getFullYear()+i);
		}
	}
	document.getElementById('calPickYear').value = date.getFullYear();
	return true;
}

function showCalPicker (targetObj) {
    
	// prevent keyboard entry
	targetObj.blur();
	// generate calendar using date or today
	var calPicker = document.getElementById('spnCalendar');
	initCalPicker(textToDate(targetObj.value));
	rebuildCalPicker( document.getElementById('calPickDay').value );
	// reveal calendar picker
	calPicker.style.left = findPosX(targetObj)-30+'px';
	calPicker.style.top = findPosY(targetObj)-18+'px';
	calPicker.style.display = 'block';
	// store the id of the targetObj
	document.getElementById('dateInputId').value = targetObj.id;
	// mask selects in forms if this is ie
	if (document.all) {ieSelectMask(calPicker);}
}

function hideCalPicker( thisDate ) {
	calendarControl = document.getElementById("spnCalendar");
	targetObj = document.getElementById(document.getElementById('dateInputId').value);
	calendarControl.style.display = "none";
	// set value of targetOjb input
	if ( thisDate !== "" ) {
		targetObj.value = thisDate;
	}
}

checkReservedDates = false;
reservedDatesData = "";
propertyIdEN = "";
function rebuildCalPicker( useDay ) {
	thisDay = useDay;
	useMonth = (document.getElementById('calPickMonth').value * 1);
	useYear = (document.getElementById('calPickYear').value * 1);
	if ( checkReservedDates && reservedDatesData == "" ) {
		newServer = document.getElementById("reservedDatesFrame");
		document.getElementById("reservedDatesFrame").src = "/hiddenServer.aspx?callName=getReservedDates&action=Get&dataElement=ReservedDates&propertyIdEN=" + propertyIdEN + "&month=" + useMonth + "&year=" + useYear;
	} else {
		februaryDays = 28;
		yearDiv4 = useYear / 4;
		if (useYear == 2000) {
			februaryDays = 29;
		}
		else if (yearDiv4.toString().indexOf(".") == -1) {
			februaryDays = 29;
		}
		maxMonthDays = new Array(31, februaryDays, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
		if ( thisDay > maxMonthDays[useMonth - 1] ) {
			thisDay = maxMonthDays[useMonth - 1];
		}
		initDate(thisDay);
		buildCalPicker(document.getElementById('calPickMonth').value, document.getElementById('calPickYear').value);
		document.getElementById('calPickDay').value = thisDay;
	}
	reservedDatesData = "";
}

function initDate( useDay ) {
	textMonth = document.getElementById('calPickMonth').value;
	textYear = document.getElementById('calPickYear').value;
	thisDate = textMonth + "/" + useDay + "/" + textYear;
}

// browser supports dynamic update of selects?
function testOptions(targetId) {
	var target = document.getElementById(targetId);
	var lgth = target.options.length - 1;
	target.options[lgth] = null;
	if (target.options[lgth]) {
		return false;
	} else {
		return true;
	}
}

function textToDate (val) {
	if (val) {
		val = val.split("/");
		return new Date(val[2]*1,(val[0]*1)-1,val[1]*1);
	} else {
		return false;
	}
}

function buildCalPicker(useMonth, useYear) {
    
	var februaryDays = 28;
	var yearDiv4 = useYear/4;
	if (useYear == 2000) {
		februaryDays = 29;
	}
	else if (yearDiv4.toString().indexOf(".") == -1) {
		februaryDays = 29;
	}
	var maxMonthDays = new Array(31, februaryDays, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var dayNameArray = new Array("S", "M", "T", "W", "T", "F", "S");
	var objDate = new Date(useYear, useMonth-1, 1);
	var firstDayOfWeek = objDate.getDay();
	var monthHtml = '<table cellspacing="0" class="calPicker"><tr>';
	for (columnCounter = 0; columnCounter < 7; columnCounter ++) {
		monthHtml = monthHtml + '<td class="days">' + dayNameArray[columnCounter] + '</td>';
	}
	monthHtml = monthHtml + "</tr>";
	var currentDay = 1;
	var nextMonthDate = 1;
	if (useMonth == 1) {
		lastMonthMaxDays = 31;
	} else {
		lastMonthMaxDays = maxMonthDays[useMonth - 2];
	}
	
	reservedToDate = "";
	reservedFlag = false;
	for (rowCounter = 0; rowCounter<6; rowCounter++) {
		monthHtml = monthHtml + "<tr>";
		if (rowCounter === 0) {
			startCounter = firstDayOfWeek;
			for (previousCounter = lastMonthMaxDays - startCounter; previousCounter < lastMonthMaxDays; previousCounter++) {
				monthHtml = monthHtml + '<td class="inactive">' + (previousCounter + 1) + '</td>';
			}
		} else {
			startCounter = 0;
		}
		if (rowCounter === 0) {
			endCounter = 6 - firstDayOfWeek;
		} else {
			endCounter = 6;
		}
		//alert("current day=" + currentDay);   // alert pops up saying "current day=1" and then again for each sunday in the month before displaying the calendar
		for (columnCounter = 0; columnCounter <= endCounter; columnCounter++) {
			if (currentDay > maxMonthDays[useMonth - 1]) {
				monthHtml = monthHtml + '<td class="inactive">' + nextMonthDate + '</td>';
				nextMonthDate = nextMonthDate + 1;
			} 
			else 
			{
			//is current month
				if ( checkReservedDates ) 
				{
					writeDate = useMonth + "/" + currentDay + "/" + useYear;
					compareCurrentDate = new Date(writeDate);
					compareReservedDate = new Date(reservedToDate);
					if (compareCurrentDate > compareReservedDate) 
					{
						reservedFlag = false;
						reservedToDate = "";
					}
					blockedIndex = reservedDatesData.indexOf( writeDate + "-" );
					if (blockedIndex > - 1) 
					{
						reservedFlag = true;
						reservedSubstring = reservedDatesData.substring( ( blockedIndex + writeDate.length + 1 ), reservedDatesData.length );
						endIndex = reservedSubstring.indexOf(",");
						reservedToDate = reservedSubstring.substring(0, endIndex);
						reservedDatesData = reservedDatesData.replace( writeDate + "-" + reservedToDate + ",", "");
					}
			    }
				if (reservedFlag) {
					monthHtml = monthHtml + '<td class="reserved" valign="top">' + currentDay + '</td>';
				} else {
					currentDate = new Date(useYear,useMonth-1,currentDay,0,0,0,0);
					if (calRestrict && currentDate < calToday) {
						monthHtml = monthHtml + '<td class="">' + currentDay + '</td>';
					} else {
						monthHtml = monthHtml + '<td onclick="hideCalPicker(\'' + useMonth + '/' + currentDay + '/' + useYear + '\');"';
						// currentDate is the date being added
						// currentDay is the day being added
						// monthHtml is the whole calendar table
						// useYear is the selected year
						// useMonth is the selected month
						// alert(calToday == currentDate);
						// alert("calToday=" + calToday + ", nextMonthDate=" + nextMonthDate + ", currentDate=" + currentDate + ", thisDay=" + thisDay + ", and currentDay=" + currentDay + ", and useMonth=" + useMonth);
						// need condition in below that month and year have to be = today's date
						var thisdate = new Date();
						var thismonth = thisdate.getMonth() + 1;
						var thisyear = thisdate.getFullYear();
						//alert(thismonth + ", " + thisyear);
						if ((thisDay == currentDay) && (thismonth == useMonth) && (thisyear == useYear)) {
							monthHtml = monthHtml + '" class="current" onmouseover="this.className=\'over\';" onmouseout="this.className=\'current\';"';
						} else {
							monthHtml = monthHtml + '" class="" onmouseover="this.className=\'over\';" onmouseout="this.className=\'\';"';
						}
						
						monthHtml = monthHtml + '>' + currentDay + '</td>';
					}
				}
				currentDay = currentDay + 1;
			}
		}
		monthHtml = monthHtml + "</tr>";
	}
	monthHtml = monthHtml + "</table>";
	document.getElementById("calendarBody").innerHTML = monthHtml;
}

function findPosX(obj) {
	var curleft = 0;
	var debug = "";
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft;
			if (document.all) {
				// make adjustments for IE and Opera
				if (!isNaN(parseInt(obj.currentStyle['borderLeftWidth'],10))) {
					curleft += parseInt(obj.currentStyle['borderLeftWidth'],10);
				}

				debug = debug + "node: " + obj.nodeName + ", ";
				debug = debug + "id: " + obj.id + ", ";
				debug = debug + "class: " + obj.className + "\n";
				debug = debug + "Left: " + parseInt(obj.offsetLeft,10) + ", ";
				debug = debug + "Lmgn: " + parseInt(obj.currentStyle['marginLeft'],10) + "\n";
				debug = debug + "Lpad : " + parseInt(obj.currentStyle['paddingLeft'],10) + ", ";
				debug = debug + "Lbdr : " + parseInt(obj.currentStyle['borderLeftWidth'],10) + "\n";
				debug = debug + "p.Left: " + parseInt(obj.offsetParent.offsetLeft,10) + ", ";
				debug = debug + "p.Lmgn: " + parseInt(obj.offsetParent.currentStyle['marginLeft'],10) + "\n";
				debug = debug + "p.Lpad : " + parseInt(obj.offsetParent.currentStyle['paddingLeft'],10) + ", ";
				debug = debug + "p.Lbdr : " + parseInt(obj.offsetParent.currentStyle['borderLeftWidth'],10) + "\n";
				debug = debug + "\n";

			} else if (document.defaultView) {
				// make adjustments for Mozilla
				curleft += parseInt(document.defaultView.getComputedStyle(obj,"").getPropertyValue('border-left-width'),10);
			}
			obj = obj.offsetParent;
		}
		debug = debug + "findPosX: " + curleft + "\n";
		//alert (debug);
	}
	return curleft;
}

function findPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop;
			if (document.defaultView) {
				curtop += parseInt(document.defaultView.getComputedStyle(obj,"").getPropertyValue('border-top-width'),10);
			}
			obj = obj.offsetParent;
		}
		if (document.all) {
			curtop += 1;
		}
	}
	return curtop;
}


