/**************************************************************************************
	UTF-8 FILE ENCODING!!!!
	
	htmlDatePicker $Id: datePicker.js,v 1.6 2006/10/06 09:27:25 ahacia Exp $
	
	Copyright (c) 2005, Jason Powell
	All Rights Reserved

	Redistribution and use in source and binary forms, with or without modification, are 
		permitted provided that the following conditions are met:

		* Redistributions of source code must retain the above copyright notice, this list of 
			conditions and the following disclaimer.
		* Redistributions in binary form must reproduce the above copyright notice, this list 
			of conditions and the following disclaimer in the documentation and/or other materials 
			provided with the distribution.
		* Neither the name of the product nor the names of its contributors may be used to 
			endorse or promote products derived from this software without specific prior 
			written permission.

	THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS 
	OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 
	MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL 
	THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE 
	GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED 
	AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING 
	NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED 
	OF THE POSSIBILITY OF SUCH DAMAGE.
	
	Changes: e-point SA 2006
	
***************************************************************************************/
// User Changeable Vars
var HighlightToday	= true; // use true or false to have the current day highlighted
var DisablePast		= false; // use true or false to allow past dates to be selectable
// The month names in your native language can be substituted below
var MonthNamesEn = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
var MonthNamesPl = new Array("Styczeń","Luty","Marzec","Kwiecień","Maj","Czerwiec","Lipiec","Sierpień","Wrzesień","Październik","Listopad","Grudzień");
var MonthNamesTable = { "en": MonthNamesEn, "pl": MonthNamesPl }
var MonthNames = new Array();

//nieaktualne:
//customOffsetTop = 124; // ile pix pod buttonem

// Global Vars
var now = new Date();
var dest = null;
var ny = now.getFullYear(); // Today's Date
var nm = now.getMonth();
var nd = now.getDate();
var sy = 0; // currently Selected date
var sm = 0;
var sd = 0;
var y = now.getFullYear(); // Working Date
var m = now.getMonth();
var d = now.getDate();
var todayDate = formatDate(d, m , y);
var l = 0;
var t = 0;
var MonthLengths = new Array(31,28,31,30,31,30,31,31,30,31,30,31);

/* useless besides some texts: */
currentYear = now.getFullYear();
currentMonth = now.getMonth();
currentDay = now.getDate();


/*
	Function: GetDate(control)

	Arguments:
		control = ID of destination control
*/
function GetDate(destInput, lang, startYearShift, endYearShift) {
	top.datePicker_startYearShift = startYearShift;
	top.datePicker_endYearShift = endYearShift;
	EnsureCalendarExists();
	DestroyCalendar();
	
	// One arguments is required, the rest are optional
	// First arguments must be the ID of the destination control
	if(arguments[0] == null || arguments[0] == "") {
		// arguments not defined, so display error and quit
		alert("ERROR: Destination control required in function call GetDate()");
		return;
	} else {
		// copy argument
		dest = arguments[0];
	}
	y = now.getFullYear();
	m = now.getMonth();
	d = now.getDate();
	sm = 0;
	sd = 0;
	sy = 0;
	var cdval = dest.value;
	if(/\d{4}.\d{2}.\d{2}/.test(dest.value)) { //BEWARE! This line assumes date format!
		// element contains a date, so set the shown date
		var vParts = cdval.split("-"); // yyyy-mm-dd
		sy = vParts[0];
		sm = vParts[1] - 1;
		sd = vParts[2];
		m=sm;
		d=sd;
		y=sy;
	}
	
	
	MonthNames = MonthNamesTable[lang];

	/* Calendar is displayed 125 pixels above the destination element
	or (somewhat) over top of it. ;)*/
	// ten jest dobry: dest.parentNode.offsetTop
	//l = dest.parentNode.offsetLeft + dest.offsetLeft + dest.offsetParent.offsetLeft + 190;
	//t = dest.parentNode.offsetTop + dest.offsetTop + customOffsetTop + 40;
	l = dest.parentNode.offsetLeft;
	t = dest.parentNode.offsetTop;
	if(t < 0) t = 0; // >
	DrawCalendar(startYearShift, endYearShift);

	// we need to close calc when clicked outside of it
	if (bv.ie) {
		document.onclick = function() { DestroyCalendar(event); }
	} else {
	body = document.getElementsByTagName('BODY')[0];
	body.addEventListener('click', DestroyCalendar, true);
	}
}

