///////////////////////////////////////////////////////////
//// Variables Générales //////////////////////////////////
///////////////////////////////////////////////////////////


///////////////////////////////////////////////////////////
//// Fonctions Générales //////////////////////////////////
///////////////////////////////////////////////////////////
function Today(){
	return DateToString(new Date());
}
///////////////////////////////////////////////////////////
//// Conversions //////////////////////////////////////////
///////////////////////////////////////////////////////////

function MySQLToDate(strDate){
		d = new Date();
		var day = strDate.substring(8,10);
		var month = strDate.substring(5,7);
		var year = strDate.substring(0,4);
		
		
		try{
			d.setDate(day);
			d.setMonth(month-1);
			d.setFullYear(year); 
		}catch (e){
			return e;
		}
		return d;  
}

function ConvertDateToMySQL(strDate){
	try{
		var reg = new RegExp("[/]+", "g");
		var ArrayDate = strDate.toString().split(reg);
		if(ArrayDate.length == 3){
			return ArrayDate[2]+"-"+ArrayDate[1]+"-"+ArrayDate[0];
		}else{
			return "0000-00-00"; 
		}
	}catch (e){ 
		return "0000-00-00"; 
	}
}

function DateToMySQL(oDate){
    var strDate;
    try{
            strDate = oDate.getFullYear() + "-" + FormatStringDate(oDate.getMonth()+1) + "-" + FormatStringDate(oDate.getDate()) + " " +
                      FormatStringDate(oDate.getHours()) + ":" + FormatStringDate(oDate.getMinutes()) + ":" + FormatStringDate(oDate.getSeconds());
            return strDate;
    }catch (e){
            return e;
    }
}

function DateToFr(strDate){
	if(strDate.toString().length > 0){
		var oDate = MySQLToDate(strDate);
		if(oDate.getMonth() != 0 && oDate.getFullYear() != 0){
			var resDate = FormatStringDate(oDate.getDate())+"/"+FormatStringDate(oDate.getMonth()+1)+"/"+oDate.getFullYear();	
			return resDate;
		}else{
			return "";
		}
	}else{
		return "";
	}
}

function stringToDate(strDate){
	if(strDate.toString().length > 0){
		d = new Date();
		
		if(strDate.toString().length >= 10){	// Format JJ/MM/AAAA
			var day = strDate.substring(0,2);
			var month = strDate.substring(3,5);
			var year = strDate.substring(6,10);
			
			try{
				d.setDate(day);
				d.setMonth(month-1);
				d.setFullYear(year); 
			}catch (e){
				return e;
			}
			  
		}
		if(strDate.toString().length > 10){	// Format JJ/MM/AAAA HH:MM
			var hour = strDate.substring(11,13);
			var minute = strDate.substring(14,16);
			
			try{
				d.setHours(parseInt(hour));
				d.setMinutes(minute);
			}catch (e){
				return e;
			}
		}
		
		return d;
	}else{
		return "";
	}
}

function DateToString(oDate){
	var strDate;
	try{
		strDate = FormatStringDate(oDate.getDate()) + "/" + FormatStringDate(oDate.getMonth()+1) + "/" + oDate.getFullYear()
		return strDate;
	}catch (e){
		return e;
	}
}

function DatetimeToString(oDate){
	var strDate;
	try{
		strDate = FormatStringDate(oDate.getDate()) + "/" + FormatStringDate(oDate.getMonth()+1) + "/" + oDate.getFullYear() + " " + FormatStringDate(oDate.getHours()) + ":" + FormatStringDate(oDate.getMinutes());
		return strDate;
	}catch (e){
		return e;
	}
}

function stringToMySql(strDate){
	var day = "", 
		month = "", 
		year = "", 
		hour = "", 
		minute = "",
		mySqlDate = "";
	if(strDate.toString().length > 0){
		
		if(strDate.toString().length >= 10){	// Format JJ-MM-AAAA
			day = strDate.substring(0,2);
			month = strDate.substring(3,5);
			year = strDate.substring(6,10);	  
			mySqlDate += year + "-" + month + "-" + day;
		}
		if(strDate.toString().length > 10){	// Format JJ-MM-AAAA HH:MM
			hour = strDate.substring(11,13);
			minute = strDate.substring(14,16);
			mySqlDate += " "+ hour + ":" + minute + ":00";
		}
		
		return mySqlDate;
	}else{
		return "";
	}
}

