//Utiliser dans les Sous-List de Contact et Inscription. Permet de 
function setSelectedFields(srcFormField,targetForm,targetFieldName)
{    
    //REMOVE CHILD FIRST    
    var oItem = targetForm.children;
    for (i=0; i<oItem.length; i++)
    {           
        if(oItem.item(i).name == targetFieldName)
        {
           targetForm.removeChild(oItem.item(i));
           i--;
        }
    }    

    //ADDING NEW CHILD
    if(srcFormField)
	    for (i=0;i<srcFormField.length;i++)
	    {       
	        if (srcFormField[i].checked)
	        {
	            var el = document.createElement("<INPUT type='checkbox' name='" + targetFieldName + "' value='" + srcFormField[i].value + "' checked style='display:none'/>");           
	            targetForm.appendChild(el);
	        }
	    }
}

//Lorsqu'on dblClick sur une ligne dans une list pour afficher le detail (view.jsp)
function listDblClick(id,submitInPopup, type, unused, form){
    if(!form) form = mainForm;   
	if(window.event) window.event.cancelBubble = true;
 
    form.viewId.value=id;    
    form.dispatch.value='view';
    
    if(type && type == 2)
        form.dispatch.value='viewLettre';
    else if(type && type == 3)
        form.dispatch.value='viewCarte';
    else if(type && type == 10)
    {
        form.dispatch.value='viewCMA';
        return submitInCMAPopup(form);
    }
    return submitInPopup(form);
}

//Lorsqu'on click sur les header des listes pour trier le contenue
function setSortFilter(filter, subsection)
{
    //alert(window.name);
    mainForm.sortFilter.value=filter;
    mainForm.dispatch.value='sort';
    if(mainForm.currentSubSection) mainForm.currentSubSection.value=subsection;
    return submitSelf(mainForm);
}

var modifiedArray = new Array();
var selectedArray = new Array();
var uniqueArray = new Array();
    

//Appeler sur un onChange des champs d'édition
//il permet d'aviser l'usager qu'un champ X a été modifier lorsqu'il essai de quitter dans sauvegarder
function addModifiedField(field)
{
    if( modifiedArray.join().indexOf(field.title) == -1 )
    {   
        modifiedArray[modifiedArray.length] = field.title;
    }    
    dirty = true;
}

//Appeler sur un onChange des champs d'édition
//il permet d'aviser l'usager qu'un champ X a été modifier lorsqu'il essai de quitter dans sauvegarder
//Pour les page ou on doit conserver les champs modifi� dans la form
function saveModifiedField(field)
{
    if( modifiedArray.join().indexOf(field.title) == -1 )
    {
        modifiedArray[modifiedArray.length] = field.title;
        
        var hidd = document.createElement('INPUT');
                hidd.type='hidden';
                hidd.name='modified[' + (modifiedArray.length - 1) + ']';
                hidd.value=field.title;
                mainForm.appendChild(hidd);
    }
    dirty = true;
}
function addModifiedFieldName(zetitle)
{
    if( modifiedArray.join().indexOf(zetitle) == -1 )
    {   
        modifiedArray[modifiedArray.length] = zetitle;
        
        var hidd = document.createElement('INPUT');
                hidd.type='hidden';
                hidd.name='modified[' + (modifiedArray.length - 1) + ']';
                hidd.value=zetitle;
                mainForm.appendChild(hidd);
    }    
    dirty = true;
}


//Ajoute les lignes selectionnees a  partir d'une liste, afin de pouvoir les identifier
//au moment d'un view ou d'un delete.
function addSelectedFieldUnique(field, uniqueKey)
{
    if( window.event )
        window.event.cancelBubble = true;
    if( field.checked )
    {
        if( selectedArray.join().indexOf(field.title) == -1 || (uniqueKey != null && uniqueArray.join().indexOf(uniqueKey) == -1) )
        {   
            var i = 0;
            for(i=0;i<selectedArray.length;i++)
            {
                if( selectedArray[i] == null )
                {   
                    selectedArray[i] = field.title;
                    uniqueArray[i] = uniqueKey;
                    break;
                }
            }
            if( i == selectedArray.length )
            {
                selectedArray[i] = field.title;
                uniqueArray[i] = uniqueKey;
            }
        }
    }
    else
    {
        if( selectedArray.join().indexOf(field.title) != -1 || (uniqueKey != null && uniqueArray.join().indexOf(uniqueKey) == -1) )
        {
            // remove field from array
            for(i=0; i< selectedArray.length; i++)
            {
                if( selectedArray[i] == field.title && (uniqueKey != null && uniqueArray[i] == uniqueKey ) )
                {
                    for(j=i+1;j<selectedArray.length;j++)
                    {
                        selectedArray[i] = selectedArray[j];
                        uniqueArray[i] = uniqueArray[j];
                        i++;
                    }
                    selectedArray[i] = null;
                    uniqueArray[i] = null
                    selectedArray.length = selectedArray.length -1;
                    uniqueArray.length = uniqueArray.length -1;
                    break;
                }
            }
        }
    }
}


