// langue
function _lg(s) {
	return ( $defined(i18n) && i18n[s]) ? i18n[s] : s;
}
function _lgNombre(n) {
	var i, o = '';
	n += '';
	for( i = n.length; i > 3; i -= 3) {
		o = i18n.thousands_sep + n.slice(i - 3, i) + o;
	}
	return n.slice(0, i) + o;
}
function sprintf(s) {
	var p, i, bits = s.split('%'),
		iCount = bits.length,
		out = bits[0];

	for( i = 1; i < iCount; i++) {
		p = /^([ds])(.*)$/.exec( bits[i]);
		if( ! p || arguments[i] === null) continue;
		switch( p[1]) {
			case 'd': out += parseInt(arguments[i], 10); break;
			case 's': out += arguments[i];
		}
		out += p[2];
	}
	return out;
}
function pluriel(s, p, n) { //ex: sprintf(pluriel( _lg("%s sungulier", _lg('%s pluriels"), iNb), _lgNombre(iNb))
	return Math.abs(n) > 1 ? p : s;
}
function constante( sCode, aParam) { // "Constante de langue" prédéfinie
	switch( sCode) {
		case 503 : return _lg( 'Site en cours de maintenance…');
		case 404 :
		case 'ajaxError' : return _lg( 'Une erreur est survenue :\n\nRafraichissez la page et essayer à nouveau.\nSi le problème persiste, contactez le webmaster.');
		case 401 :
		case 'ajaxIdentError' : return _lg( 'Votre session est terminée :\n\nRafraichissez la page et essayer à nouveau.\nSi le problème persiste, contactez le webmaster.');
		case 'datepicker' : return _lg( 'Choisissez une date');
		case 'formError' :
			return sprintf(
				pluriel(
					_lg( 'Erreur de saisie : %s erreur rencontrée lors de la validation du formulaire.'),
					_lg( 'Erreur de saisie : %s erreurs rencontrées lors de la validation du formulaire.'),
					aParam
				),
				_lgNombre( aParam)
			);
		default: return '[Erreur code: "' + sCode + '" inconnu.]';
	}
}
function format_decimal( s, sReplace) {
	return Number( /^٫|,$/i.test(i18n.decimal_sep) ? String(s).replace(i18n.decimal_sep, sReplace || '\.') : s); // \u066B
}

$.fn._lgDialogBouton = function() {
	return this.dialog('option', 'closeText', _lg('Fermer')).each( function() {
		$(this).dialog('widget').find('span.ui-button-text').each( function() {
			$(this).text( _lg( $(this).text()));
		});
	});
};

