/**
option :
	selectyear : true ou false : affiche le menu de selection de la date
	yearstart : annee de depart du menu : ex : 2012
	yearecart : nombre d'annee au total/2 : ex : 10    //afficher de 2002 à 2022
	btSpeed		: true ou false, affiche les bouton avance rapide
*/
var GbdatePickeropened=0;
var GbdatePickerVerrouille=0;
var GdateFieldName='';
var datePickerDivID = "datepicker";
var iFrameDivID = "datepickeriframe";
var GaOptionsDatePicker=new Array();

var dayArrayShort = new Array('Di', 'Lu', 'Ma', 'Me', 'Je', 'Ve', 'Sa');
var dayArrayMed = new Array('Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat');
var dayArrayLong = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
var monthArrayShort = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');
var monthArrayMed = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec');
var monthArrayLong = new Array('Janvier', 'Février', 'Mars', 'Avril', 'Mai', 'Juin', 'Juillet', 'Août', 'Septembre', 'Octobre', 'Novembre', 'Décembre');
 
// these variables define the date formatting we're expecting and outputting.
// If you want to use a different format by default, change the defaultDateSeparator
// and defaultDateFormat variables either here or on your HTML page.
var defaultDateSeparator = "/";        // common values would be "/" or "."
   // valid values are "mdy", "dmy", and "ymd"
var dateSeparator = defaultDateSeparator;
var dateFormat = defaultDateFormat;


var CorrectAttach;
/**
This is the main function you'll call from the onClick event of a button.
Normally, you'll have something like this on your HTML page:

Start Date: <input name="StartDate">
<input type=button value="select" onclick="displayDatePicker('StartDate');">

That will cause the datepicker to be displayed beneath the StartDate field and
any date that is chosen will update the value of that field. If you'd rather have the
datepicker display beneath the button that was clicked, you can code the button
like this:

<input type=button value="select" onclick="displayDatePicker('StartDate', this);">

So, pretty much, the first argument (dateFieldName) is a string representing the
name of the field that will be modified if the user picks a date, and the second
argument (displayBelowThisObject) is optional and represents an actual node
on the HTML document that the datepicker should be displayed below.

In version 1.1 of this code, the dtFormat and dtSep variables were added, allowing
you to use a specific date format or date separator for a given call to this function.
Normally, you'll just want to set these defaults globally with the defaultDateSeparator
and defaultDateFormat variables, but it doesn't hurt anything to add them as optional
parameters here. An example of use is:

<input type=button value="select" onclick="displayDatePicker('StartDate', false, 'dmy', '.');">

This would display the datepicker beneath the StartDate field (because the
displayBelowThisObject parameter was false), and update the StartDate field with
the chosen value of the datepicker using a date format of dd.mm.yyyy
*/
function displayDatePicker(dateFieldName, displayBelowThisObject, dtFormat, dtSep, option)
{
	
	
if(GbdatePickeropened){
	updateDateField(GdateFieldName);
}
if(!GbdatePickeropened){
	GdateFieldName=dateFieldName;
	if(!option){
		GaOptionsDatePicker=new Array();
	}else{
		GaOptionsDatePicker=option;
	}
	
  var targetDateField = document.getElementsByName (dateFieldName).item(0);
  GbdatePickeropened=1;
 
  // if we weren't told what node to display the datepicker beneath, just display it
  // beneath the date field we're updating
  //if (!displayBelowThisObject)
    displayBelowThisObject = targetDateField;
 
  // if a date separator character was given, update the dateSeparator variable
  if (dtSep)
    dateSeparator = dtSep;
  else
    dateSeparator = defaultDateSeparator;
 
  // if a date format was given, update the dateFormat variable
  if (dtFormat)
    dateFormat = dtFormat;
  else
    dateFormat = defaultDateFormat;
	
 	var x = 0;//displayBelowThisObject.offsetLeft + displayBelowThisObject.offsetWidth;
  	var y =0;//displayBelowThisObject.offsetTop + displayBelowThisObject.offsetHeight ;
 
 
 
  // deal with elements inside tables and such
  CorrectAttach = displayBelowThisObject.offsetParent;
  
   
  var parent = displayBelowThisObject;
/*  while (parent.offsetParent) {
    parent = parent.offsetParent;
    x += parent.offsetLeft;
    y += parent.offsetTop ;
  }
  x=x-160;*/
  //
 // y = displayBelowThisObject.getBoundingClientRect().top;
 // x = displayBelowThisObject.getBoundingClientRect().left;
  //alert(x);

  drawDatePicker(targetDateField, x, y);
}
}


