//=======================
// CONFIGURATION SETTINGS
//=======================
var PopupCal_width = 170;				// Width (in px) of the calendar popup (default=170)
var PopupCal_height = 169;			// Height (in px) of the calendar popup (default=169)

//================================
// GLOBAL VARIABLES (DON'T CHANGE)
//================================
var NewFullDate = "";
var retdayOfWeek = 0;

//=================
// JS CALENDAR CODE
//=================
function CreateCalendar(obj, StartDate_txt)
{	
	//alert("createCalendar()");
	var PosX = findPosX(obj);
	var PosY = findPosY(obj);
	var objPopup = document.getElementById('PopupCal').style;
	
	inputHeight = 0;
	var height = 0;
	var borderTopWidth = 0;
	var borderBottomWidth = 0;
	var paddingTop = 0;
	var paddingBottom = 0;
	var marginTop = 0;
	var marginBottom = 0;
	// If Mozilla/Firefox based browser
	if (document.defaultView)
	{
		//alert("Mozilla Browser");
		// Retrieve computed style of INPUT box
		var computedStyle = document.defaultView.getComputedStyle(obj,"");
		// Look at all CSS related properties related to HEIGHT
		height = parseInt(computedStyle.getPropertyValue("height").replace("px", ""));
		borderTopWidth = parseInt(computedStyle.getPropertyValue("border-top-width").replace("px", ""));
		borderBottomWidth = parseInt(computedStyle.getPropertyValue("border-bottom-width").replace("px", ""));
		paddingTop = parseInt(computedStyle.getPropertyValue("padding-top").replace("px", ""));
		paddingBottom = parseInt(computedStyle.getPropertyValue("padding-bottom").replace("px", ""));
		marginTop = parseInt(computedStyle.getPropertyValue("margin-top").replace("px", ""));
		marginBottom = parseInt(computedStyle.getPropertyValue("margin-bottom").replace("px", ""));
	}
	// If IE-based browser
	else
	{
		//alert("IE Browser");		
		try
		{
			if (obj.currentStyle["height"] == 'auto')
			{	throw 'auto exception'; }
			else
			{
				height = parseInt(obj.currentStyle["height"].replace("px",""));
			}
		}
		catch (er)
		{
			height = parseInt(obj.currentStyle["fontSize"].replace("px","")) + 2;
		}
		
		borderTopWidth = parseInt(obj.currentStyle["borderTopWidth"].replace("px", ""));
		borderBottomWidth = parseInt(obj.currentStyle["borderBottomWidth"].replace("px", ""));
		paddingTop = parseInt(obj.currentStyle["paddingTop"].replace("px", ""));
		paddingBottom = parseInt(obj.currentStyle["paddingBottom"].replace("px", ""));
		marginTop = parseInt(obj.currentStyle["marginTop"].replace("px", ""));
		marginBottom = parseInt(obj.currentStyle["marginBottom"].replace("px", ""));
		
	}
	// SUM all of these values to determine how tall the INPUT box really is when rendered by the browser
	inputHeight = height + borderTopWidth + borderBottomWidth + paddingTop + paddingBottom + marginTop + marginBottom;
	if (isNaN(inputHeight))
	{
		inputHeight = height + borderTopWidth + borderBottomWidth + paddingTop + paddingBottom;
	}
	
	objPopup.width = PopupCal_height+'px';
	objPopup.height = PopupCal_width+'px';
	objPopup.left = PosX+'px';								// Left position (in px) to draw the calendar popup
	objPopup.top = (PosY+inputHeight)+'px';		// Top position (in px) to draw the calendar popup
	objPopup.visibility = 'visible';
	
	var ShortMonNames = Array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
		
	var startMDY = "";
	var startYear = "";
	var startMonth = "";
	var startDay = "";
	var TodaysDate = new Date();
	var todayYear = TodaysDate.getFullYear();
	var todayDay = TodaysDate.getDate();
	var todayMonth = (parseInt(TodaysDate.getMonth()) + 1); // Corrected +1
	
	//alert("StartDate_txt: "+StartDate_txt);
	// If StartDate_txt is passed, use it as the date for displaying the calendar
	if (StartDate_txt != null)
	{
		var pieces = StartDate_txt.split("/"); // Split on slash character
		// Split the text date MM/YYYY format into 2 date variables
		if (pieces.length == 2)
		{
			startMonth = pieces[0];
			startYear = pieces[1];
			startDay = "1";
		}
		// Split the text date MM/DD/YYYY format into 3 date variables
		else
		{
			startMonth = pieces[0];
			startDay = pieces[1];
			startYear = pieces[2];
			todayYear = startYear;
			todayDay = startDay;
			todayMonth = startMonth;
		}
	}
	// If no date is passed in, use today's actual date as the start date for displaying the calendar
	else
	{
		startMonth = todayMonth;
		startYear = todayYear;
		startDay = todayDay;
	}
	//alert("startYear: "+startYear+"\nstartDay: "+startDay+"\nstartMonth: "+startMonth);	
	
	// Retrieve the 3 character month abbreviation
	var ShortMonthName = ShortMonNames[startMonth-1];
	// Build a MM/DD/YYYY format date for the first day in the selected month
	var startMDY = startMonth+"/1/"+startYear;
	
	// Subtract 1 month from the startMDY
	var PrevMonthYear = AddCalendarMonths(-1, startMDY);
	var StringDate_arr = PrevMonthYear.split("/"); // Split on slash character
	var PrevMonthYear = StringDate_arr[0]+"/"+StringDate_arr[2];
	//alert("PrevMonthYear: "+PrevMonthYear);
	
	// Add 1 month to the startMDY
	var NextMonthYear = AddCalendarMonths(1, startMDY);
	var StringDate_arr = NextMonthYear.split("/"); // Split on slash character
	var NextMonthYear = StringDate_arr[0]+"/"+StringDate_arr[2];
	//alert("NextMonthYear: "+NextMonthYear);
	
	// Build startMY using startMonth and startYear
	var startMY = startMonth+"/"+startYear;
	// Take the startMY and find the Sunday on or before the 1st of the month	
	CalStartDate = FindStartDate(startMY);
	// Split on slash character
	var CalStart_arr = CalStartDate.split("/");
	var currentMonth = CalStart_arr[0];
	var currentDay = CalStart_arr[1];
	var currentYear = CalStart_arr[2];
		
	var OutputHTML = "<div class=\"calPrev\" onClick=\"CreateCalendar(document.getElementsByName('"+obj.name+"')[0], '"+PrevMonthYear+"')\" title=\""+PrevMonthYear+"\"></div><div class=\"calLabel\">"+ShortMonthName+" "+startYear+"</div><div class=\"calNext\" onClick=\"CreateCalendar(document.getElementsByName('"+obj.name+"')[0], '"+NextMonthYear+"')\" title=\""+NextMonthYear+"\"></div><div class=\"calClose\" title=\"Close Calendar\" onClick=\"ClosePopupCal()\"></div><div class=\"clear\"></div>\n";
	OutputHTML += "<div class=\"float calHeader\"><div class=\"calHeaderText\">S</div></div><div class=\"float calHeader\"><div class=\"calHeaderText\">M</div></div><div class=\"float calHeader\"><div class=\"calHeaderText\">T</div></div><div class=\"float calHeader\"><div class=\"calHeaderText\">W</div></div><div class=\"float calHeader\"><div class=\"calHeaderText\">T</div></div><div class=\"float calHeader\"><div class=\"calHeaderText\">F</div></div><div class=\"float calHeader\"><div class=\"calHeaderText\">S</div></div><div class=\"clear\"></div>";

	var counter = 0;
	var isDateInCurrentMonth = true;
	
	// Calculate the NumWeeksToDisplay value based upon the number of days in the month 
	// and the day of the week that the 1st of the month falls upon
	var daysInMonth = DaysInMonth(startMonth,startYear);
	
	// Create JS DateTime variables for the 1st and last dates of the month
	var MonStart = new Date();
	MonStart.setFullYear(startYear, (startMonth-1), 1);
	//alert("MonStart: "+startMonth+"/"+1+"/"+startYear);
	var MonEnd = new Date();
	MonEnd.setFullYear(startYear, (startMonth-1), daysInMonth);
	//alert("MonEnd: "+startMonth+"/"+daysInMonth+"/"+startYear);
	var CurDate = new Date();
		
	// Retrieve DayOfWeek number (0-6) for the MonStart DateTime
	var dayOfWeek = MonStart.getDay();
	
	// Determine the exact fraction of weeks needed to display all of the dates for this 
	// calendar month (including days leading up to the 1st of the month)
	var NumWeeks = ((daysInMonth + dayOfWeek) / 7);
	
	// Round the NumWeeks up to the next whole number, compare against 5, taking the MAX
	var NumWeeksToDisplay = Math.max(Math.ceil(NumWeeks), 5); // Forces a minimum of 5 weeks
	
	if (NumWeeksToDisplay == 6)
	{ document.getElementById('PopupCal').style.height = '190px'; }
	else if (NumWeeksToDisplay == 5)
	{ document.getElementById('PopupCal').style.height = PopupCal_height+'px'; }
	
	// Show NumWeeksToDisplay weeks of dates on the calendar
	for (var days=currentDay; counter<(NumWeeksToDisplay*7); days++)
	{
		counter++;
		if (counter % 7 == 1)
		{	OutputHTML += "<div class=\"clear\"></div>\n"; }
		
		// Update our JS DateTime variable
		CurDate.setFullYear(currentYear, (currentMonth-1), days);
						
		// If the day to output on the calendar is TODAY
		if ((days==todayDay)&&(currentMonth==todayMonth)&&(currentYear==todayYear))
		{	OutputHTML += '<div class="calToday" title="TODAY - '+days+' '+ShortMonNames[currentMonth-1]+' '+currentYear+'"><div class="calDayText" onClick="SubmitValue(\''+obj.name+'\', \''+currentMonth+'/'+days+'/'+currentYear+'\')">'+days+'</div></div>';	}
		else
		{
			// Output calendar DIV for this date
			if ((CurDate < MonStart) || (CurDate > MonEnd))
			{	OutputHTML += '<div class="calInactive" title="'+days+' '+ShortMonNames[currentMonth-1]+' '+currentYear+'"><div class="calDayText" onClick="SubmitValue(\''+obj.name+'\', \''+currentMonth+'/'+days+'/'+currentYear+'\')">'+days+'</div></div>';	}
			else
			{	OutputHTML += '<div class="calActive" title="'+days+' '+ShortMonNames[currentMonth-1]+' '+currentYear+'"><div class="calDayText" onClick="SubmitValue(\''+obj.name+'\', \''+currentMonth+'/'+days+'/'+currentYear+'\')">'+days+'</div></div>';	}
		}
		
		// If current day is End Of Month, increment Month
		if (days >= DaysInMonth(currentMonth, currentYear))
		{
			days = 0;
			if (currentMonth == 12)
			{	
				currentMonth = 1;
				currentYear++;
			}
			else
			{	currentMonth++;	}
		}
	}
	document.getElementById('PopupCal').innerHTML = OutputHTML;
}
// USES CORRECTED month value (1-12), not 0-11 JS Date
function DaysInMonth(month,year)
{
	var dd = new Date(year, month, 0);
	return dd.getDate();
}
// Adds or subtracts a certain number of days from the string orgDate
function AddCalendarDays(dayIncrement, orgDate)
{
	var orgDate_arr = orgDate.split("/"); // Split on slash character
	var orgMonth = parseInt(orgDate_arr[0]);
	var orgDay = parseInt(orgDate_arr[1]);
	var orgFullYear = parseInt(orgDate_arr[2]);
	var incrementDifference = (orgDay + dayIncrement);	
	
	// If our incrementDifference is larger than the number of days in this current month
	if (incrementDifference > DaysInMonth(orgMonth, orgFullYear) )
	{
		if (orgMonth == 12)
		{
			newMonth = 1;
			newFullYear = orgFullYear + 1;
		}
		else
		{
			newMonth = orgMonth + 1;
			newFullYear = orgFullYear;
		}
		newDay = 0;
		increment = dayIncrement - (DaysInMonth(orgMonth, orgFullYear) - orgDay);
		return AddCalendarDays(increment, newMonth+"/"+newDay+"/"+newFullYear);
	}
	// If our dayIncrement + originalDays is less than or equal to zero, we need to decrement a month
	else if (incrementDifference <= 0)
	{
		if (orgMonth == 1)
		{
			newMonth = 12;
			newFullYear = orgFullYear - 1;
		}
		else
		{
			newMonth = orgMonth - 1;
			newFullYear = orgFullYear;
		}
		newDay = DaysInMonth((orgMonth-1), newFullYear);	
		return AddCalendarDays(incrementDifference, newMonth+"/"+newDay+"/"+newFullYear);
	}	
	// If our dayIncrement is smaller than the number of days in this current month, 
	// and our incrementDifference is greater than zero
	else ( (dayIncrement <= DaysInMonth(orgMonth, orgFullYear) ) && (incrementDifference > 0) )
	{
		NewFullDate = orgMonth+"/"+incrementDifference+"/"+orgFullYear;
	}
	return NewFullDate;
	NewFullDate = "";
}

