// GO1.1 Generic onload by Brothercake 
// http://www.brothercake.com/
function addOnloadFunction(generic) {
	if(typeof window.addEventListener != 'undefined')
	{
	  //.. gecko, safari, konqueror and standard
	  window.addEventListener('load', generic, false);
	}
	else if(typeof document.addEventListener != 'undefined')
	{
	  //.. opera 7
	  document.addEventListener('load', generic, false);
	}
	else if(typeof window.attachEvent != 'undefined')
	{
	  //.. win/ie
	  window.attachEvent('onload', generic);
	}
	//** remove this condition to degrade older browsers
	else
	{
	  //.. mac/ie5 and anything else that gets this far
	  //if there's an existing onload function
	  if(typeof window.onload == 'function')
	  {
	    //store it
	    var existing = onload;
	    //add new onload handler
	    window.onload = function()
	    {
	      //call existing onload function
	      existing();
	      //call generic onload function
	      generic();
	    };
	  }
	  else
	  {
	    //setup onload function
	    window.onload = generic;
	  }
	}
}

// Pour les liens conditionnels au navigateur ----------------------------------------------------------------------------------------------------------
function createBrowserBookmarkLink() {
	if (window.sidebar && ("addPanel" in window.sidebar) && (isFirefox || isFlock) ) { // Firefox Bookmark, Flock Favorites
		document.write('<a class="addBookmarkLink" href="javascript:window.sidebar.addPanel(document.title,document.location.href,\'\');">Marquez cette page</a>'); 
	} else if(window.external && ("AddFavorite" in window.external) && (isMSIE)) { // IE Favorite
		document.write('<a class="addBookmarkLink" href="javascript:window.external.AddFavorite(document.location.href,document.title);">Ajoutez aux favoris</a>'); 
	} else if(isOpera || isFirefox || isFlock) { //Opera Hotlist, Firefox  Bookmark, Flock Favorites
		document.write('<a class="addBookmarkLink" href="' + escape(document.location.href) + '" rel="sidebar" title="' + document.title + '">Signet vers la page</a>'); 
	}
}

function createPrintLink() {
	if (window.print) {
		document.write('<a class="printLink" href="javascript:window.print();">Imprimer</a>'); 
	}
}

function createWebBookmarkLink() {
	document.write('<a class="addWebLink" href="http://res.feedsportal.com/viral/bookmark_fr.cfm?title=' + escape(document.title) + '&link=' + escape(document.location.href) + '" title="Ouvre une nouvelle fen&ecirc;tre" onclick="window.open(this.href);return false;">Partagez ce lien sur vos r&eacute;seaux</a>');
}

function createSearchEngineLink() {
	if (   (window.external && ("AddSearchProvider" in window.external) && (isFirefox || isFlock || isMSIE) )
		|| (window.sidebar  && ("addSearchEngine" in window.sidebar)    && (isFirefox) )
	) {
		document.write('<a class="addSearchEngineLink" href="javascript:installSearchEngine();">Ajouter EquaThEque &agrave; vos moteurs de recherche ' + theBrowser + '</a>');
	}
}

function installSearchEngine() {
	if (window.external && ("AddSearchProvider" in window.external) && (isFirefox || isFlock || isMSIE)) { // Firefox, Flock, IE
		window.external.AddSearchProvider(document.location.protocol + "//" + document.location.host + "/recherche.php");
	} else if (window.sidebar && ("addSearchEngine" in window.sidebar) && (isFirefox)) { // Firefox < 2
		window.sidebar.addSearchEngine(
			document.location.protocol + "//" + document.location.host + "/recherche-plugin.php",
			document.location.protocol + "//" + document.location.host + "/favico.ico",
			"EquaThEque", "");
	}
}

// Pour l'attente lors de la navigation ----------------------------------------------------------------------------------------------------------
var waitOn = false;
function waitPage() {
	window.setTimeout("displayWait()",10);
}
function displayWait() {
	window.scroll(0,0);
	//document.getElementById("tempContent").innerHTML = document.getElementById("content").innerHTML; //cf displayContent()
	document.getElementById("content").innerHTML = document.getElementById("waitContener").innerHTML;
	waitOn = true;
}
function displayContent() {
	if(waitOn == true) {
		//document.getElementById("content").innerHTML = document.getElementById("tempContent").innerHTML; //Nécessaire uniquement pour Firefox 2.0 (Voir plus tard pour gérer ce cas qui fait un affichage déplaisant sur les autres versions
		waitOn = false;
	}
}