//Gestion des Equipes. ce code empeche l utilisateur de decocher tout le monde
//au moin un user doit etre coche dans la listes des usagers de l equipe
//Le parametre refreshContent est passe seulement lorsque appeler de L Agenda
//puisqu on veut faire un refresh.
function clickTeamUser(elt,refreshContent)
{
    if( elt.checked == false )
    {
        var chk = elt.form.selectedUserIds;
        var clicked = false;
        if( chk && chk.length && chk.length > 0 )
        {
            for(i=0;i<chk.length;i++)
            {
                if( chk[i].checked == true )
                {
                    clicked = true;
                    break;
                }
            }
        }
        if( !clicked )
        {
            elt.checked = true;
            window.event.cancelBubble = true;
            return false;
        }
    }
    if(!refreshContent){ 
        return true;
    }
    else{
	return mainForm.defaultSubmit2.click();
    }
}


// This function shows the calendar under the element having the given id.
// It takes care of catching "mousedown" signals on document and hiding the
// calendar if the click was outside.

//DEFAULT VALUE IF param=null
//rangeDe    = 1980
//rangeA     = currentYears du PC Local de l utilisateur
//dateFormat = %d-%m-%Y 
//--autres format de date aussi possible(%d-%m-%Y %H:%M)

function showCalendar(id, rangeDe,rangeA,dateFormat) {
  var el = document.getElementById(id);  

  if (window.calendar != null) 
  {
    // we already have some calendar created
    window.calendar.hide();                 // so we hide it first.
  } 
  else
  {
    // first-time call, create the calendar.
    var cal = new Calendar(0, null, selected, closeHandler);

    // uncomment the following line to hide the week numbers
    cal.weekNumbers = false;
    cal.showsOtherMonths = false; 
  
    window.calendar = cal;                  // remember it in the global var    
  
    cal.yearStep = 3;
    cal.create();
  }

  if(rangeDe == null)
      rangeDe = 1980;
  if(rangeA == null)
      rangeA = (new Date()).getFullYear();   

  window.calendar.setRange(rangeDe, rangeA);        // min/max year allowed.

  // set the specified date format
  if(dateFormat == null)    
    window.calendar.setDateFormat('%d-%m-%Y');    
  else
    window.calendar.setDateFormat(dateFormat)         
  
  window.calendar.parseDate(el.value);      // try to parse the text in field

  window.calendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  window.calendar.showAtElement(el, 'Bl');        // show the calendar
  return false;
}

var MONTH_NAMES=new Array('January','February','March','April','May','June','July','August','September','October','November','December','Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec');
var DAY_NAMES=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sun','Mon','Tue','Wed','Thu','Fri','Sat');
function LZ(x) {return(x<0||x>9?"":"0")+x}

var DAYSINMONTH = [31,28,31,30,31,30,31,31,30,31,30,31];

// ------------------------------------------------------------------
// isDate ( date_string, format_string )
// Returns true if date string matches format of format string and
// is a valid date. Else returns false.
// It is recommended that you trim whitespace around the value before
// passing it to this function, as whitespace is NOT ignored!
// ------------------------------------------------------------------
function isDate(val,format) {
	var date=getDateFromFormat(val,format);
	if (date==0) { return false; }
	return true;
	}

// -------------------------------------------------------------------
// compareDates(date1,date1format,date2,date2format)
//   Compare two date strings to see which is greater.
//   Returns:
//   1 if date1 is greater than date2
//   0 if date2 is greater than date1 of if they are the same
//  -1 if either of the dates is in an invalid format
// -------------------------------------------------------------------
function compareDates(date1,dateformat1,date2,dateformat2) {
	var d1=getDateFromFormat(date1,dateformat1);
	var d2=getDateFromFormat(date2,dateformat2);
	if (d1==0 || d2==0) {
		return -1;
		}
	else if (d1 > d2) {
		return 1;
		}
	return 0;
	}