function FindStartDate(currentMY)
{
	var orgDate_arr = currentMY.split("/"); // Split on slash character
	var orgMonth = parseInt(orgDate_arr[0]);
	var orgFullYear = parseInt(orgDate_arr[1]);
	var orgDay = 1;
	var retDateString = orgMonth+"/"+orgDay+"/"+orgFullYear;
	
	var retDate = new Date();
	// Set JavaScript date to return date string
	retDate.setFullYear(orgFullYear, (orgMonth-1), orgDay);
	// Retrieve DayOfWeek for the JavaScript date
	var dayOfWeek = retDate.getDay();
	if (dayOfWeek > 0)
	{	retDateString = AddCalendarDays(-dayOfWeek, retDateString);	}
	return retDateString;
}

// Adds or subtracts a certain number of months from the string orgDate
function AddCalendarMonths(monthIncrement, orgDate)
{
	NewFullDate = "";
	var orgDate_arr = orgDate.split("/"); // Split on slash character
	var orgMonth = parseInt(orgDate_arr[0]);
	var orgDay = parseInt(orgDate_arr[1]);
	var orgFullYear = parseInt(orgDate_arr[2]);
	
	// If we are doing a positive increment (adding a month)
	if (monthIncrement > 0)
	{
		incrementDifference = (monthIncrement + orgMonth);
		if (incrementDifference > 11)
		{
			orgMonth = 1;
			orgFullYear++;
			incrementDifference = incrementDifference-12;
			return AddCalendarMonths(incrementDifference, orgMonth+"/"+orgDay+"/"+orgFullYear);
		}
		else
		{
			NewFullDate = incrementDifference+"/"+orgDay+"/"+orgFullYear;
		}
	}
	// If we are doing a negative increment (subtracting a month)
	else if (monthIncrement < 0)
	{
		if (orgMonth == 1)
		{
			orgMonth = 12;
			orgFullYear--;
			monthIncrement++;
		}
		incrementDifference = (monthIncrement + orgMonth);
		if (incrementDifference <= 0)
		{
			orgMonth = 12;
			orgFullYear--;
			return AddCalendarMonths(incrementDifference, orgMonth+"/"+orgDay+"/"+orgFullYear);			
		}
		else
		{
			NewFullDate = incrementDifference+"/"+orgDay+"/"+orgFullYear;
		}
	}
	else
	{
		NewFullDate = orgMonth+"/"+orgDay+"/"+orgFullYear;
	}
	return NewFullDate;
}

function ClosePopupCal()
{
	document.getElementById('PopupCal').style.visibility = 'hidden';
	document.getElementById('PopupCal').style.left = '0px';
	document.getElementById('PopupCal').style.top = '0px';
	document.getElementById('PopupCal').style.width = '0px';
	document.getElementById('PopupCal').style.height = '0px';
}
function SubmitValue(ElementName, Value)
{
	ClosePopupCal();
	var obj = document.getElementsByName(ElementName);
	obj[0].value = Value;
}
function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
	{
		while(1) 
		{
			curleft += obj.offsetLeft;
			if(!obj.offsetParent)
			{	break;	}
			obj = obj.offsetParent;
		}
	}
	else if(obj.x)
	{	curleft += obj.x;	}
	return curleft;
}
function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
	{
		while(1)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
			{	break;	}
			obj = obj.offsetParent;
		}
	}
	else if(obj.y)
	{	curtop += obj.y;	}
	return curtop;
}