/**
Draw the datepicker object (which is just a table with calendar elements) at the
specified x and y coordinates, using the targetDateField object as the input tag
that will ultimately be populated with a date.

This function will normally be called by the displayDatePicker function.
*/
//addLoadEvent(initMouseMove);
function initMouseMove(){
	// document.onmousemove = mouseMove;
	
}
GnXMouse=0;
GnYMouse=0;
function mouseMove(e){
	  var _x=0;
	  var _y=0;
  
  
      if(e == undefined)
        e = event;

    if( e.pageX != undefined){ // gecko, konqueror,
        _x = e.pageX;
        _y = e.pageY;
    }else if(event != undefined && event.x != undefined && event.clientX == undefined){ // ie4 ?
        _x = event.x;
        _y = event.y;
    }else if(e.clientX != undefined ){ // IE6,  IE7, IE5.5
        if(document.documentElement){
           _x = e.clientX + ( document.documentElement.scrollLeft || document.body.scrollLeft);
            _y = e.clientY + ( document.documentElement.scrollTop || document.body.scrollTop);
        }else{
            _x = e.clientX + document.body.scrollLeft;
            _y = e.clientY + document.body.scrollTop;
        }
    /*}else if(event != undefined && event.x != undefined){ // IE6,  IE7, IE5.5
        tooltip.x = event.x + ( document.documentElement.scrollLeft || document.body.scrollLeft);
        tooltip.y = event.y + ( document.documentElement.scrollTop || document.body.scrollTop);
    */
    }else{
		
        _x = 0;
        _y = 0;
    }
	GnXMouse=_x; 
    GnYMouse=_y ;
	
}

function drawDatePicker(targetDateField, x, y)
{
GbdatePickerVerrouille=1;
  var dt = getFieldDate(targetDateField.value );
 
  // the datepicker table will be drawn inside of a <div> with an ID defined by the
  // global datePickerDivID variable. If such a div doesn't yet exist on the HTML
  // document we're working with, add one.
if (!document.getElementById(datePickerDivID)) {
    // don't use innerHTML to update the body, because it can cause global variables
    // that are currently pointing to objects on the page to have bad references
    //document.body.innerHTML += "<div id='" + datePickerDivID + "' class='dpDiv'></div>";
	
	 var newNodeParent = document.createElement("div");	
	 newNodeParent.setAttribute("id",  datePickerDivID+"parent");	
     newNodeParent.setAttribute("onMouseOver", "updateDateField('"+targetDateField.name+"')");
	  document.body.appendChild(newNodeParent);
		$(datePickerDivID+"parent").style.position='absolute';	
		$(datePickerDivID+"parent").style.width='300px';
		$(datePickerDivID+"parent").style.height='300px';
		$(datePickerDivID+"parent").style.zIndex='9999';
		$(datePickerDivID+"parent").style.left=(G_oMouseX-50)+'px';
		$(datePickerDivID+"parent").style.top=(G_oMouseY-50)+'px';
		$(datePickerDivID+"parent").onmouseover=function(){if(!GbdatePickerVerrouille){eval("updateDateField('"+targetDateField.name+"')")}};

    var newNode = document.createElement("div");	 
    newNode.setAttribute("id", datePickerDivID);	
    newNode.setAttribute("class", "dpDiv");
    newNode.setAttribute("style", "z-index: 10000;visibility: hidden;");	
	
	
    document.body.appendChild(newNode);
	//var parent = displayBelowThisObject;
  	//parent = parent.offsetParent;
	//CorrectAttach.appendChild(newNode);
	
  }
 
  // move the datepicker div to the proper x,y coordinate and toggle the visiblity
  var pickerDiv = document.getElementById(datePickerDivID);
  $(datePickerDivID).onmouseover=function(){GbdatePickerVerrouille=0;};
  pickerDiv.style.position = "absolute";

  
  
  
  pickerDiv.style.left = (G_oMouseX-20) + "px";
  pickerDiv.style.top =(G_oMouseY-20) + "px";
  pickerDiv.style.visibility = (pickerDiv.style.visibility == "visible" ? "hidden" : "visible");
  pickerDiv.style.display = (pickerDiv.style.display == "block" ? "none" : "block");
  pickerDiv.style.zIndex = 10000;
  
  // draw the datepicker table
  refreshDatePicker(targetDateField.name, dt.getFullYear(), dt.getMonth(), dt.getDate());
}


