/*  Copyright Mihai Bazon, 2002, 2003  |  http://dynarch.com/mishoo/
 * ---------------------------------------------------------------------------
 *
 * The DHTML Calendar
 *
 * Details and latest version at:
 * http://dynarch.com/mishoo/calendar.epl
 *
 * This script is distributed under the GNU Lesser General Public License.
 * Read the entire license text here: http://www.gnu.org/licenses/lgpl.html
 *
 * This file defines helper functions for setting up the calendar.  They are
 * intended to help non-programmers get a working calendar on their site
 * quickly.  This script should not be seen as part of the calendar.  It just
 * shows you what one can do with the calendar, while in the same time
 * providing a quick and simple method for setting it up.  If you need
 * exhaustive customization of the calendar creation process feel free to
 * modify this code to suit your needs (this is recommended and much better
 * than modifying calendar.js itself).*
 *
 * Revision history: 
 * NB20061117 	Input field separated into year-month and day fields
 *				The change is not effective for the flat calendar, only pop-up
 */

// $Id: calendar-setup.js,v 1.25 2005/03/07 09:51:33 mishoo Exp $

/**
 *  This function "patches" an input field (or other element) to use a calendar
 *  widget for date selection.
 *
 *  The "params" is a single object that can have the following properties:
 *
 *    prop. name   | description
 *  -------------------------------------------------------------------------------------------------
 *   inputField    | the ID of an input field to store the date (either this property must be set, or both the next two fields)
 *   inputFieldYM  | the ID of an input field to store the date (NB added)
 *   inputFieldD   | the ID of an input field to store the date (NB added)
 *   displayArea   | the ID of a DIV or other element to show the date
 *   button        | ID of a button or other element that will trigger the calendar
 *   eventName     | event that will trigger the calendar, without the "on" prefix (default: "click")
 *   ifFormat      | date format that will be stored in the input field
 *   ifFormatYM    | date format that will be stored in the input field (NB added)
 *   ifFormatD     | date format that will be stored in the input field (NB added)
 *   daFormat      | the date format that will be used to display the date in displayArea
 *   singleClick   | (true/false) wether the calendar is in single click mode or not (default: true)
 *   firstDay      | numeric: 0 to 6.  "0" means display Sunday first, "1" means display Monday first, etc.
 *   align         | alignment (default: "Br"); if you don't know what's this see the calendar documentation
 *   range         | array with 2 elements.  Default: [1900, 2999] -- the range of years available
 *   weekNumbers   | (true/false) if it's true (default) the calendar will display week numbers
 *   flat          | null or element ID; if not null the calendar will be a flat calendar having the parent with the given ID
 *   flatCallback  | function that receives a JS Date object and returns an URL to point the browser to (for flat calendar)
 *   disableFunc   | function that receives a JS Date object and should return true if that date has to be disabled in the calendar
 *   onSelect      | function that gets called when a date is selected.  You don't _have_ to supply this (the default is generally okay)
 *   onClose       | function that gets called when the calendar is closed.  [default]
 *   onUpdate      | function that gets called after the date is updated in the input field.  Receives a reference to the calendar.
 *   date          | the date that the calendar will be initially displayed to
 *   showsTime     | default: false; if true the calendar will include a time selector
 *   timeFormat    | the time format; can be "12" or "24", default is "12"
 *   electric      | if true (default) then given fields/date areas are updated for each move; otherwise they're updated only on close
 *   step          | configures the step of the years in drop-down boxes; default: 2
 *   position      | configures the calendar absolute position; default: null
 *   cache         | if "true" (but default: "false") it will reuse the same calendar object, where possible
 *   showOthers    | if "true" (but default: "false") it will show days from other months too
 *
 *  None of them is required, they all have default values.  However, if you
 *  pass none of "inputField", "displayArea" or "button" you'll get a warning
 *  saying "nothing to setup".
 */
