//The following code must be added to any page that wants to call the calendar.  The top section sets a bunch of display options as described.
//The script file reference is, obviously, the main file where the java that creates the calendar's core features is stored.
//The third section are the calls that first, create the calendar and second set the data from the calendar into a given field. These functions 
// can be replaced by other functions that perform the same functionality, although if you change the second you need to update the 
// _calendarCallbackFunction variable in section 1. I also added the 2 controls used by my page that interact with the section 3 functions.

//Section 1
//    <script type="text/javascript">
//        var _monthNames=new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
//        var _rightToLeft=false; // which direction do month navigators take you? >> can be forward or backward
//        var _minMonth=7 // how far back will the calendar go [MAS 12/31/2008]
//        var _minYear=2008 // how far back will the calendar go [MAS 12/31/2008]
//        var _maxMonth=99 // how far ahead will the calendar go [MAS 12/31/2008]
//        var _maxYear=9999 // how far ahead will the calendar go [MAS 12/31/2008]
//        var _weekdayStart // 0 = Sunday, 1 = Monday.  Anything else defaults to Sunday [MAS 12/31/2008]
//        var _weekdayBackColor="#aed2ff" //background color of the day of week header row [MAS 12/31/2008]
//        var _calendarBackground="e6e6e6"; //possible recursion issue if this is a color name not a hex number  
//        var _calenderBorderSize=1;
//        var _calenderBorderColor="blue";
//        var _calenderCellColor="#ffffff"; //recursion issue if this is set as a color name [MAS 12/30/2008]
//        var _calenderCellFontName="Tahoma"; // the dates
//        var _calenderCellFontSize="11px";
//        var _calenderTextFontName="Tahoma"; // the month name label
//        var _calenderTextFontSize="12px";
//        var _calenderTextColor="black";
//        var _calendarCellWidth=25; // added to support smaller calendars/cells [MAS 12/30/2008]
//        var _calendarCellHeight=25; // added to support smaller calendars/cells [MAS 12/30/2008]
//        var _calendarAddLight=-50; //mousehover highlight shading (moves RGB that amount so white backgrounds should have a negative shading black backgrounds positive
//        var _calendarCallbackFunction="CalendarCallback"; //if you change the function that passes the data back to your web page, note it here.
//        var _calendarTop="150px"; //any value other than "0px" will set the left and top corner for the panel. "0px" sets it to default in the middle of the screen [MAS 12/30/2008]
//        var _calendarLeft="180px"; //any value other than "0px" will set the left and top corner for the panel. "0px" sets it to default in the middle of the screen [MAS 12/30/2008]
//        var _dateField; //the name of the field to return the value to [MAS 1/22/2009]
//    </script>
//Section 2
//    <script src="/includes/Calendar.js" type="text/javascript"></script>
//Section 3
//    <script type="text/javascript">
//        function BrowseDate(fldName) {
//          _dateField = fldName;
//	        var strDate = document.getElementById(_dateField).value;
//	        var arrParts=strDate.split("/");
//	        OpenCalendar(parseInt(arrParts[2]), parseInt(arrParts[0]), parseInt(arrParts[1]));
//        }
//
//        function CalendarCallback(strSelectedDate) {
//	        var date=new Date(strSelectedDate);
//	        document.getElementById(_dateField).value = (date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear();
//        }
//    </script>
//Section 4 - Replace the paramter of BrowseDate() to match the id of the date input field
//      <input type=text name="dSearch" id="dSearch" size="15" value="<%=[YourOptionalDateVariable]%>" style="SomeStyle">
//      <img src="/images/cal.jpg" onclick="BrowseDate('dSearch');" style="vertical-align: bottom;">

var _panelID="CalendarPanel";
var _currentYear=0;
var _currentMonth=-1;
var _dayCodes=new Array("Su", "Mo", "Tu", "We", "Th", "Fr", "Sa", "Su");
if (_weekdayStart != 1) _weekdayStart = 0;