// ------------------------------------------------------------------
// formatDate (date_object, format)
// Returns a date in the output format specified.
// The format string uses the same abbreviations as in getDateFromFormat()
// ------------------------------------------------------------------
function formatDate2(date,format) {
	format=format+"";
	var result="";
	var i_format=0;
	var c="";
	var token="";
	var y=date.getYear()+"";
	var M=date.getMonth()+1;
	var d=date.getDate();
	var E=date.getDay();
	var H=date.getHours();
	var m=date.getMinutes();
	var s=date.getSeconds();
	var yyyy,yy,MMM,MM,dd,hh,h,mm,ss,ampm,HH,H,KK,K,kk,k;
	// Convert real date parts into formatted versions
	var value=new Object();
	if (y.length < 4) {y=""+(y-0+1900);}
	value["y"]=""+y;
	value["yyyy"]=y;
	value["yy"]=y.substring(2,4);
	value["M"]=M;
	value["MM"]=LZ(M);
	value["MMM"]=MONTH_NAMES[M-1];
	value["NNN"]=MONTH_NAMES[M+11];
	value["d"]=d;
	value["dd"]=LZ(d);
	value["E"]=DAY_NAMES[E+7];
	value["EE"]=DAY_NAMES[E];
	value["H"]=H;
	value["HH"]=LZ(H);
	if (H==0){value["h"]=12;}
	else if (H>12){value["h"]=H-12;}
	else {value["h"]=H;}
	value["hh"]=LZ(value["h"]);
	if (H>11){value["K"]=H-12;} else {value["K"]=H;}
	value["k"]=H+1;
	value["KK"]=LZ(value["K"]);
	value["kk"]=LZ(value["k"]);
	if (H > 11) { value["a"]="PM"; }
	else { value["a"]="AM"; }
	value["m"]=m;
	value["mm"]=LZ(m);
	value["s"]=s;
	value["ss"]=LZ(s);
	while (i_format < format.length) {
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		if (value[token] != null) { result=result + value[token]; }
		else { result=result + token; }
		}
	return result;
	}

//Utility functions for parser numeric fields in CMA
function formatNumberCMA(field)
{
	field.value = field.value.replace(',', '.');
	field.value = field.value.replace(/[^0-9.?-]/g,"");
	if (isNaN(field.value))
		field.value = "?";
}

// ------------------------------------------------------------------
// Utility functions for parsing in getDateFromFormat()
// ------------------------------------------------------------------
function _isInteger(val) {
	var digits="1234567890";
	for (var i=0; i < val.length; i++) {
		if (digits.indexOf(val.charAt(i))==-1) { return false; }
		}
	return true;
	}
function _getInt(str,i,minlength,maxlength) {
	for (var x=maxlength; x>=minlength; x--) {
		var token=str.substring(i,i+x);
		if (token.length < minlength) { return null; }
		if (_isInteger(token)) { return token; }
		}
	return null;
	}
	
// ------------------------------------------------------------------
// getDateFromFormat( date_string , format_string )
//
// This function takes a date string and a format string. It matches
// If the date string matches the format string, it returns the 
// getTime() of the date. If it does not match, it returns 0.
// ------------------------------------------------------------------
function getDateFromFormat(val,format) {
	val=val+"";
	format=format+"";
	var i_val=0;
	var i_format=0;
	var c="";
	var token="";
	var token2="";
	var x,y;
	var now=new Date();
	var year=now.getYear();
	var month=now.getMonth()+1;
	var date=1;
	var hh=now.getHours();
	var mm=now.getMinutes();
	var ss=now.getSeconds();
	var ampm="";
	
	while (i_format < format.length) {
		// Get next token from format string
		c=format.charAt(i_format);
		token="";
		while ((format.charAt(i_format)==c) && (i_format < format.length)) {
			token += format.charAt(i_format++);
			}
		// Extract contents of value based on format token
		if (token=="yyyy" || token=="yy" || token=="y") {
			if (token=="yyyy") { x=4;y=4; }
			if (token=="yy")   { x=2;y=2; }
			if (token=="y")    { x=2;y=4; }
			year=_getInt(val,i_val,x,y);
			if (year==null) { return 0; }
			i_val += year.length;
			if (year.length==2) {
				if (year > 70) { year=1900+(year-0); }
				else { year=2000+(year-0); }
				}
			}
		else if (token=="MMM"||token=="NNN"){
			month=0;
			for (var i=0; i<MONTH_NAMES.length; i++) {
				var month_name=MONTH_NAMES[i];
				if (val.substring(i_val,i_val+month_name.length).toLowerCase()==month_name.toLowerCase()) {
					if (token=="MMM"||(token=="NNN"&&i>11)) {
						month=i+1;
						if (month>12) { month -= 12; }
						i_val += month_name.length;
						break;
						}
					}
				}
			if ((month < 1)||(month>12)){return 0;}
			}
		else if (token=="EE"||token=="E"){
			for (var i=0; i<DAY_NAMES.length; i++) {
				var day_name=DAY_NAMES[i];
				if (val.substring(i_val,i_val+day_name.length).toLowerCase()==day_name.toLowerCase()) {
					i_val += day_name.length;
					break;
					}
				}
			}
		else if (token=="MM"||token=="M") {
			month=_getInt(val,i_val,token.length,2);
			if(month==null||(month<1)||(month>12)){return 0;}
			i_val+=month.length;}
		else if (token=="dd"||token=="d") {
			date=_getInt(val,i_val,token.length,2);
			if(date==null||(date<1)||(date>31)){return 0;}
			i_val+=date.length;}
		else if (token=="hh"||token=="h") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>12)){return 0;}
			i_val+=hh.length;}
		else if (token=="HH"||token=="H") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>23)){return 0;}
			i_val+=hh.length;}
		else if (token=="KK"||token=="K") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<0)||(hh>11)){return 0;}
			i_val+=hh.length;}
		else if (token=="kk"||token=="k") {
			hh=_getInt(val,i_val,token.length,2);
			if(hh==null||(hh<1)||(hh>24)){return 0;}
			i_val+=hh.length;hh--;}
		else if (token=="mm"||token=="m") {
			mm=_getInt(val,i_val,token.length,2);
			if(mm==null||(mm<0)||(mm>59)){return 0;}
			i_val+=mm.length;}
		else if (token=="ss"||token=="s") {
			ss=_getInt(val,i_val,token.length,2);
			if(ss==null||(ss<0)||(ss>59)){return 0;}
			i_val+=ss.length;}
		else if (token=="a") {
			if (val.substring(i_val,i_val+2).toLowerCase()=="am") {ampm="AM";}
			else if (val.substring(i_val,i_val+2).toLowerCase()=="pm") {ampm="PM";}
			else {return 0;}
			i_val+=2;}
		else {
			if (val.substring(i_val,i_val+token.length)!=token) {return 0;}
			else {i_val+=token.length;}
			}
		}
	// If there are any trailing characters left in the value, it doesn't match
	if (i_val != val.length) { return 0; }
	// Is date valid for month?
	if (month==2) {
		// Check for leap year
		if ( ( (year%4==0)&&(year%100 != 0) ) || (year%400==0) ) { // leap year
			if (date > 29){ return 0; }
			}
		else { if (date > 28) { return 0; } }
		}
	if ((month==4)||(month==6)||(month==9)||(month==11)) {
		if (date > 30) { return 0; }
		}
	// Correct hours value
	if (hh<12 && ampm=="PM") { hh=hh-0+12; }
	else if (hh>11 && ampm=="AM") { hh-=12; }
	var newdate=new Date(year,month-1,date,hh,mm,ss);
	return newdate.getTime();
	}