/*
	function DestoryCalendar()
	
	Purpose: Destory any already drawn calendar so a new one can be drawn
*/
function DestroyCalendar() {
	// First check, if user clicked document outside of calc/
	// This is extremely lame, because of browser detection, 
	// but incompatibilities rule all other options out.
	var klicked = null;
	if (!bv.ie && arguments[0] && arguments[0] instanceof Event) {
		if(arguments[0].target) { //Gecko
			klicked = arguments[0].target;
		}
	}
	if (bv.ie) { //MSIE
		try {
			klicked = arguments[0].srcElement;
		} catch (e) {
			return false;
		}
	}
	
	if (calcWasClicked(klicked)) {
		return false; //do not destroy if datePicker elements clicked - that means INIT!
	}
	
	doDestroyCalendar();
	
	return;
}

function doDestroyCalendar() {
	var cal = document.getElementById("dpCalendar");
	if(cal != null) {
		cal.innerHTML = null;
		cal.style.display = "none";
	}
}

function calcWasClicked(clicked_element) {
	if (clicked_element == null) {
		return false;
	}
	calc_klicked = false;
	p = clicked_element.parentNode;
	while (p && p.tagName.toLowerCase() != 'body') {
		if (p.getAttribute("id") == 'dpCalendar') {
			calc_klicked = true;
			break;
		}
		p = p.parentNode;
	}
	if (clicked_element.parentNode.className == 'datePickerElementC' || calc_klicked) {
		return true; 
	}
	return false;
}

function DrawCalendar() {
	DestroyCalendar();
	cal = document.getElementById("dpCalendar");
	cal.style.left = l + "px";
	cal.style.top = t + "px";
	
	var sCal = "<table class=t_datePicker><tr><td class=\"prevButton\"><a href=\"javascript: PrevMonth();\" title=\"Previous Month\"></a></td>"+
		"<td class=\"cellMonth\" width=\"80%\" colspan=\"5\">"+ drawMonthSelector() +" "+ drawYearSelector() +"</td>"+
		"<td class=\"nextButton\"><a href=\"javascript: NextMonth();\" title=\"Next Month\"></a></td></tr>";
		// nie potrzeba dni tygodnia.
		//+"<tr><td>S</td><td>M</td><td>T</td><td>W</td><td>T</td><td>F</td><td>S</td></tr>";
	var wDay = 1;
	var wDate = new Date(y,m,wDay);
	if(isLeapYear(wDate)) {
		MonthLengths[1] = 29;
	} else {
		MonthLengths[1] = 28;
	}
	var dayclass = "";
	var isToday = false;
	for(var r=1; r<7; r++) {
		sCal = sCal + "<tr>";
		for(var c=0; c<7; c++) {
			var wDate = new Date(y,m,wDay);
			if(wDate.getDay() == c && wDay<=MonthLengths[m]) {
				if(wDate.getDate()==sd && wDate.getMonth()==sm && wDate.getFullYear()==sy) {
					dayclass = "cellSelected";
					isToday = true;  // only matters if the selected day IS today, otherwise ignored.
				} else if(wDate.getDate()==nd && wDate.getMonth()==nm && wDate.getFullYear()==ny && HighlightToday) {
					dayclass = "cellToday";
					isToday = true;
				} else if (c==0) {
					dayclass = "cellSunday";
				} else {
					dayclass = "cellDay";
					isToday = false;
				}
				if(((now > wDate) && !DisablePast) || (now <= wDate) || isToday) { // >
					// user wants past dates selectable
					sCal = sCal + "<td class=\""+dayclass+"\"><a href=\"javascript: ReturnDay("+wDay+");\">"+wDay+"</a></td>";
				} else {
					// user wants past dates to be read only
					sCal = sCal + "<td class=\""+dayclass+"\">"+wDay+"</td>";
				}
				wDay++;
			} else {
				sCal = sCal + "<td class=\"unused\"></td>";
			}
		}
		sCal = sCal + "</tr>";
	}
	sCal = sCal + "<tr><td colspan=\"7\"><table><tr><td><a href=\"#\" class=\"teva_button_prev\" onClick=\"doSelectDate();\" id=\"current_date_button\" title="+ todayDate +"><span>"+ todayDate +"</span></a></td><td><a href=\"#\" class=\"teva_button\" onClick=\"doClean();\"><span>Wyczyść</span></a></td></tr></table></td></tr></table>"
	cal.innerHTML = sCal; // works in FireFox, opera
	cal.style.display = "inline";
	
	
	
}

