var currentcalendar="";

// Cariable to hold the last date used
var defaultDate = new Date();
/// <summary>
/// Initialise the Calendar
/// </summary>
function InitialiseCalendar(strDateBox, strMonthBox, strInterval, tabIndex)
{
	var strCalendarElementName = "Calendar_" + strDateBox + "_" + strMonthBox; 
	var strCalendarTextBox =  strDateBox + "_" + strMonthBox;

	if (document.getElementById(strCalendarElementName) == null)
	{
		// Create Div to be used as Airport Finder
		var calendarElement= document.createElement("div");
		calendarElement.id = strCalendarElementName
		calendarElement.style.display = "none";

		// Use Differant Size and positions for moz and ie
		if (isIE()) 
		{
			// IE
			calendarElement.style.top= "21px";
			calendarElement.style.width = "172px";
			
			// Also if ie create an IFrame to put under the div to hide drop downs
			if (!document.getElementById("CalendarCover_"+ strDateBox +"_" + strMonthBox))
			{
				var elemDropCover = document.createElement("IFRAME");
				elemDropCover.id = "CalendarCover_"+ strDateBox +"_" + strMonthBox;
				elemDropCover.style.display = "none";
				elemDropCover.style.position = "absolute";
				elemDropCover.src = "javascript:false";
				elemDropCover.frameBorder="0";
				elemDropCover.scrolling = "no";
				document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox).appendChild(elemDropCover);
			}
		}
		else
		{
			// moz
			calendarElement.style.left ="0px";
			calendarElement.style.top= "16px";
			calendarElement.style.width = "172px";
		}
		
		// Create the hidden fields to hold the calendar information
		if (document.getElementById(strDateBox)==null)
		{
			var hidDateBox= document.createElement("input");
			hidDateBox.id = strDateBox;
			hidDateBox.name= strDateBox;
			hidDateBox.type="hidden";
			document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox).appendChild(hidDateBox);				
		}
		
		if (document.getElementById(strMonthBox)==null)
		{
			var hidMonthBox= document.createElement("input");
			hidMonthBox.id = strMonthBox;
			hidMonthBox.name= strMonthBox;
			hidMonthBox.type="hidden";
			document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox).appendChild(hidMonthBox);
		}		

		// Create the calender input  box if it doesnt already exist
		if (!document.getElementById(strDateBox + "_" + strMonthBox))
		{
			var elemCalendarText= document.createElement("input");
			elemCalendarText.type = "text";
			elemCalendarText.name = strDateBox + "_" + strMonthBox;
			elemCalendarText.id = strDateBox + "_" + strMonthBox;			
			elemCalendarText.size="25";
			elemCalendarText.className="TextBox";
			elemCalendarText.tabIndex=tabIndex
//			elemCalendarText.onFocus = "DrawCalendar('DD1','MD1');"
			elemCalendarText.readOnly = true;
			document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox).appendChild(elemCalendarText);
			//<input type="text"  tabindex="7" class="TextBox" readonly value="" size="25" name="DD1_MD1" id="DD1_MD1" autocomplete="off" onFocus="DrawCalendar('DD1','MD1');">			
		}

		document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox).style.display ="inline";
		var spanBox = document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox)
		spanBox.style.position ="relative";
		spanBox.style.top="0px";
		
		// Append the div to the document
		document.getElementById("CalendarSection_" + strDateBox + "_" + strMonthBox).insertBefore(calendarElement,document.getElementById(strCalendarTextBox));

		// Set Default's
		if (document.getElementById(strCalendarTextBox).value!="")
		{
			var dateInterval = document.getElementById(strCalendarTextBox).value;
			defaultDate.setDate(defaultDate.getDate() + parseInt(dateInterval));
		}
		else
		{
			defaultDate.setDate(defaultDate.getDate() + parseInt(strInterval));
		}
		
		SelectDate(strDateBox, strMonthBox,defaultDate);

		// Add Key Press Event
		document.getElementById(strCalendarTextBox).onkeyup = Calendar_KeyPress;
		//document.getElementById(strCalendarTextBox).onblur = RemoveCalendarOnBlur
		document.getElementById(strCalendarTextBox).onfocus = RemoveCalendarOnBlur
	}
	calendarElement.className="CalDropDown";	
}