// ------------------------------------------------------------------
// parseDate( date_string [, prefer_euro_format] )
//
// This function takes a date string and tries to match it to a
// number of possible date formats to get the value. It will try to
// match against the following international formats, in this order:
// y-M-d   MMM d, y   MMM d,y   y-MMM-d   d-MMM-y  MMM d
// M/d/y   M-d-y      M.d.y     MMM-d     M/d      M-d
// d/M/y   d-M-y      d.M.y     d-MMM     d/M      d-M
// A second argument may be passed to instruct the method to search
// for formats like d/M/y (european format) before M/d/y (American).
// Returns a Date object or null if no patterns match.
// ------------------------------------------------------------------
function parseDate(val) {
	var preferEuro=(arguments.length==2)?arguments[1]:false;
	generalFormats=new Array('y-M-d','MMM d, y','MMM d,y','y-MMM-d','d-MMM-y','MMM d');
	monthFirst=new Array('M/d/y','M-d-y','M.d.y','MMM-d','M/d','M-d');
	dateFirst =new Array('d/M/y','d-M-y','d.M.y','d-MMM','d/M','d-M');
	var checkList=new Array('generalFormats',preferEuro?'dateFirst':'monthFirst',preferEuro?'monthFirst':'dateFirst');
	var d=null;
	for (var i=0; i<checkList.length; i++) {
		var l=window[checkList[i]];
		for (var j=0; j<l.length; j++) {
			d=getDateFromFormat(val,l[j]);
			if (d!=0) { return new Date(d); }
			}
		}
	return null;
	}



function dontShowCalendar(id, rangeDe,rangeA,dateFormat) {
  var el = document.getElementById(id);  

  if (window.calendar == null) 
  {
    // first-time call, create the calendar.
    var cal = new Calendar(0, null, selected, closeHandler);

    // uncomment the following line to hide the week numbers
    cal.weekNumbers = false;
    cal.showsOtherMonths = false; 
  
    window.calendar = cal;                  // remember it in the global var    
  
    if(rangeDe == null)
        rangeDe = 1980;
    if(rangeA == null)
        rangeA = (new Date()).getYear();   

    cal.setRange(rangeDe, rangeA);        // min/max year allowed.
    cal.create();
  }
  
  // set the specified date format
  if(dateFormat == null)    
    window.calendar.setDateFormat('%d-%m-%Y');    
  else
    window.calendar.setDateFormat(dateFormat)         
  
  window.calendar.parseDate(el.value);      // try to parse the text in field

  window.calendar.sel = el;                 // inform it what input field we use

  // the reference element that we pass to showAtElement is the button that
  // triggers the calendar.  In this example we align the calendar bottom-right
  // to the button.
  window.calendar.showAtElement(el, 'Bl');        // show the calendar
  
  window.calendar.hide();
  return false;
}

