
window.targetUrlDomain = 'logistique';

/* fonction qui remplace la value en valeur vide du champ input text */
var ft = true;
function changeCouleurRecherche(champ) {
	if (champ.name == 'q') {
		if (champ.value == 'Actualités, investissements, fiches entreprise,...') champ.value = '';
		champ.className = 'focusRecherche';
	}
	else {
		champ.value = '';
		champ.className = 'focusRecherche';
	}
}
function testMotCle(champ, root) {
	if (champ.length == 0) {
		 return;
	}
	else {
		if (champ == 'Actualités, investissements, fiches entreprise,...') {
			return;
		}
		else {
			document.location.href = root + 'recherche=' + urlencode(champ);
		}
	}
}


var recHead = true;
function inputRechercheArticle(recherche) {
	if (recHead == true && recherche.value == 'Actualités, archives, fiches entreprise...') {
		recHead = false;
		recherche.value = '';
		recherche.className = 'focusRecherche';
	}
}


var rec404 = true;
function changeCouleurRecherche404(recherche) {
	if (rec404 == true && recherche.value == 'Actualités, archives, fiches entreprise...') {
		rec404 = false;
		recherche.value = '';
		recherche.className = 'focusRecherche';
	}
}


var moncompte = true;
function changeCouleurCompte(recherche) {
	if (moncompte == true && recherche.value == 'Email') {
		moncompte = false;
		recherche.value = '';
		recherche.className = 'champConnexionFocus';
	}
}


var moncomptemdp = true;
function changeCouleurCompteMdp(recherche) {
	if (moncomptemdp == true && recherche.value == 'Mot de passe') {
		moncomptemdp = false;
		recherche.value = '';
		recherche.className = 'champConnexionFocus';
	}
}

/* fonction de popup des outil des articles */
function montre(id) {
	var d = document.getElementById(id);
     for (var i = 1; i<=80; i++) {
          if (document.getElementById('popdiv'+i)) {document.getElementById('popdiv'+i).style.display='none';}
     }
	if (d) {d.style.display='block';}
}


function cite2(id) {
	// On recherche le div qui contient le texte
	var root = document.getElementById(id);
	var commentaire = document.getElementById('commentaire');
	if (!root || !commentaire) return false;
	var list = root.getElementsByTagName('p');
	if (!list.length) return false;
	if (list[1].className != 'vosReactionTexte') return false;
	if (commentaire.value.charAt(commentaire.value.lenght-1) != "\n")
		commentaire.value += "\n";
	commentaire.value += '"'+list[1].innerHTML.replace(/<br[^>]*>/ig, "\n")+'"'+"\n";
	commentaire.focus();
	return true;
}



function outilReseau(id){
	if (document.getElementById(id).className == "visible"){
		document.getElementById(id).className = "invisible";
		var disp = document.getElementById('envoyer_page_message');
		if (disp) disp.style.display = '';
		var hide = document.getElementById('envoyer_page_error');
		if (hide) hide.style.display = 'none';
	}
	else {
		document.getElementById(id).className = "visible";
	}
}


function correctPNG() // correctly handle PNG transparency in Win IE 5.5 & 6.
{
   var arVersion = navigator.appVersion.split("MSIE")
   var version = parseFloat(arVersion[1])
   if ((version >= 5.5) && (document.body.filters)) 
   {
      for(var i=0; i<document.images.length; i++)
      {
         var img = document.images[i]
         var imgName = img.src.toUpperCase()
         if (imgName.substring(imgName.length-3, imgName.length) == "PNG")
         {
            var imgID = (img.id) ? "id='" + img.id + "' " : ""
            var imgClass = (img.className) ? "class='" + img.className + "' " : ""
            var imgTitle = (img.title) ? "title='" + img.title + "' " : "title='" + img.alt + "' "
            var imgStyle = "display:inline-block;" + img.style.cssText 
            if (img.align == "left") imgStyle = "float:left;" + imgStyle
            if (img.align == "right") imgStyle = "float:right;" + imgStyle
            if (img.parentElement.href) imgStyle = "cursor:hand;" + imgStyle
            var strNewHTML = "<span " + imgID + imgClass + imgTitle
            + " style=\"" + "width:" + img.width + "px; height:" + img.height + "px;" + imgStyle + ";"
            + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
            + "(src=\'" + img.src + "\', sizingMethod='scale');\"></span>" 
            img.outerHTML = strNewHTML
            i = i-1
         }
      }
   }    
}