// Pour ouvrir un lien dans une nouvelle fenetre ----------------------------------------------------------------------------------------------------------
var windowIsOpenning = false
function showWindow(file,width,height,top,left,name,scrollbars) {
		if(!windowIsOpenning) {
			windowIsOpenning = true;
			if(!name) name = '';
			if(!scrollbars) scrollbars = 'no';

			var win = window.open(file,name,"height="+height+",width="+width+",top="+top+",left="+left+",status=yes,toolbar=no,menubar=no,location=no,resizable=no,scrollbars=" + scrollbars + ",modal=no,dependable=yes");
			win.focus();
			windowIsOpenning = false;
			return win;
		} else {
			return null;
		}
}

// Pour precharger les images ----------------------------------------------------------------------------------------------------------
var theImages=new Array();
function preloadImages(){
	for (i=0;i<preloadImages.arguments.length;i++){
		theImages[i] = new Image();
		theImages[i].src = preloadImages.arguments[i];
	}
}

// Pour gérer le focus sur un champs de formulaire ----------------------------------------------------------------------------------------------------------
function focusField(ID) {
	var champ = document.getElementById(ID);
	champ.focus();
}
function styleFocusField(ID) {
	var champ = document.getElementById(ID);

	var styleFocusFunction = new Function("document.getElementById('" + ID + "').className='" + champ.className + "focus';");
	if(typeof champ.onfocus == 'function') {
		var existingFocusFunction = champ.onfocus;
		champ.onfocus = function() {
			existingFocusFunction();
			styleFocusFunction();
		};
	} else {
		champ.onfocus = styleFocusFunction;
	}

	var styleBlurFunction = new Function("document.getElementById('" + ID + "').className='" + champ.className + "'");
	if(typeof champ.onblur == 'function') {
		var existingBlurFunction = champ.onblur;
		champ.onblur = function() {
			existingBlurFunction();
			styleBlurFunction();
		};
	} else {
		champ.onblur = styleBlurFunction;
	}
}

function defaultValueField(ID) {
	var champ = document.getElementById(ID);

	var defaultValueFocusFunction = new Function("var field = document.getElementById('" + ID + "');if(field.value==field.defaultValue) field.value='';");
	if(typeof champ.onfocus == 'function') {
		var existingFocusFunction = champ.onfocus;
		champ.onfocus = function() {
			existingFocusFunction();
			defaultValueFocusFunction();
		};
	} else {
		champ.onfocus = defaultValueFocusFunction;
	}

	var defaultValueBlurFunction = new Function("var field = document.getElementById('" +  ID + "');if(field.value=='') field.value=field.defaultValue;");
	if(typeof champ.onblur == 'function') {
		var existingBlurFunction = champ.onblur;
		champ.onblur = function() {
			existingBlurFunction();
			defaultValueBlurFunction();
		};
	} else {
		champ.onblur = defaultValueBlurFunction;
	}
}

// Pour gérer l'affichage des actualites ----------------------------------------------------------------------------------------------------------
var RSS_NUMBER_DISPLAY = 5;
function displayRSS(name) {
	var news;
	if(news = document.getElementById(name + (RSS_NUMBER_DISPLAY+1))) {
		if(news.style.display && news.style.display == "none") {
			expandRSS(name);
			document.getElementById(name + "displayText").innerHTML = "Moins d'info...";
		} else {
			collapseRSS(name);
			document.getElementById(name + "displayText").innerHTML = "Plus d'info...";
		}
		document.getElementById(name + "displayText").style.display = "block"
	} else {
		document.getElementById(name + "displayText").style.display = "none"
	}
}
function collapseRSS(name) {
	var news;
	var num = RSS_NUMBER_DISPLAY;
	while(true) {
		if(news = document.getElementById(name + (++num))) {
			news.style.display = "none";
		} else {
			break;
		}
	}
}
function expandRSS(name) {
	var news;
	var num = RSS_NUMBER_DISPLAY;
	while(true) {
		if(news = document.getElementById(name + (++num))) {
			news.style.display = "block";
		} else {
			break;
		}
	}
}

// Pour gérer l'affichage des suggestions de recherche en AJAX ----------------------------------------------------------------------------------------------------------
var xObjRequest = null;

function initAJAXConnection() {
	if(XHConn) xObjRequest = new XHConn();
}