//take 9 or 99 and returns a int ie. 8 = 8, 09 = 9, 10 = 10
function parseTimePartToInt(value)
{
	if (value.charAt(0) == '0') //if leading 0 remove it or parseint will return 0
		return parseInt(value.charAt(1));
	else
		return parseInt(value);
}
function formatHeure(eltToFormat,errMsg, hFin, dDebut, dFin)
{
	var valid = true;
	var heure = eltToFormat.value.toLowerCase().trim();
	var ampm = '';
	if (usesAMPM)
	{
		if (heure.search(/pm?/i) >= 0)
			ampm = ' PM';
		else
			ampm = ' AM';
		
		heure = heure.replace(/(\s*pm?)|(\s*am?)/i, '');
	}
	else if (heure.search(/(pm?)|(am?)/i) >= 0)
		valid = false;
	
	if (heure == '')
		valid = false;
	
	var split = heure.split(/[\sh:]/gi); //white-space, h or H, :
	heure = split[0];
	var hours = 0;
	var minutes = 0;
	if (valid)
	{
		if (split.length ==1) //pas de separateur
		{
			if (checkNr(heure))
			{
				if(heure.length < 3)//9 = 09:00 //10 = 10:00
				{
					hours = parseTimePartToInt(heure);
				}
				else if (heure.length < 4) //120 = 01:20
				{
					hours = parseInt(heure.substring(0,1));
					minutes = parseTimePartToInt(heure.substring(1,3));
				}
				else if (heure.length < 5) //1200 = 12:00
				{
					hours = parseTimePartToInt(heure.substring(0,2));
					minutes = parseTimePartToInt(heure.substring(2,4));
				}
				else valid = false;
			}
			else 
				valid = false;
		}
		else if (split.length == 2) //separateur
		{
			if (checkNr(heure))
			{
				if(heure.length < 3) //9: = 09 // 10: = 10
					hours = parseTimePartToInt(heure);
				else 
					valid = false;
			}
			else 
				valid = false;
				
			if (checkNr(split[1]))
			{
				if(split[1].length == 2) // :10 = 10
					minutes = parseTimePartToInt(split[1]);
				else 
					valid = false;
			}
			else 
				valid = false;
		}
		else
			valid = false;
	}
	
	if(!valid || (!usesAMPM && (hours < 0 || hours >= 24)) || (usesAMPM && (hours < 0 || hours > 12)) ||
			minutes < 0 || minutes >= 60 )
	{
		alert(errMsg);
		var now = new Date();
		heure = simpleFormatHeure('' + now.getHours() + ':' + String.leftPad(now.getMinutes(), 2, '0'));
	}
	else
		heure = String.leftPad(hours, 2, '0') + ':' + String.leftPad(minutes, 2, '0') + ampm;

	if(hFin && dDebut && dFin)
		changeHFin(heure, hFin, dDebut, dFin);
	eltToFormat.value = heure;

}
function simpleFormatHeure(heure)
{
	if (heure instanceof Date) {
		heure = heure.getHours()+':'+String.leftPad(heure.getMinutes(), 2, '0');
	}
	var split = heure.split(/[\s|:]/g);
	split[0] = String.leftPad(split[0], 2, '0');
	split[1] = String.rightPad(split[1], 2, '0');
	hour = split[0] + ':' + split[1];
	if (usesAMPM)
	{
		if (split.length == 3)
		{
			if (split[2].search(/pm?/i) >= 0)
				hour = hour + ' PM';
			else 
				hour = hour + ' AM';
		}
		else
			hour = convertToAMPM(hour);
	}
	return hour;
}
function checkHDebut(hFin, eltDebut, eltDateDebut, eltDateFin)
{
	var heureFin = hFin;
	var heureDebut = eltDebut.value;
	if (usesAMPM)
	{
		//convert to 24 hour
		heureFin = convertTo24(heureFin);
		heureDebut = convertTo24(heureDebut);
	}
	var dFin = Date.parse(eltDateFin.value+' ' + heureFin);
	var dDebut = Date.parse(eltDateDebut.value + ' ' + heureDebut);
	return dFin >= dDebut;
}
function changeHFin(value, eltFin, eltDateDebut, eltDateFin)
{
	var split = value.split(/[\s|:]/g);
	var hours = parseTimePartToInt(split[0]);
	var addDay = false;
	if (usesAMPM)
	{
		if (hours == 12)
			hours = 0;
		if (split[2].search(/am/i) >= 0 && hours == 11)
			split[2] = 'PM';
		else if (split[2].search(/pm/i) >= 0 && hours == 11)
		{
			split[2] = 'AM';
			addDay=true;
		}
		eltFin.value = simpleFormatHeure((hours + 1) + ':' + split[1] + ' ' + split[2]);
	}
	else
	{
		if(hours < 23)
			eltFin.value = simpleFormatHeure((hours + 1) + ':' + split[1]);
		else
		{
			eltFin.value = simpleFormatHeure('00:' + split[1]);
			addDay=true;
		}
	}
	if (addDay)
	{
		dontShowCalendar(eltDateDebut.id, null,2020,jFmt);
			
		window.calendar.date.setTime(window.calendar.date.getTime() + 1000*60*60*24);
		eltDateFin.value = window.calendar.date.print(window.calendar.dateFormat);
	}
}
function checkNr ( nr )
{
	if (nr.match(/^[0-9]+$/))
		return true;
	else
		return false;
}
/*Takes a valid AMPM hour(99:99 ?M) and converts it to the 24 hour format(99:99)*/
function convertTo24(value)
{
	var split = value.split(/[\s|:]/g);
	var hours = parseTimePartToInt(split[0]);
	if (split[2].search(/am/i) >= 0 && hours == 12)
		hours = 0;
	else if (split[2].search(/pm/i) >= 0 && hours != 12)
		hours += 12;
	//else 1-11 AM, 12 PM, don't change hour

	return String.leftPad(hours, 2, '0') + ':' + split[1];
}
/*Takes a valid 24 hour(99:99) and converts it to the AMPM hour format(99:99 ?M)*/
function convertToAMPM(value)
{
	var split = value.split(':');
	var hours = parseTimePartToInt(split[0]);
	var ampm = ' AM';
	if (hours > 11)
		ampm = ' PM';
	if (hours == 0) 
		hours = 12;
	if (hours > 12)
		hours -= 12;
	return String.leftPad(hours, 2, '0') + ':' + split[1] + ampm;
}

