// Usage : Veuillez entrez une date : <input name="date"  onclick="displayCalendar(this);" readonly="readonly" style="cursor: text" />
// ajouter <script type="text/javascript" src="/communsGen/js/formCalendar.js"></script>

// Project: Dynamic Date Selector (DtTvB) - 2006-03-16
// Script featured on JavaScript Kit- http://www.javascriptkit.com
// Code begin...
// Set the initial date.

// Output Element

// Container
//var ds_ce = ds_getel('ds_conclass');

// A function to show the calendar.
// When user click on the date, it will set the content of t.
function displayCalendar(t , options ) {
	// Get Element By Id
	this.ds_getel=function(id) {
		return document.getElementById(id);
	}
	// Get the left and the top of the element.
	this.ds_getleft=function(el) {
		var tmp = el.offsetLeft;
		el = el.offsetParent
		while(el) {
			tmp += el.offsetLeft;
			el = el.offsetParent;
		}
		return tmp;
	}
	this.ds_gettop=function(el) {
		var tmp = el.offsetTop;
		el = el.offsetParent
		while(el) {
			tmp += el.offsetTop;
			el = el.offsetParent;
		}
		return tmp;
	}	
	this.ds_ob_clean=function() {
		this.ds_ob = '';
	}
	this.ds_ob_flush=function() {
		var ds_oe = this.ds_getel('ds_calclass');
		ds_oe.innerHTML = this.ds_ob;
		this.ds_ob_clean();
	}
	this.ds_echo=function(t) {
		this.ds_ob += t;
	}

	// Calendar template
	this.ds_template_main_above=function (t) {
		return '<table class="ds_tbl">'
		     + '<tr>'
			 + '<td class="ds_head" style="cursor: pointer" onclick="ds_py();">&lt;&lt;</td>'
			 + '<td class="ds_head" style="cursor: pointer" onclick="ds_pm();">&lt;</td>'
			 + '<td class="ds_head" style="cursor: pointer" onclick="ds_hi();" colspan="3">['+ ds_closewin +']</td>'
			 + '<td class="ds_head" style="cursor: pointer" onclick="ds_nm();">&gt;</td>'
			 + '<td class="ds_head" style="cursor: pointer" onclick="ds_ny();">&gt;&gt;</td>'
			 + '</tr>'
		     + '<tr>'
			 + '<td colspan="7" class="ds_head">' + t + '</td>'
			 + '</tr>'
			 + '<tr>';
	}
	
	this.ds_template_day_row=function(t) {
		return '<td class="ds_subhead">' + t + '</td>';
		// Define width in CSS, XHTML 1.0 Strict doesn't have width property for it.
	}
	
	this.ds_template_new_week=function() {
		return '</tr><tr>';
	}
	
	this.ds_template_blank_cell=function(colspan) {
		return '<td colspan="' + colspan + '"></td>'
	}
	
	this.ds_template_day=function(d, m, y) {
		var today = new Date();
		var todayCell=((today.getDate()===d && (today.getMonth()+1)===m &&  today.getFullYear()===y )?"ds_cellToday":"ds_cell")
		
		var todayCell=((this.ds_currentDateInField.getDate()===d && (this.ds_currentDateInField.getMonth()+1)===m &&  this.ds_currentDateInField.getFullYear()===y )?"ds_cellSelected":todayCell)
		
	
		return '<td class="'+ todayCell +'" ><a onclick="ds_onclick(' + d + ',' + m + ',' + y + ')">' + d + '</a></td>';
		// Define width the day row.
	}
	
	this.ds_template_main_below=function() {
		return '</tr>'
		     + '</table>';
	}
	
	// This one draws calendar...
	this.ds_draw_calendar=function(m, y) {
		// First clean the output buffer.
		this.ds_ob_clean();
		// Here we go, do the header
		this.ds_echo (this.ds_template_main_above(ds_monthnames[m - 1] + ' ' + y));
		for (i = 0; i < 7; i ++) {
			this.ds_echo (this.ds_template_day_row(ds_daynames[i]));
		}
		// Make a date object.
		var ds_dc_date = new Date();
		ds_dc_date.setDate(1);
		ds_dc_date.setMonth(m - 1);
		ds_dc_date.setFullYear(y);
		
		if (m == 1 || m == 3 || m == 5 || m == 7 || m == 8 || m == 10 || m == 12) {
			days = 31;
		} else if (m == 4 || m == 6 || m == 9 || m == 11) {
			days = 30;
		} else {
			days = (y % 4 == 0) ? 29 : 28;
		}
		var first_day = ds_dc_date.getDay();
		var first_loop = 1;
		// Start the first week
		this.ds_echo (this.ds_template_new_week());
		// If sunday is not the first day of the month, make a blank cell...
		if (first_day != 0) {
			this.ds_echo (this.ds_template_blank_cell(first_day));
			
		}
		//alert("first_day="+ ds_dc_date.getDay() + " m="+ (m-1) +" ds_dc_date="+ds_dc_date)
		var j = first_day;
		for (i = 0; i < days; i ++) {
			// Today is sunday, make a new week.
			// If this sunday is the first day of the month,
			// we've made a new row for you already.
			if (j == 0 && !first_loop) {
				// New week!!
				this.ds_echo (this.ds_template_new_week());
			}
			// Make a row of that day!
			this.ds_echo (this.ds_template_day(i + 1, m, y));
			// This is not first loop anymore...
			first_loop = 0;
			// What is the next day?
			j ++;
			j %= 7;
		}
		// Do the footer
		this.ds_echo (this.ds_template_main_below());
		// And let's display..
		this.ds_ob_flush();
		// Scroll it into view.
		//this.ds_ce.scrollIntoView();
	}


	
	// Hide the calendar.
	this.ds_hi=function () {
		this.ds_ce.style.display = 'none';
	}
	
	// Moves to the next month...
	this.ds_nm=function() {
		// Increase the current month.
		this.ds_c_month ++;
		// We have passed December, let's go to the next year.
		// Increase the current year, and set the current month to January.
		if (this.ds_c_month > 12) {
			this.ds_c_month = 1; 
			this.ds_c_year++;
		}
		// Redraw the calendar.
		this.ds_draw_calendar(this.ds_c_month, this.ds_c_year);
	}
	
	// Moves to the previous month...
	this.ds_pm=function() {
		this.ds_c_month = this.ds_c_month - 1; // Can't use dash-dash here, it will make the page invalid.
		// We have passed January, let's go back to the previous year.
		// Decrease the current year, and set the current month to December.
		if (this.ds_c_month < 1) {
			this.ds_c_month = 12; 
			this.ds_c_year = this.ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
		}
		// Redraw the calendar.
		this.ds_draw_calendar(this.ds_c_month, this.ds_c_year);
	}
	
	// Moves to the next year...
	this.ds_ny=function() {
		// Increase the current year.
		this.ds_c_year++;
		// Redraw the calendar.
		this.ds_draw_calendar(this.ds_c_month, this.ds_c_year);
	}
	
	// Moves to the previous year...
	this.ds_py=function() {
		// Decrease the current year.
		this.ds_c_year = this.ds_c_year - 1; // Can't use dash-dash here, it will make the page invalid.
		// Redraw the calendar.
		this.ds_draw_calendar(this.ds_c_month, this.ds_c_year);
	}
	
	// Format the date to output.
	this.ds_format_date=function(d, m, y) {
		// 2 digits month.
		m2 = '00' + m;
		m2 = m2.substr(m2.length - 2);
		// 2 digits day.
		d2 = '00' + d;
		d2 = d2.substr(d2.length - 2);
		// YYYY-MM-DD
	//	return y + '-' + m2 + '-' + d2;
		return d2 + '/' + m2 + '/' + y;
	}
	
	// When the user clicks the day.
	this.ds_onclick=function(d, m, y) {
		// Hide the calendar.
		this.ds_hi();
		// Set the value of it, if we can.
		if (typeof(this.ds_element.value) != 'undefined') {
			this.ds_element.value = this.ds_format_date(d, m, y);
		// Maybe we want to set the HTML in it.
		} else if (typeof(this.ds_element.innerHTML) != 'undefined') {
			this.ds_element.innerHTML = this.ds_format_date(d, m, y);
		// I don't know how should we display it, just alert it to user.
		} else {
			alert (this.ds_format_date(d, m, y));
		}
		if(typeof(this.callBackFunction) !='undefined'){
			this.callBackFunction()
		}
	}
	
	
	

	this.cssFile= "/communsGen/js/formCalendar.css"
	if(typeof options != 'undefined') { this.options = options; } else { this.options = {}; }
	if(this.options && this.options.callBackFunction) { this.callBackFunction = this.options.callBackFunction; }
	if(this.options && this.options.cssFile) { this.cssFile = this.options.cssFile; }
	
	this.langue='fr'
	if(this.options && this.options.langue) { this.langue = this.options.langue; }
	
	
	
	//ajouter l'équivalent de : <link rel='stylesheet' href='/communsGen/js/formCalendar.css' type='text/css'/>
	var fileref=document.createElement("link")
	fileref.setAttribute("rel", "stylesheet")
	fileref.setAttribute("type", "text/css")
	fileref.setAttribute("href", this.cssFile )
	document.getElementsByTagName("head")[0].appendChild(fileref)

	
	if (!document.getElementById("ds_conclass")){
		//ajouter l'équivalent de <div class='ds_box' id='ds_conclass' style='display: none;'><div id='ds_calclass'></div></div>
		var div1=document.createElement("div")
		div1.setAttribute("class", "ds_box")
		div1.setAttribute("id", "ds_conclass")
		div1.setAttribute("style", "display:none;position:absolute;" )
		
			var div2=document.createElement("div")
			div2.setAttribute("id", "ds_calclass")
			div1.appendChild(div2)
		document.getElementsByTagName("body")[0].insertBefore(div1, document.getElementsByTagName("body")[0].firstChild );
		/* on ajoute les styles en javascript pour IE */
		this.ds_getel('ds_conclass').style.display="none";
		this.ds_getel('ds_conclass').style.position="absolute";
	}
	// Output Buffering
	this.ds_ob = ''; 
	
	
	if (this.langue.toLowerCase()=='us' || this.langue.toLowerCase()=='gb' ){
		var ds_monthnames = [
		'January', 'February', 'March', 'April', 'May', 'June',
		'July', 'August', 'September', 'October', 'November', 'December'
		]; // You can translate it for your language.
		var ds_daynames = [
		'Sun', 'Mon', 'Tue', 'Wen', 'Thi', 'Fri', 'Sat'
		]; // You can translate it for your language.
		var ds_closewin = "Close";
	}else{
	
		var ds_monthnames = [
		'Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin',
		'Juillet', 'Aout', 'Septembre', 'Octobre', 'Novembre', 'Décembre'
		]; // You can translate it for your language.
		var ds_daynames = [
		'Dim', 'Lun', 'Mar', 'Me', 'Jeu', 'Ven', 'Sam'
		]; // You can translate it for your language.
		var ds_closewin = "Fermer";	
	}
	this.ds_ce = this.ds_getel('ds_conclass');
	// Set the element to set...
	this.ds_element = t;
	// Make a new date, and set the current month and year.
	var ds_sh_date = new Date();
	
	if(t.value!="" && t.value.split("/").length==3 ){
		var tempoDate=t.value.split("/")
		//ds_sh_date.setDate( parseInt(tempoDate[0]) );
		//ds_sh_date.setMonth( parseInt(tempoDate[1]) - 1);
		//ds_sh_date.setFullYear( parseInt(tempoDate[2]) );
		ds_sh_date.setDate( tempoDate[0] );
		ds_sh_date.setMonth(tempoDate[1] - 1);
		ds_sh_date.setFullYear( tempoDate[2] );
		
	}
	this.ds_c_month = ds_sh_date.getMonth() + 1;
	this.ds_c_year = ds_sh_date.getFullYear();
	this.ds_currentDateInField=ds_sh_date;

	if(this.ds_ce.style.display != 'none'){
		//alert("ddd="+ this.ds_ce.style.display)
		this.ds_hi()
	}else{

		// Draw the calendar
		this.ds_draw_calendar(this.ds_c_month, this.ds_c_year);
		// To change the position properly, we must show it first.
		this.ds_ce.style.display = '';
		// Move the calendar container!
		the_left = this.ds_getleft(t);
		the_top = this.ds_gettop(t) + t.offsetHeight;
		this.ds_ce.style.left = the_left + 'px';
		this.ds_ce.style.top = the_top + 'px';
		// Scroll it into view.
		//this.ds_ce.scrollIntoView();
	}
}
// And here is the end.
//document.write ("<link rel='stylesheet' href='/communsGen/js/formCalendar.css' type='text/css'/>")
//document.write ("<div class='ds_box' id='ds_conclass' style='display: none;'><div id='ds_calclass'></div></div>")
Date.prototype.Add = function(strInterval, intIncrement)
    {
    	/*
    	Usage
    	var mydate = new Date('6/20/2008');
    	alert(mydate.Add("D", 10));
    	*/
    	
        if(
        strInterval != "M"
        && strInterval != "D"
        && strInterval != "Y"
        && strInterval != "h"
        && strInterval != "m"
        && strInterval != "uM"
        && strInterval != "uD"
        && strInterval != "uY"
        && strInterval != "uh"
        && strInterval != "um"
        && strInterval != "us"
        )
        {
            throw("DateAdd: Second parameter must be M, D, Y, h, m, uM, uD, uY, uh, um or us");
        }
 
        if(typeof(intIncrement) != "number")
        {
            throw("DateAdd: Third parameter must be a number");
        }
 
        switch(strInterval)
        {
            case "M":
            this.setMonth(parseInt(this.getMonth()) + parseInt(intIncrement));
            break;
 
            case "D":
            this.setDate(parseInt(this.getDate()) + parseInt(intIncrement));
            break;
 
            case "Y":
            this.setYear(parseInt(this.getFullYear()) + parseInt(intIncrement));
            break;
 
            case "h":
            this.setHours(parseInt(this.getHours()) + parseInt(intIncrement));
            break;
 
            case "m":
            this.setMinutes(parseInt(this.getMinutes()) + parseInt(intIncrement));
            break;
 
            case "s":
            this.setSeconds(parseInt(this.getSeconds()) + parseInt(intIncrement));
            break;
 
            case "uM":
            this.setUTCMonth(parseInt(this.getUTCMonth()) + parseInt(intIncrement));
            break;
 
            case "uD":
            this.setUTCDate(parseInt(this.getUTCDate()) + parseInt(intIncrement));
            break;
 
            case "uY":
            this.setUTCFullYear(parseInt(this.getUTCFullYear()) + parseInt(intIncrement));
            break;
 
            case "uh":
            this.setUTCHours(parseInt(this.getUTCHours()) + parseInt(intIncrement));
            break;
 
            case "um":
            this.setUTCMinutes(parseInt(this.getUTCMinutes()) + parseInt(intIncrement));
            break;
 
            case "us":
            this.setUTCSeconds(parseInt(this.getUTCSeconds()) + parseInt(intIncrement));
            break;
        }
        return this;
    }


function testDate(dateStr){
	if (dateStr+""!=""){
		var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/; 
		var matchArray = dateStr.match(datePat);    
		if (matchArray == null) {  alert("La date n'est pas d'un format valide (JJ/MM/AAAA).");     return false;      } 
		month = matchArray[3]; 
		day = matchArray[1]; 
		year = matchArray[4]; 
		if (month < 1 || month > 12) {   alert("Le mois doit etre entre 1 et 12.");           return false;            }
		if (day < 1 || day > 31) {  alert("Le jour doit etre entre 1 et 31.");             return false;              }
		if ((month==4 || month==6 || month==9 || month==11) && day==31)
			{  alert("Le mois de "+month+" n\'a pas 31 jours!"); return false  }  
		if (month == 2) {   var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)); if (day>29 || (day==29 && !isleap)) {  alert("Fevrier " + year + " n\'a pas " + day + " jours!"); return false; }  }
	}
	return true;
}