function loadSuggestion() {
	if(!xObjRequest) {
		initAJAXConnection();
	}
	if (xObjRequest) {
		var searchValue=document.getElementById("fieldFastSearch").value;
		if(searchValue.length > 2) {
			xObjRequest.abort();
			xObjRequest.connect("recherche_suggestions.php", "GET", "paramFormat=json&paramFastSearch=" + escape(searchValue), displaySuggestion);
		} else {
			directHideSuggestion()
		}
	}
}

var displaySuggestion = function (xObjResponse) {
	var divSuggestion = document.getElementById("suggestion");
	try {
		var responseSuggestion = eval(xObjResponse.responseText);
		if(responseSuggestion && responseSuggestion.length == 2) {
			var searchValue = responseSuggestion[0];
			var maReg = new RegExp( searchValue, "gi"); //pour mettre en valeur les caractères recherchés sans case
			var searchFind = "<strong>"+searchValue+"</strong>";
			var listSuggestion = responseSuggestion[1];
			
			if(listSuggestion.length > 0) {
				var htmlSuggestion = "";
				for(i=0;i < listSuggestion.length; i++) {
					var laSuggestion = listSuggestion[i];
					var laSuggestionAffichee =  laSuggestion;
					/*if(laSuggestionAffichee.length > 40) {
						laSuggestionAffichee = laSuggestionAffichee.substring(0,39) + "...";
					}*/
					laSuggestionAffichee =  laSuggestionAffichee.replace( maReg, searchFind);
					htmlSuggestion += ("\n<a href='recherche_equation_traitement.php?paramFastSearch=" + escape(laSuggestion).replace('+','%2B') + "' onclick='waitPage();' title='" + laSuggestion.replace("\"","&quot;").replace("\'","&#39;") + "'>" + laSuggestionAffichee + "</a><br/>");
				}
				if(listSuggestion.length == 20) {
					htmlSuggestion += ("\n<a class='bottom' href='recherche_equation_traitement.php?paramFastSearch=" + escape(searchValue).replace('+','%2B') + "' onclick='waitPage();' >Plus de résultats...</a><br/>");
				}
				divSuggestion.innerHTML = htmlSuggestion;
				divSuggestion.style.display = "block";
				divSuggestion.style.opacity = 1;
				divSuggestion.style.filter = "alpha(opacity=" + divSuggestion.style.opacity*100 + ")";
			} else {
				directHideSuggestion();
			}
		} else {
			directHideSuggestion();
		}
	} catch(e) {
		directHideSuggestion();
	}
};

function hideSuggestion() {
	var divSuggestion = document.getElementById("suggestion");

	if(!divSuggestion.style.opacity) divSuggestion.style.opacity = 1;
	if(!divSuggestion.style.filter) divSuggestion.style.filter = "alpha(opacity=100)";

	var opacity = Math.round(parseFloat(divSuggestion.style.opacity)*100)/100;
	if(opacity > 0.1) {
		opacity -= 0.1;
		divSuggestion.style.opacity = opacity;
		divSuggestion.style.filter = "alpha(opacity=" + Math.round(opacity*100) + ")";
		window.setTimeout('hideSuggestion()',50);
	} else {
		window.setTimeout('directHideSuggestion()',50);
	}
}

function directHideSuggestion() {
	var divSuggestion = document.getElementById("suggestion");

	divSuggestion.innerHTML = "";
	divSuggestion.style.display = "none";
}