function mySqlToString(mySqlDate){
	var day = "", 
		month = "", 
		year = "", 
		hour = "", 
		minute = "",
		strDate = "";
	if(mySqlDate.toString().length > 0){
		
		if(mySqlDate.toString().length >= 10){	// Format JJ/MM/AAAA
			day = mySqlDate.substring(8,10);
			month = mySqlDate.substring(5,7);
			year = mySqlDate.substring(0,4);	  
			strDate += day + "/" + month + "/" + year;
		}
		if(mySqlDate.toString().length > 10){	// Format JJ/MM/AAAA HH:MM
			hour = mySqlDate.substring(11,13);
			minute = mySqlDate.substring(14,16);
			strDate += " "+ hour + ":" + minute;
		}
		
		return strDate;
	}else{
		return "";
	}
}

/**
 * comment function
 */
function getGMT() {
        var day;
        var Today = new Date();
        var gmtAdjust=-Today.getTimezoneOffset()/60;
        var lsm = new Date;
        var lso = new Date;
        lsm.setMonth(2); lsm.setDate(31); day = lsm.getDay(); lsm.setDate(31-day);
        lso.setMonth(9); lso.setDate(31); day = lso.getDay(); lso.setDate(31-day);
        if (Today < lsm || Today >= lso) gmtAdjust -= 1;
        return gmtAdjust;
}

// Formatte un object (ex : "1" => retourne "01")
function FormatStringDate(element){
	if(element.toString().length == 1){
		element = "0"+element;
	}
	return element;
}


///////// Contrôles /////////////////////////////////////////////////////////////////////////////////
function is_int(input){
    return parseInt(input, 10)==input;
}

///////// Méthodes Génériques ///////////////////////////////////////////////////////////////////////

///////////// String /////////////////////////////////
String.prototype.startsWith = function(str){ return (this.match("^"+str)==str); }
String.prototype.endsWith = function(str){ return (this.match(str+"$")==str); }
String.prototype.trim = function(){ return (this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, "")); }

//	Exemple utilisation : 
//	document.write( String.format( "two tokens, two args ({0},{1})<br />", "arg1", "arg2" ) );
String.format = function( text ){
    //check if there are two arguments in the arguments list
    if ( arguments.length <= 1 )
    {
        //if there are not 2 or more arguments there's nothing to replace
        //just return the original text
        return text;
    }
    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for( var token = 0; token <= tokenCount; token++ ){
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace( new RegExp( "\\{" + token + "\\}", "gi" ), arguments[ token + 1 ] );
    }
    return text;
};
///////////// Int ////////////////////////////////////
function CurrencyFormatted(amount)
{
	var i = parseFloat(amount);
	if(isNaN(i)) { i = 0.00; }
	var minus = '';
	if(i < 0) { minus = '-'; }
	i = Math.abs(i);
	i = parseInt((i + .005) * 100);
	i = i / 100;
	s = new String(i);
	if(s.indexOf('.') < 0) { s += '.00'; }
	if(s.indexOf('.') == (s.length - 2)) { s += '0'; }
	s = minus + s;
	return s;
}



///////////// Array //////////////////////////////////
/**
 * Suppression des doublons dans un Array
 * Utilisation : oArray = oArray.clearDoublon();
 */
Array.prototype.clearDoublon=function() {
	ArrayLength=this.length;
	var TempArray = new Array();
	TempArray=this;
	TempArray2=this
	var cleared=false
	
	for (i=0;i<ArrayLength;i++){ 
		for (j=0;j<TempArray.length;j++){ 	
			if(!cleared &&(i==j)){j++;}
			cleared=false;
			if(TempArray[i]==TempArray2[j]){
				TempArray2=middlepop(TempArray,j);
				TempArray=TempArray2;
				cleared=true;
				j--;
			}
		}
	}
	return TempArray;
}
function middlepop(Tab,a){
	return (a>Tab.length)?false:(Tab.slice(0,a).concat(Tab.slice(a+1,Tab.length)));
}

/**
 *Suppression d'un element dans un Array //
 *Utilisation : oArray.remove();
 */
Array.prototype.remove = function(p_val) {
	var toRemove = null;
	for(var i = 0, l = this.length; i < l; i++) {
		if(this[i] == p_val) { toRemove = { id: i, value: this[i] }; }
	}
	
	if (toRemove != null) {
		for (var i = toRemove.id; i < this.length; i++) {
		this[i] = this[i+1];
	}
	this.pop();
	return toRemove.value;
}

return null;
}

/// IE fix indexOf ////////
if(!Array.indexOf){
	Array.prototype.indexOf = function(obj){
		for(var i=0; i<this.length; i++){
		    if(this[i]==obj){
		        return i;
		    }
		}
		return -1;
	}
}
////////////////////////////////////////////////////////