function closeHandler(cal) {
  cal.hide();                        // hide the calendar
//  window.calendar=null;
}

function calDateFormat(date, str){
    var m = date.getMonth();
    var d = date.getDate();
    var y = date.getFullYear();
    var wn = date.getWeekNumber();
    var w = date.getDay();
    var s = {};
    var hr = date.getHours();
    var pm = (hr >= 12);
    var ir = (pm) ? (hr - 12) : hr;
    var dy = date.getDayOfYear();
    if (ir == 0)
        ir = 12;
    var min = date.getMinutes();
    var sec = date.getSeconds();
    s["%a"] = Calendar._SDN[w]; // abbreviated weekday name [FIXME: I18N]
    s["%A"] = Calendar._DN[w]; // full weekday name
    s["%b"] = Calendar._SMN[m]; // abbreviated month name [FIXME: I18N]
    s["%B"] = Calendar._MN[m]; // full month name
    // FIXME: %c : preferred date and time representation for the current locale
    s["%C"] = 1 + Math.floor(y / 100); // the century number
    s["%d"] = (d < 10) ? ("0" + d) : d; // the day of the month (range 01 to 31)
    s["%e"] = d; // the day of the month (range 1 to 31)
    // FIXME: %D : american date style: %m/%d/%y
    // FIXME: %E, %F, %G, %g, %h (man strftime)
    s["%H"] = (hr < 10) ? ("0" + hr) : hr; // hour, range 00 to 23 (24h format)
    s["%I"] = (ir < 10) ? ("0" + ir) : ir; // hour, range 01 to 12 (12h format)
    s["%j"] = (dy < 100) ? ((dy < 10) ? ("00" + dy) : ("0" + dy)) : dy; // day of the year (range 001 to 366)
    s["%k"] = hr;       // hour, range 0 to 23 (24h format)
    s["%l"] = ir;       // hour, range 1 to 12 (12h format)
    s["%m"] = (m < 9) ? ("0" + (1+m)) : (1+m); // month, range 01 to 12
    s["%M"] = (min < 10) ? ("0" + min) : min; // minute, range 00 to 59
    s["%n"] = "\n";     // a newline character
    s["%p"] = pm ? "PM" : "AM";
    s["%P"] = pm ? "pm" : "am";
    // FIXME: %r : the time in am/pm notation %I:%M:%S %p
    // FIXME: %R : the time in 24-hour notation %H:%M
    s["%s"] = Math.floor(date.getTime() / 1000);
    s["%S"] = (sec < 10) ? ("0" + sec) : sec; // seconds, range 00 to 59
    s["%t"] = "\t";     // a tab character
    // FIXME: %T : the time in 24-hour notation (%H:%M:%S)
    s["%U"] = s["%W"] = s["%V"] = (wn < 10) ? ("0" + wn) : wn;
    s["%u"] = w + 1;    // the day of the week (range 1 to 7, 1 = MON)
    s["%w"] = w;        // the day of the week (range 0 to 6, 0 = SUN)
    // FIXME: %x : preferred date representation for the current locale without the time
    // FIXME: %X : preferred time representation for the current locale without the date
    s["%y"] = ('' + y).substr(2, 2); // year without the century (range 00 to 99)
    s["%Y"] = y;        // year with the century
    s["%%"] = "%";      // a literal '%' character

    var re = /%./g;

    var a = str.match(re);
    for (var i = 0; i < a.length; i++) {
        var tmp = s[a[i]];
        if (tmp) {
            re = new RegExp(a[i], 'g');
            str = str.replace(re, tmp);
        }
    }

    return str;
};