var Calendar_Focus=function()
{
	var strTextBoxName = new String(this.id);
	var arrBoxNames = strTextBoxName.split("_");
	DrawCalendar(arrBoxNames[0],arrBoxNames[1]);
}

var Calendar_KeyPress=function(event)
{
	// Concat the names of the textboxs
	Calendar_SelectionChange(event, this.id);
}

function Calendar_SelectionChange(KeyPressed, strTextBoxName)
{
	var key = "";
	if (isIE())
	{
		key  = event.keyCode;
	}
	else
	{
		key= KeyPressed.keyCode;
	}
	var yesterday = new Date();
	yesterday.setDate(yesterday.getDate()-1);
	
	var PreSelectedDate = new Date(document.getElementById(strTextBoxName).value);
	var OldDate = new Date(document.getElementById(strTextBoxName).value);
	if (key == 38)
	{
		// Up Key Pressed
		PreSelectedDate.setDate(PreSelectedDate.getDate() - 7);
	}
	else if (key == 40)
	{
		// Down Key Pressed
		PreSelectedDate.setDate(PreSelectedDate.getDate() + 7);		
	}
	else if (key == 37)
	{
		// Left Key Pressed
		PreSelectedDate.setDate(PreSelectedDate.getDate() -1);
	}
	else if (key == 39)
	{
		// Right Key Pressed
		PreSelectedDate.setDate(PreSelectedDate.getDate() +1);		
	}
	else if(key == 13)
	{
		var arrBoxNames = strTextBoxName.split("_");
		SelectDate(arrBoxNames[0], arrBoxNames[1],PreSelectedDate)
	}
	
	if (key != 13)
	{
		if (PreSelectedDate >=yesterday)
		{
			// Update the Text box value
			document.getElementById(strTextBoxName).value = getDayName(PreSelectedDate.getDay()) + " " + PreSelectedDate.getDate() + " " + getMonthName(PreSelectedDate.getMonth()) + " " + PreSelectedDate.getFullYear();
			
			// Select the date
			var seperateDateBoxName = new String(strTextBoxName); 

			RemoveCalendar(seperateDateBoxName.substring(0,3) + "_" +  seperateDateBoxName.substring(4,7))
			DrawMonth(seperateDateBoxName.substring(0,3), seperateDateBoxName.substring(4,7), PreSelectedDate);
//			DrawCalendar(seperateDateBoxName.substring(0,3), seperateDateBoxName.substring(4,7));
		}	
	}
}

/// <summary>
/// Draw the calendar on the screen
/// </summary>
function DrawCalendar(strDateBox, strMonthBox)
{
	// Concat the names of the textboxs
	if (currentcalendar!="")
	{
	
	RemoveCalendar(currentcalendar);
	}
	var strCalendarElementName = "Calendar_" + strDateBox + "_" + strMonthBox;
	var strCalendarTextBox =  strDateBox + "_" + strMonthBox;
	currentcalendar =  strDateBox + "_" + strMonthBox;

	var calendarElement = document.getElementById(strCalendarElementName);
	startDate = new Date(document.getElementById(strCalendarTextBox).value);

	if (calendarElement.childNodes.length == 0)
	{
		// Draw the calendar
		DrawMonth(strDateBox, strMonthBox, startDate);
	}
	else
	{
		RemoveCalendar(strDateBox + "_" + strMonthBox)
	}
	
}


/// <summary>
/// Remove the calendar on Blur
/// </summary>
var RemoveCalendarOnBlur = function ()
{
	setTimeout("RemoveCalendar(\"" + this.id + "\")", 500);
}

