// plugin jQuery
$.fn.initClass = function( sNewClass) {
	return this.each(function() {
		$(this).removeClass().addClass( sNewClass);
	});
};
$.fn.replaceClass = function( sOldClass, sNewClass) {
	return this.each(function() {
		$(this).removeClass( sOldClass).addClass( sNewClass);
	});
};
$.fn.check = function(opt) {
	return this.each(function() {
		this.checked = (opt == 'toggle') ? !this.checked : $is_true(opt, true);
	});
};
$.fn.visible = function() {
	return this.each(function() {
		$(this).css({ visibility: 'visible' });
	});
};
$.fn.hidden = function() {
	return this.each(function() {
		$(this).css({ visibility: 'hidden' });
	});
};
$.fn.toShow = function( b) {
	var fct = $is_true(b, false) ? 'show' : 'hide';
	return this.each(function() {
		$(this)[fct]();
	});
};
$.fn.collisionfenetre = function(e) {
	var d = document, db = d.body;

	return this.each( function() {
		var w = $(this).outerWidth(),
			h = $(this).outerHeight(),
			clientWidth = d.documentElement.clientWidth,
			clientHeight = d.documentElement.clientHeight,
			iMaxX = ( Math.max(d.documentElement.scrollLeft, db.scrollLeft) + (clientWidth != 0 ? clientWidth : db.clientWidth)),
			iMaxY = ( Math.max(d.documentElement.scrollTop, db.scrollTop) + (clientHeight != 0 ? clientHeight : db.clientHeight));

		$(this).css({
			left: ( iMaxX < (e.pageX + w) ? e.pageX - w : e.pageX), // bord droit de la fenêtre trop près
			top: ( iMaxY < (e.pageY + h) ? e.pageY - h : e.pageY) // bas de la fenêtre trop près
		});
	});
};
$.fn.contenuAjax = function( options) {
	// Options
	var o = $.extend( {
		url: '',
		type: 'get',
		data: '',
		dataType: 'html',
		place: 'append',
		loadclass: 'ajaxloading_small',
		timeout: 0,
		success_function: null,
		success_callback: function(){},
		error_callback: function(){},
		complete_callback: function(){},
		beforeSend_callback: function(){},
		beforeSend_test_ident: null // { test_ident, [error_callback]}
	}, options);

	return this.each(function(){
		var t = $(this);

		$.ajax({
			url: o.url,
			type: o.type,
			data: o.data,
			dataType: o.dataType,
			context: $(this),
			beforeSend : function() {
				t.addClass(o.loadclass);
				o.beforeSend_callback( this);
				if( o.beforeSend_test_ident !== null) {
					if( ! test_ident( o.beforeSend_test_ident)) {
						t.removeClass(o.loadclass);
						if( o.beforeSend_test_ident.error_callback) {
							o.beforeSend_test_ident.error_callback( this);
						}
						return false;
					}
				}
			},
			error: function(oXhr, sStatus, errorThrown) {
				o.error_callback( this);
			},
			success: function(data) {
				if( $.isFunction( o.success_function)) {
					o.success_function( data, this);
				} else {
					if( o.place !== null) {
						t[o.place](data);
					}
				}
				o.success_callback(data, this);
			},
			complete: function() {
				t.removeClass(o.loadclass);
				o.complete_callback( this);
			}
		});
	});
};