function closeTimer(){   //Timer de 5 secondes (5000 milisecondes)
   timeoutID = setTimeout("document.getElementById('envoieArticleReaction').className='invisible'",5000);
}


function closeTimer2(){   //Timer de 5 secondes (5000 milisecondes)
   timeoutID = setTimeout("document.getElementById('envoieArticleReaction2').className='invisible'",5000);
}

function urlencode(str) {

	var reg1 = / & /g;
	var reg2 = / /g;
	
    return (str.replace(reg1, '+').replace(reg2, '+'));
}





//Bloc regions de la colonne de droite
function gotonewpage(what) {
	value = what.options[what.selectedIndex].value;
	if (value == "") return;
	  window.location.href = value;
	}


/**
* Espace de nom pour stocker les différents méthodes pour ne pas poluer window
*/
Utile = {
	
	/**
	 * Renvoi un UID aléatoire et unique
	 * @return string
	 */
	randomUID: function() {
		 return (Math.random()*Math.pow(10, 16)).toString().replace(/^([\.])+.*$/, '$1')+'_'+(new Date().valueOf());
	},
	
	/**
	 * Décode et renvoi un objet contenant les paramètres JS stockées dans la balise params d'un noeud
	 * @param Element element Le noeud Element d'où extraire les paramètres
	 * @param Object toExtend Un eventuel objet a étendre
	 * @return Object
	 */
	getParams: function(element, toExtend) {
		var paramString  = element.getAttribute('params');
		var returnObject = toExtend || {};
		if (paramString == null) return returnObject;
		
		try { eval('var params = {'+paramString+'}'); }
		catch (e) { var params = {}; }

		return jQuery.extend(returnObject, params);
	},
	
	/**
	 * Converti une date jj/mm/aaaa vers sont format ISO.
	 */
	frDateToISODate: function(string, asDate) {
		var ISODateText = string.slice(3, 5)+'/'+string.slice(0, 2)+'/'+string.slice(6);
		return asDate ? new Date(Date.parse(ISODateText)) : ISODateText;
	},
	
	/**
	 * Converti une date mm/jj/aaaa vers sont format ISO.
	 */
	enDateToISODate: function(string, asDate) {
		var ISODateText = string.slice(0, 2)+'/'+string.slice(3, 5)+'/'+string.slice(6);
		return asDate ? new Date(Date.parse(ISODateText)) : ISODateText;
	},
	
	/**
	 * Fonction date comme ne php. 
	 * @param format
	 * @param timestamp
	 * @return string
	 * From PHPJS
	 */
	date: function(format, timestamp) {
	    var that = this;
	    var jsdate=((typeof(timestamp) == 'undefined') ? new Date() : (typeof(timestamp) == 'number') ? new Date(timestamp*1000) : new Date(timestamp));
	    var pad = function (n, c){if ( (n = n + "").length < c )return new Array(++c - n.length).join("0") + n;else return n;};
	    var _dst = function (t) {var dst=0;var jan1 = new Date(t.getFullYear(), 0, 1, 0, 0, 0, 0);var june1 = new Date(t.getFullYear(), 6, 1, 0, 0, 0, 0);var temp = jan1.toUTCString();var jan2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));temp = june1.toUTCString();var june2 = new Date(temp.slice(0, temp.lastIndexOf(' ')-1));var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);if (std_time_offset === daylight_time_offset) dst = 0;else {var hemisphere = std_time_offset - daylight_time_offset;if (hemisphere >= 0) std_time_offset = daylight_time_offset;dst = 1;};return dst;};
	    var ret = '';
	    var txt_weekdays = ["Dimanche","Lundi","Mardi","Mercredi","Jeudi","Vendredi","Samedi"];
	    var txt_ordin = {1:"er",2:"me",3:"me",21:"",22:"",23:"",31:""};
	    var txt_months =  ["", "Janvier", "Fevrier", "Mars", "Avril","Mai", "Juin", "Juillet", "Aout", "Septembre", "Octobre", "Novembre","Decembre"];
	    var f = {d: function (){return pad(f.j(), 2);},D: function (){var t = f.l();return t.substr(0,3);},j: function (){return jsdate.getDate();},l: function (){return txt_weekdays[f.w()];},N: function (){return f.w() + 1;},S: function (){return txt_ordin[f.j()] ? txt_ordin[f.j()] : 'th';},w: function (){return jsdate.getDay();},z: function (){return (jsdate - new Date(jsdate.getFullYear() + "/1/1")) / 864e5 >> 0;},W: function (){var a = f.z(), b = 364 + f.L() - a;var nd2, nd = (new Date(jsdate.getFullYear() + "/1/1").getDay() || 7) - 1;if (b <= 2 && ((jsdate.getDay() || 7) - 1) <= 2 - b){return 1;}if (a <= 2 && nd >= 4 && a >= (6 - nd)){nd2 = new Date(jsdate.getFullYear() - 1 + "/12/31");return that.date("W", Math.round(nd2.getTime()/1000));};return (1 + (nd <= 3 ? ((a + nd) / 7) : (a - (7 - nd)) / 7) >> 0);},F: function (){return txt_months[f.n()];},m: function (){return pad(f.n(), 2);},M: function (){var t = f.F();return t.substr(0,3);},n: function (){return jsdate.getMonth() + 1;},t: function (){var n;if ( (n = jsdate.getMonth() + 1) == 2 ){return 28 + f.L();};if ( n & 1 && n < 8 || !(n & 1) && n > 7 ){return 31;};return 30;},L: function (){var y = f.Y();return (!(y & 3) && (y % 1e2 || !(y % 4e2))) ? 1 : 0;},o: function (){if (f.n() === 12 && f.W() === 1) {return jsdate.getFullYear()+1;}if (f.n() === 1 && f.W() >= 52) {return jsdate.getFullYear()-1;};return jsdate.getFullYear();},Y: function (){return jsdate.getFullYear();},y: function (){return (jsdate.getFullYear() + "").slice(2);},a: function (){return jsdate.getHours() > 11 ? "pm" : "am";},A: function (){return f.a().toUpperCase();},B: function (){var off=(jsdate.getTimezoneOffset()+60)*60;var theSeconds=(jsdate.getHours()*3600)+(jsdate.getMinutes()*60)+jsdate.getSeconds()+off;var beat=Math.floor(theSeconds/86.4);if(beat>1000){beat-=1000;};if(beat<0){beat+=1000;};if((String(beat)).length==1){beat="00"+beat;};if((String(beat)).length==2){beat="0"+beat;};return beat;},g: function (){return jsdate.getHours() % 12 || 12;},G: function (){return jsdate.getHours();},h: function (){return pad(f.g(), 2);},H: function (){return pad(jsdate.getHours(), 2);},i: function (){return pad(jsdate.getMinutes(), 2);},s: function (){return pad(jsdate.getSeconds(), 2);},u: function (){return pad(jsdate.getMilliseconds()*1000, 6);},e: function () {return 'UTC';},I: function (){return _dst(jsdate);},O: function (){var t = pad(Math.abs(jsdate.getTimezoneOffset()/60*100), 4);t = (jsdate.getTimezoneOffset() > 0) ? "-"+t : "+"+t;return t;},P: function (){var O = f.O();return (O.substr(0, 3) + ":" + O.substr(3, 2));},T: function () {return 'UTC';},Z: function (){return -jsdate.getTimezoneOffset()*60;},c: function (){return f.Y() + "-" + f.m() + "-" + f.d() + "T" + f.h() + ":" + f.i() + ":" + f.s() + f.P();},r: function (){return f.D()+', '+f.d()+' '+f.M()+' '+f.Y()+' '+f.H()+':'+f.i()+':'+f.s()+' '+f.O();},U: function (){return Math.round(jsdate.getTime()/1000);}};
	    return format.replace(/[\\]?([a-zA-Z])/g, function (t, s){
	        if ( t!=s ){ret = s;} else if (f[s]){ret = f[s]();} else {ret = s;}
	        return ret;
	    });
	},
	
	/**
	 * Gère le redimensionnement automatique des dialogues
	 */
	dialogResize: function(body) {
		
		var jBody 		= jQuery(body),
			jBodyChilds = jBody.children(),
			options     = body.options;
		
		
		if (options.autoWidth || options.autoHeight) {
			
			var width  = body.preCalculedWidth  || -1,
				height = body.preCalculedHeight || -1,
				windowInnerWidth  = window.innerWidth  || document.documentElement.clientWidth,
				windowInnerHeight = window.innerHeight || document.documentElement.clientHeight,
				windowScrollTop   = jQuery(window).scrollTop(),
				windowScrollLeft  = jQuery(window).scrollLeft();
			
			if (width == -1 | height == -1) {
				jBodyChilds.each(function() {
					var jThis = jQuery(this);
					var position = jThis.position();
					width  = Math.max(width,  jThis.width()  + position.left);
					height = Math.max(height, jThis.height() + position.top);
				});
				body.preCalculedWidth  = width;
				body.preCalculedHeight = height;
			}
			
			if (options['maxWidth'])
				width  = Math.min(width, options.maxWidth);
			if (options['maxHeight'])
				height = Math.min(height, options.maxHeight);
			
			if (options['minWidth'])
				width  = Math.max(width, options.minWidth);
			if (options['minHeight'])
				height = Math.max(height, options.minHeight);
			
			// Pas plus grand que la fenêtre elle même , moins 20 pixels autours (20 à gauche et 20 à droite => 40)
			width  = Math.min(windowInnerWidth  - 40, width);
			height = Math.min(windowInnerHeight - 40, height);
			
			var left = (windowInnerWidth  - width)  / 2;
			var top  = (windowInnerHeight - height) / 2;
			if (width)  {
				body.parentNode.style.width  = width+'px';
				body.parentNode.style.left   =  (left + windowScrollLeft)+'px';
				if (jBodyChilds.length == 1) {
					jBodyChilds.get(0).style.width  = width+'px';
				}
			}
			
			if (height) {
				body.parentNode.style.height = height+'px';
				body.parentNode.style.top    = (top + windowScrollTop)+'px';
				if (jBodyChilds.length == 1) {
					jBodyChilds.get(0).style.height     = height+'px';
					jBodyChilds.get(0).dialogAutoHeight = true;
				}
			}
		}
	},
	
	getDocumentHeight: function() {
	    var D = document;
	    return Math.max(
	        Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
	        Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
	        Math.max(D.body.clientHeight, D.documentElement.clientHeight)
	    );
	},
	
	getDocumentWidth: function() {
		var D = document;
		return Math.max(
				Math.max(D.body.scrollWidth, D.documentElement.scrollWidth),
				Math.max(D.body.offsetWidth, D.documentElement.offsetWidth),
				Math.max(D.body.clientWidth, D.documentElement.clientWidth)
		);
	},
	
	// Converti une url en objet
	deserialize: function(url) {
		
		var data = {};
		var chunks = String(url).split('&');
		for (var i = 0; i < chunks.length; i++) {
			var pair = chunks[i].split('=');
			data[pair[0]] = (pair.length == 2) ? pair[1] : null;
		}
		return data;
		
	},
	
	// Récupère la position du curseur dans un textarea
	// Affecte les propriétées du textarea pour qu'il soit compatible avec les méthodes W3C
	parseTextareaCaretPosition: function(oTextarea) {
		var docObj = oTextarea.ownerDocument;
		var result = {start:0, end:0, caret:0};
		
		if (navigator.appVersion.indexOf("MSIE")!=-1) {
			if (oTextarea.tagName.toLowerCase() == "textarea") {
				if (oTextarea.value.charCodeAt(oTextarea.value.length-1) < 14) {
					oTextarea.value=oTextarea.value.replace(/34/g,'')+String.fromCharCode(28);
				}
				var oRng = docObj.selection.createRange();
				var oRng2 = oRng.duplicate();
				oRng2.moveToElementText(oTextarea);
				oRng2.setEndPoint('StartToEnd', oRng);
				result.end = oTextarea.value.length-oRng2.text.length;
				oRng2.setEndPoint('StartToStart', oRng);
				result.start = oTextarea.value.length-oRng2.text.length; 
				result.caret = result.end;
				if (oTextarea.value.substr(oTextarea.value.length-1) == String.fromCharCode(28)) {
					oTextarea.value = oTextarea.value.substr(0, oTextarea.value.length-1);
				}			
			} else {
				var range = docObj.selection.createRange();
				var r2 = range.duplicate();			
				result.start = 0 - r2.moveStart('character', -100000);
				result.end = result.start + range.text.length;	
				result.caret = result.end;
			}			
		} else {
			result.start = oTextarea.selectionStart;
	    	result.end   = oTextarea.selectionEnd;
			result.caret = result.end;
		}
		if (result.start < 0) {
			 result = {start:0, end:0, caret:0};
		}
		oTextarea.selectionStart = result.start;
		oTextarea.selectionEnd   = result.end;
		return result;
	},
	
	fullScreenModalAjax: function(display) {
		var modalDiv = document.getElementById('fullScreenModalAjax_div');
		if (!modalDiv) {
			modalDiv = document.createElement('DIV');
			modalDiv.id = 'fullScreenModalAjax_div';
			modalDiv.className = 'fullScreenModalAjax';
			modalDiv.display = 'none';
			modalDiv.style.position =  "absolute";
			modalDiv.style.top  = 0;
			modalDiv.style.left = 0;
			document.body.appendChild(modalDiv);
			jQuery(window).resize(function() {
				modalDiv.style.height  = Utile.getDocumentHeight()+"px";
				modalDiv.style.width   = Utile.getDocumentWidth()+"px";
			});
		}
		
		if (display) {
			modalDiv.style.zIndex  = 5000;
			modalDiv.style.display = '';
		}
		else {
			modalDiv.style.display = 'none';
		}
	},
	
	parseHTTPHeaders: function(string) {
		// Parse HTTP Headers as returned by the server
		var headerLines = string.split("\n"),
			headers = {};
		for (var i = 0; i < headerLines.length; i++) {
			var name = String(headerLines[i]).replace(/^([^:]+):.*$/, '$1');
			if (name == '') continue;
			headers[name] = headerLines[i].replace(/^[^:]+: ?(.*)$/, '$1').replace("\r", "");
		}
		return headers;
	},
	
	// From PHPJS
	htmlEntitiesDecode: function (string, quote_style) {
		var hash_map = {}, symbol = '', tmp_str = '', entity = '', tmp_str = string.toString();
	    if (false === (hash_map = Utile.getHtmlTranslationTable('HTML_ENTITIES', quote_style))) return false;
	    for (symbol in hash_map) { entity = hash_map[symbol]; tmp_str = tmp_str.split(entity).join(symbol); }
	    tmp_str = tmp_str.split('&#039;').join("'");
	    return tmp_str;
	},
	
	// From PHPJS
	getHtmlTranslationTable: function(table, quote_style) {
		var entities={},hash_map={},decimal=0,symbol='',constMappingTable={},constMappingQuoteStyle={},useTable={},useQuoteStyle={};
		constMappingTable={0:'HTML_SPECIALCHARS',1:'HTML_ENTITIES'};
		constMappingQuoteStyle={0:'ENT_NOQUOTES',2:'ENT_COMPAT',3:'ENT_QUOTES'};
		useTable=!isNaN(table)?constMappingTable[table]:table?table.toUpperCase():'HTML_SPECIALCHARS';
		useQuoteStyle=!isNaN(quote_style)?constMappingQuoteStyle[quote_style]:quote_style?quote_style.toUpperCase():'ENT_COMPAT';
	    if(useTable!=='HTML_SPECIALCHARS'&&useTable!=='HTML_ENTITIES')throw new Error("Table: "+useTable+' not supported');
		if(useTable==='HTML_ENTITIES')entities={38:'&amp;',60:'&lt;',62:'&gt;',160:'&nbsp;',161:'&iexcl;',162:'&cent;',163:'&pound;',164:'&curren;',165:'&yen;',166:'&brvbar;',167:'&sect;',168:'&uml;',169:'&copy;',170:'&ordf;',171:'&laquo;',172:'&not;',173:'&shy;',174:'&reg;',175:'&macr;',176:'&deg;',177:'&plusmn;',178:'&sup2;',179:'&sup3;',180:'&acute;',181:'&micro;',182:'&para;',183:'&middot;',184:'&cedil;',185:'&sup1;',186:'&ordm;',187:'&raquo;',188:'&frac14;',189:'&frac12;',190:'&frac34;',191:'&iquest;',192:'&Agrave;',193:'&Aacute;',194:'&Acirc;',195:'&Atilde;',196:'&Auml;',197:'&Aring;',198:'&AElig;',199:'&Ccedil;',200:'&Egrave;',201:'&Eacute;',202:'&Ecirc;',203:'&Euml;',204:'&Igrave;',205:'&Iacute;',206:'&Icirc;',207:'&Iuml;',208:'&ETH;',209:'&Ntilde;',210:'&Ograve;',211:'&Oacute;',212:'&Ocirc;',213:'&Otilde;',214:'&Ouml;',215:'&times;',216:'&Oslash;',217:'&Ugrave;',218:'&Uacute;',219:'&Ucirc;',220:'&Uuml;',221:'&Yacute;',222:'&THORN;',223:'&szlig;',224:'&agrave;',225:'&aacute;',226:'&acirc;',227:'&atilde;',228:'&auml;',229:'&aring;',230:'&aelig;',231:'&ccedil;',232:'&egrave;',233:'&eacute;',234:'&ecirc;',235:'&euml;',236:'&igrave;',237:'&iacute;',238:'&icirc;',239:'&iuml;',240:'&eth;',241:'&ntilde;',242:'&ograve;',243:'&oacute;',244:'&ocirc;',245:'&otilde;',246:'&ouml;',247:'&divide;',248:'&oslash;',249:'&ugrave;',250:'&uacute;',251:'&ucirc;',252:'&uuml;',253:'&yacute;',254:'&thorn;',255:'&yuml;'}
	    if(useQuoteStyle!=='ENT_NOQUOTES')entities['34']='&quot;';
		if(useQuoteStyle==='ENT_QUOTES')entities['39']='&#39;';
		for(decimal in entities){symbol=String.fromCharCode(decimal);hash_map[symbol]=entities[decimal];}
		return hash_map;
	},
	
	// From PHPJS
	sprintf: function ( ) {var j=arguments,m=0,n=function(b,a,e,c){e||(e=" ");a=b.length>=a?"":Array(1+a-b.length>>>0).join(e);return c?b+a:a+b},o=function(b,a,e,c,f,d){var g=c-b.length;if(g>0)b=e||!f?n(b,c,d,e):b.slice(0,a.length)+n("",g,"0",true)+b.slice(a.length);return b},l=function(b,a,e,c,f,d,g){b=b>>>0;e=e&&b&&{"2":"0b","8":"0","16":"0x"}[a]||"";b=e+n(b.toString(a),d||0,"0",false);return o(b,e,c,f,g)},q=function(b,a,e,c,f,d){if(c!=null)b=b.slice(0,c);return o(b,"",a,e,f,d)};return j[m++].replace(/%%|%(\d+\$)?([-+\'#0 ]*)(\*\d+\$|\*|\d+)?(\.(\*\d+\$|\*|\d+))?([scboxXuidfegEG])/g, function(b,a,e,c,f,d,g){var h;if(b=="%%")return"%";f=false;h="";for(var i=false,k=false,r=" ",s=e.length,p=0;e&&p<s;p++)switch(e.charAt(p)){case " ":h=" ";break;case "+":h="+";break;case "-":f=true;break;case "'":r=e.charAt(p+1);break;case "0":i=true;break;case "#":k=true;break}c=c?c=="*"?+j[m++]:c.charAt(0)=="*"?+j[c.slice(1,-1)]:+c:0;if(c<0){c=-c;f=true}if(!isFinite(c))throw new Error("sprintf: (minimum-)width must be finite");d=d?d=="*"?+j[m++]:d.charAt(0)=="*"?+j[d.slice(1,-1)]:+d:"fFeE".indexOf(g)> -1?6:g=="d"?0:undefined;a=a?j[a.slice(0,-1)]:j[m++];switch(g){case "s":return q(String(a),f,c,d,i,r);case "c":return q(String.fromCharCode(+a),f,c,d,i);case "b":return l(a,2,k,f,c,d,i);case "o":return l(a,8,k,f,c,d,i);case "x":return l(a,16,k,f,c,d,i);case "X":return l(a,16,k,f,c,d,i).toUpperCase();case "u":return l(a,10,k,f,c,d,i);case "i":case "d":b=parseInt(+a,10);h=b<0?"-":h;a=h+n(String(Math.abs(b)),d,"0",false);return o(a,h,f,c,i);case "e":case "E":case "f":case "F":case "g":case "G":b=+a;h= b<0?"-":h;a=["toExponential","toFixed","toPrecision"]["efg".indexOf(g.toLowerCase())];g=["toString","toUpperCase"]["eEfFgG".indexOf(g)%2];a=h+Math.abs(b)[a](d);return o(a,h,f,c,i)[g]();default:return b}})}

}

/**
* @return DOMElement Le conteneur des donnée
*/
jqPopup = function(elem, url, data, callback, options) {
	
	// Création de la div en utilisant DOM car un lag existe dans la synchro
	var body  = document.createElement("div"),
		jBody = jQuery(body);
	
	// Traitement des options
	if (!options) options = {};
	var jqThis = jQuery(elem),
		params = Utile.getParams(elem, {popupFrame: false, popupReloadOnClose: false});
	jQuery.extend(params, options);
	var options = {
			draggable:   params.popupDraggable   || false,
			modal:       params.popupModal       || true,
			autoOpen:    params.popupAutoOpen    || true,
			position:    params.popupPosition    || 'center',
			autoHeight:  params.popupAutoHeight  || params.popupAutoResize || false,
			autoWidth:   params.popupAutoWidth   || params.popupAutoResize || false,
			dialogClass: params.popupDialogClass || 'jqDialogSimple',
			close: function(event, ui) {
				jQuery(elem).dialog("destroy");
				var parentNode = body.parentNode;
				parentNode.removeChild(body);
				parentNode.parentNode.removeChild(parentNode);
			},
			open: function(dialogEvent) {
				jQuery(".ui-widget-overlay").click(function() {
					jQuery(dialogEvent.target).dialog("close");
					if (params.popupReloadOnClose) window.location = window.location;
				});
			}
	};
	if (params['popupWidth'])  options.width  = params.popupWidth;
	if (params['popupHeight']) options.height = params.popupHeight;

	body.options = options;
	
	var tmpDivId = (elem.id || Utile.randomUID()) + '_popup',
		tmpDivFrameId = tmpDivId + '_ifrm';
	
	body.id = '#'+tmpDivId;
	
	if (!url && elem.nodeName == 'A') {
		url = elem.href.replace('#', ' #');
	}
	
	if (!data) data = null;
	
	// La gestion du cache ... SOB ...
	var randVal = Math.random();
	url += '&rnd=' + randVal;
	
	if (params.popupFrame) {
		// Impossible de charger par POST. On envoi les données par GET
		if (data) {
			var serializedData = jQuery.param(data);
			url += url.search(/\?/) === false ? '?' : '&';
			url += serializedData;
		}
		
		jBody.append('<iframe src="'+url+'" style="width:100%;height:100%;border:0;padding:0;margin:0" id="'+tmpDivFrameId+'"></iframe>');
		document.body.appendChild(body);
		jBody.dialog(options);
		
	}
	else {
		if (!data) data = {};
		data.fromJs = true;
		
		if (!jQuery.isFunction(callback)) callback = function(responseText, textStatus, XMLHttpRequest) {
			if (Utile) Utile.dialogResize(body);
			if (jQuery.behaviors) jQuery.behaviors.apply(body);
		}
		jBody.append('<div style="height:100%;background: white url(\'/images/loading.gif\') no-repeat center center">&nbsp;</div>');
		
		jBody.dialog(options).load(url, data, callback);
	}
	
	// Dans le cas d'un redimensionnement de fenêtre
	jQuery(window).resize(function() {
		Utile.dialogResize(body);
	});
	
	return body;
	
}

jQuery.behaviors = (function() {
	var behaviors = [];
	return {
		register: function(behavior) { if (typeof behavior == 'function') behaviors.push(behavior); },
		apply:    function(node) {
			if (!node) node = document.body;
			for (var i = 0, iMax = behaviors.length; i < iMax; i++) behaviors[i](node);
		}
	}
})();
jQuery(function() { jQuery.behaviors.apply(); });

jqPopupReplace = function(event) {
	
	var target	= event.target,
		data	= null,
		url		= null,
		method  = 'GET';
	
	// On recherche la div qui contient les données
	var jBody = jQuery(target).parents('.ui-dialog-content.ui-widget-content');
	if (!jBody) return true;
	var body  = jBody.get(0);
	
	if (target.nodeName == 'FORM') {
		var form  = target,
			jForm = jQuery(target),
			formMethod = form.method.toUpperCase();
		
		data  = jForm.serialize();
		data += (data == '' ? '' : '&')+'fromJs=1';
		url   = form.action ;
		if (formMethod == 'POST') {
			data = Utile.deserialize(data);
		}
		else {
			url += (/\?/.test(url) ? '&' : '?') + data;
		}
	}
	else if (target.nodeName == 'A') {
		url = target.href;
	}
	var randVal = Math.random();
	url += '&rnd=' + randVal;

	jQuery.ajax({
		url: url,
		data: data,
		async: true,
		cache: false,
		type: 'POST',
		success: function(data, textStatus) {
			body.innerHTML = data;
			if (Utile) Utile.dialogResize(body);
			if (jQuery.behaviors) jQuery.behaviors.apply(body);		
		},
		complete: function (XMLHttpRequest, textStatus) {
			var headers = Utile.parseHTTPHeaders(XMLHttpRequest.getAllResponseHeaders());
			if (headers['X-REDIRECT']) {
				window.location.href = headers['X-REDIRECT'];
			}
		}
	});
	
	event.stopPropagation();
	return false; 
	
}

window.App = window['App'] || {};
App.Messages = App['Messages'] || {};
App.Dispatch = App.Dispatch || {};


window.App.Cookie = {
	set: function (name, value, days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days * 24 * 3600000));
			var expires = "; expires=" + date.toGMTString();
		}
		else var expires = "";
		document.cookie = name + "=" + value + expires + "; path=/";
	},
	
	get: function (name) {
		var ca = document.cookie.split(';'), c = '';
		name += "=";
		for (var i = 0; i < ca.length; i++) {
			c = ca[i];
			while (c.charAt(0) == ' ') c = c.substring(1, c.length);
			if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
		}
		return null;
	},
	
	unset: function(name) {
		App.Cookie.set(name, "", -1);
	}	
}