/// <summary>
/// Remove the calendar from the screen
/// </summary>
function RemoveCalendar(strCalendarName)
{
	// Loop through the airports
	if (document.getElementById("Calendar_" + strCalendarName))
	{
		if (document.getElementById("Calendar_" + strCalendarName).hasChildNodes())
		{
			var childs = document.getElementById("Calendar_" + strCalendarName);
			var arrLength = childs.childNodes.length;

			// Remove Objects one by one
			for (count=0; count<arrLength; count++)
			{
				try
				{
					var obj = childs.firstChild;
					childs.removeChild(obj);
				}
				catch(e)
				{
				}
			}
		}
		document.getElementById("Calendar_" + strCalendarName).style.display="none";
		if (document.getElementById("CalendarCover_" + strCalendarName))
			document.getElementById("CalendarCover_" + strCalendarName).style.display="none";
	}
}


/// <summary>
/// Tell The calendar to draw a different month
/// </summary>
function ChangeMonth(strDateBox, strMonthBox, startDate)
{
	var showDate = new Date(startDate);
	RemoveCalendar(strDateBox + "_" + strMonthBox);
	DrawMonth(strDateBox, strMonthBox, showDate)
}

/// <summary>
/// Select the date hide the calendar and enter it into the fields
/// </summary>
function SelectDate(strDateBox, strMonthBox,selectedDate)
{

	// Check Date Box Exists
	if (document.getElementById(strDateBox + "_" + strMonthBox))
	{
		selectedDate = new Date(selectedDate);
		document.getElementById(strDateBox).value = selectedDate.getDate();
	
		var strMonth = new String(selectedDate.getMonth() + 1);
		if (strMonth.length ==1)
			strMonth = "0" + strMonth;
	
		document.getElementById(strMonthBox).value = strMonth +""+ selectedDate.getFullYear();
		RemoveCalendar(strDateBox + "_" +strMonthBox);
	
		document.getElementById(strDateBox + "_" + strMonthBox).value = getDayName(selectedDate.getDay()) + " " + selectedDate.getDate() + " " + getMonthName(selectedDate.getMonth()) + " " + selectedDate.getFullYear();
		
		// Convert them to string objects
		var DateBoxAsString = new String (strDateBox)
		var MonthBoxAsString = new String (strMonthBox)
		var DateBoxCount = new Number(DateBoxAsString.substr(2,1));

		// Check date is before 
		CheckDateBox(DateBoxAsString, MonthBoxAsString, selectedDate, DateBoxCount + 1)
	}
}

/// <summary>
/// Check the Dates is valid
/// </summary>
function CheckDateBox(DateBoxAsString, MonthBoxAsString, selectedDate, DateBoxCount)
{
	//  Get Names of the Next Date Box
	var nextDateBox = DateBoxAsString.substr(0,2) + DateBoxCount
	var nextMonthBox = MonthBoxAsString.substr(0,2)  + DateBoxCount

	// Check the date in the next box is set
	if (document.getElementById(nextDateBox))
	{
		// Foirmulate Date from text boxes
		var strDateFromNextBox = new String(document.getElementById(nextDateBox).value);
		var strMonthYearFromNextBox = new String(document.getElementById(nextMonthBox).value);
		var DateInNextBox = new Date();
		DateInNextBox.setYear(strMonthYearFromNextBox.substr(2,4));
		DateInNextBox.setMonth(strMonthYearFromNextBox.substr(0,2));
		DateInNextBox.setMonth(DateInNextBox.getMonth() -1);
		DateInNextBox.setDate(strDateFromNextBox);
		
		// Check that its after today if not increment onwards
		if (DateInNextBox <= selectedDate)
		{
			selectedDate.setDate(selectedDate.getDate() + 7);
			SelectDate(nextDateBox, nextMonthBox, selectedDate);
		}
	}
}

///------------------------------------- Draw Month Functions For --------------------------------