function OpenCalendar(defYear, defMonth, defDay) {
	var now=new Date();
	if ((typeof defYear == "undefined")||(isNaN(defYear)))
		defYear = now.getFullYear();
	if ((typeof defMonth == "undefined")||(isNaN(defMonth)))
		defMonth = now.getMonth();
	else
		defMonth--;
	if ((typeof defDay == "undefined")||(isNaN(defDay)))
		defDay = now.getDate();

    //if a month limit is supplied, but no year set year to current year (if before/after current month) 
    //or set month to 1 or 12 if year is supplied but month is not [MAS 12/31/2008]
    if ((_minMonth != 0) && (_minYear == 0)) {
        if (_minMonth < now.getMonth()) {
            _minYear = now.getFullYear() - 1
        } else {
            _minYear = now.getFullYear() - 1
        }
    }
    if ((_minMonth == 0) && (_minYear != 0)) {
        _minMonth = 1
    }
    if ((_maxMonth != 0) && (_maxYear == 0)) {
        if (_maxMonth > now.getMonth()) {
            _maxYear = now.getFullYear()
        } else {
            _maxYear = now.getFullYear() - 1
        }
    }
    if ((_maxMonth == 0) && (_maxYear != 0)) {
        _maxMonth = 12
    }
    // end [MAS]
    
	FillCalendar(defYear, defMonth+1, defDay);
	
	var objPanel = document.getElementById(_panelID);
	objPanel.style.display = "block";
	var panelWidth = GetElementWidth(objPanel);
	var panelHeight = GetElementHeight(objPanel);
	var bodyWidth = document.body.clientWidth;
	var bodyHeight = document.body.clientHeight;
	var panelLeft = parseInt((bodyWidth/2)-(panelWidth/2));
	var panelTop = parseInt((bodyHeight / 2) - (panelHeight / 2));
	if (_calendarLeft == "0px") {
		objPanel.style.left = panelLeft + "px";
    } else {
        objPanel.style.left = _calendarLeft;
    }
    if (_calendarTop == "0px") {
    	objPanel.style.top = panelTop+"px";
    } else {
        objPanel.style.top = _calendarTop;
    }
}

function FillCalendar(year, month, day) {
	//var date=new Date();
	//date.setFullYear(year+1, month, day);
	//alert(date);
	
	_currentYear = year;
	_currentMonth = month-1;
	
	var daysCount=DaysInMonth(year, month);
	
	var date=new Date();
	date.setFullYear(year,month-1,1);
	var firstDay=date.getDay();
	
	var objPanel = document.getElementById(_panelID);
	if (!objPanel) {
		objPanel = document.createElement("div");
		objPanel.id = _panelID;
		objPanel.style.position = "absolute";
		objPanel.style.zIndex = _zIndex;
		objPanel.style.display = "none";
		objPanel.style.border = _calenderBorderSize+"px solid "+_calenderBorderColor;
		objPanel.style.backgroundColor = _calendarBackground;
//		objPanel.onclick = new Function("HideCalendar()");
		document.body.appendChild(objPanel);
	}
	
	while (objPanel.childNodes.length > 0)
		objPanel.removeChild(objPanel.childNodes[0]);

	BuildCalendarDetails(objPanel, _currentMonth, _currentYear);
	
	//should be moved and set on page in scripttag with other variables some day
	var cellWidth=_calendarCellWidth;
	var cellHeight=_calendarCellHeight;
	var currentSlot=1;
	var currentDay=0;
	var slotCount=daysCount+firstDay-_weekdayStart;
	var objTable=document.createElement("table");
	objTable.setAttribute("border", "0");
	objTable.setAttribute("cellpadding", "0");
	objTable.setAttribute("cellspacing", "0");
	var objRow=0;
	objRow=objTable.insertRow(objTable.rows.length);
	for (var zz=_weekdayStart;zz<=(_weekdayStart+6);zz++) {
    	objCell=objRow.insertCell(objRow.cells.length);
		objCell.setAttribute("width", cellWidth+"");
		objCell.setAttribute("height", cellHeight+"");
		objCell.style.border = "1px solid black";
		objCell.style.textAlign = "center";
		objCell.style.backgroundColor = _weekdayBackColor;
		objCell.style.fontFamily = _calenderCellFontName;
		objCell.style.fontSize = _calenderCellFontSize;
		objCell.style.cursor = "pointer";
		objCell.innerHTML = _dayCodes[zz]+"";
    }

	while (currentSlot <= slotCount) {
		if (((currentSlot-1)%7) == 0) {
			objRow=objTable.insertRow(objTable.rows.length);
		}
		for (var i=0+_weekdayStart; i<=6+_weekdayStart; i++) {
			if (currentSlot > slotCount)
				break;
			var objCell=objRow.insertCell(objRow.cells.length);
			if ((i >= firstDay) || (currentDay > 0))
			    currentDay++;
			objCell.setAttribute("width", cellWidth+"");
			objCell.setAttribute("height", cellHeight+"");
			objCell.style.border = "1px solid black";
			objCell.style.textAlign = "center";
			objCell.style.backgroundColor = _calenderCellColor;
			objCell.style.fontFamily = _calenderCellFontName;
			objCell.style.fontSize = _calenderCellFontSize;
			objCell.style.cursor = "pointer";
			objCell.onmouseover = new Function("PutMoreLight(this)");
			objCell.onmouseout = new Function("RestoreColor(this)");
			objCell.onclick = new Function("CalenderCellClick(this);");
			objCell.innerHTML = (currentDay==0?"&nbsp;":currentDay+"");
			currentSlot++;
		}
	}
	objPanel.appendChild(objTable);
	//window.resizeTo(objTable.clientWidth, objPanel.offsetHeight);
	
	BuildCancelButton(objPanel); // [MAS 2/19/2009]

}