window.App.getText = function() {
	if (!arguments.length) return;
	var args = arguments, lang = App['lang'] || 'fr';
	if (!App['Messages']) return args[0];
	if (!App.Messages[lang]) return args[0];
	if (!App.Messages[lang][args[0]]) return args[0];
	args[0] = App.Messages[lang][args[0]];
	return Utile.sprintf.apply(this, args);
}
window.App.trad = window.App.getText;

jQuery(document).ready(function() {
	
	// Gestion des popup depuis un lien
	jQuery("a.jqPopup").click(function(event) {
		jqPopup(event.currentTarget,jQuery(this).attr('href'));
		event.stopPropagation();
		return false;
	});
	
	// onglets
	jQuery(".jq_tabs_container").each(function(){
		jQuery(this).find(".jq_panel").hide();
		if ( jQuery(this).find(".jq_tabs > li.active a").length !== 0 ) {
			// on affiche le contenu de l'onglet actif
			jQuery(this).find(jQuery(this).find(".jq_tabs > li.active a").attr("href")).show();
		}
		else {
			// on affiche le contenu du premier onglet
			jQuery(this).find(jQuery(this).find(".jq_tabs > li:first a").attr("href")).show();
			jQuery(this).find(".jq_tabs > li:first").addClass("active");
		};
	});
	
	jQuery(".jq_tabs > li a").click(function() {
		if (jQuery(this).attr("href") != "#") {
			var tabs_container = jQuery(this).closest(".jq_tabs_container");
			tabs_container.find(".jq_panel").hide();
			tabs_container.find(jQuery(this).attr("href")).show();
			tabs_container.find(".jq_tabs > li").removeClass("active");
			jQuery(this).parent("li").addClass("active");
		}
		return(false);
	});
});