/// <summary>
/// Draw the Month to the screen
/// </summary>
function DrawMonth(strDateBox, strMonthBox, startDate)
{
	
	
	//FIXX REQUIRED....
	//we have a problem houston...when initial date is greater than 28th...
	//as we are passing on full dates dunno to move from one month to the next when displaying calendar problems arise when
	//the following or previous month has less days in..
	//eg if when say going forward current date is 31st Jan and we add month on then feb is initaily skipped as feb 31 
	//don't exist and date then becomes 2nd Mar...
	//same thing happens going in reverse say we move from 31 may to 31st of april..well you get the picture...
	//Soooo to fix it I simply say if the initaial date passed to calendar is greater than 28th then reduce it by 3...
	//let's hope may fixx doesn't cause any other problems!!...as is normally the case....
		
	// concat the names of the Boxs
	var strCalendarElementName = "Calendar_" + strDateBox + "_" + strMonthBox;
	var strCalendarTextBox =  strDateBox + "_" + strMonthBox;
	var divCalendar = document.getElementById(strCalendarElementName);

	// Turn Readonly off on the following month - to work round IE bug
	var Datebox2 = new String (strDateBox)
	var Monthbox2 = new String (strMonthBox)
	var DateBoxCount = new Number(Datebox2.substr(2,1));
	DateBoxCount ++;
	
	// Create Table to hold the Month
	var calendarTable= document.createElement("table");
	calendarTable.id="CalendarTable";
	calendarTable.cellSpacing=0;
	calendarTable.cellPadding=1;
	calendarTable.width="100%";

	// Create Row to Hold Month Name
	var calendarNameRow = calendarTable.insertRow(calendarTable.rows.length);
	calendarNameRow.className="CalendarHeader";
	// Create link to previous Month
	var previousMonthCell= document.createElement("td");

	var previousMonth= new Date(startDate);
	var today = new Date();

	if (previousMonth >= today)
	{
		var previousLink = document.createElement("a");
		previousMonth.setMonth(previousMonth.getMonth()-1);
		previousLink.href="javascript:ChangeMonth(\"" + strDateBox + "\",\"" + strMonthBox + "\"," + "\"" + previousMonth + "\");";
		previousLink.className="calendarNavLink";

		var textArrows= document.createTextNode("<<");
		previousLink.appendChild(textArrows);
		previousMonthCell.appendChild(previousLink);
	}

	calendarNameRow.appendChild(previousMonthCell);

	// Create Cell To Hold Month Name
	var calendarNameCell = document.createElement("td");
	var calendarMonthName = document.createTextNode(getMonthName(startDate.getMonth()) + " " + startDate.getFullYear());
	calendarNameCell.className="calendarMonthName";
	calendarNameCell.colSpan="5";
	calendarNameCell.appendChild(calendarMonthName);
	calendarNameRow.appendChild(calendarNameCell);

	// Create link to Next Month
	var nextMonthCell= document.createElement("td");
	var nextLink = document.createElement("a");
	var nextMonth= new Date(startDate);
	//*****FIXXXXX*********//
	if (nextMonth.getDate()>28)
	nextMonth.setDate(nextMonth.getDate()-3);
	//*****END OF FIXXXXX**********//
	nextMonth.setMonth(nextMonth.getMonth()+1);
	nextLink.href="javascript:ChangeMonth(\"" + strDateBox + "\",\"" + strMonthBox + "\"," + "\"" + nextMonth + "\");";
	nextLink.className="calendarNavLink";
	var textArrows= document.createTextNode(">>");
	nextLink.appendChild(textArrows);
	nextMonthCell.appendChild(nextLink);
	calendarNameRow.appendChild(nextMonthCell);

	// Creates Days Accross the Top
	// Create Row to Hold Days Name
	var calendarDayRow = calendarTable.insertRow(calendarTable.rows.length);

	// Loop through days Creating them
	for (var count=0; count < 7; count++)
	{
		var calendarDayCell = document.createElement("td");
		var strDay = new String(getDayName(count));
		var calendarDayName= document.createTextNode(strDay.substr(0,2));
		calendarDayCell.className="calendarDayHeader";
		calendarDayCell.style.textAlign = "center";
		calendarDayCell.appendChild(calendarDayName);
		calendarDayRow.appendChild(calendarDayCell);
	}

	// Add All Dates to the Calendar
	var dateCount=1;
	var foundFirstDayFlag=0
	var pointerDate= new Date(startDate.getFullYear(), startDate.getMonth(), 1);

	// Find Day
	for (var rowCount=0; rowCount<=5; rowCount++)
	{
		var calendarDayRow = calendarTable.insertRow(calendarTable.rows.length);
		// Create a Cell for everyday in the month
		for (var count=0; count < 7; count++)
		{
			var calendarDayCell = document.createElement("td");

			// See if this is the first day of the month
			if (foundFirstDayFlag==0)
			{
				if ((count == pointerDate.getDay()) && (dateCount == pointerDate.getDate()))
				{
					// First Day of the Month
					foundFirstDayFlag =1;
					var calendarDayName= drawDayLink(dateCount, pointerDate, strDateBox, strMonthBox)
					dateCount ++;
					var pointerDate= new Date(startDate.getFullYear(), startDate.getMonth(), dateCount);
				}
				else
				{
					calendarDayCell.className="calendarEmptyCell";
					var calendarDayName= document.createTextNode(" ");
				}
			}
			else
			{
				// Check we havent exceeded the amount of days in the month
				if (((dateCount-1)<getDays(pointerDate.getMonth(),pointerDate.getFullYear())) && (dateCount == pointerDate.getDate()))
				{
					// Write Date in the Cell
					var calendarDayName= drawDayLink(dateCount, pointerDate, strDateBox, strMonthBox)
					dateCount ++;
					var pointerDate= new Date(startDate.getFullYear(), startDate.getMonth(), dateCount);
				}
				else
				{
					calendarDayCell.className="calendarEmptyCell";
					var calendarDayName= document.createTextNode(" ");
					rowCount=5;
				}
			}
			calendarDayCell.style.textAlign = "center";
			calendarDayCell.appendChild(calendarDayName);
			calendarDayRow.appendChild(calendarDayCell);
		}
	}

	// Get Date
	divCalendar.style.display = "block";
	divCalendar.appendChild(calendarTable);
	
	if (document.getElementById("CalendarCover_"+ strDateBox +"_" + strMonthBox))
	{
		// Position IFrame Just Below the calendar
		document.getElementById("CalendarCover_" + strDateBox + "_" + strMonthBox).style.position="absolute";
		document.getElementById("CalendarCover_" + strDateBox + "_" + strMonthBox).style.top=divCalendar.style.top;
		document.getElementById("CalendarCover_" + strDateBox + "_" + strMonthBox).style.width=divCalendar.offsetWidth;
		document.getElementById("CalendarCover_" + strDateBox + "_" + strMonthBox).style.left=divCalendar.offsetLeft;
		document.getElementById("CalendarCover_" + strDateBox + "_" + strMonthBox).style.height=divCalendar.offsetHeight;
		document.getElementById("CalendarCover_" + strDateBox + "_" + strMonthBox).style.display=divCalendar.style.display;
		document.getElementById("CalendarCover_" +  strDateBox + "_" + strMonthBox).style.zIndex=divCalendar.style.zIndex -1;
	}
}