/**
 *  Tries to identify the date represented in a string.  If successful it also
 *  calls this.setDate which moves the calendar to the given date.
 */
function calParseDate(str, fmt) {
    var y = 0;
    var m = -1;
    var d = 0;
    var a = str.split(/\W+/);
    var b = fmt.match(/%./g);
    var i = 0, j = 0;
    var hr = 0;
    var min = 0;
    for (i = 0; i < a.length; ++i) {
        if (!a[i])
            continue;
        switch (b[i]) {
            case "%d":
            case "%e":
            d = parseInt(a[i], 10);
            break;

            case "%m":
            m = parseInt(a[i], 10) - 1;
            break;

            case "%Y":
            case "%y":
            y = parseInt(a[i], 10);
            (y < 100) && (y += (y > 29) ? 1900 : 2000);
            break;

            case "%b":
            case "%B":
            for (j = 0; j < 12; ++j) {
                if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { m = j; break; }
            }
            break;

            case "%H":
            case "%I":
            case "%k":
            case "%l":
            hr = parseInt(a[i], 10);
            break;

            case "%P":
            case "%p":
            if (/pm/i.test(a[i]) && hr < 12)
                hr += 12;
            break;

            case "%M":
            min = parseInt(a[i], 10);
            break;
        }
    }
    if (y != 0 && m != -1 && d != 0) {
        return (new Date(y, m, d, hr, min, 0));
    }
    y = 0; m = -1; d = 0;
    for (i = 0; i < a.length; ++i) {
        if (a[i].search(/[a-zA-Z]+/) != -1) {
            var t = -1;
            for (j = 0; j < 12; ++j) {
                if (Calendar._MN[j].substr(0, a[i].length).toLowerCase() == a[i].toLowerCase()) { t = j; break; }
            }
            if (t != -1) {
                if (m != -1) {
                    d = m+1;
                }
                m = t;
            }
        } else if (parseInt(a[i], 10) <= 12 && m == -1) {
            m = a[i]-1;
        } else if (parseInt(a[i], 10) > 31 && y == 0) {
            y = parseInt(a[i], 10);
            (y < 100) && (y += (y > 29) ? 1900 : 2000);
        } else if (d == 0) {
            d = a[i];
        }
    }
    if (y == 0) {
        var today = new Date();
        y = today.getFullYear();
    }
    if (m != -1 && d != 0) {
        return (new Date(y, m, d, hr, min, 0));
    }
};

function formatAsInt(num) {
	if(isNaN(num))
		num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	num = Math.floor(num/100).toString();
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
		num = num.substring(0,num.length-(4*i+3))+' '+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + num);
}

//*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_
//Debut fonctions pour selection dans listes
function changeSelected(check)
{
    if(check.checked)
    {
        nbSelected = nbSelected + 1;
        if(hidd = document.getElementById(check.value))
            mainForm.removeChild(hidd);
    }
    else
    {
        if(hidd = document.getElementById(check.value))
            mainForm.removeChild(hidd);
        
        nbSelected = nbSelected - 1;
    }
    setNbSelected(nbSelected);
}

function selectSearchChanged(box, allChecks)
{
    if(allChecks && typeof(allChecks.length) == 'undefined' )
    {
        allChecks.length = 1;
        allChecks[0] = allChecks;
    }
    for(i=0;allChecks && i<allChecks.length;i++)
    {
        if( box.checked)
        {
            allChecks[i].checked=true;
        }
        else
        {
            allChecks[i].checked=false;
        }
    }
}

function selectCurrentChanged(checked, allChecks)
{
    if(allChecks && typeof(allChecks.length) == 'undefined' )
    {
        allChecks.length = 1;
        allChecks[0] = allChecks;
    } 
    for(i=0;allChecks && i<allChecks.length;i++)
    {
           if( checked )
	        {
	            if(!allChecks[i].checked && allChecks[i].type == 'checkbox')
	            {
	                allChecks[i].checked=true;
	                nbSelected = nbSelected + 1;
	            }
	        }
	        else
	        {

	            if(allChecks[i].checked && allChecks[i].type == 'checkbox')
	            {
	                    
	                allChecks[i].checked=false;
	                 
	                nbSelected = nbSelected - 1;
                    hidd = document.getElementById(allChecks[i].value)
                    if(hidd)
                        mainForm.removeChild(hidd);
	            }
	        }
	        addSelectedFieldUnique(allChecks[i], allChecks[i].value);
    }
    setNbSelected(nbSelected);
}

