//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//BROWSER DETECTION

//Netscape : Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.3.1) Gecko/20030425
//IE : Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)

var ie6 = false;
var ie = false;
var moz = false;

function browser() {
	/*
	alert('Nom_Browser = ' + navigator.appName);
	alert('Version_Browser = ' + navigator.appVersion);
	alert('User_Agent = ' + navigator.userAgent);
	*/
	var ua = navigator.userAgent.toLowerCase(); 
	moz = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
	ie = (ua.indexOf('msie') != -1); 
	if (ie) {
		//alert('versionMinor = ' + parseFloat( ua.substring( ua.indexOf('msie ') + 5 ) ));
		if (ua.toUpperCase().indexOf('MSIE 6') != -1 || ua.toUpperCase().indexOf('MSIE 5.5') != -1 || ua.toUpperCase().indexOf('MSIE 7.0') != -1)
			ie6 = true;
	}
}
browser();

//===================================================================
// GESTION DES EVENEMENTS
//===================================================================

// Methode d'ajout d'un gestionnaire d'evenement

function addEvent( obj, type, fn )
{
	if (obj.addEventListener) // moz
	{
		obj.addEventListener( type, fn, false );
	}
	else if (obj.attachEvent) // ie
	{
		obj["e"+type+fn] = fn;
		obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
		obj.attachEvent( "on"+type, obj[type+fn] );
	}
}
// gestion des touches de fonction pour la fenetre principale
// CFL 20080618 : A GARDER !! permet de lancer l'apercu de la fiche
addEvent(document, 'keydown', OnKeyFxxDown);

function KillEvent(oEvent)
{
	if (oEvent.preventDefault) oEvent.preventDefault(); // moz
	if (oEvent.stopPropagation) oEvent.stopPropagation(); // moz
	oEvent.cancelBubble = true;
	oEvent.returnValue = false;
}

function GetKeyCode(oEvent)
{
	return (oEvent.keyCode ? oEvent.keyCode : oEvent.which);
}

//----- FUNCTION KEYS ( F1, F2, ..., F9, F10 )
function OnKeyFxxDown(oEvent) // RET : boolean
{
	oEvent = (oEvent ? oEvent : this.parentWindow.event);
	var keyCode = GetKeyCode(oEvent);
	if (oEvent && keyCode >= 112 && keyCode <= 123)
	{
		switch (keyCode)
		{
			/*case 112 :  OnKeyF1(oEvent) ;  break ;
			case 113 :  OnKeyF2(oEvent) ;  break ;
			case 114 :  OnKeyF3(oEvent) ;  break ;
			case 115 :  OnKeyF4(oEvent) ;  break ;
			case 116 :  OnKeyF5(oEvent) ;  break ;
			case 117 :  OnKeyF6(oEvent) ;  break ;
			case 118 :  OnKeyF7(oEvent) ;  break ;
			case 119 :  OnKeyF8(oEvent) ;  break ;
			case 120 :  OnKeyF9(oEvent) ;  break ;
			case 121 :  OnKeyF10(oEvent) ;  break ;
			case 122 :  OnKeyF11(oEvent) ;  break ;*/
			case 123 :  OnKeyF12(oEvent) ;  break ;
		}
	}
}
function OnKeyF12(oEvent)
{
	afficherApercu();
	KillEvent(oEvent);
}

// Controle les données des toolbox et nettoie leur contenu
function nettoyerDonnees()
{
	if (document.getElementsByName('FCK_EDITORS_NAMES')[0]) {
		var editorsNames = document.getElementsByName('FCK_EDITORS_NAMES')[0].value.split(";");
		for (i=0;i<editorsNames.length;i++) {
			if (editorsNames[i].length>0) {
				try{
					var editorName = editorsNames[i].substring(0,editorsNames[i].indexOf("_FCK"));
					if ( !(FCKeditorAPI.GetInstance(eval("'"+editorName+"'")).Status == FCK_STATUS_COMPLETE) ){
						return false;
						break;
					}
						
				}catch(err){
					return false;
				}
			}
		}
 	}
 	return true;
	
}

// Initialise le focus dans un formulaire de saisie de fiche
function initFocus()
{
	loadFckEditor();
	
	var oFirstToolbox = null;
	var sFirstToolboxName = '';
	if (window.frames.length > 0)
	{
		oFirstToolbox = window.frames[0];
		sFirstToolboxName = oFirstToolbox.name.substring(9);
	}
	var lFields = window.document.forms[0].elements;
	var oField;
	for (var i=0; i < lFields.length; i++)
	{
		oField = lFields[i];
		// on met le focus sur le 1er champ text non readonly non rempli
		if (oField.type == 'text' && ! oField.getAttribute('readonly') && oField.value=='')
		{
			//alert(oField.name);
			oField.focus();
			return;
		}
		// ou sur le 1er champ toolbox (iframe) de la page
		else if (oField.type == 'hidden' && oField.name == sFirstToolboxName)
		{
			//alert(oField.name);
			if (oFirstToolbox)
			{
				oFirstToolbox.focus();
			}
			return;
		}
		// ou sur le 1er champ combo de la page (sauf traduction)
		/*else if (oField.type == 'select-one' && oField.name != 'AUTRE_LANGUE')
		{
			//alert(oField.name);
			oField.focus();
			return;
		}*/
	}
}