// added function [MAS 2/19/2009]
function BuildCancelButton(objContainer) {

    var objSpan = document.createElement("div");
    objSpan.id = "calendar_cancel";
    objSpan.style.textAlign = "center";
    
    var btnCancel = BuildCalendarButton("Cancel");
    btnCancel.style.fontSize = "10px";
    btnCancel.onclick = CancelClick;
    
    objSpan.appendChild(btnCancel);
    
    objContainer.appendChild(objSpan);

}

function BuildCalendarDetails(objContainer, month, year) {
	var btnPreviousMonth=BuildCalendarButton((_rightToLeft)?">>":"<< "); //added a space to make it display properly in IE - no idea why it was cutting off one of the '<' and only on the back button... [MAS 12/31/2008]
	btnPreviousMonth.onclick = PreviousMonthClick;
	
	var btnNextMonth=BuildCalendarButton((_rightToLeft)?"<< ":">>"); //added a space to make it display properly in IE - no idea why it was cutting off one of the '<' and only on the back button... [MAS 12/31/2008]
	btnNextMonth.onclick = NextMonthClick;
	
	var objMonthSpan=BuildCalendarSpan(_monthNames[month]);
	var objYearSpan=BuildCalendarSpan(year+"");
	
	var showNext = true;
	var showPrev = true;
	if (_minYear > year) showPrev = false;
	if (_maxYear < year) showNext = false;
	if (_minYear == year) {
	    if (_minMonth > month) showPrev = false;
	}
	if (_maxYear == year) {
	    if (_maxMonth <= (month+1)) showNext = false;
	}	

	var objSpan=document.createElement("div");
	objSpan.id = _panelID+"_details";
	objSpan.style.textAlign = "center";
	objSpan.appendChild(BuildCalendarSpan("&nbsp;"));
	if (_rightToLeft) {
		if (showNext) objSpan.appendChild(btnNextMonth);
		objSpan.appendChild(BuildCalendarSpan("&nbsp;"));
		objSpan.appendChild(objMonthSpan);
		objSpan.appendChild(BuildCalendarSpan("&nbsp;&nbsp;&nbsp;"));
		objSpan.appendChild(objYearSpan);
		objSpan.appendChild(BuildCalendarSpan("&nbsp;"));
		if (showPrev) objSpan.appendChild(btnPreviousMonth);
	}
	else {
		if (showPrev) objSpan.appendChild(btnPreviousMonth);
		objSpan.appendChild(BuildCalendarSpan("&nbsp;"));
		objSpan.appendChild(objYearSpan);
		objSpan.appendChild(BuildCalendarSpan("&nbsp;&nbsp;&nbsp;"));
		objSpan.appendChild(objMonthSpan);
		objSpan.appendChild(BuildCalendarSpan("&nbsp;"));
		if (showNext) objSpan.appendChild(btnNextMonth);
	}
	objSpan.appendChild(BuildCalendarSpan("&nbsp;"));
	//objSpan.appendChild(BuildCalendarSpan("<br />"));
	objContainer.appendChild(objSpan);
}