// Pour tester la compatibilité du navigateur avec l'affichage du MathML ----------------------------------------------------------------------------------------------------------
function testMathML() {
	/*
	Sous IE 8 :
	Ce site Web souhaite exécuter le module complémentaire " MathPlayer Behavior " publié par " Design Science Inc. ".
	Cliquez ici si vous faites confiance à ce site et à ce module pour l'autoriser à s'exécuter...
	Exécuter le module complémentaire
	*/

	var isMathMLavailable = false;
	var isBrowserVersionOK = false;

	if(isNetscape || isFirefox || isKmeleon || isFlock) {
		if(browserVersion >= 5) {
			isMathMLavailable = true;
			isBrowserVersionOK = true;
		}
	} else if(isOpera) {
		if(browserVersion >= 9) {
			isMathMLavailable = true;
			isBrowserVersionOK = true;
		}
	} else if(isMSIE || isAOL) {
		if(browserVersion >= 4) {
			try {
				var mmlActiveX = new ActiveXObject("MathPlayer.Factory.1");
				isMathMLavailable = true;
				mmlActiveX = null;
			} catch (e) {
			}
			isBrowserVersionOK = true;
		}
	}

	var msg = "";
	if(!isMathMLavailable) {
		if(isBrowserVersionOK) {
			msg += "<b>La configuration de votre navigateur internet n'est pas optimale</b>.";
			msg += "\n<br/><br/>Il se peut que les équations ne soit pas affichées correctement.";
			if(isMSIE || isAOL) {
				msg += ("\n\n<br/><br/>Vous utilisez une version " + theBrowser + " qui permet l'affichage des équations si vous installez le plugin <a href='http://www.dessci.com/en/products/mathplayer/download.htm' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>MathPlayer</a>.");
				msg += "\n\n<br/><br/>Les équations seraient aussi parfaitement affichées si vous utilisiez une version récente de l'un des navigateurs suivants :";
				msg += "\n<br/><br/><a href='http://www.mozilla.org' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Firefox</a>";
				msg += "\n<br/><a href='http://www.opera.com' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Opera</a>";
				msg += "\n<br/><a href='http://kmeleon.sourceforge.net' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>K-Meleon</a>";
				msg += "\n<br/><a href='http://www.flock.com' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Flock</a>";
			}
		} else {
			msg += "<b>La configuration de votre navigateur internet n'est pas optimale</b>.";
			msg += "\n<br/><br/>Il se peut que les équations ne soit pas affichées correctement.";
			msg += "\n\n<br/><br/>Les équations seraient parfaitement affichées si vous utilisiez une version récente de l'un des navigateurs suivants :";
			msg += "\n<br/><br/><a href='http://www.mozilla.org' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Firefox</a>";
			msg += "\n<br/><a href='http://www.opera.com' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Opera</a>";
			msg += "\n<br/><a href='http://kmeleon.sourceforge.net' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>K-Meleon</a>";
			msg += "\n<br/><a href='http://www.flock.com' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Flock</a>";
			msg += "\n<br/><a href='http://www.microsoft.com' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>Microsoft Internet Explorer</a> avec le plugin <a href='http://www.dessci.com/en/products/mathplayer/download.htm' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>MathPlayer</a>";
			msg += "\n<br/><a href='http://www.aol.fr' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>America Online Browser</a> avec le plugin <a href='http://www.dessci.com/en/products/mathplayer/download.htm' title='Ouvre une nouvelle fenêtre' onclick='window.open(this.href);return false;'>MathPlayer</a>";
		}
	}
	if(msg.length > 0) {
		document.getElementById("alertContent").innerHTML = msg;
		document.getElementById("alertContener").style.display = "block";
	}
}

// Pour afficher le MathML ----------------------------------------------------------------------------------------------------------
function afficheMathML(ID) {
	showWindow('affiche_mathML.html?paramDivMathML='+ID,600,500,20,20,'winMathML',false);
}

function litMathML() {
	var ID = getURLParamValue(document.location.href,'paramDivMathML')
	var mathMLnode = window.opener.document.getElementById(ID);
	var mathMLStr = node2string(mathMLnode,"").slice(1);

	document.getElementById('mathML').value = mathMLStr;
}


function node2string(inNode,indent) {
// Last Version by David GRIMA Feb 28 2004
// thanks to James Frazer for contributing an initial version of this function
// thanks to Peter Jipsen http://www.chapman.edu/~jipsen for Version 1.3 Feb 22 2004
   var str = "";
   if(inNode && inNode.nodeType == 1) { // (undefine inNode fix by David GRIMA)
       var name = inNode.nodeName.toLowerCase(); // (IE fix)
       str = "\r" + indent + "<" + name;
       for(var i=0; i < inNode.attributes.length; i++)
           if (inNode.attributes[i].nodeValue!="italic" &&
               inNode.attributes[i].nodeValue!="" &&  //stop junk attributes
               inNode.attributes[i].nodeValue!="inherit" && // (mostly IE)
               inNode.attributes[i].nodeValue!=undefined)
               str += " "+inNode.attributes[i].nodeName+"="+
                     "\""+inNode.attributes[i].nodeValue+"\"";
       if (name == "math") 
           str += " xmlns=\"http://www.w3.org/1998/Math/MathML\"";
       str += ">";
       for(var i=0; i<inNode.childNodes.length; i++)
           str += node2string(inNode.childNodes[i], indent+"  ");
       if (name != "mo" && name != "mi" && name != "mn") str += "\r"+indent;
       str += "</" + name + ">";
   }
   else if(inNode &&  inNode.nodeType == 3) { // (undefine inNode fixed by David GRIMA)
       var st = inNode.nodeValue;
       for (var i=0; i<st.length; i++)
           if (st.charCodeAt(i)<32 || st.charCodeAt(i)>126)
               str += "&#"+st.charCodeAt(i)+";";
           else if (st.charAt(i)=="<") str += "&lt;";
           else if (st.charAt(i)==">") str += "&gt;";
           else if (st.charAt(i)=="&") str += "&amp;";
           else str += st.charAt(i);
   }
   return str;
}

