
var day;
var month;
var year;
var hour;
var minute;
var second;
var clock_set = 0;



/**
 * Formats number to two digits.
 *
 * @param   int number to format.
 */
function formatNum2(i, valtype) {
    f = (i < 10 ? '0' : '') + i;
    if (valtype && valtype != '') {
        switch(valtype) {
            case 'month':
                f = (f > 12 ? 12 : f);
                break;

            case 'day':
                f = (f > 31 ? 31 : f);
                break;

            case 'hour':
                f = (f > 24 ? 24 : f);
                break;

            default:
            case 'second':
            case 'minute':
                f = (f > 59 ? 59 : f);
                break;
        }
    }

    return f;
}

/**
 * Formats number to four digits.
 *
 * @param   int number to format.
 */
function formatNum4(i) {
    return (i < 1000 ? i < 100 ? i < 10 ? '000' : '00' : '0' : '') + i;
}


/**
 * Initializes and Opens calendar window.
 *
 * @div_area   string      id du div qui reçoit le calendrier
 * @param   string      form name
 * @param   string      field name
 * @param   string      edit type - date/timestamp
 */
function initCalendar(div_area, form, field, type) {
	cache(div_area);
	if (document.getElementById) {
		cnt = document.getElementById(div_area);
	} else if (document.all) {
		cnt = document.all[div_area];
	}

///////////////// Traitement des données de date ////////////////
	dateField = eval("document." + form + "." + field);
	dateType = type;
	if (!year && !month && !day) {
		/* Called for first time */
		if (dateField.value) {
			value = dateField.value;
			if (dateType == 'datetime' || dateType == 'date') {
				if (dateType == 'datetime') {
					parts   = value.split(' ');
					value   = parts[0];

					if (parts[1]) {
						time		= parts[1].split(':');
						hour		= parseInt(time[0],10);
						minute	= parseInt(time[1],10);
						second	= parseInt(time[2],10);
					}//end if (parts[1])
				}//end if (ddateType == 'datetime')
				date	= value.split("-");
				day	= parseInt(date[2],10);
				month	= parseInt(date[1],10) - 1;
				year	= parseInt(date[0],10);
			} else if (dateType == 'date_fra') {
				day	= parseInt(value.substr(0,2),10);
				month	= parseInt(value.substr(3,2),10) - 1;
				year	= parseInt(value.substr(6,4),10);
			} else {
				year        = parseInt(value.substr(0,4),10);
				month       = parseInt(value.substr(4,2),10) - 1;
				day         = parseInt(value.substr(6,2),10);
				hour        = parseInt(value.substr(8,2),10);
				minute      = parseInt(value.substr(10,2),10);
				second      = parseInt(value.substr(12,2),10);
			}//end if (dateType == 'datetime' || dateType == 'date')
		}//end if (dateField.value)
		if (isNaN(year) || isNaN(month) || isNaN(day) || day == 0) {
			dt      = new Date();
			year    = dt.getFullYear();
			month   = dt.getMonth();
			day     = dt.getDate();
		}
		if (isNaN(hour) || isNaN(minute) || isNaN(second)) {
			dt      = new Date();
			hour    = dt.getHours();
			minute  = dt.getMinutes();
			second  = dt.getSeconds();
		}
	} else {//if (!year && !month && !day)
		/* Moving in calendar */
		if (month > 11) {
			month = 0;
			year++;
		}
		if (month < 0) {
			month = 11;
			year--;
		}
	}//end if (!year && !month && !day)
///////////////////////////fin du traitement des données de date////////////////


///////// Construction du premier tableau /////////////////
	var tbl = document.createElement("table");
	var tblBody = document.createElement("tbody");
	var tblRow = document.createElement("tr");
	var tblTh = document.createElement("th");
	tbl.setAttribute("class", "calendar");
	//patch pour la compatiblité avec ie
	tbl.setAttribute("className", "calendar");

//Création de la navigation par mois
	var texte = document.createTextNode("«");
	tA = document.createElement("a");
	tA.href = "javascript:month--; initCalendar(\'"+div_area+"\', \'"+form+"\', \'"+field+"\', \'"+type+"\');";
	tA.appendChild(texte);
	texte = document.createTextNode("\u00a0");
	tA.appendChild(texte);
	tblTh.appendChild(tA);
	tbl.width = "214px";

	var tblSelect = document.createElement("select");
	tblSelect.setAttribute('id', 'select_month');
	tblSelect.setAttribute('name', 'monthsel');
//	tblSelect.setAttribute("onchange", "month =  parseInt(document.getElementById('select_month').value) ;  initCalendar(\'"+div_area+"\', \'"+form+"\', \'"+field+"\', \'"+type+"\');");
/***    Patch pour IE qui gère mal le setAttribute   ****/
	tblSelect.onchange = function(){month=parseInt(document.getElementById('select_month').value); initCalendar(div_area, form, field, type);};

	for (i =0; i < 12; i++) {
		var selOption = document.createElement("option");
		selOption.setAttribute("value", "" + i + "");
		if (i == month) selOption.setAttribute("selected","selected");
		texte = document.createTextNode(month_names[i]);
		selOption.appendChild(texte);
		tblSelect.appendChild(selOption);
	}
	tblTh.appendChild(tblSelect);
/* //Ecriture du mois en tant que texte simple (si non utilisation du select)
	var tblMois = document.createElement("input");
	tblMois.type = 'hidden';
	tblMois.setAttribute('id', 'select_month');
	tblMois.setAttribute('name', 'monthsel');
	tblMois.setAttribute('value', month);
	texte = document.createTextNode(month_names[month]);
	tblTh.appendChild(tblMois);
	tblTh.appendChild(texte);
//*/


	texte = document.createTextNode("\u00a0");
	tblTh.appendChild(texte);
	texte = document.createTextNode("»");
	tA = document.createElement("a");
	tA.href = "javascript:month++; initCalendar(\'"+div_area+"\', \'"+form+"\', \'"+field+"\', \'"+type+"\');";
	tA.appendChild(texte);
	tblTh.appendChild(tA);
	tblRow.appendChild(tblTh);

//Création de la navigation par année
	var tblTh = document.createElement("th");
	var texte = document.createTextNode("«");
	tA = document.createElement("a");
	tA.href = "javascript:year--; initCalendar(\'"+div_area+"\', \'"+form+"\', \'"+field+"\', \'"+type+"\');";
	tA.appendChild(texte);
	tblTh.appendChild(tA);
	texte = document.createTextNode("\u00a0");
	tblTh.appendChild(texte);
/*
	var tblSelect = document.createElement("select");
	tblSelect.setAttribute('id', 'select_year');
	tblSelect.setAttribute('name', 'yearsel');
	tblSelect.setAttribute("onchange", "year =  parseInt(document.getElementById('select_year').value) ;  initCalendar(\'"+div_area+"\', \'"+form+"\', \'"+field+"\', \'"+type+"\');");
	for (i = year - 2; i < year + 5; i++) {
		var selOption = document.createElement("option");
		selOption.setAttribute("value", "" + i + "");
		if (i == year) selOption.setAttribute("selected","selected");
		texte = document.createTextNode(i);
		selOption.appendChild(texte);
		tblSelect.appendChild(selOption);
	}
	tblTh.appendChild(tblSelect);
*/
	var tblAnnee = document.createElement("input");
	tblAnnee.type = 'hidden';
	tblAnnee.setAttribute('id', 'select_year');
	tblAnnee.setAttribute('name', 'monthsel');
	tblAnnee.setAttribute('value', year);
	texte = document.createTextNode(year);
	tblTh.appendChild(tblAnnee);
	tblTh.appendChild(texte);

	texte = document.createTextNode("\u00a0");
	tblTh.appendChild(texte);
	texte = document.createTextNode("»");
	tA = document.createElement("a");
	tA.href = "javascript:year++; initCalendar(\'"+div_area+"\', \'"+form+"\', \'"+field+"\', \'"+type+"\');";
	tA.appendChild(texte);
	tblTh.appendChild(tA);
	tblRow.appendChild(tblTh);

//Création du bouton de fermeture
	var tblTh = document.createElement("th");
	tblTh.setAttribute("class", "Xcal");
	tblTh.setAttribute("className", "Xcal");
	var tA = document.createElement("a");
	tA.setAttribute("class", "Xcal");
	tA.setAttribute("className", "Xcal");
	tA.href = "javascript:cache(\'" + div_area + "\');";
	texte = document.createTextNode("X");
	tA.appendChild(texte);
	tblTh.appendChild(tA);
	tblRow.appendChild(tblTh);

//	tblRow.appendChild(tform);
	tblBody.appendChild(tblRow);
	tbl.appendChild(tblBody);
///////// fin du premier tableau /////////////////

	cnt.appendChild(tbl);

///////// Construction du deuxième tableau /////////////////
	var tbl = document.createElement("table");
	tbl.setAttribute("class", "calendar");
	tbl.setAttribute("className", "calendar");
	var tblHead = document.createElement("thead");
	var tblBody = document.createElement("tbody");
	var tblRow = document.createElement("tr");
	var tblCell = document.createElement("td");
	tbl.width = "214px";

//En-tête
	for (i = 0; i < 7; i++) {
		var tblTh = document.createElement("th");
		var texte = document.createTextNode(day_names[i]);
		tblTh.appendChild(texte);
		tblRow.appendChild(tblTh);
	}
	tblHead.appendChild(tblRow);
	tbl.appendChild(tblHead);

//Corps du calendrier
	var tblRow = document.createElement("tr");
	var firstDay = new Date(year, month, 1).getDay();
	var lastDay = new Date(year, month + 1, 0).getDate();
	dayInWeek = 0;
	//cellules hors calendrier
	for (i = 0; i < firstDay; i++) {
		var tblCell = document.createElement("td");
		tblRow.appendChild(tblCell);
		dayInWeek++;
	}
	//Fin de la colonne
	for (i = 1; i <= lastDay; i++) {
		if (dayInWeek == 7) {
			tblBody.appendChild(tblRow);
			tblRow = document.createElement("tr");
			dayInWeek = 0;
		}

		dispmonth = 1 + month;

		if (dateType == 'datetime' || dateType == 'date') {
			actVal = formatNum4(year) + "-" + formatNum2(dispmonth, 'month') + "-" + formatNum2(i, 'day');
		} else if(dateType == 'date_fra') {
			actVal = formatNum2(i, 'day') + "/" + formatNum2(dispmonth, 'month') + "/" + formatNum4(year);
		} else {
			actVal = "" + formatNum4(year) + formatNum2(dispmonth, 'month') + formatNum2(i, 'day');
		}

		//Jours du calendrier
		var tblCell = document.createElement("td");
		var tA = document.createElement("a");
		tA.href = "javascript:returnDate('" + actVal + "', '" + div_area + "');";
		var texte = document.createTextNode(i);
		tA.appendChild(texte);
		tblCell.appendChild(tA);
		if (i == day){
			tblCell.setAttribute("class", "selected");
			tblCell.setAttribute("className", "selected");
		}
		tblRow.appendChild(tblCell);
		dayInWeek++;
	}
	for (i = dayInWeek; i < 7; i++) {
		var tblCell = document.createElement("td");
		tblRow.appendChild(tblCell);
	}

	tblBody.appendChild(tblRow);
	tbl.appendChild(tblBody);
	cnt.appendChild(tbl);

	//Fonction cachant les select dans le périmètre du div - pour IE
	fSwapSelect(div_area);
}