/**
This is the function that actually draws the datepicker calendar.
*/
function refreshDatePicker(dateFieldName, year, month, day)
{
  // if no arguments are passed, use today's date; otherwise, month and year
  // are required (if a day is passed, it will be highlighted later)
  var thisDay = new Date();
 
  if ((month >= 0) && (year > 0)) {
    thisDay = new Date(year, month, 1);
  } else {
    day = thisDay.getDate();
    thisDay.setDate(1);
  }
 
  // the calendar will be drawn as a table
  // you can customize the table elements with a global CSS style sheet,
  // or by hardcoding style and formatting elements below
  var crlf = "\r\n";
  var TABLE = "<table cols=7 class='dpTable' width='200'>" + crlf;
  var xTABLE = "</table>" + crlf;
  var TR = "<tr class='dpTR'>";
  var TR_title = "<tr class='dpTitleTR'>";
  var TR_days = "<tr class='dpDayTR'>";
  var TR_todaybutton = "<tr class='dpTodayButtonTR'>";
  var xTR = "</tr>" + crlf;
  var TD = "<td class='dpTD' onMouseOut='this.className=\"dpTD\";' onMouseOver=' this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var TD_title = "<td colspan=5 class='dpTitleTD'>";
  var TD_buttons = "<td class='dpButtonTD'>";
  var TD_todaybutton = "<td colspan=7 class='dpTodayButtonTD'>";
  var TD_days = "<td class='dpDayTD'>";
  var TD_selected = "<td class='dpDayHighlightTD' onMouseOut='this.className=\"dpDayHighlightTD\";' onMouseOver='this.className=\"dpTDHover\";' ";    // leave this tag open, because we'll be adding an onClick event
  var xTD = "</td>" + crlf;
  var DIV_title = "<div class='dpTitleText'>";
  var DIV_selected = "<div class='dpDayHighlight'>";
  var xDIV = "</div>";
 var nNbLignes=0;
  // start generating the code for the calendar table
  var html = TABLE;
 
  // this is the title bar, which displays the month and the buttons to
  // go back to a previous month or forward to the next month
  var sSelectYear=thisDay.getFullYear();
 
	  if(GaOptionsDatePicker['selectyear']==true){
		  sSelectYear="<select onChange=\"GbdatePickerVerrouille=1;refreshDatePicker('" + dateFieldName + "', this.value, " + thisDay.getMonth() + ");\">";
		  for(var i=(parseInt(thisDay.getFullYear())-parseInt(GaOptionsDatePicker['ecartyear'])); i<(parseInt(thisDay.getFullYear())+parseInt(GaOptionsDatePicker['ecartyear']));i++){
			  if(parseInt(thisDay.getFullYear())==i){
				    sSelectYear+="<option value=\""+i+"\" selected=\"selected\">"+i+"</option>";
			  }else{
				      sSelectYear+="<option value=\""+i+"\">"+i+"</option>";
			  }
		  }
		  sSelectYear+="</select>";
	  }
 
  
  
  
  html += TR_title;
  html += TD_buttons +getButtonCode(dateFieldName, thisDay, -1, "&nbsp;&lt;&nbsp;") +xTD;
  html += TD_title + DIV_title + monthArrayLong[ thisDay.getMonth()] + " " + sSelectYear + xDIV + xTD;
  html += TD_buttons +getButtonCode(dateFieldName, thisDay, 1, "&nbsp;&gt;&nbsp;") + xTD;
  html += xTR;
 
  // this is the row that indicates which day of the week we're on
  html += TR_days;
  for(i = 0; i < dayArrayShort.length; i++)
    html += TD_days + dayArrayShort[i] + xTD;
  html += xTR;
 
  // now we'll start populating the table with days of the month
  html += TR;
 nNbLignes=0;
  // first, the leading blanks
  for (i = 0; i < thisDay.getDay(); i++)
    html += TD + "&nbsp;" + xTD;
 
  // now, the days of the month
  do {
    dayNum = thisDay.getDate();
    TD_onclick = " onclick=\"updateDateField('" + dateFieldName + "', '" + getDateString(thisDay) + "');\">";
    
    if (dayNum == day)
      html += TD_selected + TD_onclick + DIV_selected + dayNum + xDIV + xTD;
    else
      html += TD + TD_onclick + dayNum + xTD;
    
    // if this is a Saturday, start a new row
    if (thisDay.getDay() == 6){
      html += xTR + TR;
	   nNbLignes++;
	}
    
    // increment the day
    thisDay.setDate(thisDay.getDate() + 1);
  } while (thisDay.getDate() > 1)
 
  // fill in any trailing blanks
  if (thisDay.getDay() > 0) {
    for (i = 6; i >= thisDay.getDay(); i--)
      html += TD + "&nbsp;" + xTD;
  }
  html += xTR;

  // add a button to allow the user to easily return to today, or close the calendar
  var today = new Date();
  var todayString = "Today is " + dayArrayMed[today.getDay()] + ", " + monthArrayMed[ today.getMonth()] + " " + today.getDate();
  html += TR_todaybutton + TD_todaybutton;
  html += "<div style=\"float:left;\"><button class='dpTodayButton' onClick='refreshDatePicker(\"" + dateFieldName + "\");'>&nbsp;Aujourd'hui&nbsp;</button> </div><div style=\"float:right;\">";
  html += "<button class='dpTodayButton' onClick='updateDateField(\"" + dateFieldName + "\");'>&nbsp;Fermer&nbsp;</button></div>";
  html += xTD + xTR;
 
  // and finally, close the table
  html += xTABLE;
 
  document.getElementById(datePickerDivID).innerHTML = html;
  // add an "iFrame shim" to allow the datepicker to display above selection lists
  adjustiFrame();
}