/// <summary>
/// Creates the link and the function to call to set the date
/// </summary>
function drawDayLink(dateCount, selectedDate, strDateBox, strMonthBox)
{
	// Create todays date and one for 330 days in the future
	var today = new Date();
	today.setDate(today.getDate() -1);
	var dtFuture = new Date();
	dtFuture.setDate(dtFuture.getDate() + 330);

	// Check that the link is valid
	if ((selectedDate>dtFuture) || (selectedDate<today))
	{
		var dayLink = document.createElement("span");
		dayLink.className="calendarInvalid";
		var textDate= document.createTextNode(dateCount);
	}
	else 
	{
		var dayLink = document.createElement("a");
		dayLink.className="calendarDayLink";
		dayLink.href="javascript:SelectDate(\"" + strDateBox + "\",\"" + strMonthBox + "\"," + "\"" + selectedDate + "\");";
		dayLink.id = "DateSelect_" + selectedDate.getDate() + "_" + selectedDate.getMonth();
		
		// Mark if its the selected Date Different Class if its today
		var PreSelectedDate = new Date(document.getElementById(strDateBox + "_" + strMonthBox).value);
		if ((selectedDate.getDate() == PreSelectedDate.getDate()) && (selectedDate.getMonth() == PreSelectedDate.getMonth()))
		{
			dayLink.className="CalendarSelected";
		}
	}

	var textDate= document.createTextNode(dateCount);
	dayLink.appendChild(textDate);

	return dayLink;
}