Calendar.setup = function (params) {
	function param_default(pname, def) { if (typeof params[pname] == "undefined") { params[pname] = def; } };

	param_default("inputField",     null);
	param_default("inputFieldYM",   null);	//NB added
	param_default("inputFieldD",    null);	//NB added
	param_default("displayArea",    null);
	param_default("button",         null);
	param_default("eventName",      "click");
	param_default("ifFormat",       "%Y/%m/%d");
	param_default("ifFormatYM",     "%Y/%m");	//NB added
	param_default("ifFormatD",      "%d");		//NB added
	param_default("daFormat",       "%Y/%m/%d");
	param_default("singleClick",    true);
	param_default("disableFunc",    null);
	param_default("dateStatusFunc", params["disableFunc"]);	// takes precedence if both are defined
	param_default("dateText",       null);
	param_default("firstDay",       null);
	param_default("align",          "Br");
	param_default("range",          [1900, 2999]);
	param_default("weekNumbers",    true);
	param_default("flat",           null);
	param_default("flatCallback",   null);
	param_default("onSelect",       null);
	param_default("onClose",        null);
	param_default("onUpdate",       null);
	param_default("date",           null);
	param_default("showsTime",      false);
	param_default("timeFormat",     "24");
	param_default("electric",       true);
	param_default("step",           2);
	param_default("position",       null);
	param_default("cache",          false);
	param_default("showOthers",     false);
	param_default("multiple",       null);

//	var tmp = ["inputField", "displayArea", "button"];
	var tmp = ["inputField", "inputFieldYM", "inputFieldD", "displayArea", "button"]; //NB replacing line above
	for (var i in tmp) {
		if (typeof params[tmp[i]] == "string") {
			params[tmp[i]] = document.getElementById(params[tmp[i]]);
		}
	}
//	if (!(params.flat || params.multiple || params.inputField || params.displayArea || params.button)) {
	if (!(params.flat || params.multiple || params.inputField || (params.inputFieldYM && params.inputFieldD) || params.displayArea || params.button)) { //NB replacing line above
		alert("Calendar.setup:\n  Nothing to setup (no fields found).  Please check your code");
		return false;
	}

	function onSelect(cal) {
		var p = cal.params;
		var update = (cal.dateClicked || p.electric);
//		if (update && p.inputField) {									//NB replaced by code blocks below
//			p.inputField.value = cal.date.print(p.ifFormat);
//			if (typeof p.inputField.onchange == "function")
//				p.inputField.onchange();
//		}
		if (update) {
			if (p.inputField) {
				p.inputField.value = cal.date.print(p.ifFormat);
				if (typeof p.inputField.onchange == "function")
					p.inputField.onchange();
			}
			else if (p.inputFieldYM &&p.inputFieldYM) {
				p.inputFieldYM.value = cal.date.print(p.ifFormatYM);
				if (typeof p.inputFieldYM.onchange == "function")
					p.inputFieldYM.onchange();

				p.inputFieldD.value = cal.date.print(p.ifFormatD);
				if (typeof p.inputFieldD.onchange == "function")
					p.inputFieldD.onchange();
			}
		}
		if (update && p.displayArea)
			p.displayArea.innerHTML = cal.date.print(p.daFormat);
		if (update && typeof p.onUpdate == "function")
			p.onUpdate(cal);
		if (update && p.flat) {
			if (typeof p.flatCallback == "function")
				p.flatCallback(cal);
		}
		if (update && p.singleClick && cal.dateClicked)
			cal.callCloseHandler();
	};

	if (params.flat != null) {
		if (typeof params.flat == "string")
			params.flat = document.getElementById(params.flat);
		if (!params.flat) {
			alert("Calendar.setup:\n  Flat specified but can't find parent.");
			return false;
		}
		var cal = new Calendar(params.firstDay, params.date, params.onSelect || onSelect);
		cal.showsOtherMonths = params.showOthers;
		cal.showsTime = params.showsTime;
		cal.time24 = (params.timeFormat == "24");
		cal.params = params;
		cal.weekNumbers = params.weekNumbers;
		cal.setRange(params.range[0], params.range[1]);
		cal.setDateStatusHandler(params.dateStatusFunc);
		cal.getDateText = params.dateText;

		if (params.ifFormat) {
			cal.setDateFormat(params.ifFormat);
		}
		else if (params.ifFormatYM && params.ifFormatD) { //NB else added
			cal.setDateFormat(params.ifFormatYM+"-"+params.ifFormatD);
		}
		if (params.inputField && typeof params.inputField.value == "string") {
			cal.parseDate(params.inputField.value);
		}
		else if ((params.inputFieldYM && typeof params.inputFieldYM.value == "string") &&	//else added
		    	 (params.inputFieldD  && typeof params.inputFieldD.value  == "string")) {
			cal.parseDate(params.inputFieldYM.value+"-"+params.inputFieldD.value);
		}
		
		cal.create(params.flat);
		cal.show();
		return false;
	}

//	var triggerEl = params.button || params.displayArea || params.inputField;
	var triggerEl = params.button || params.displayArea || params.inputField || params.inputFieldYM || params.inputFieldD; //NB replacing line above
	triggerEl["on" + params.eventName] = function() {
	
	
		//var dateEl = params.inputField || params.displayArea; 				//NB two lines not required after change below
		//var dateFmt = params.inputField ? params.ifFormat : params.daFormat;
		if (params.inputField) //NB replacing lines above
			var dateFmt = params.ifFormat;
		else if (params.inputFieldYM && params.inputFieldD)
			var dateFmt = params.ifFormatYM+"-"+params.ifFormatD;
		else
			dateFmt = params.daFormat;

		var mustCreate = false;
		var cal = window.calendar;
//		if (dateEl) 																	//NB replaced bu block below
//			params.date = Date.parseDate(dateEl.value || dateEl.innerHTML, dateFmt);
		if (params.inputField) 
			params.date = Date.parseDate(params.inputField.value || params.inputField.innerHTML, dateFmt);
		else if (params.inputFieldYM && params.inputFieldD )			
			params.date = Date.parseDate(params.inputFieldYM.value+"-"+params.inputFieldD.value, dateFmt);

		if (!(cal && params.cache)) {
			window.calendar = cal = new Calendar(params.firstDay,
							     params.date,
							     params.onSelect || onSelect,
							     params.onClose || function(cal) { cal.hide(); });
			cal.showsTime = params.showsTime;
			cal.time24 = (params.timeFormat == "24");
			cal.weekNumbers = params.weekNumbers;
			mustCreate = true;
		} else {
			if (params.date)
				cal.setDate(params.date);
			cal.hide();
		}
		if (params.multiple) {
			cal.multiple = {};
			for (var i = params.multiple.length; --i >= 0;) {
				var d = params.multiple[i];
				var ds = d.print("%Y%m%d");
				cal.multiple[ds] = d;
			}
		}
		cal.showsOtherMonths = params.showOthers;
		cal.yearStep = params.step;
		cal.setRange(params.range[0], params.range[1]);
		cal.params = params;
		cal.setDateStatusHandler(params.dateStatusFunc);
		cal.getDateText = params.dateText;
		cal.setDateFormat(dateFmt);
		if (mustCreate)
			cal.create();
		cal.refresh();
		if (!params.position)
//			cal.showAtElement(params.button || params.displayArea || params.inputField, params.align);	//NB replaced by line below
			cal.showAtElement(params.button || params.displayArea || params.inputField|| params.inputFieldYM || params.inputFieldD, params.align); //NB added
		else
			cal.showAt(params.position[0], params.position[1]);
		return false;
	};

	return cal;
};