/**
 * Returns date from calendar.
 *
 * @param   string     date text
 */
function returnDate(d, divarea) {
	txt = d;
	if (dateType != 'date' && dateType != 'date_fra') {
		// need to get time
		h = parseInt(document.getElementById('hour').value,10);
		m = parseInt(document.getElementById('minute').value,10);
		s = parseInt(document.getElementById('second').value,10);
		if (dateType == 'datetime') {
			txt += ' ' + formatNum2(h, 'hour') + ':' + formatNum2(m, 'minute') + ':' + formatNum2(s, 'second');
		} else {
			// timestamp
			txt += formatNum2(h, 'hour') + formatNum2(m, 'minute') + formatNum2(s, 'second');
		}
	}
	//Mémorise le jour
	if (dateType == 'date_fra') {
		day = parseInt(txt.substr(0,2),10);
	}else{
		day = parseInt(txt.substr(6,2),10);
	}

	dateField.value = txt;
	cache(divarea);
}




function cache(id) {
	  if (document.getElementById) {
//		  document.getElementById(id).style.visibility="hidden";
		  document.getElementById(id).innerHTML="";
		} else if (document.all) {
		  document.all[id].innerHTML="";
		} else if (document.layers) {
		  document.layers[id].innerHTML="";
		}

	fSwapSelect(id);
}

/* Renvoie par défaut la date courante
* Utilisé par recherche.php pour FMA, sollicité par "Aujourd'hui"
*/
function valjour(){
  dat = new Date();
  mois = dat.getMonth() + 1;
  jour = dat.getDate() + "/" + mois + "/" + dat.getFullYear();
  document.form1.dat_debut_ouvac.value = jour;
  document.form1.dat_fin_ouvac.value = jour;
}