//===================================================================
// FONCTIONNALITES TOOLBOX
//===================================================================
var noeudA = null;
var noeudIMG = null;

function modifieLien( objet, code, libelle) {
	
	var urlsite = document.location.toString().substring(0,document.location.toString().indexOf("servlet/")+8);
	var nouveauLien = ""; 
	if( objet == 'mailto')
		nouveauLien = urlsite+"[mailto]annuaire;"+code+ "[/mailto]";
	
	else if( objet == 'mailto-url')
		nouveauLien = "mailto:"+code;
	
	else if( objet == 'url'){
		nouveauLien = code;
		//ancre
		if(nouveauLien.indexOf("#") != -1 && nouveauLien.indexOf("http://") == -1)
			nouveauLien = urlsite+"[id-ancre]"+code+"[/id-ancre]";
				
	} else if(objet == ''){
		nouveauLien = urlsite+"[id-document];"+code+ "[/id-document]";
	} else if (objet == 'lien') {
		nouveauLien = code;
	}
	else 
		nouveauLien = urlsite+"[id-fiche]"+objet+";"+code+ "[/id-fiche]";
	
	if(nouveauLien != null && nouveauLien != ""){
			noeudA.setAttribute("href", nouveauLien);
			noeudA.setAttribute("class","ktoolbox");
	}
	liendanskt = false;
	noeudA = null;
}

function showLienDblClick(typePopup) {
	var langue = '0';//window.document.forms[0].LANGUE.value; // TODO: remettre une variable pour la langue
	if (ie) {
		if (typePopup == "lien") {
			liendanskt = true;
			window.open("/adminsite/toolbox/choix_lien.jsp?LANGUE_FICHE="+langue+"&RENVOI=IN", "list", "width=500,height=330,top=100,left=100,scrollbars=yes,status=yes");
		}
		else if (typePopup == "mailto") {
			liendanskt = true;
			window.open("/adminsite/toolbox/mailto.jsp?LANGUE_FICHE="+langue+"&RENVOI=IN", "list", "width=350,height=300,top=100,left=100,scrollbars=yes,status=yes");
		}
	}
}


/* Traitement des données résultats renvoyées par la fenêtre mère
   pour les tags K-Portal */
function save(objet, code, libelle)
{
	save2(objet, code, libelle, '');
}

function save2(objet, code, libelle, rubrique_forcage)
{

	if (objet == 'tag' || objet == 'newsletter')
	{
		txtHtml = code;
		oEditor.FCK.InsertHtml(txtHtml);
	}
	else
	{
		var urlsite = document.location.toString().substring(0, document.location.toString().indexOf("servlet/")+8);
		if (objet == 'url') {
			txtHtml = code;
			//ancre sur les liens internes uniquement
			if(txtHtml.indexOf("#") != -1 && txtHtml.indexOf("http://") == -1)
				txtHtml = "[id-ancre]"+code+"[/id-ancre]";
		}
		else//ici on est forcément sur un lien de requete puisque maintenant les liens internes ne passent pas là
		{
			txtHtml = "[id-fiche]"+objet+";"+code+ "[/id-fiche]";
			if (rubrique_forcage.length > 0)
			{
				txtHtml += '&RF='+rubrique_forcage;
			}
		}
		//cmdExec(nomApplet, 'CreateLink', txtHtml);
		window.parent.GetE("tag_kportal").value = txtHtml;
		window.parent.parent.Ok();
	}

	/* CFL 20080617 : inBackOffice() --> ENCORE UTILE??? */
	if (inBackOffice()) {
		// Cas de l'administration
		if (field1 != "")
			eval( "window.document.forms[0]."+field1+".value = code;");
		if (field2 != "")
			eval( "window.document.forms[0]."+field2+".value = libelle;");
	} else	{
		// Cas particulier du WEB 
		if (field1 != "")
			eval( "window.document.forms['form_saisie_front']."+field1+".value = code;");
		if (field2 != "")
			eval( "window.document.forms['form_saisie_front']."+field2+".value = libelle;");
	}
	
	if( texte != "") {
		// JSS 20020612-001 Type d'insertion (liste)
   		if( typeInsertion == "liste") {
			codeHtml = "[traitement;requete;"+conversionRequete(objet,code)+"]";

		} else {

			var codeHtml = '<a ';
	 
	 		if( objet == 'mailto')
				codeHtml += " href=\"[mailto]annuaire;"+code+ "[/mailto]\" >" + libelle + "</a>";
			else if( objet == 'mailto-url')
				codeHtml += " href=\"mailto:"+code+ "\" >" + libelle + "</a>";

			else if( objet == 'url')
				codeHtml += " href=\""+code+ "\" >" + libelle + "</a>";
			else if(objet == '')
				codeHtml += " href=\"[id-document]"+objet+";"+code+ "[/id-document]\" >" + libelle + "</a>";
			else
				codeHtml += " href=\"[id-fiche]"+objet+";"+code+ "[/id-fiche]\" >" + libelle + "</a>";
		}

		insererTexte( texte, codeHtml);
	}

	if( fieldRequete != "") {
		chaine = "\"OBJET="+objet;
		if( code.length > 0)
			chaine = chaine +"&"+code;
		chaine = chaine +"\"";

		eval( "window.document.forms[0]."+fieldRequete+".value = "+ chaine );
	}

	field1 = "";
	field2 = "";

	fieldRequete = "";

	texte = "";

	nomApplet = "";
  
	// JSS 20020612-001 Type d'insertion (liste)
	typeInsertion="";
}