// Encode
function js_encode( s) { return new String(s).replace(/\\/g, '\\\\').replace(/"/g, '\&#34;').replace(/\'/g, '\&#39'); }
function url_encode( s) { return encodeURIComponent( s); }
function url_decode( s) { return decodeURIComponent( s); }
function html_encode( s) { return new String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '\&#34;'); }

// Chaine
function tronquer( s, iMax) {
	s = $.trim( s);
	return ( s.length > iMax) ? s.substr( 0, iMax / 2) + '[\u2026]' + Right(s, iMax / 2) : s;
}
function couper( s, iMax) {
	s = $.trim( s);
	return ( s.length > iMax) ? Left(s, iMax) + '[\u2026]' : s;
}
function Left( s, n) {
	return String(s).substring(0, n);
}
function Right( s, n) {
	var iLen = String(s).length;
	return String(s).substring(iLen, iLen - n);
}

function convert_poids_fichier( iPoidsOctet, iRound, sNorme) {
	iRound = Math.pow(10, $defined(iRound) ? iRound : 2);
	if( sNorme == 'SI') {
		var aPrefixe = ['octets', 'kio', 'Mio', 'Gio', 'Tio', 'Pio', 'Eio', 'Zio', 'Yio'],
			iFacteur = 1000;
	} else { // IEC
		var aPrefixe = ['octets', 'ko', 'Mo', 'Go', 'To', 'Po', 'Eo', 'Zo', 'Yo'];
			iFacteur = 1024;
	}
	for( var i = 0; iPoidsOctet >= iFacteur && $defined( aPrefixe[ i + 1]); i++) {
		iPoidsOctet /= iFacteur;
	}
	return new String( Math.round(iPoidsOctet * iRound) / iRound).replace(/\./, i18n.decimal_sep) + '&nbsp;' + aPrefixe[i];
}

//url rewriting
function format_urlrewriting(s, ucfirst) {
	s = s.toUpperCase();
	s = s.toLowerCase();

	var a = [ ['àáâãäå','a'], ['ç','c'], ['èéêë','e'], ['ìíîï','i'], ['òóôõöø','o'], ['ùúûü','u'], ['ýÿ','y'], ['ñ','n'], ['\u0153','oe'], ['æ','ae'], ['ß','ss'] ];
	for(var i = 0, iLen = a.length; i < iLen; i++) {
		s = s.replace(new RegExp('[' + a[i][0] + ']', 'g'), a[i][1]);
	}
	s = $.trim( s.replace(/[^a-z0-9_\s\'\:\/\[\]-]/g,''));
	s = s.replace(/[\s\'\:\/\[\]-]+/g,' ');
	s = s.replace(/[ ]/g,'-');

	return ucfirst ? s.charAt(0).toUpperCase() + s.slice(1) : s;
}

// Date
function date2timestamp( sFormat, sDate){ // dd/mm/yy hh.nn.ss
	var iPosD = sFormat.indexOf('d'),
		iPosM = sFormat.indexOf('m'),
		iPosY = sFormat.indexOf('y'),
		iPosH = sFormat.indexOf('h'),
		iPosMn = sFormat.indexOf('n'),
		iPosS = sFormat.indexOf('s'),
		d = sDate.substring( iPosD, iPosD + 2),
		m = sDate.substring( iPosM, iPosM + 2),
		y = sDate.substring( iPosY, iPosY + 4), // !YYYY
		h = sDate.substring( iPosH + 2, iPosH + 4),
		mn = sDate.substring( iPosMn + 2, iPosMn + 4),
		s = sDate.substring( iPosS + 2, iPosS + 4);
	return new Date( y, m, d, h, mn, s).getTime();
}

// syncho avec PHP
function format_html_id( s, sReplace) {
	var sR = sReplace || '';
	return s.replace(/^[^a-z_]+/i, sR).replace(/\W+/, sR);
}

// @see d_box_alert en php
function d_box_alert( options) {
	var o = $.extend({
		code: 'attention',
		text: '',
		id: 'box_alert',
		'attention': 'help-attention',
		'information': 'help-information',
		'critique': 'help-critique',
		'interrogation': 'help-interrogation',
		'formulaire-echec': 'help-form-echec',
		'formulaire-ok': 'help-form-ok'
	}, options);

	return '<div' + (o.id ? ' id="' + o.id + '"' : '') + ' class="helpBoxInfos-ON ' + ( o[o.code] || '') + '">' + o.text + '</div>';
}

// impression
function imprimer( oFrame) {
	if( window.print) {
		if( oFrame) {
			oFrame.focus();
			oFrame.print();
		} else {
			window.print();
		}
	} else {
		alert( _lg("Utilisez la commande d'impression de votre navigateur"));
	}
	return false;
}

function getEvent(e) { return e || window.event; }
function $defined(o) { return typeof o !== 'undefined'; }
function $is_true(t, v) { return $defined(t) ? t : v; }
function $id( s) { return document.getElementById(s) || null; }
function $redirect(sUrl, oWindow) {
	oWindow = oWindow || window;
	oWindow.location = ( sUrl || oWindow.location);
}
// mobile
function isAndroid() { return navigator.userAgent.indexOf('Android') >= 0 && navigator.userAgent.indexOf('Mobile') >= 0; }
function isIphone() { return navigator.userAgent.indexOf('iPod') >= 0 || navigator.userAgent.indexOf('iPhone') >= 0; }
function isTouch() { return ('ontouchstart' in window) || isIphone() || isAndroid() || navigator.userAgent.indexOf('Fennec') >= 0; }

function $insertCSS( url) {
	var sLink = '';
	url = $.isArray( url) ? url : [ url];

	$.each( url, function(i) {
		sLink += '<link rel="stylesheet" href="' + url[i] + '" />';
	});
	$('head').append( sLink);
}
function $insertScript(url) {
	var sScript = '';
	url = $.isArray( url) ? url : [ url];

	$.each( url, function(i) {
		sScript += '<script src="' + url[i] + '"></script>';
	});
	$('head').append( sScript);
}

// tableau
function ArrayDedoublonne(aOrigine) {
	var bDoublon, i, j, k = 0, aTab = [];
	for( i = 0, length = aOrigine.length; i < length; i++) {
		bDoublon = false;
		for(j = 0; j < k && !bDoublon; j++) {
			if(aOrigine[i] === aTab[j]) {
				bDoublon = true;
			}
		}
		if( ! bDoublon) {
			aTab[k++] = aOrigine[i];
		}
	}
	return aTab;
}
// recherche dichotomique si déjà trié sinon -> $.inArray
// bType (true = entier)
function ArrayRecherche_dicho(aOrigine, valeur, bType) {
	var trouve = -1, valTab, milieu = 0,
		debut = 0, // debut du tableau
		fin = aOrigine.length; // fin du tableau

	valeur = bType ? parseFloat(valeur) : valeur.toString();
	if( fin > 0) {
		while( trouve == -1) {
			milieu = Math.floor((debut + fin ) / 2);
			valTab = bType ? parseFloat(aOrigine[milieu]) : aOrigine[milieu].toString();
			if( valTab === valeur) {
				trouve = milieu;
			} else {
				if( fin - debut <= 1) {
					break;
				} else {
					if( valTab > valeur) {
						fin = milieu;
					} else {
						debut = milieu;
					}
				}
			}
		}
	}
	return trouve;
}
// pour trier des nombres (croissant) : tab.sort(compare_num)
// tab.sort() (croissant) pour des chaines
function trie_num_croissant(a, b) { return a - b; }
function trie_num_decroissant(a, b) { return b - a; }

function get_url_param( sUrl, sParam, bTous) {
	var aResults = new RegExp( "[\\?&]" + sParam.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]") + "=([^&#]*)").exec( sUrl);
	return $is_true(bTous, false) ? aResults : ( aResults === null ? null : aResults[1]);
}

// popup
var WindowPopupReference = null;
function popup(sURL, sNom, sOption, iW, iH, isCenter) {
//if(WindowPopupReference == null || WindowPopupReference.closed) {
	if( sOption == 'all=yes') {
		sOption = 'directories=1,location=1,menubar=1,resizable=1,scrollbars=1,status=1,toolbar=1';
	}
	sOption += ((sOption != '') ? ',' : '') + 'width=' + iW + ',height=' + iH;
	if( window.screen && isCenter) {
		sOption += ',left=' + ((screen.width - iW) / 2) + ',top=' + ((screen.height - iH) / 2);
	}
	WindowPopupReference = window.open(sURL, sNom, sOption);
	WindowPopupReference.focus();
/*} else {
	WindowPopupReference.focus();
}*/
}

function log( v) { (typeof console !== 'undefined' && console.log) && console.log( v); }
