//Collection of javascript included in every page header

//OnLoad hook-up mechanism

function jsQSOnLoad() {
	//Check if a custom onload function is defined
	if (window.jsCustomOnLoad) {
		jsCustomOnLoad();		
	}
}

function jsHookUpOnLoad(funCustomOnLoad) {
	// DOM2
	if ( typeof window.addEventListener != "undefined" )
		window.addEventListener( "load", funCustomOnLoad, false );

	// IE 
	else if ( typeof window.attachEvent != "undefined" )
		window.attachEvent( "onload", funCustomOnLoad );

	else {
		if ( window.onload != null ) {
			var oldOnload = window.onload;
			window.onload = function ( e ) {
				oldOnload( e );
				funCustomOnLoad();
			};
		}
		else 
			window.onload = funCustomOnLoad;
	}
}

//open_window : no more used. Is here for compatibility reasons -> probably in swissmedia project
function open_window(url) { 
	var corpagri
	corpagri = window.open(url,"QuickSitePortal",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=640,height=480'); 
} 

function jsOpenWindow640480(pstrUrl) {
	var objWindow
	objWindow = window.open(pstrUrl, "QuickSite",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=640,height=480'); 
}

function jsOpenWindow(pstrUrl, pintWidth, pintHeight) {
	if (true) {
		//Use ThickBox
		if (TB_show) {
			TB_show('none', pstrUrl + '&TB_iframe=true&height='+pintHeight+'&width='+pintWidth);
		}
		else {
			parent.TB_show('none', pstrUrl + '&TB_iframe=true&height='+pintHeight+'&width='+pintWidth);
		}
	}
	else {
		var objWindow
		objWindow = window.open(pstrUrl, "_blank",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=' + pintWidth + ',height=' + pintHeight); 
		//window.showModalDialog(pstrUrl, "", "dialogHeight:" + pintHeight + "px; dialogWidth:" + pintWidth + "px;")
	}
}

function jsOpenPopupWindow(pstrUrl, pintWidth, pintHeight) {
	var objWindow
	objWindow = window.open(pstrUrl, "_blank",'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width=' + pintWidth + ',height=' + pintHeight); 
}

var IFrameObj; // our IFrame object

function CallToServer(URL) {
	if (!document.createElement) {return true};
	var IFrameDoc;
	if (!IFrameObj && document.createElement) {
		// create the IFrame and assign a reference to the
		// object to our global variable IFrameObj.
		// this will only happen the first time 
		// callToServer() is called
	 try {
			var tempIFrame=document.createElement('iframe');
			tempIFrame.setAttribute('id','RSIFrame');
			tempIFrame.style.border='0px';
			tempIFrame.style.width='0px';
			tempIFrame.style.height='0px';
			IFrameObj = document.body.appendChild(tempIFrame);
			
			if (document.frames) {
				// this is for IE5 Mac, because it will only
				// allow access to the document object
				// of the IFrame if we access it through
				// the document.frames array
				IFrameObj = document.frames['RSIFrame'];
			}
		} catch(exception) {
			// This is for IE5 PC, which does not allow dynamic creation
			// and manipulation of an iframe object. Instead, we'll fake
			// it up by creating our own objects.
			iframeHTML='\<iframe id="RSIFrame" style="';
			iframeHTML+='border:0px;';
			iframeHTML+='width:0px;';
			iframeHTML+='height:0px;';
			iframeHTML+='"><\/iframe>';
			document.body.innerHTML+=iframeHTML;
			IFrameObj = new Object();
			IFrameObj.document = new Object();
			IFrameObj.document.location = new Object();
			IFrameObj.document.location.iframe = document.getElementById('RSIFrame');
			IFrameObj.document.location.replace = function(location) {
				this.iframe.src = location;
			}
		}
	}
	
	if (navigator.userAgent.indexOf('Gecko') !=-1 && !IFrameObj.contentDocument) {
		// we have to give NS6 a fraction of a second
		// to recognize the new IFrame
		setTimeout('callToServer()',10);
		return false;
	}
	
	if (IFrameObj.contentDocument) {
		// For NS6
		IFrameDoc = IFrameObj.contentDocument; 
	} else if (IFrameObj.contentWindow) {
		// For IE5.5 and IE6
		IFrameDoc = IFrameObj.contentWindow.document;
	} else if (IFrameObj.document) {
		// For IE5
		IFrameDoc = IFrameObj.document;
	} else {
		return true;
	}
	
	IFrameDoc.location.replace(URL);
	return false;
}

function buildQueryString(theFormName) {
	theForm = document.forms[theFormName];
	var qs = ''
	for (e=0;e<theForm.elements.length;e++) {
		if (theForm.elements[e].name!='') {
			qs+=(qs=='')?'?':'&'
			qs+=theForm.elements[e].name+'='+escape(theForm.elements[e].value)
			}
		}
	return qs
}

function jsSetCookie(pstrName, pstrValue, pintNbDays) {
	var expires = "";
	
	if (pintNbDays != 0) {
		var d = new Date();
		d.setTime( d.getTime() + pintNbDays * 24 * 60 * 60 * 1000 );
		expires = "; expires=" + d.toGMTString();
	}

	document.cookie = pstrName + "=" + escape(pstrValue) + expires + "; path=/";
}

function jsGetCookie(pstrName) {

	var search;
	var offset;
	var end;

	search = pstrName + "="
	offset = document.cookie.indexOf(search) 
	if (offset != -1) {
		offset += search.length ;
		end = document.cookie.indexOf(";", offset) ;
		if (end == -1)
			end = document.cookie.length;
		return unescape(document.cookie.substring(offset, end));
	}
	else
		return "";
}					

function jsRemoveCookie(pstrName) {
	jsSetCookie(pstrName, '', -1 );
}

function jsPlaySong(pstrContainer, pstrUrl) {
	var objContainer = document.getElementById(pstrContainer);
	if (objContainer) {
		objContainer.innerHTML = embedSound(pstrUrl); 
	}
	return false;
}

function embedSound(sound)
{
	return '<embed src="' + sound + '" autostart="true" ' +
		'width="320" height="32">';
}

function jsToggleVisibility(pstrDivID) {
	var e = document.getElementById(pstrDivID);
	if (e) {
		if (e.style.display == 'none') 
			e.style.display = 'block'
		else
			e.style.display = 'none'
			
	}
}

function jsOEA(b, c, a) {
	var e = a + "@" + b + "." + c;
	document.write("<a href='mai" + "lto:"+e+"'>");
	document.write(e);
	document.write("</a>"); 
};

function IsNumeric(sText)
{
   var ValidChars = "0123456789.-";
   var IsNumber=true && (sText.length > 0);
   var Char;
 
   for (i = 0; i < sText.length && IsNumber == true; i++) 
      { 
      Char = sText.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         IsNumber = false;
         }
      }
   return IsNumber;
   
}

function GetNumber(sText) {
	if (IsNumeric(sText)) {
		if (sText.indexOf('.') == -1)
			return parseInt(sText);	
		else
			return parseFloat(sText);
	}
	else {
	  return 0;
	}
}

function endsWith(src, suffix) {
    var startPos = src.length - suffix.length;
    if (startPos < 0) {
      return false;
    }
    return (src.lastIndexOf(suffix, startPos) == startPos);
};


/* jQuery function */
//AjaxLogin function
//Shoud probably be moved in a more specific js file
function AjaxLogin(){
	$('#syspopupMenu').hide();
	TB_show('Login', '/qsPortal/AjaxLogin.asp?width=320&height=172');
	/*
	$('#divResults').remove();
	$('body').prepend("<div id='divResults'></div>");
	$('#divResults').loadIfModified('/qsPortal/AjaxLogin.asp', function(){
		var posX = document.body.clientWidth;
		var posY = document.body.clientHeight;
		posX = (posX - 300) /2;
		posY = (posY - $('#divResults').height()) /2;		
		$('#divResults').css({position: "absolute", 
													left: posX + "px",
													top: posY + "px" });
		$('#divResults').fadeIn('slow');
		}
	);
	*/
}

//AjaxLogout function
//Should probably be moved in a more specific js file
function AjaxLogout(){	

	// DTA v428 10.6.2008 modification de l'appel ajax depuis la version 1.2.6 du jquery.
	$.ajax({
		type:		'GET',
		cache:		false,
		dataType:	'html',
		async:		false,
		url:		'/qsPortal/Quicklogout.asp',
		success:	function(req){
						document.location.reload();
					}
	});		
}



/*
jqLoadAjaxForm loads a form in a a centered popup window 
*/

 
// DTA v428 21.7.2008 Cette fonction n'est plus utilié nulle part. Je la mets en commentaire.
/*
function jqLoadAjaxForm(url, formId, strCloseText, callback) {
	//First remove any existing div container
	$('#divAjaxForm').remove();
	$('body').prepend("<div id='divAjaxForm'><div id='divAjaxTitle'><a href=''>" + strCloseText + "</a></div><div id='divAjaxContent'></div></div>");
	$('#divAjaxForm').css({position: "absolute", display:"none"});			
	$('#divAjaxTitle a').click(function(){$('#divAjaxForm').remove(); return false;})
	$('#divAjaxForm').Draggable({handle:'#divAjaxTitle'});
	$('#divAjaxContent').loadIfModified(url, function(){
		var posX = document.body.clientWidth;
		var posY = document.body.clientHeight;
		posX = (posX - $('#divAjaxForm').width()) /2 + document.body.scrollLeft;
		posY = (posY - $('#divAjaxForm').height()) /2 + document.body.scrollTop;
		$('#divAjaxForm').css({position: "absolute", 
													left: posX + "px",
													top: posY + "px" });			
		//$('#divAjaxForm').width('1000px');
		$('#divAjaxForm').fadeIn('slow');
		//Add the form handler
		$('#' + formId).ajaxForm(function(r){
			//hide the container
			$('#divAjaxForm').fadeOut(function(){$('#divAjaxForm').remove()});
			//Call the callback
			callback(r);
		});
	});	

}
*/

/*
jqLoadAjaxIFrame loads a form in a a centered popup window with the content in an iframe 
To be further enhanced...
*/
function jqLoadAjaxIFrame(url, pwidth, pheight, strCloseText, callback) {
	//First remove any existing div container
	$('#divAjaxForm').remove();
	$('body').prepend("<div id='divAjaxForm'><div id='divAjaxTitle'><a href=''>" + strCloseText + "</a></div><div id='divAjaxContent'><iframe id='iframeAjaxContent' frameborder='0' hspace='0' src='" + url + "' style='width:" + (pwidth-30) + "px;height:" + (pheight-40) + "px' onload='jqIFrameLoaded();'></iframe></div></div>");
	$('#divAjaxForm').css({position: "absolute", display:"none"});
	$('#divAjaxTitle a').click(function(){$('#divAjaxForm').remove(); return false;})
	$('#divAjaxForm').Draggable({handle:'#divAjaxTitle'});

	var posX = document.body.clientWidth;
	var posY = document.body.clientHeight;
	posX = (posX - pwidth) /2 + document.body.scrollLeft;
	posY = (posY - pheight) /2 + document.body.scrollTop;
	$('#divAjaxForm').css({position: "absolute", 
							left: posX + "px",
							top: posY + "px", width: pwidth + 'px', height:pheight + 'px' });			
}

function jqIFrameLoaded() {
	$('#divAjaxForm').fadeIn('slow');
	//alert('w:' + $('#divAjaxContent').width() + ', h: ' + $('#divAjaxContent').height());
	//alert('w:' + $('#divAjaxForm').width() + ', h: ' + $('#divAjaxForm').height());
}

//Add the trim function to the string object
String.prototype.trim = function(){return this.replace(/^\s+|\s+$/g, "")};

// DTA v428 15.7.2008
// vérifie qu'un captcha est valide
function jsCheckCaptcha(pstrHashCode, pstrCode)
{
	var objCaptcha;
	
	$.ajax({
		type:'GET',
		async:	false,
		dataType:'json',
		url:'/qsPortal/Ajax/Get.asp', 
		data:"Ajax=captcha&_strHashCode=" + pstrHashCode + "&_strCode=" + pstrCode,
		error:function(req, err)
		{
			alert(err);
		},
		success:function(req)
		{
			objCaptcha = req;
		}
	});
	
	try
	{
		return objCaptcha.blnValid;
	}catch(e)
	{
		return false;
	}	
	
}

//QSP395 : Changed the resize to only resize vertically and add horizontal scrollbars if needed
//The height is also adjusted with 22px more to give some space to the scrollbar.
function adjustIFrameSize (iframeWindow) {
	var s = iframeWindow.name;
	s = s.replace(/_*$/, '');
	if (navigator.appVersion.indexOf("Safari") != -1) {
	//Treat Safari here
	}		
	else if (iframeWindow.document.height) {
	//How comes here
    var iframeElement = parent.document.getElementById(s);
    if (iframeElement) {
		iframeElement.style.height = iframeWindow.document.height + 22 + 'px';
    }
    //iframeElement.style.width = iframeWindow.document.width + 'px';
  }
  else if (document.all) {
    //IE comes here
    var iframeElement = parent.document.all[s];
    if (iframeElement) {
	if (iframeWindow.document.compatMode &&
		iframeWindow.document.compatMode != 'BackCompat') 
	{
		iframeElement.style.height = iframeWindow.document.documentElement.scrollHeight + 22 + 'px';
		//iframeElement.style.width = iframeWindow.document.documentElement.scrollWidth + 0 + 'px';
	}
	else {
		//IE 6.0 comes here			
		iframeElement.style.height = iframeWindow.document.body.scrollHeight + 22 + 'px';
		//iframeElement.style.width = iframeWindow.document.body.scrollWidth + 0 + 'px';
	}
	}
}
  //Scroll the page to the top
  if (document.body.scrollTop)
	document.body.scrollTop = 0;
}


// DTA 8.11.2007 retourne un texte traduit par la base de donnée de traduction
function jsTrad(pstrText)
{
	var strTradText = '';
	
	$.ajax({
		type:'GET',
		async:	false,
		dataType:'html',
		url:'/qsPortal/Ajax/Get.asp', 
		data:"Ajax=Trad&strText=" + pstrText,
		error:function(req, err)
		{
			alert(err);
		},
		success:function(req)
		{
			strTradText = req;
		}
	});
	
	return strTradText;
	
}

// DTA v422 29.1.2008 Fonction permentant d'évaluer les javascriptscript après un appel ajax
function jsPostEval(pobjElement, pblReplaceVar)
{
	strJs = '';
	$(pobjElement).find("script").each(function(){
		if(this.innerHTML)
			// DTA v423 4.2.2008 On n'interprète pas les script qui contiennent la fonction jsOEA
			if(this.innerHTML.indexOf("jsOEA") == -1)
				strJs += '\n' + this.innerHTML;
	});
	// si une variable est initialisé avec le mot clé var, il n'est pas évalué par la fonction eval()
	// on supprime donc tous les var
	if(typeof(pblReplaceVar) != "undefined")
		if(pblReplaceVar == true)
			strJs = strJs.replace(/var /g, '');
	eval(strJs);
}

// DTA v423 6.2.2008 Fonction qui retourne vrai si le contenu d'un champs text est un caractère
// e = objet event retourné par un objet textbox
function jsIsNumber(e)
{
      blnRet = false;
      lngChar = e.keyCode;
      
      // si keyCode est à zéro,
      // on utilise certainement Firefox qui utilise
      // l'attribut charCode
      if(lngChar == 0)
            lngChar = e.charCode;
      
      // chiffre de 0 à 9
      if(lngChar > 47 && lngChar < 58)
            blnRet = true;

      // insert
      if(lngChar == 45)
            blnRet = true;
      
      // caractère point      
      if(lngChar == 46)
            blnRet = true;

      // delete
      if(lngChar == 46)
            blnRet = true;

      // Backspace
      if(lngChar == 8)
            blnRet = true;

      // Home
      if(lngChar == 36)
            blnRet = true;

      // End
      if(lngChar == 35)
            blnRet = true;
      
      // flèche
      if(lngChar > 36 && lngChar < 41)
            blnRet = true;
                        
      // alert(blnRet);
      return blnRet;
      
}

// DTA v428 16.6.2008 Fonction qui retourne vrai si le contenu d'un champs text est un temps
// e : objet event retourné par un objet textbox
function jsIsTime(e)
{
	blnRet = false;
	
	lngChar = e.keyCode;
	
	if(lngChar == 0)
		lngChar = e.charCode;
		
	blnRet = jsIsNumber(e);

	// Deux-point (:)
	if(lngChar == 58)
		blnRet = true;

	// alert(blnRet);
	return blnRet;
}

// DTA v423 13.02.2008 lance une requête au serveur toutes les 5 min. pour marquer sa présence
function jsKeepAlive()
{
	if(jQuery)
		jQuery.ajax({
			type:'GET',
			async:	false,
			dataType:'html',
			url:'/qsPortal/Ajax/Get.asp', 
			data:'Ajax=KeepAlive',
			error:function(req, err)
			{
			},
			success:function(req)
			{
				//
				// evite un bug avec internet explorer.
				// si la fonction est lancé dans un tickbox et que celle si est refermé tout de suite après,
				// le timer n'est pas annulé et s'execute après les 5 minutes. La fonction n'est plus retrouvé 
				// pour je ne sais quelle raison et on obtient un message d'erreur.
				//
				// On teste à présent si la fonction est toujours présente avant de l'executer une seconde fois.
				// 
				//setTimeout("jsKeepAlive()", 5 * 60 * 1000);
				setTimeout("if(typeof(jsKeepAlive) == 'function') jsKeepAlive()", 5 * 60 * 1000);
			}
		});
}

// DTA v424 3.3.2008 retourne un objet contenant la position de l'écran
function clsqsScreenRect(pobjWindow)
{
	if(!pobjWindow)
		pobjWindow = window;
	
	if (pobjWindow.pageYOffset || pobjWindow.pageXOffset) {
		yScrolltop = pobjWindow.pageYOffset;
		xScrollleft = pobjWindow.pageXOffset;
	} else if (pobjWindow.document.documentElement && pobjWindow.document.documentElement.scrollTop || pobjWindow.document.documentElement.scrollLeft ){   // Explorer 6 Strict
		yScrolltop = pobjWindow.document.documentElement.scrollTop;
		xScrollleft = pobjWindow.document.documentElement.scrollLeft;
	} else if (pobjWindow.document.body) {// all other Explorers
		yScrolltop = pobjWindow.document.body.scrollTop;
		xScrollleft = pobjWindow.document.body.scrollLeft;
	}
	pageWidth = pobjWindow.innerWidth || pobjWindow.document.body.clientWidth;
	pageHeight = pobjWindow.innerHeight || pobjWindow.document.body.clientHeight;

	xScrollMax = pobjWindow.scrollMaxX || pobjWindow.document.body.scrollWidth;
	yScrollMax = pobjWindow.scrollMaxY || pobjWindow.document.body.scrollHeight;
	
	this.Page = { 
		Width: pageWidth + xScrollMax,
		Height: pageHeight + yScrollMax 
	};
	this.View = { 
		Width: pageWidth,
		Height: pageHeight 
	};
	this.Rect = {
		minX: xScrollleft,
		minY: yScrolltop,
		maxX: xScrollleft + pageWidth,
		maxY: yScrolltop + pageHeight
	}
	return this;
}

//
// DTA v426 29.4.2008 Retourne la valeur d'une clée se trouvant dans le querystring
//
function jsGetQueryString(pstrKey)
{
	var strQuery = window.location.search.substring(1);
	var arrVars = strQuery.split('&');

	for (i = 0; i < arrVars.length; i++) {
		var arrPair = arrVars[i].split('=');
		if ( arrPair.length > 1) {
			if (arrPair[0].toLowerCase() == pstrKey.toLowerCase()) {
				return arrPair[1];
			}
		}
	}
	
	return null;
}

// RSC 29.05.2008 Ajoute le noeud dans les logs QuickAd
function jsQuickAdLog(plngNodeFK, plngContextNodeFK, pstrUrl)
{
	
	$.ajax({
		type:'POST',
		async:	false,
		dataType:'html',
		url:'/qsPortal/Ajax/QuickAdLog.asp', 
		data:"N=" + plngNodeFK + "&C=" + plngContextNodeFK + "&U='" + encodeURIComponent(pstrUrl) + "'",
		error:function(req, err)
		{
		},
		success:function(req)
		{
		}
	});
	
	return true;
	
}