//=========================================================
// GESTION DES IMAGES DANS LA TOOLBOX
//=========================================================

/* Renvoie une image sélectionnée dans une popup */
function renvoyerImagePopup(id, height, width, alt, border, hspace, vspace, align)
{
	if (field1 != '') // champ photo
	{
		saveImageField(id, alt);
	}
	else
	{
		var urlsite = document.location.toString();
		var url = urlsite.substring(0, urlsite.indexOf("servlet/") + 8) + "com.univ.utils.LectureImageToolbox?TAG=[id-image]" + id + "[/id-image]";
		if (id.indexOf("F")==-1)
		{
			alt = "[legende-image]" + id + "[/legende-image]";
		}
		if (nomApplet != '') // toolbox normale
		{
			saveImageToolbox(url, height, width, alt, border, hspace, vspace, align);
		}
		else // toolbox dégradée (mode HTML)
		{
			saveImageEditeurJS(url, height, width, alt, border, hspace, vspace, align);
			window.opener.SetUrl( url, width, height, alt);
		}
	}
	field1 = '';
	field2 = '';
	nomForm = '';
	texte = '';
	nomApplet = '';
}

/* Colle l'image sélectionnée dans le champ de type photo */
function saveImageField(id, alt)
{
	if (field1 != '') { // champ photo
		var oForm = (nomForm == '' ? window.document.forms[0] : window.document.forms[nomForm]);
		oForm[field1].value = id;
		oForm[field2].value = alt;
	}
}

/* Colle l'image sélectionnée dans la toolbox wysiwyg */
function saveImageToolbox(url, height, width, alt, border, hspace, vspace, align)
{
	if (testMode(nomApplet, true))
	{
		if (moz)
		{
			var framounette = getThisDocumentContent(nomApplet);
			img = framounette.createElement('img');
			img.setAttribute('class', 'ktoolbox');
			img.setAttribute('src', url);
			var style = '';
			if (width != '') {
				style += 'width:' + width + 'px; ';
			}
			//if (height != '') {
			//	style += 'height:' + height + 'px; ';
			//}
			if (border && border != '') {
				style += 'border:' + border + 'px solid #000; ';
			}
			if ((vspace && vspace != '') || (hspace && hspace != '')) {
				style += 'margin:' + vspace + 'px ' + hspace + 'px;';
			}
			img.setAttribute('style', style);
			img.setAttribute('align', align);
			img.setAttribute('alt', alt);
			if (alt.length != 0) {
				img.setAttribute('title', alt);
			}
			insertNodeAtSelection(nomApplet, img);
		}
		else
		{
			var temp = '<img src="' + url + '"';
			temp += ' class="ktoolbox"';
			temp += ' style="';
			if (width != '') {
				temp += 'width: ' + width + 'px; ';
			}
			//if (height != '') {
			//	temp += 'height: ' + height + 'px; ';
			//}
			if (border != '') {
				temp += 'border: ' + border + 'px solid #000; ';
			}
			if ((vspace && vspace != '') || (hspace && hspace != '')) {
				temp += 'margin: ' + vspace + 'px ' + hspace + 'px;';
			}
			temp += '"';
			if (align != '') {
				temp += ' align="' + align + '"';
			}
			temp += ' alt="' + alt + '"';
			if (alt != '') {
				temp += ' title="' + alt + '"';
			}
			temp += ' />';

			insertHTML(nomApplet, temp);
		}
	}
}