// langue
function _lg(s) {
	return ($defined(i18n) && i18n[s]) ? i18n[s] : s;
}
function _lgNombre(n) {
	var 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 i, bits = s.split('%'),
		iCount = bits.length,
		out = bits[0],
		re = /^([ds])(.*)$/;

	for( i = 1; i < iCount; i++) {
		var p = re.exec(bits[i]);
		if (!p || arguments[i] === null) continue;
		if (p[1] == 'd') {
			out += parseInt(arguments[i], 10);
		} else if (p[1] == '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 n != 1 ? p : s;
}

$.fn._lgDialogBouton = function() {
	return this.each(function() {
		$(this).dialog('option', { closeText: _lg('Fermer') }).dialog('widget').find('span.ui-button-text').each( function() {
			var s = 'Non traduit';
			switch( $(this).text()) {
				case 'Annuler': s = _lg('Annuler'); break;
				case 'Enregistrer': s = _lg('Enregistrer');	break;
				case 'Fermer': s = _lg('Fermer'); break;
				case 'Supprimer': s = _lg('Supprimer');	break;
				case 'Transmettre': s =	_lg('Transmettre'); break;
			}
			$(this).text( s);
		});
	});
};

// renvoi JUSTE si on est loggué ou pas
function test_ident( options) {
	var oXhr = false,
		o = $.extend( {
			url: URL_SITE + 'index.php',
			data: 'p=identification&mod=test_ident',
			afficheMsg : true,
			msg: constante('ajaxIdentError')
		}, options);

	$.ajax({
		url: o.url,
		data: o.data,
		timeout: 10000,
		async: false,
		error: function(oXhr, sStatus, errorThrown) {
			alert( constante('ajaxError'));
			oXhr = false;
		},
		success: function(data) {
			oXhr = (data == 'ok');
		}
	});
	if( !oXhr && o.afficheMsg) {
		alert( o.msg);
	}
	return oXhr;
}

// "Constante" prédéfinie
function constante( sCode, aParam) {
	switch( sCode) {
		case 'datepicker' : return _lg( 'Choisissez une date');
		case 'ajaxError' : return _lg( 'Une erreur est survenue :\n\nRafraichissez la page et essayer à nouveau.\nSi le problème persiste, contactez le webmaster.');
		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 '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.]';
	}
}

// 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;'); }
function html_decode( s) { return new String(s).replace(/&amp;/g, '&').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&#34/g, '"'); }
function isHtml_encode( s) { return (s.search(/&amp;/g) != -1 || s.search(/&lt;/g) != -1 || s.search(/&gt;/g) != -1 || s.search(/&#34;/g) != -1); }
function html_decode_if_encode() { return isHtml_encode(s) ? html_decode(s) : s; }

// Tronque la chaine passée en paramètre
function tronquer( s, iMax) {
	s = $.trim( s);
	return ( s.length > iMax ) ? s.substr( 0, iMax / 2) + '[\u2026]' + Right(s, iMax / 2) : s;
}
// coupe
function couper( s, iMax) {
	s = $.trim( s);
	return ( s.length > iMax ) ? Left(s, iMax) + '[\u2026]' : s;
}

function Left( s, n){
	if( n <= 0) {
		return '';
	} else if( n > String(s).length){
		return s;
	} else {
		return String(s).substring(0, n);
	}
}
function Right( s, n){
	if( n <= 0) {
		return '';
	} else if (n > String(s).length) {
		return s;
	} else {
		var iLen = String(s).length;
		return String(s).substring(iLen, iLen - n);
	}
}

// Date
function date2timestamp( sFormat, sDate){ // dd/mm/yy hh.nn.ss
	var sPosD = sFormat.indexOf('d'),
		sPosM = sFormat.indexOf('m'),
		sPosY = sFormat.indexOf('y'),
		sPosH = sFormat.indexOf('h'),
		sPosMn = sFormat.indexOf('n'),
		sPosS = sFormat.indexOf('s'),
		d = sDate.substring( sPosD, sPosD + 2),
		m = sDate.substring( sPosM, sPosM + 2),
		y = sDate.substring( sPosY, sPosY + 4),
		h = sDate.substring( sPosH + 2, sPosH + 4), // ! yy = 4
		mn = sDate.substring( sPosMn + 2, sPosMn + 4),
		s = sDate.substring( sPosS + 2, sPosS + 4);
	return new Date( y, m, d, h, mn, s).getTime();
}

// syncho avec PHP
function format_html_id( s, sReplace) {
	sReplace = $defined(sReplace) ? sReplace : '';
	return s.replace(/^[^a-z_]+/i, sReplace).replace(/\W+/, sReplace);
}

function format_decimal( s, sReplace) {
	sReplace = $defined(sReplace) ? sReplace : '\.';
	switch( i18n.decimal_sep) {
		case ',': return Number( String(s).replace(',', sReplace));
		case '٫': return Number( String(s).replace('٫', sReplace)); // \u066B
		default: return Number( s);
	}
}

// @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 id="' + o.id + '" class="helpBoxInfos-ON' + ( o[o.code] ? ' ' + o[o.code] : '') + '">' + o.text + '</div>';
}

// Events
function getEvent(e) { return e || window.event; }

function $redirect(sUrl, oWindow) {
	if( !$defined(oWindow)) oWindow = window;
	if( !$defined(sUrl) || sUrl == '') sUrl = oWindow.location;
	oWindow.location = sUrl;
}

function $defined(o) { return (o != undefined); }
function $is_true(t, v) { return $defined(t) ? t : v; }

function $id( s) {
	return s ? document.getElementById(s) : null;
}

function $insertCSS( url) {
	var sLink = '';
	url = $.isArray( url) ? url : [ url];

	$.each( url, function(i) {
		sLink += '<link rel="stylesheet" href="' + url[i] + '" type="text/css" />';
	});
	$('head').append( sLink);
}
function $insertScript(url) {
	var sScript = '';
	url = $.isArray( url) ? url : [ url];

	$.each( url, function(i) {
		sScript += '<script type="text/javascript" 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();*/
}

// DEBUG
var dW = null;
function debug(text) {
	if (!window.top.dW || window.top.dW.closed) {
		showDebug();
	}
	dW = window.top.dW.document.write(text + '\n');
}
function showDebug() {
	window.top.dW = window.open('', 'Debug', 'left=0,top=0,width=300,height=700,scrollbars=yes,status=yes,resizable=yes');
	window.top.dW.opener = self;
	window.top.dW.document.open();
	window.top.dW.document.write('<html><head><title>Debug</title></head><body><div align="right" onclick="if(wp = window.opener){wp.hideDebug();wp.showDebug();}">[ Reset ]</div><pre>\n');
}
function hideDebug() {
	if (window.top.dW && ! window.top.dW.closed) {
		window.top.dW.close();
		window.top.dW = null;
	}
}