function PrevMonth() {
	m--;
	if(m==-1) {
		m = 11;
		y--;
	}
	DrawCalendar();
}

function NextMonth() {
	m++;
	if(m==12) {
		m = 0;
		y++;
	}
	DrawCalendar();
}

function drawYearSelector() {
	ret = "<select name=year id=yearSelector onchange=yearSelected(this)>";

	var startYearShift = (typeof top.datePicker_startYearShift == "undefined")? 3  : top.datePicker_startYearShift;
	var endYearShift   = (typeof top.datePicker_endYearShift   == "undefined")? 10 : top.datePicker_endYearShift;
	var suma = currentYear + endYearShift;
	for (i=currentYear - startYearShift; i<= currentYear + endYearShift; i++) {
		selectedV = "";
		if (i == y) {
			selectedV = " selected "
		}
		ret += "<option value="+ i + selectedV+ ">"+ i +"</option>";
	}
	ret += "</select>";
	return ret;
}

function yearSelected(selectYear) {
	y = parseInt(selectYear[selectYear.selectedIndex].value);
	DrawCalendar();
}

function drawMonthSelector() {
		ret = "<select name=month id=monthSelector onchange=monthSelected(this)>";
	for (i=0; i < 12; i++) {
		selectedV = "";
		if (i == m) {
			selectedV = " selected "
		}
		ret += "<option value="+ i + selectedV+ ">"+ MonthNames[i] +"</option>";
	}
	ret += "</select>";
	return ret;
}

function monthSelected(selectMonth) {
	m = parseInt(selectMonth[selectMonth.selectedIndex].value);
	DrawCalendar();
}

function ReturnDay(day) {
	cDest = document.getElementById('current_date_button');
	dest.value = formatDate(day, m, y);
	if (typeof dest.onchange != 'undefined')
	{
		datePickerChange(dest.value);
	}
	//cDest.value = 
	doDestroyCalendar();
}

function formatDate(day, month, year) {
	tmp_d = ""+day;
	if (tmp_d.length == 1) {
		tmp_d = "0"+tmp_d;
	}
	tmp_m = ""+(month + 1);
	if (tmp_m.length == 1) {
		tmp_m = "0"+tmp_m;
	}
	
	return (""+ year +"-"+ tmp_m +"-"+ tmp_d);
}

function doSelectDate() {
	cDest = document.getElementById('current_date_button');
	dest.value = cDest.title;
	if (typeof dest.onchange != 'undefined')
	{
		datePickerChange(dest.value);
	}
	doDestroyCalendar();
}

function doClean() {
	dest.value = "";
	doDestroyCalendar();
}

function EnsureCalendarExists() {
	if(document.getElementById("dpCalendar") == null) {
		var eCalendar = document.createElement("div");
		eCalendar.setAttribute("id", "dpCalendar");
		document.body.appendChild(eCalendar);
	}
}

function isLeapYear(dTest) {
	var y = dTest.getYear();
	var bReturn = false;
	
	if(y % 4 == 0) {
		if(y % 100 != 0) {
			bReturn = true;
		} else {
			if (y % 400 == 0) {
				bReturn = true;
			}
		}
	}
	
	return bReturn;
}