/* Colle l'image sélectionnée dans la toolbox html (mode dégradé) */
function saveImageEditeurJS(url, height, width, alt, border, hspace, vspace, align)
{
	if (texte != '')
	{
		var codeHtml = '<img ';
		codeHtml += ' alt="' + alt + '"';
		codeHtml += ' title="' + alt + '"';
		codeHtml += ' style="';
		codeHtml += 'width: ' + width + 'px; ';
		//codeHtml += 'height: ' + height + 'px; ';
		if (border != '') {
			codeHtml += 'border: ' + border + 'px solid #000; ';
		}
		if ((vspace && vspace != '') || (hspace && hspace != '')) {
			codeHtml += 'margin: ' + vspace + 'px ' + hspace + 'px;';
		}
		codeHtml += '"';
		codeHtml += ' align="' + align + '"';
		codeHtml += ' src="' + url + '" />';

		insererTexte(texte, codeHtml);
	}
}

/* Traitement des donnees resultats renvoyees par la fenetre mere */
function saveFormulaire( code, style)	{
	if( nomApplet != "") {
		var codeHtml = "[formulaire;CODE=";

		codeHtml += code;
		codeHtml += "&STYLE=";
		codeHtml += style;
		codeHtml += "]";

		if(moz)
			insertNodeAtSelection(nomApplet,codeHtml);
		else {
			insertHTML(nomApplet, codeHtml);
			focusFrame(nomApplet);
		}
	}
	field1 = "";
	field2 = "";
	fieldRequete = "";
	texte = "";
	nomApplet = "";
}

/* Traitement des données résultats renvoyées par la fenêtre mère */
function saveFormulaire( code, style,element)	{

	var codeHtml = "";
	
	if(element=="0000")
	{
		codeHtml += "[formulaire;CODE=";
		codeHtml += code;
		codeHtml += "&STYLE=";
		codeHtml += style;
		codeHtml += "]";
	}
	else
	{
		codeHtml += "[cf;";
		codeHtml += code;
		codeHtml += ";";
		codeHtml += style;
		codeHtml += ";";
		codeHtml += element;
		codeHtml += "]";
	}

	oEditor.FCK.InsertHtml('<p>'+codeHtml+'</p>');
	
	field1 = "";
	field2 = "";
	fieldRequete = "";
	texte = "";
	nomApplet = "";
}

function saveDocument(id, titre, NOM_FICHIER_JOINT, POIDS_FICHIER_JOINT, FORMAT_FICHIER_JOINT, PATH_FICHIER_JOINT)	{
	if( nomApplet != "") {
		var urlsite = document.location.toString().substring(0,document.location.toString().indexOf("servlet/")+8);
	
		txtHtml = urlsite+"[id-document];"+id+"[/id-document]";
		cmdExec(nomApplet, 'CreateLink', txtHtml);
	}

	if (field1 != "") {
  		eval( "window.document.forms[0]."+field1+".value = id;");
  		eval( "window.document.forms[0]."+field2+".value = titre;");
  		eval( "window.document.forms[0].NOM_"+field1+".value = NOM_FICHIER_JOINT;");
  		eval( "window.document.forms[0].POIDS_"+field1+".value = POIDS_FICHIER_JOINT;");
  		eval( "window.document.forms[0].FORMAT_"+field1+".value = FORMAT_FICHIER_JOINT;");
  		eval( "window.document.forms[0].PATH_"+field1+".value = PATH_FICHIER_JOINT;");
	}

	if( texte != "") {
		var codeHtml = '<a';

		codeHtml += " href=\"[id-document];"+id+"[/id-document]\" >";
		codeHtml += titre+"</a>";

		insererTexte( texte, codeHtml);
	}

	field1 = "";
	field2 = "";
	fieldRequete = "";
	texte = "";
	nomApplet = "";

}

function savePageLibre(code, titre, langue)	{
	
	if (field1 != "") {
		eval( "window.document.forms[0]."+field1+".value = code+',LANGUE='+langue+',TYPE=pagelibre';");
		eval( "window.document.forms[0]."+field2+".value = 'pagelibre : '+titre;");
	}

	field1 = "";
	field2 = "";
	fieldRequete = "";
	texte = "";
	nomApplet = "";
}

/**
 * Méthode qui parse une requete KPortal pour renvoyer la valeur du parametre demandé.
 */
function renvoyerParametre(requete, nomParametre) {
	var regDiese=new RegExp("[#]+", "g");

	var res = "";
	var chaineARechercher = nomParametre + '=';	
	chaineARechercher=chaineARechercher.toUpperCase();
	
	var tabDiese = requete.split(regDiese);
	for (var i=0; i<tabDiese.length; i++) {
		var paramValue = tabDiese[i];
		if(paramValue.indexOf(nomParametre, 0) != -1) {
			res = paramValue.substring(nomParametre.length + 1);
		}
	}
	
	return res;
}