////////// The functions below is added by NB 20061115 when preparing the pop-up calendar //////////
/**
* Global vars
*/
var g_yearRange = [2000,2099]; //restricting year range, - no paricular reason to make this restriction
var g_specialDates;			   //array of spcial dates for the year stored in g_year	
var g_year;					   //the selected year

/**
 * This function is the only one called from HTML-code and tells the calendar what control (onClick event) 
 * that should trig the launch of the calendar. The initial alignment of the calendar is relative to this
 * control, and is defined by parameter 'alignment'. It also defines the input/output fields for year-month 
 * and day.
 */

function PopUpCalendarSetup(dm, dd, button, alignment) {
    Calendar.setup({
    	inputFieldYM   : dm,
    	inputFieldD    : dd,
    	ifFormatYM	   : "%Y-%m", //YYYY-mm
    	ifFormatD	   : "%d",	 //dd
        button         : button,
        align          : alignment,
	    range		   : g_yearRange,		//array with two elements: the first and last year of the range
 		dateStatusFunc : dateStatusHandler 	//flags a data as special (marked as holiday)
    });
}

/**
* The function is "installed" by PopUpCalendarSetup() and is called to check if a date is 
* should be flagged as special (all dates are valid, but holidays will be marked with colors as
* saturdays and sundays
*/ 
function dateStatusHandler(date, y, m, d) {
	if (dateIsSpecial(y, m, d)) {
		//alert("special date:"+d);
		return 'special';
	}
    else 
    	return false;
}

/**
* The function checks if a specific date is a holiday
*/
function dateIsSpecial(year, month, day) {
	var m;
    if (year<g_yearRange[0] || year>g_yearRange[1]) //no check on special days when outside the calendars year range
    	return false;
           
    if (year!=g_year) { 	
	    g_specialDates=setSpecialDates(year);	
	    g_year=year;
	}
    var m=g_specialDates[month];
    if (!m) return false;
    for (var i in m) if (m[i]==day) return true;
    
    return false;	
}
                    