/// <summary>
/// Focus on a selected Date
/// </summary>
function FocusOnSelectedDate(selectedDate, OldDate)
{
	// Reset Old Date 
	var oldSelectedDateElement = document.getElementById("DateSelect_" + OldDate.getDate() + "_" + OldDate.getMonth())
	if ((oldSelectedDateElement) && (selectedDate!=OldDate))
	{
		oldSelectedDateElement.className="calendarDayLink";
	}
	
	var selectedDateElement = document.getElementById("DateSelect_" + selectedDate.getDate() + "_" + selectedDate.getMonth())
	if (selectedDateElement)
	{
		selectedDateElement.className="CalendarSelected";
	}
}

///------------------------------------- General Date Functions For --------------------------------

/// <summary>
/// Checks if year is leap year
/// </summary>
function leapYear(year)
{
	if (year % 4 == 0) // basic rule
	{
		return true; // is leap year
	}
	/* else */ // else not needed when statement is "return"
	else
	{
		return false; // is not leap year
	}
}

/// <summary>
/// Returns and Array of Months and Days
/// </summary>
function getDays(month, year)
{
	// create array to hold number of days in each month
	var ar = new Array(12);
	ar[0] = 31; // January
	
	if (leapYear(year)) {
		ar[1] = 29;
	} else {
		ar[1] = 28;
	}
	
//	ar[1] = (leapYear(year)) ? 29 : 28; // February    <--- Doesn't seem to work...

	ar[2] = 31; // March
	ar[3] = 30; // April
	ar[4] = 31; // May
	ar[5] = 30; // June
	ar[6] = 31; // July
	ar[7] = 31; // August
	ar[8] = 30; // September
	ar[9] = 31; // October
	ar[10] = 30; // November
	ar[11] = 31; // December
	// return number of days in the specified month (parameter)
	return ar[month];
}

/// <summary>
/// Returns the name of a month
/// </summary>
function getMonthName(month)
{
	// create array to hold name of each month
	var ar = new Array(12);
	ar[0] = "January";
	ar[1] = "February";
	ar[2] = "March";
	ar[3] = "April";
	ar[4] = "May";
	ar[5] = "June";
	ar[6] = "July";
	ar[7] = "August";
	ar[8] = "September";
	ar[9] = "October";
	ar[10] = "November";
	ar[11] = "December";

	//if(month==-1||month==12)
	if(month==-1)
	{
		ar[month]=ar[11]
	}
	if(month==12)
	{
		ar[month]=ar[0]
	}

	// return name of specified month (parameter)
	return ar[month];
}


/// <summary>
/// Returns the name of a month
/// </summary>
function getDayName(day)
{
	// create array to hold name of each month
	var ar = new Array(7);
	ar[0] = "Sun";
	ar[1] = "Mon";
	ar[2] = "Tue";
	ar[3] = "Wed";
	ar[4] = "Thu";
	ar[5] = "Fri";
	ar[6] = "Sat";


	// return name of specified month (parameter)
	return ar[day];
}