function checkTest(test, message){
    if(!test){
        jAlert(message, "Erreur");
        return false;
    }
    return true;
}

function checkLength(o,n,min,max,divTips) {
	if ( o.val().length > max || o.val().length < min ) {
			o.addClass('ui-state-error');
			if(divTips != ""){
				updateTips(divTips, "Le nombre de caractères du champ '" + n + "' doit être compris entre "+min+" et "+max+".");
			} else {
				jAlert("Le nombre de caractères du champ '" + n + "' doit être compris entre "+min+" et "+max+".",'Erreur de saisie');
			}
			return false;
		} else {
			o.removeClass('ui-state-error');
			return true;
	}
}

function checkRegexp(o,regexp,n) {
	if(o.val() != ""){
		if ( !( regexp.test( o.val() ) ) ) {
			o.addClass('ui-state-error');
			jAlert(n,'Erreur de saisie');
			//updateTips(n);
			return false;
		} else {
			o.removeClass('ui-state-error');
			return true;
	}
}
return true;
}

function checkInt(o,n){
	if(o.val() != null){
		if ( o.val().length > 0 && o.val() != parseInt(o.val())){
			o.addClass('ui-state-error');
			jAlert("Le champs '" + n + "' doit contenir un nombre entier.","Erreur de saisie");
			return false;
		} else {
			o.removeClass('ui-state-error');
			return true;
		}
	} else {
		o.addClass('ui-state-error');
		return false;
	}
}

function checkNumber(o,n){
	if ( o.val().length > 0 ){
		for ( i = 0 ; i < o.val().length; i++){
			if( !is_int(o.val()[i]) ){
				o.addClass('ui-state-error');
				jAlert("Le champs '" + n + "' ne doit contenir que des chiffres.","Erreur de saisie");
				return false;
			}
		}
	}
	o.removeClass('ui-state-error');
	return true;
}

function checkDateFr(o,n){
	var regDate = new RegExp("[/]+", "g");
	if ( o.val().length > 0 ){
		var arrayDate = o.val().split(regDate);
		if(arrayDate.length != 3 || !is_int(arrayDate[0])  || !is_int(arrayDate[1]) || !is_int(arrayDate[2]) 
			|| arrayDate[0].length > 2 || arrayDate[1].length > 2 || arrayDate[2].length != 4 ){
			o.addClass('ui-state-error');
			jAlert("Erreur de saisie dans le champs '" + n + "'. eg 31/01/2001","Erreur de saisie");
			return false;
		}
	}
	o.removeClass('ui-state-error');
	return true;
}

function updateTips(tips, t) {
	$(tips).text(t).effect("highlight",{},1500);
}

////////////////////////////////////////////////////////////////////////////////////
//// Disable/Enable Element ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
/*
 * Désactive un élément
 */
function disable(element){
	$(element).attr("disabled", true);
}
/*
 * Active un élément
 */
function enable(element){
	$(element).removeAttr("disabled");
}
////////////////////////////////////////////////////////////////////////////////////
//// check/uncheck Element ////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////////
function check(element){
	$(element).attr("checked", true);
}

function uncheck(element){
	$(element).removeAttr("checked");
}

function addslashes (str) {
     return (str+'').replace(/([\\"'])/g, "\\$1").replace(/\u0000/g, "\\0");
}

function stripslashes (str) {
    return (str+'').replace(/\\(.?)/g, function (s, n1) {
        switch (n1) {
            case '\\':
                return '\\';
            case '0':
                return '\0';
            case '':
                return '';
            default:
                return n1;
        }
    });
}



function getCookieVal(offset) {
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1)
      		endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function GetCookie (name) {
	var arg=name+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen) {
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg)
                        return getCookieVal (j);
                i=document.cookie.indexOf(" ",i)+1;
                        if (i==0) break;}
	return null;
}

jQuery.fn.extend({
   findPosition : function() {
       Oobj = jQuery(this).get(0);
       var Ocurleft = Oobj.offsetLeft || 0;
       var Ocurtop = Oobj.offsetTop || 0;
       return {x:Ocurleft,y:Ocurtop};
   }
});

function Wait( seconde, callback ){
   setTimeout( function(){ callback }, seconde*1000);
}

function  printProps(obj, objName) {
  var output = "" ;
  for (var prop in obj) {
    output += objName + "." + prop + " = " + obj[prop] + "\n" ;
  }
  return output ;
}