function getButtonCode(dateFieldName, dateVal, adjust, label)
{
  var newMonth = (dateVal.getMonth () + adjust) % 12;
  var newYear = dateVal.getFullYear() + parseInt((dateVal.getMonth() + adjust) / 12);
  var newYearSpeed=newYear+1;
  var newMonthSpeed=dateVal.getMonth();
   
  if (newMonth < 0) {
    newMonth += 12;
    newYear += -1;
  }
  var sBouton1="<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYear + ", " + newMonth + ");'>" + label + "</button>";
  var sBouton2="<button class='dpButton' onClick='refreshDatePicker(\"" + dateFieldName + "\", " + newYearSpeed + ", " + newMonthSpeed + ");'>" + label +  label + "</button>";
 var sBoutons='';
 if(GaOptionsDatePicker['btSpeed']==true){
 if(adjust<0){
	  sBoutons= "<div style=\"width:40px;\">"+sBouton1+ sBouton2+"</div>";
 }else{
	   sBoutons="<div style=\"width:40px;\">"+ sBouton2+ sBouton1+"</div>";
 }
}else{
	sBoutons=sBouton1;
}
  return sBoutons;
}



function getDateString(dateVal)
{
  var dayString = "00" + dateVal.getDate();
  var monthString = "00" + (dateVal.getMonth()+1);
  dayString = dayString.substring(dayString.length - 2);
  monthString = monthString.substring(monthString.length - 2);
 
  switch (dateFormat) {
    case "dmy" :
      return dayString + dateSeparator + monthString + dateSeparator + dateVal.getFullYear();
    case "ymd" :
      return dateVal.getFullYear() + dateSeparator + monthString + dateSeparator + dayString;
    case "mdy" :
    default :
      return monthString + dateSeparator + dayString + dateSeparator + dateVal.getFullYear();
  }
}