// Pour la gestion de URL et des Cookies ----------------------------------------------------------------------------------------------------------
function getURLParamValue(url,paramName) {
	var paramValue = null;
	var querystring = getURLQuerystring(url);

	if (querystring) {
		var arrayOfParameters = querystring.split("&");
		var tempParamName;
		var tempParamValue;
		var parameter;

		for (var i = 0; i < arrayOfParameters.length; i++) {
			parameter = arrayOfParameters[i];
			posEqual = parameter.indexOf("=");

			if(posEqual > 0) {
				tempParamName = parameter.substring(0,posEqual);
				tempParamValue = parameter.substring(posEqual+1,parameter.length);
			} else {
				tempParamName = parameter;
				tempParamValue = parameter;
			}

			if(tempParamName == paramName) {
				paramValue = tempParamValue;
				break;
			}
		}
	}
	
	return paramValue;
}

function getURLQuerystring(url)
{
	var querystring;

	if ((url != null) && (url != ""))
	{
		querystring = unescape(url);
		
		var posQuerystring = querystring.indexOf("?");
		if (posQuerystring > 0)	{
			var posAnchor = querystring.indexOf("#");
			if (posAnchor > 0) {
				querystring = querystring.substring(posQuerystring+1, posAnchor);
			} else {
				querystring = querystring.substring(posQuerystring+1);
			}
		} else {
			querystring = null;
		}
	}

	return querystring;
}

function getURLAnchor(url) {
	var anchor;

	if ((url != null) && (url != ""))
	{
		anchor = unescape(url);
		
		var posAnchor = anchor.indexOf("#");
		if (posAnchor > 0) {
			anchor = anchor.substring(posAnchor+1);
		} else {
			anchor = null;
		}
	}

	return anchor;
}

function getURLUri(url) {
	var uri;

	if ((url != null) && (url != ""))
	{
		uri = unescape(url);
		
		var posQuerystring = uri.indexOf("?");
		if (posQuerystring > 0)	{
				uri = uri.substring(0, posQuerystring);
		} else {
			var posAnchor = uri.indexOf("#");
			if (posAnchor > 0) {
				uri = uri.substring(0, posAnchor);
			}
		}
	}

	return uri;
}

function replaceURLParamValue(url,paramName,newParamValue) {
		var newURL;
		
		var uri = getURLUri(url);
		var querystring = getURLQuerystring(url);
		var anchor = getURLAnchor(url);

		newURL = uri;

		if(querystring) {
			var re = new RegExp(paramName + "=","gi");
			var s = "old" + paramName + "=";
		
			newURL = newURL + "?" + querystring.replace(re,s) + "&" + paramName + "=" + newParamValue;
		}
		else {
			newURL = newURL + "?" + paramName + "=" + newParamValue;
		}

		if(anchor) newURL = newURL + "#" + anchor;

		return newURL;
}

function setCookie(name,value,expires,path,domain,secure) {
	document.cookie = name + "=" + escape (value) +
	((expires) ? "; expires=" + expires.toGMTString() : "") +
	((path) ? "; path=" + path : "; path=/") +
	((domain) ? "; domain=" + domain : "") +
	((secure) ? "; secure" : "");
}

function getCookieVal (offset) {
	var endstr = document.cookie.indexOf (";", offset);
	if (endstr == -1) { endstr = document.cookie.length; }
	return unescape(document.cookie.substring(offset, endstr));
}

function getCookie(name) {
	var arg = name + "=";
	var alen = arg.length;
	var clen = document.cookie.length;
	var i = 0;
	while (i < clen) {
		var j = i + alen;
		if (document.cookie.substring(i, j) == arg) {
			return getCookieVal (j);
		}
		i = document.cookie.indexOf(" ", i) + 1;
		if (i == 0) break; 
	}
	return null;
}

function deleteCookie(name) {
	setCookie(name,"",new Date(1999,11,31));
}
