// written by Tan Ling Wee on 2 Dec 2001
// last updated 10 Apr 2002
// email :	fuushikaden@yahoo.com
// modified (very little) by Sai on 01/02/05
// email :	sai_freelance@yahoo.com

var startAt = 0									 // 0 - sunday; 1 - monday
var showWeekNumber = 1
var showToday = 1
var imgDir = "Types/Form/Calendar/"

var todayStringEN = "Today is"
var todayStringNL = "Vandaag is"
var weekString = "wk"

var calendarPopup, monthSelector, yearSelector, monthSelected, yearSelected, dateSelected, oldMonthSelected, oldYearSelected, oldDateSelected, monthConstructed, yearConstructed, intervalID1, intervalID2, timeoutID1, timeoutID2, ctlToPlaceValue, dateFormat, nStartingYear;

var calendarConstructed=false;
var ie=document.all;
var dom=document.getElementById;

var ns4=document.layers;
var today = new Date();
var dateNow = today.getDate();
var monthNow = today.getMonth();
var yearNow = today.getFullYear();

var imgsrc = new Array("Down1.gif","Down2.gif","Left1.gif","Left2.gif","Right1.gif","Right2.gif");
var img = new Array();
var clickedInsideCalendar = false;

if (dom)
{
	for (var i=0; i<imgsrc.length; i++ )
	{
		img[i] = new Image();
		img[i].src= img + imgsrc[i];
	}
	
	document.write ("<div onclick='clickedInsideCalendar=true' id='calendar' class='div-style'><table width="+((showWeekNumber == 1)?250:220)+" class='table-style'><tr class='title-background-style' ><td><table width='"+((showWeekNumber == 1)?248:218)+"'><tr><td class='title-style'><strong><span id='caption'></span></strong></td><td align=right><a href='javascript:hideCalendar();'><img src='"+imgDir+"close.gif' WIDTH='12' HEIGHT='11' BORDER='0' ALT='Close the Calendar'></a></td></tr></table></td></tr><tr><td class='body-style'><span id='calendarContent'></span></td></tr>");
		
	if (showToday == 1)
		document.write ("<tr class='today-style'><td><span id='lblToday'></span></td></tr>");
		
	document.write ("</table></div><div id='selectMonth' class='div-style'></div><div id='selectYear' class='div-style'></div>");
}