/**
* Description of algorithm developed by Carl Friedrich Gauss (1777-1855) to find the holidays dependent on the Easter Sunday
* m=year as 4 digits
* a=m mod 19
* b=m mod 4
* c=m mod 7
* year			x	y
* 1700-1799 	23	3
* 1800-1899		23	4
* 1900-1999		24	5
* 2000-2099		24	5
* 2100-2199		24	6
* 2200-2299		25	0
* d=(19a + x) mod 30
* e=(2b+4c+6d+y) mod 7
* Easter Sunday day is the valid data of these two dates:
* f=d+e+22 of mars if 1<=f<=31
* f=d+e-9 of april if  1<=f<=30
* two exceptions must be corrected for: 
* Apr 26 -> Apr 19 if d=28 and e=6 and a>10
* Apr 25 -> Apr 18 if d=28 and e=6 and a>10
* Remarks: The earliest date for Easter Sunday is Mars 22, and the latest Apr 25
*/

/**
* The function returns the x, y parameter for a given year array used to find the Easter Sunday.<b> 
*/
function getYearParams(year) {
	var PARAM = [[23,3], [23,4], [24,5], [24,5], [24,6],[25,0]]; //parameters defined by Gauss
    if (year<1700 || 2200<year) return false;
      	return PARAM[Math.floor(year/100)-17];
}

/**
* The function returns the number of days since Mars 1 for the Easter Sunday in a given year.
* Returns false if no x, y parameters are found for the given year
*/            
function findEasterSundayAsDaysSinceMarsFirst(year) {
	var month;				//month of the Easter Sunday (starting on 0)
	var daysSinceMarsFirst; //Easter Sunday as days since Mars 1
   	var yearParams=getYearParams(year);
   	if (!yearParams) return false;
   	var a=year%19;
   	var b=year%4;
   	var c=year%7;
   	var d=(19*a+yearParams[0])%(30);
   	var e=(2*b+4*c+6*d+yearParams[1])%7;
   	var f=d+e+22; //date in Mars
   	if (1>=f<=31) { //checking if day f is a valid day within Mars				
		month=2;	//Mars
    	daysSinceMarsFirst=f;
    }
    else {
    	month=3;	//April
        f=d+e-9; 	//date in April
       //exceptions only for April
        if ((e==6)&&(a>10)) {
			if (d==26) d=19; else {if (d==25) d=18};
		}
		daysSinceMarsFirst=31+f;
	}
	return daysSinceMarsFirst
}

/**
* The function returns the 2-dim array specialDays containing these days:
* New Years Day (Jan 1)
* Maunday Thursday 
* Good Friday
* Easter Monday
* Ascension Day
* Wit Monday
* Labour Day (May 1)
* National Day (May 17)
* Christmas Day
* Boxing Day
*/
function setSpecialDates(year) {
	var specialDays=new Array();
	var m;
	specialDays[0]=new Array();		//Jan 
	specialDays[0][specialDays[0].length]=1;	//New Years Day
	specialDays[2]=new Array(); 	//Mars
	specialDays[3]=new Array(); 	//Apr
	specialDays[4]=new Array(); 	//May
	specialDays[4][specialDays[4].length]=1;	//Labour Day 
	specialDays[4][specialDays[4].length]=17;	//National Day 
	specialDays[5]=new Array(); 	//Jun
	specialDays[11]=new Array(); 	//Dec
	specialDays[11][specialDays[11].length]=25;	//Christmas Day 
	specialDays[11][specialDays[11].length]=26;	//Boxing Day 
	//Easter Holdiday and dependent Holidays
	var e=findEasterSundayAsDaysSinceMarsFirst(year);
	d=e-3;
	m=2+Math.floor(d/31); //month
	specialDays[m][specialDays[m].length]=d%31; //Maunday Thursday
	d++;
	m=2+Math.floor(d/31);
	specialDays[m][specialDays[m].length]=d%31; //Good Friday
	d+=3;
	m=2+Math.floor(d/31);
	specialDays[m][specialDays[m].length]=d%31; //Easter Monday
	//Ascension day (39 days after Easter Sunday)      	
	d=e+39;
	//finding month for Ascension day
	if (Math.floor(d/92)) 		//checking if is in June
		specialDays[5][specialDays[5].length]=Math.floor(d%92); 
	else if (Math.floor(d/61)) 	//checking if is in May
		specialDays[4][specialDays[4].length]=Math.floor(d%61); 
	else if (Math.floor(d/31)) 	//checking if is in April
		specialDays[3][specialDays[3].length]=Math.floor(d%31); 
	//Wit Monday (50 days after Easter Sunday)      	
	d=e+50;
	//finding month for Wit Monday
	if (Math.floor(d/92)) 		//checking if is in June
		specialDays[5][specialDays[5].length]=Math.floor(d%92); 
	else if (Math.floor(d/61)) 	//checking if is in May
		specialDays[4][specialDays[4].length]=Math.floor(d%61); 
		
	return specialDays;
}


            
