/*---------------------------------------------------------------------------------------------------
* Liste des fonctions utiles CoMpuS [AD]
* @der.mod : 05/02/2007
* @pré-requis : Appel de la librairie jQuery
*/

/*
* Gère la sélection de l'élément gràce à son ID
*****************************************************************************************************/
function getElement(id){ if(document.getElementById){ return document.getElementById(id); }else if(document.all){ return document.all[id]; } else return; }

/*
* Gestion de l'ouverture des liens dans une nouvelles fenêtres
*****************************************************************************************************/
function open_ext_link(mClass, newTitle, mBloc){
	if(typeof mClass == "undefined"){ mClass = "opblank"; }
	if(typeof newTitle == "undefined"){ newTitle = ""; }
	if(typeof mBloc == "undefined"){ mBloc = ""; }

	$(mBloc+"a."+mClass).attr("title", function() { return (typeof this.title == "undefined" ? "" : this.title) + newTitle; });
	$(mBloc+"a."+mClass).click(function(){ window.open(this.href); return false; });
}
$(document).ready(function(){ open_ext_link(); });

/*
* Gère l'appel des fonctions - [ py Peter van der Beken ]
*****************************************************************************************************/
function chainHandler(obj, handlerName, handler) {
	obj[handlerName] = (function(existingFunction) {
		return function() {
			handler.apply(this, arguments);
			if (existingFunction)
				existingFunction.apply(this, arguments); 
		};
	})(handlerName in obj ? obj[handlerName] : null);
};

/*
* Gère le comportement des boites de confirmation
*****************************************************************************************************/
function mConfirm(mMessage, mUrl){
	if(confirm(mMessage)){ document.location.href =  mUrl; }
}

/*
* Gère le comportement des boites de confirmation avec validation de formulaire
*****************************************************************************************************/
function sConfirm(mMessage, mForm){
	if(confirm(mMessage)){ getElement(mForm).submit(); }
}

/*
* Renvoie au sein d'un champ une valeur données
*****************************************************************************************************/
function setChp(mVal, mChamp, pPopup){
	if(pPopup == "undefined" || pPopup == ''){ pPopup = false; }else{ pPopup = true; }				// Champ à MAJ appartient à la page parente de la popup si != ''
	if(pPopup == true){ mChp = window.opener.document.getElementById(mChamp); }else{ mChp = getElement(mChamp); }
	if(mChp){ mChp.value = mVal; }
}

/*
* Récupère une information dans un champ et transmet cette dernière à la fenêtre de gestion des médias
*****************************************************************************************************/
function getChp(mVal, mChamp){
	if(getElement(mChamp)){
		popupCentrer(mVal + 'manager/outils/media/popup_media.php?mc=' + mChamp + '&mvc=' + getElement(mChamp).value + '&typeOut=url', 'media_compus', 660, 595, 'alwaysRaised=yes,dependent=yes,toolbar=no,menubar=no,resizable=yes,scrollbars=yes,status=no');
		return false;
	}
}

/*
* Ouvre un média dans un nouvelle fenêtre
*****************************************************************************************************/
function openFile(mFile, mUrlSite){
	if(getElement(mFile) && mUrlSite != "undefined"){
		var mValFile	= getElement(mFile).value;
		if(mValFile.indexOf('http://') != -1){ window.open(mValFile); }else{ window.open(mUrlSite + mValFile); }
	}
	return false;
}

/*
* Ouvre le mailer du client pour rédation d'un email
*****************************************************************************************************/
function mailTo(mMail, mError){
	if(getElement(mMail)){
		var mValMail	= getElement(mMail).value;
		if(verif_email(mValMail)){ document.location = "mailto:" + mValMail; }else{ alert(mError); }
	}
	return false;
}

/*
* Vérifie la validité d'une adresse email
*****************************************************************************************************/
function verif_email(monEmail){
	var reg = /^[a-z0-9._-]+@[a-z0-9.-]{2,}[.][a-z]{2,6}$/
	return (reg.exec(monEmail)!=null) 
}

/*
* Vérifie la validité d'une adresse URL (HTTP / FTP)
*****************************************************************************************************/
function verif_url(monUrl){
	var reg	= monUrl.match(/^(ftp|http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}((:[0-9]{1,5})?\/.*)?$/i);
	return (reg == null ? false : true);
}

/*
* Popup prédéfinie pour les fenêtres d'aide de CoMpuS
*****************************************************************************************************/
function popup(url){
	popupCentrer(url, 'aide_compus', 510, 595, 'alwaysRaised=yes,dependent=yes,toolbar=no,menubar=no,resizable=yes,scrollbars=yes,status=no');
}

/*
* Ouvre une popup aux dimensions souhaités et la centre dans l'écran
*****************************************************************************************************/
function popupCentrer(page, nom, largeur, hauteur, options) {
	var top  = (screen.height-hauteur)/2;
	var left = (screen.width-largeur)/2;
	window.open(page, nom, "top="+top+",left="+left+",width="+largeur+",height="+hauteur+","+options);
}

/*
* Equivalent de trim en PHP -> enlève les espaces aux extrèmités d'une chaine
*****************************************************************************************************/
function trim(s) {
	s = s.replace(/[ ]*$/,'');
	s = s.replace(/^[ ]*/,'');
	return s;
}