function getFieldDate(dateString)
{
  var dateVal;
  var dArray;
  var d, m, y;
 
  try {
    dArray = splitDateString(dateString);
    if (dArray) {
      switch (dateFormat) {
        case "dmy" :
          d = parseInt(dArray[0], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
        case "ymd" :
          d = parseInt(dArray[2], 10);
          m = parseInt(dArray[1], 10) - 1;
          y = parseInt(dArray[0], 10);
          break;
        case "mdy" :
        default :
          d = parseInt(dArray[1], 10);
          m = parseInt(dArray[0], 10) - 1;
          y = parseInt(dArray[2], 10);
          break;
      }
      dateVal = new Date(y, m, d);
    } else if (dateString) {
      dateVal = new Date(dateString);
    } else {
      dateVal = new Date();
    }
  } catch(e) {
    dateVal = new Date();
  }
 
  return dateVal;
}



function splitDateString(dateString)
{
  var dArray;
  if (dateString.indexOf("/") >= 0)
    dArray = dateString.split("/");
  else if (dateString.indexOf(".") >= 0)
    dArray = dateString.split(".");
  else if (dateString.indexOf("-") >= 0)
    dArray = dateString.split("-");
  else if (dateString.indexOf("\\") >= 0)
    dArray = dateString.split("\\");
  else
    dArray = false;
 
  return dArray;
}


function updateDateField(dateFieldName, dateString)
{
GdateFieldName='';
var targetDateField = document.getElementsByName (dateFieldName).item(0);
  if (dateString)
    targetDateField.value = dateString;
	 targetDateField.onchange();
  var pickerDiv = document.getElementById(datePickerDivID);
  pickerDiv.style.visibility = "hidden";
  pickerDiv.style.display = "none";

 GbdatePickeropened=0;
  adjustiFrame();
  targetDateField.focus();
  if(document.getElementById(datePickerDivID)){
   $(datePickerDivID).remove();
  }
  if(document.getElementById(datePickerDivID+"parent")){
  	$(datePickerDivID+"parent").remove();
  }
    
  if ((dateString) && (typeof(datePickerClosed) == "function"))
    datePickerClosed(targetDateField);
}



function adjustiFrame(pickerDiv, iFrameDiv){}

function verifFieldDatePicker(obj){

	
	var sValue = obj.value;
	var bHasTiret = true;
	var bHasSlash = true;
	if(sValue.indexOf('/')==-1){bHasSlash = false;}
	if(sValue.indexOf('-')==-1){bHasTiret = false;}
	
	if(!bHasTiret && !bHasSlash){
		var bWellFormed = true;
		switch(sValue.length){
			case 6:
				var sD = sValue.substr(0,2);
				var sM = sValue.substr(2,2);
				var sY = sValue.substr(4,2);
				if(sY>70){
					sY='19'+sY;
				}else{
					sY='20'+sY;
				}
				break;
			case 8:
				var sD = sValue.substr(0,2);
				var sM = sValue.substr(2,2);
				var sY = sValue.substr(4,4);
				break;
			default:
				bWellFormed = false;
				break;
		}
		obj.value = sD+'/'+sM+'/'+sY;

	}
	
	//date par defaut
	thisDay = new Date();
	defautjj=thisDay.getDate();
	defautmm=thisDay.getMonth()+1;

	defautaaaa=thisDay.getFullYear();

	var sChaine=obj.value;
	
	if(sChaine.indexOf('/')>0){
		var aChaine=sChaine.split("/");
	}else{
		var aChaine=array();
		aChaine[0]=sChaine.substr(0,2);
		aChaine[1]=sChaine.substr(2,2);
		aChaine[2]=sChaine.substr(4,4);
	}
	
	var error=0;
	var jj=parseInt(parseFloat(aChaine[0]));

	if(jj==0 || !jj){
		jj=defautjj;
		error++;
	}
	if(aChaine[1].substr(0,1)=="0"){
		aChaine[1]=aChaine[1].substr(1,1);
	}
	var mm=parseInt(aChaine[1]);
	if( !mm ){
		mm=defautmm;
		error++;
	}
	var aaaa=parseInt(aChaine[2]);
	if(aaaa==0 || !aaaa ||  aaaa<1900 || aaaa<=0){
		aaaa=defautaaaa;
		error++;
	}
	if(error>0){
		var sBgColor = obj.style.backgroundColor;
		obj.style.backgroundColor="#FF0000";
		setTimeout("retablirFieldBgColor('"+obj.id+"','"+sBgColor+"')",1000);
	}
	
	thisDay = new Date(aaaa, (mm-1),jj);
	jj=thisDay.getDate();
	mm=thisDay.getMonth();
	aaaa=thisDay.getFullYear();
	if(jj<10){jj="0"+jj;}
	mm++;
	if(mm<10){mm="0"+mm;}
		
	obj.value=jj+"/"+mm+"/"+aaaa;
}

function retablirFieldBgColor(sId,sColor){
	$(sId).style.backgroundColor = sColor;
}