function BuildCalendarButton(strText) {
    var bName = "btn"+ ((strText==">>")?((_rightToLeft)?"Bck":"Fwd"):((_rightToLeft)?"Fwd":"Bck")); // [MAS 12/31/2008]
	var result=document.createElement("button");
	result.setAttribute("type", "button");
	result.setAttribute("id", bName); // [MAS 12/31/2008]
	result.style.fontSize = "14px";
	result.style.align = ((strText==">>")?"right":"left");
	result.innerHTML = strText;
	return result;
}

function BuildCalendarSpan(strText) {
	var result=document.createElement("span");
	result.style.fontFamily = _calenderTextFontName;
	result.style.fontSize = _calenderTextFontSize;
	result.style.color = _calenderTextColor;
	result.innerHTML = strText;
	return result;
}

function CalenderCellClick(objCell) {
	//hide:
	HideCalendar();
	
	//set date:
	var date=new Date();
    if (objCell.innerHTML == "&nbsp;") {
        eval(_calendarCallbackFunction+"('')");
    } else {
    	date.setFullYear(_currentYear, _currentMonth, parseInt(objCell.innerHTML));
	    //activate callback function:
	    eval(_calendarCallbackFunction+"('"+date+"')");
    }

}

function HideCalendar() {
	var objPanel = document.getElementById(_panelID);
	objPanel.style.display = "none";
}

function CancelClick() {
    HideCalendar();
}

function PreviousMonthClick() {
	_currentMonth--;
	if (_currentMonth < 0) {
		_currentMonth = 11;
		_currentYear--;
	}
	FillCalendar(_currentYear, _currentMonth+1, 1);
}

function NextMonthClick() {
	_currentMonth++;
	if (_currentMonth > 11) {
		_currentMonth = 0;
		_currentYear++;
	}
	FillCalendar(_currentYear, _currentMonth+1, 1);
}

function DaysInMonth(year, month) {
	var date=new Date();
	var result=0;
	date.setFullYear(year, month-1, 1);
	while ((date.getFullYear() <= year)&&(date.getMonth() <= (month-1))) {
		result++;
		if (result > 31) {
			alert("error getting days in month!\nyear: "+year+", month: "+month);
			return 0;
		}
		date.setFullYear(year, month-1, date.getDate()+1);
	}
	return result;
}

function GetElementWidth(element) {
	return element.clientWidth;
}

function GetElementHeight(element) {
	return element.clientHeight;
}

var arrColoredControls=new Array();
function PutMoreLight(objControl, color, lightAmount) {
	var cancelAddLight=objControl.getAttribute("cancel_add_light");
	if (cancelAddLight == "1")
		return true;
	
	if (typeof color == "undefined")
		color = _calenderCellColor;
	
	if (typeof lightAmount == "undefined")
		lightAmount = _calendarAddLight;
	
	arrColoredControls[objControl] = color;
	
	var R=HexToInt(color.substring(1, 3));
	var G=HexToInt(color.substring(3, 5));
	var B=HexToInt(color.substring(5, 7));
	
	R = SafeAdd(R, lightAmount, 0, 255);
	G = SafeAdd(G, lightAmount, 0, 255);
	B = SafeAdd(B, lightAmount, 0, 255);
	
	var lightedColor=BuildColor(R, G, B);
	objControl.style.backgroundColor = lightedColor;
}

function RestoreColor(objControl) {
	var cancelAddLight=objControl.getAttribute("cancel_add_light");
	if (cancelAddLight == "1")
		return true;
	objControl.style.backgroundColor = arrColoredControls[objControl];
}

function IntToHex(num) {
	if (num < 10)
		return (num+"");
	
	switch (num) {
		case 10: return "a";
		case 11: return "b";
		case 12: return "c";
		case 13: return "d";
		case 14: return "e";
		case 15: return "f";
	}
	
	return IntToHex(parseInt(num/16))+IntToHex(parseInt(num%16));
}

function HexToInt(strHex) {
	return parseInt(strHex, 16);
}

function SafeAdd(num, addition, min, max) {
	num += addition;
	if (num > max)
		num = max;
	if (num < min)
		num = min;
	return num;
}

function BuildColor(r, g, b) {
	var R=IntToHex(r);
	var G=IntToHex(g);
	var B=IntToHex(b);
	R=(R.length == 1)?("0"+R):R;
	G=(G.length == 1)?("0"+G):G;
	B=(B.length == 1)?("0"+B):B;
	return "#"+R+G+B;
}