/*
* Gère l'affichage ou le cachage d'un élément (plus changement +/-)
*****************************************************************************************************/
function afficheAlterne(id, mode, pathImage, imgPlus, imgMoins){
	if(typeof pathImage == "undefined"){ pathImage = "/manager/images/"; }
	if(typeof imgPlus == "undefined"){ imgPlus = "plus.png"; }
	if(typeof imgMoins == "undefined"){ imgMoins = "moins.png"; }
	
	element				= getElement(id);
	img					= getElement('img_'+id);
	
	if(element.style) {
		if(mode == 0) {
			if(element.style.display == 'block' ) {
				element.style.display = 'none';
				img.src	= pathImage + imgPlus;
			} else {
				element.style.display = 'block';
				img.src	= pathImage + imgMoins;
			}
		} else if(mode == 1) {
			element.style.display = 'block';
			img.src		= pathImage + imgMoins;
		} else if(mode == -1) {
			element.style.display = 'none';
			img.src		= pathImage + imgPlus;
		}
	}
}

/*
* Renvoie la date actuelle
*****************************************************************************************************/
function setActuDate(mChamp, type){
	if(typeof type == "undefined"){ type = true; }
	if(type == true){
		var mDate	= new Date();
		var y		= mDate.getFullYear();
		var m		= mDate.getMonth();
		var d		= (String)(mDate.getDate());
		var h		= (String)(mDate.getHours());
		var i		= (String)(mDate.getMinutes());
		var s		= (String)(mDate.getSeconds());
	}else{
		var mDate	= new Date(2037, 11, 31, 23, 59, 59);
		var y		= mDate.getFullYear();
		var m		= mDate.getMonth();
		var d		= (String)(mDate.getDate());
		var h		= (String)(mDate.getHours());
		var i		= (String)(mDate.getMinutes());
		var s		= (String)(mDate.getSeconds());
	}
	
	if(m.length == 1){ m = '0'+m; }
	if(d.length == 1){ d = '0'+d; }
	if(h.length == 1){ h = '0'+h; }
	if(i.length == 1){ i = '0'+i; }
	if(s.length == 1){ s = '0'+s; }

	if(mChamp == null){ mChamp = 'mdate'; }else{ mChamp = 'mdate_' + mChamp; }						// Cas plusieurs occurences de dates sur une même page
	getElement(eval('"'+mChamp+'_y"')).value = y;
	getElement(eval('"'+mChamp+'_m"')).selectedIndex = m;
	getElement(eval('"'+mChamp+'_d"')).value = d;
	getElement(eval('"'+mChamp+'_h"')).value = h;
	getElement(eval('"'+mChamp+'_i"')).value = i;
	getElement(eval('"'+mChamp+'_s"')).value = s;
}

/*
* Vérifie et renvoie une chaîne conforme au type URL
*****************************************************************************************************/
function str2url(mChamp, oChamp, ucfirst, urlOK, urlNoK, typeUrl){
	if(typeof urlOK == "undefined"){ urlOK = ""; }
	if(typeof urlNoK == "undefined"){ urlNoK = ""; }
	if(typeof typeUrl == "undefined"){ typeUrl = 1; }												// Si 0, url de type dossier, si 1 URL externe avec http://
	
	var is_ok					= true;
	var str						= getElement(mChamp).value;
	var ostr					= str;
	
	if(typeUrl > 0){																				// Dossier
		str	= str.toUpperCase();
		str = str.toLowerCase();
		str = str.replace(/[\u00E0\u00E1\u00E2\u00E3\u00E4\u00E5]/g,'a');
		str = str.replace(/[\u00E7]/g,'c');
		str = str.replace(/[\u00E8\u00E9\u00EA\u00EB]/g,'e');
		str = str.replace(/[\u00EC\u00ED\u00EE\u00EF]/g,'i');
		str = str.replace(/[\u00F2\u00F3\u00F4\u00F5\u00F6\u00F8]/g,'o');
		str = str.replace(/[\u00F9\u00FA\u00FB\u00FC]/g,'u');
		str = str.replace(/[\u00FD\u00FF]/g,'y');
		str = str.replace(/[\u00F1]/g,'n');
		str = str.replace(/[\u0153]/g,'oe');
		str = str.replace(/[\u00E6]/g,'ae');
		str = str.replace(/[\u00DF]/g,'ss');
		str = str.replace(/[^a-z0-9\s\'_\:\/\[\]-]/g,'');
		str = trim(str);
		str = str.replace(/[\s\'\:_\/\[\]-]+/g,' ');
		str = str.replace(/[ ]/g,'-');
		
		if(str != ostr || str == ''){ is_ok = false; }												// Nom de dossier invalide
		
		if (ucfirst == 1) {
			c	= str.charAt(0);
			str	= c.toUpperCase()+str.slice(1);
		}
		if(is_ok == true){ if(urlOK != ""){ alert(urlOK); } }else{ if(urlNoK != ""){ alert(urlNoK); } }
	}else{
		if(!verif_url(str)){ is_ok = false; }														// URL HTTP invalide
		if(is_ok == true){ if(urlOK != ""){ alert(urlOK); } }else{ if(urlNoK != ""){ alert(urlNoK); } }
	}
	getElement(oChamp).value	= str;																// Retourne la chaîne correctement formatée
}

/*
* Fonction de calback permettant la gestion onglet avec l'éditeur wysying
*****************************************************************************************************/
function callBTb(tlink, thtmltitle, thtmlcontent){
	if(typeof tlink != "undefined"){
		var tlink				= tlink.toString();
		if(tlink.lastIndexOf("#") != -1){
			tlink				=  tlink.substring(tlink.lastIndexOf("#")+1);
			if(tabs[tlink] == false){
				$("#" + tlink + " textarea").each(function(){
					var idtbjs	= $(this).attr("id")
					var mtb		= new jsToolBar(getElement(idtbjs));
					mtb.draw("xhtml");
				});
				tabs[tlink]		= true;
			}
		}
	}
}