var monthNameEN = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var monthNameNL = new Array("januari","februari","maart","april","mei","juni","juli","augustus","september","oktober","november","december");
var monthNameShortEN = new Array("Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec");
var monthNameShortNL = new Array("jan","feb","mrt","apr","mei","jun","jul","aug","sep","okt","nov","dec");
var dayNameEN = new Array ("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
var dayNameNL = new Array ("zo","ma","di","wo","do","vr","za");

// Default is NL
var monthName = monthNameNL;
var dayName = dayNameNL;
var todayString = todayStringNL; 
var monthNameShort = monthNameShortNL;

// Set monday as first
if ( startAt == 1 )
	dayName.push( dayName.shift() );

/* hides <select> and <applet> objects (for IE only) */
function hideElement( elmID, overDiv )
{
	if( ie )
	{
		var obj;
		for( i = 0; i < document.all.tags( elmID ).length; i++ )
		{
			obj = document.all.tags( elmID )[i];
			if( !obj || !obj.offsetParent )
				continue;
			
			// Find the element's offsetTop and offsetLeft relative to the BODY tag.
			objLeft = obj.offsetLeft;
			objTop = obj.offsetTop;
			objParent = obj.offsetParent;
			
			while( objParent != null && objParent.tagName.toUpperCase() != "BODY" )
			{
				objLeft += objParent.offsetLeft;
				objTop += objParent.offsetTop;
				objParent = objParent.offsetParent;
			}
	
			objHeight = obj.offsetHeight;
			objWidth = obj.offsetWidth;

			if(( overDiv.offsetLeft + overDiv.offsetWidth ) <= objLeft );
			else if(( overDiv.offsetTop + overDiv.offsetHeight ) <= objTop );
			else if( overDiv.offsetTop >= ( objTop + objHeight ));
			else if( overDiv.offsetLeft >= ( objLeft + objWidth ));
			else
				obj.style.visibility = "hidden";
		}
	}
}
	
/*
* unhides <select> and <applet> objects (for IE only)
*/
function showElement( elmID )
{
	if( ie )
	{  
		var obj;
		for( i = 0; i < document.all.tags( elmID ).length; i++ )
		{
			obj = document.all.tags( elmID )[i];
			
			if( !obj || !obj.offsetParent )
				continue;
			
			obj.style.visibility = "";
		}
	}
}

function HolidayRec (d, m, y, desc)
{
	this.d = d;
	this.m = m;
	this.y = y;
	this.desc = desc;
}

var HolidaysCounter = 0;
var Holidays = new Array();

function addHoliday (d, m, y, desc)
{
	Holidays[HolidaysCounter++] = new HolidayRec ( d, m, y, desc );
}

function swapImage(srcImg, destImg){
	if (ie)
		document.getElementById(srcImg).setAttribute("src",imgDir + destImg);
}

function init()
{
	if ( !ns4 )
	{
		calendarPopup=(dom)?document.getElementById("calendar").style : ie? document.all.calendar : document.calendar;
		hideCalendar();

		monthSelector=(dom)?document.getElementById("selectMonth").style : ie? document.all.selectMonth	: document.selectMonth;

		yearSelector=(dom)?document.getElementById("selectYear").style : ie? document.all.selectYear : document.selectYear;

		monthConstructed=false;
		yearConstructed=false;

		if (showToday == 1)
			document.getElementById("lblToday").innerHTML =	todayString + " <a class='today-style' href='javascript:monthSelected=monthNow;yearSelected=yearNow;constructCalendar();'>"+dayName[(today.getDay()-startAt == -1)?6:(today.getDay()-startAt)]+", " + dateNow + " " + monthName[monthNow].substring(0,3)	+ "	" +	yearNow	+ "</a>";
		
		sHTML1= "<span id='spanLeft'  class='title-control-normal-style' onmouseover='swapImage(\"changeLeft\",\"Left2.gif\");this.className=\"title-control-select-style\";' onclick='javascript:decMonth()' onmouseout='clearInterval(intervalID1);swapImage(\"changeLeft\",\"Left1.gif\");this.className=\"title-control-normal-style\";' onmousedown='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"StartDecMonth()\",500)'	onmouseup='clearTimeout(timeoutID1);clearInterval(intervalID1)'>&nbsp;<img id='changeLeft' src='"+imgDir+"Left1.gif' width=11 height=11 BORDER=0>&nbsp;</span>&nbsp;";
		sHTML1+="<span id='spanRight' class='title-control-normal-style' onmouseover='swapImage(\"changeRight\",\"Right2.gif\");this.className=\"title-control-select-style\";' onmouseout='clearInterval(intervalID1);swapImage(\"changeRight\",\"Right1.gif\");this.className=\"title-control-normal-style\";' onclick='incMonth()' onmousedown='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"StartIncMonth()\",500)'	onmouseup='clearTimeout(timeoutID1);clearInterval(intervalID1)'>&nbsp;<img id='changeRight' src='"+imgDir+"Right1.gif' width=11 height=11 BORDER=0>&nbsp;</span>&nbsp";
		sHTML1+="<span id='spanMonth' class='title-control-normal-style' onmouseover='swapImage(\"changeMonth\",\"Down2.gif\");this.className=\"title-control-select-style\";' onmouseout='swapImage(\"changeMonth\",\"Down1.gif\");this.className=\"title-control-normal-style\";' onclick='popUpMonth()'></span>&nbsp;";
		sHTML1+="<span id='spanYear'  class='title-control-normal-style' onmouseover='swapImage(\"changeYear\",\"Down2.gif\");this.className=\"title-control-select-style\";'	onmouseout='swapImage(\"changeYear\",\"Down1.gif\");this.className=\"title-control-normal-style\";'	onclick='popUpYear()'></span>&nbsp;";
		
		document.getElementById("caption").innerHTML =	sHTML1;

		calendarConstructed=true;
	}
}

function hideCalendar()
{
	if ( calendarPopup )
	{
		calendarPopup.visibility="hidden";
		if ( monthSelector != null)
			monthSelector.visibility="hidden";
		if ( yearSelector != null )
			yearSelector.visibility="hidden";

		showElement( 'SELECT' );
		showElement( 'APPLET' );
	}
}

function closeCalendar() 
{
	hideCalendar();
	ctlToPlaceValue.value = ConstructDate( dateSelected, monthSelected, yearSelected, dateFormat );
	ctlToPlaceValue.field.OnChange();
}

/*** Month Pulldown	***/

function StartDecMonth()
{
	intervalID1 = setInterval("decMonth()",80);
}

function StartIncMonth()
{
	intervalID1 = setInterval("incMonth()",80);
}

function incMonth()
{
	monthSelected++;
	if ( monthSelected > 11 )
	{
		monthSelected=0;
		yearSelected++;
	}
	constructCalendar();
}

function decMonth()
{
	monthSelected--;
	if ( monthSelected < 0 )
	{
		monthSelected=11;
		yearSelected--;
	}
	constructCalendar();
}

function constructMonth()
{
	popDownYear();
	if ( !monthConstructed )
	{
		sHTML = "";
		for ( i=0; i<12; i++ )
		{
			sName =	monthName[i];
			if (i == monthSelected)
				sName =	"<strong>" +	sName +	"</strong>";
			
			sHTML += "<tr><td id='m" + i + "' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='this.className=\"dropdown-normal-style\"' onclick='clickedInsideCalendar=true;monthConstructed=false;monthSelected=" + i + ";constructCalendar();popDownMonth();event.cancelBubble=true;'>&nbsp;" + sName + "&nbsp;</td></tr>";
		}

		document.getElementById("selectMonth").innerHTML = "<table width=70	class='dropdown-style' cellspacing=0 onmouseover='clearTimeout(timeoutID1)'	onmouseout='clearTimeout(timeoutID1);timeoutID1=setTimeout(\"popDownMonth()\",100);event.cancelBubble=true'>" + sHTML + "</table>";
		monthConstructed=true;
	}
}

function popUpMonth()
{
	constructMonth();
	monthSelector.visibility = (dom||ie)? "visible"	: "show";
	monthSelector.left = parseInt(calendarPopup.left) + 50;
	monthSelector.top =	parseInt(calendarPopup.top) + 26;
}

function popDownMonth()
{
	monthSelector.visibility= "hidden";
}

/*** Year Pulldown ***/

function incYear()
{
	var newYear;
	for ( i=0; i<7; i++ )
	{
		newYear = (i+nStartingYear)+1;
		if ( newYear == yearSelected )
			txtYear = "&nbsp;<strong>"	+ newYear +	"</strong>&nbsp;";
		else
			txtYear = "&nbsp;" + newYear + "&nbsp;";
			
		document.getElementById( "y"+i ).innerHTML = txtYear;
	}
	nStartingYear++;
	clickedInsideCalendar=true;
}

function decYear() 
{
	var newYear;
	for	(i=0; i<7; i++)
	{
		newYear = (i+nStartingYear)-1;
		if ( newYear == yearSelected )
			txtYear = "&nbsp;<strong>"	+ newYear +	"</strong>&nbsp;";
		else
			txtYear = "&nbsp;" + newYear + "&nbsp;";
		document.getElementById("y"+i).innerHTML = txtYear;
	}
	nStartingYear--;
	clickedInsideCalendar=true;
}

function selectYear( nYear )
{
	yearSelected=parseInt(nYear+nStartingYear);
	yearConstructed=false;
	constructCalendar();
	popDownYear();
}

function constructYear()
{
	popDownMonth();
	var sHTML =	"";
	if ( !yearConstructed )
	{
		var sHTML = "<tr><td align='center' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='clearInterval(intervalID1);this.className=\"dropdown-normal-style\"' onmousedown='clearInterval(intervalID1);intervalID1=setInterval(\"decYear()\",30)' onmouseup='clearInterval(intervalID1)'>-</td></tr>";
		var j = 0;
		nStartingYear = yearSelected - 3;
		var sName;
		for ( i=(yearSelected-3); i<=(yearSelected+3); i++ )
		{
			sName = i;
			if ( i == yearSelected )
				sName =	"<strong>" +	sName +	"</strong>";

			sHTML += "<tr><td id='y" + j + "' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='this.className=\"dropdown-normal-style\"' onclick='clickedInsideCalendar=true;selectYear("+j+");event.cancelBubble=true'>&nbsp;" + sName + "&nbsp;</td></tr>"
			j++;
		}

		sHTML += "<tr><td align='center' onmouseover='this.className=\"dropdown-select-style\"' onmouseout='clearInterval(intervalID2);this.className=\"dropdown-normal-style\"' onmousedown='clearInterval(intervalID2);intervalID2=setInterval(\"incYear()\",30)'	onmouseup='clearInterval(intervalID2)'>+</td></tr>";
		document.getElementById("selectYear").innerHTML = "<table width=44 class='dropdown-style' onmouseover='clearTimeout(timeoutID2)' onmouseout='clearTimeout(timeoutID2);timeoutID2=setTimeout(\"popDownYear()\",100)' cellspacing=0>"	+ sHTML	+ "</table>";
		yearConstructed = true;
	}
}

function popDownYear()
{
	clearInterval(intervalID1);
	clearTimeout(timeoutID1);
	clearInterval(intervalID2);
	clearTimeout(timeoutID2);
	yearSelector.visibility= "hidden";
}

function popUpYear()
{
	var leftOffset;

	constructYear();
	yearSelector.visibility = (dom||ie)? "visible" : "show";
	leftOffset = parseInt(calendarPopup.left) + document.getElementById("spanYear").offsetLeft;
	if (ie)
		leftOffset += 6;
	
	yearSelector.left =	leftOffset;
	yearSelector.top = parseInt(calendarPopup.top) +	26;
}

/*** calendar ***/

function WeekNbr(today)
{
	var Year = today.getFullYear();
	var Month = today.getMonth();
	var Day = today.getDate();
	var now = Date.UTC(Year,Month,Day+1,0,0,0);
	var Firstday = new Date();
	Firstday.setYear(Year);
	Firstday.setMonth(0);
	Firstday.setDate(1);
	var then = Date.UTC(Year,0,1,0,0,0);
	var Compensation = Firstday.getDay();
	if (Compensation > 3) Compensation -= 4;
	else Compensation += 3;
	var NumberOfWeek =  Math.round((((now-then)/86400000)+Compensation)/7);
	return NumberOfWeek;
}

function constructCalendar()
{
	var dateMessage;
	var startDate =	new Date( yearSelected,monthSelected,1 );
	var endDate = new Date( yearSelected,monthSelected+1,1 );
	endDate = new Date(endDate	- (24*60*60*1000));

	var numDaysInMonth = endDate.getDate();

	var datePointer = 0;
	var dayPointer = startDate.getDay() - startAt;
	
	if (dayPointer<0)
		dayPointer = 6;

	var sHTML = "<table	border=0 class='body-style'><tr>";

	if (showWeekNumber == 1)
		sHTML += "<td width=27 align=right><strong>" + weekString + "</strong>&nbsp;</td><td width=1 rowspan=7 class='weeknumber-div-style'><img src='"+imgDir+"divider.gif' width=1></td>";

	for (i=0; i<7; i++)
	{
		sHTML += "<td width='27' align='right'><strong>"+ dayName[i]+"</strong></td>";
	}
	sHTML +="</tr><tr>";
	
	if (showWeekNumber == 1)
		sHTML += "<td align=right>" + WeekNbr(startDate) + "&nbsp;</td>";

	for ( var i=1; i<=dayPointer;i++ )
	{
		sHTML += "<td>&nbsp;</td>";
	}

	for ( datePointer=1; datePointer<=numDaysInMonth; datePointer++ )
	{
		dayPointer++;
		sHTML += "<td align=right>";

		var sStyle="normal-day-style"; //regular day

		if ((datePointer == dateNow)&&(monthSelected == monthNow)&&(yearSelected == yearNow)) //today
			sStyle = "current-day-style";
		else if	(dayPointer % 7 == (startAt * -1) +1) //end-of-the-week day
			sStyle = "end-of-weekday-style";

		//selected day
		if ( (datePointer == oldDateSelected) && (monthSelected == oldMonthSelected)	&& ( yearSelected == oldYearSelected ) )
			sStyle += " selected-day-style";

		sHTML += "<a class='"+sStyle+"' href='javascript:dateSelected="+datePointer+";closeCalendar();'>" + datePointer + "</a>"

		if ((dayPointer+startAt) % 7 == startAt)
		{ 
			sHTML += "</tr><tr>";
			if ((showWeekNumber == 1)&&(datePointer<numDaysInMonth))
				sHTML += "<td align=right>" + (WeekNbr(new Date(yearSelected,monthSelected,datePointer+1))) + "&nbsp;</td>";
		}
	}

	document.getElementById("calendarContent").innerHTML = sHTML;
	document.getElementById("spanMonth").innerHTML = "&nbsp;" +	monthName[monthSelected] + "&nbsp;<img id='changeMonth' src='"+imgDir+"Down1.gif' WIDTH='11' HEIGHT='11' BORDER=0>";
	document.getElementById("spanYear").innerHTML =	"&nbsp;" + yearSelected	+ "&nbsp;<img id='changeYear' src='"+imgDir+"Down1.gif' WIDTH='11' HEIGHT='11' BORDER=0>";
}

function popUpCalendar( buttonElement, inputElement, format )
{
	if ( !calendarConstructed )
	{
		init();
		popUpCalendar( buttonElement, inputElement, format );
		return;
	}

	if ( calendarPopup == null || calendarPopup.visibility != "hidden" )
		return;

	ctlToPlaceValue = inputElement;
	dateFormat = format;
	
	// Get date from input element
	var date = ParseDate( inputElement.value );
	if ( date != null )
	{
		dateSelected = date.getDate();
		monthSelected = date.getMonth();
		yearSelected = date.getFullYear();
	}
	else
	{
		dateSelected = dateNow;
		monthSelected = monthNow;
		yearSelected = yearNow;
	}
	
	// Set old selected date
	oldDateSelected=dateSelected;
	oldMonthSelected=monthSelected;
	oldYearSelected=yearSelected;

	var aTag = buttonElement;
	var leftpos=0;
	var toppos=0;
	while( aTag != null && aTag.tagName != "BODY" )
	{
		aTag = aTag.offsetParent;
		if ( aTag == null )
			break;
		leftpos += aTag.offsetLeft;
		toppos += aTag.offsetTop;
	}

	constructCalendar (1, monthSelected, yearSelected);
	calendarPopup.visibility = (dom||ie)? "visible" : "show";

	hideElement( 'SELECT', document.getElementById("calendar") );
	hideElement( 'APPLET', document.getElementById("calendar") );			

	clickedInsideCalendar = true;
}

// Override document keypress and onclick
document._xcalOnKeyPress = document.onkeypress;
document.onkeypress = function hidecal1 ()
{
	try
	{
		if ( event.keyCode == 27 )
			hideCalendar();
	}
	catch ( e )
	{
	}

	if ( document._xcalOnKeyPress )
		document._xcalOnKeyPress();
}

document._xcalOnClick = document.onclick;
document.onclick = function hidecal2 ()
{		 
	if (!clickedInsideCalendar)
	{
		hideCalendar();
	}
	clickedInsideCalendar = false;
	if ( document._xcalOnClick )
		document._xcalOnClick();
}


function ParseDate( dateString )
{
	var now = new Date();
	var day = dateNow;
	var month = monthNow;
	var year = yearNow;

	// Guard
	if ( dateString == null || dateString == '' )
		return;

	// Get date pieces
	var dateSeparator = '-';		
	var datePieces = dateString.split( dateSeparator );
	if ( datePieces.length < 2 )
	{
		alert( "Invalid date '" + dateString + "'" );
		return;
	}
	
	// Strip leading zeros
	for ( var i=0; i<datePieces.length; i++ )
	{
		while ( datePieces[ i ].substring( 0, 1 ) == '0' )
			datePieces[ i ] = datePieces[ i ].substring( 1 );
	}
	
	// Fill in the date pieces
	day = parseInt( datePieces[ 0 ] );
	month = parseInt( datePieces[ 1 ] ) - 1;
	year = parseInt( datePieces[ 2 ] );

	// Return date
	if ( isNaN( day ) || isNaN( month ) || isNaN( year ) )
		return;
	else
		return new Date( year, month, day );
} 

function FormatDate( date, dateFormat )
{
	if( date == null )
		return '';
	else
		return ConstructDate( date.getDate(), date.getMonth(), date.getFullYear(), dateFormat );	
}

function padZero(num) {
	return (num	< 10)? '0' + num : num ;
}

function ConstructDate( d,m,y, dateFormat )
{
	var sTmp = dateFormat;
	sTmp = sTmp.replace( "dd","<e>");
	sTmp = sTmp.replace( "d","<d>");
	sTmp = sTmp.replace( "<e>",padZero(d));
	sTmp = sTmp.replace( "<d>",d);
	sTmp = sTmp.replace( "MMMM","<o>");
	sTmp = sTmp.replace( "MMM","<p>");
	sTmp = sTmp.replace( "MM","<n>");
	sTmp = sTmp.replace( "M","<m>");
	sTmp = sTmp.replace( "<m>",m+1);
	sTmp = sTmp.replace( "<n>",padZero(m+1));
	sTmp = sTmp.replace( "<o>",monthName[m]);
	sTmp = sTmp.replace( "<p>",monthNameShort[m]);
	sTmp = sTmp.replace( "yyyy", y );
	return sTmp.replace ("yy",y%100);
}