function selectNone(allChecks)
{
    if(allChecks && typeof(allChecks.length) == 'undefined' )
    {
        allChecks.length = 1;
        allChecks[0] = allChecks;
    }
    for(i=0;allChecks && i<allChecks.length;i++)
    {

        if(allChecks[i].type == 'checkbox' && allChecks[i].checked)
        {
            allChecks[i].checked=false;
        }
        else if( allChecks[i].type != 'checkbox')
        {
            mainForm.removeChild(allChecks[i]);
            i--;
        }
    }
    setNbSelected(0);
}

function setNbSelected(value)
{
    try{
    if (typeof(value) != 'undefined')
    	nbSelected = value;
    document.getElementById('nbSelected').innerText = nbSelected;
    }catch(e){}
}
function formatAsMoney(mnt)
{

    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
                      // alert('formatAsMoney('+mnt+')');
//    return formatAsCurrency(mnt, lFmt,lGroupSep,lDecimalSep);
}
function formatAsCurrency(mnt, fmt, groupSep, decimalSep) 
{
try{
	mnt = (''+mnt).replace(',','');
	alert(mnt);
	mnt = mnt.replace('[^0-9\.\-]','');
		alert(mnt);
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    mnt = (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
    if( typeof(fmt) == 'undefined')
		return mnt;
    trimFmt = fmt.replace(/\'.*\'/g,'');
	groupSize = (trimFmt.indexOf('.')!=-1?trimFmt.indexOf('.'):0)- (trimFmt.indexOf(' ')!=-1?trimFmt.indexOf(' '):0) -1;
	if(groupSize <= 0) groupSize=3;	
	retVal='';
	stringMnt = ''+mnt;
	
	stringMnt = stringMnt.substring(0, stringMnt.indexOf('.'));
	for(i=0; i<stringMnt.length;i++)
	{
		if( i!=0 && ((stringMnt.length-i)%groupSize)==0 )
			retVal+=groupSep;
		retVal+= stringMnt.charAt(i);
	}

	prefix='';
	suffix='';
	j=0;
	if(fmt.charAt(j) == '\'')
	{	
		i=1;
		do{	prefix+=fmt.charAt(i++); }
		while( i < fmt.length && fmt.charAt(i)!='\'');
	}
	j=prefix.length+2;
	if(fmt.substring(j).indexOf('\'') != -1)
	{	
		i=fmt.substring(j).indexOf('\'')+1;
		do{	suffix+=fmt.substring(j).charAt(i++); }
		while(i < fmt.length && fmt.substring(j).charAt(i)!='\'');
	}
	stringMnt = ''+mnt;
	stringMnt = stringMnt.substring(stringMnt.indexOf('.')+1);
	return prefix + retVal + decimalSep + stringMnt + suffix;
}catch(exc){alert(exc.message);}
}
function checkString(tf) {
    var value = formatAsMoney(tf.value.replace(',', '.'));
    if(value)
        tf.value = value;
    else
        tf.value = '0.00';
}


function formatAsPourc(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*10000))/10000;
    var ret = (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
    return ret;
}
function checkPourc(tf) {
    var value = formatAsPourc(tf.value.replace(',', '.'));
    if(value)
        tf.value = value;
    else
        tf.value = '0.00';
}

function checkDouble(tf) {
    checkPourc(tf);
}
function checkNumber(tf,emptyIfZero) {
	mnt = tf.value.replace(',', '.');
	if(mnt)
	{
		mnt -= 0;
    	mnt = (Math.round(mnt*100))/100;
    }
    
    if(mnt)
    	tf.value = (emptyIfZero==true? (mnt>0?mnt:'') : mnt);
    else
        tf.value = (emptyIfZero==true? '':'0');
}
function checkInt(tf,emptyIfZero) {
	mnt = tf.value.replace(',', '.');
	if(mnt)
	{
		mnt -= 0;
    	mnt = (Math.round(mnt) - mnt >= mnt - Math.floor(mnt)?Math.round(mnt):Math.floor(mnt))
    }
    
    if(mnt)
    	tf.value = (emptyIfZero==true? (mnt>0?mnt:'') : mnt);
    else
        tf.value = (emptyIfZero==true? '':'0');
}
//Fin fonctions pour selection dans listes
//*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_*_

function hideSave()
{
	try
	{
		document.getElementById("pleaseWait").style.display = "block";
		document.getElementById("tableSubmit").disabled = true;
		document.getElementById("tableSubmit").style.display  = "none";
	}
	catch(e){}
}

function showSave()
{
	try
	{
		document.getElementById("pleaseWait").style.display = "none";
		document.getElementById("tableSubmit").disabled = false;
		document.getElementById("tableSubmit").style.display  = "block";
	}
	catch(e){}
}

