// check the screen resolution
var reg = /-$|[\s;~]/

/* Fix Bug 22072 : ne pas bloquer le client
if (screen.width<1024||screen.height<768) {
  location = "screen_size_ko.jsp";
}
*/


function validateSubaccount(errorMessage){
  var subac = document.loginForm.userSubac.value;
  if(subac == undefined){
	  return true;
	}
  if(reg.test(subac)){
    alert(errorMessage);
    return false;
  }else if(subac.length > 30){
	alert(subaccountMaxSizeError);
	return false;  
  }else{
    return true;
  }
}

 // Checks if parameter is a letter or digit and any other specified character
 // e.g. isLetterOrNumber('i', "_-. @:") returns true
 // e.g. isLetterOrNumber('@', "_-. @:") returns true
 // e.g. isLetterOrNumber('$', "_-. @:") returns false
 function isLetterOrNumber(c, otherChars)
 {
	var cList = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" + otherChars;
	for (var i = 0; i < cList.length; i++)
	{
		 if (cList.charAt(i) == c)
			return true;
	}
	return false;
 }
 
/*
* Submit form in a frame.
*
* @param actionUrl Name of the action (ex: viewPrefrences).
* @targetValue Name of the form target (frame name)
* @actionToPerform Name of the action
*/
function doAction(actionUrl, frameName, targetValue, event, referer){
	var formElement = null

  	if (frameName != null && frameName.length > 0)
  	{
  		formElement = top.frames[frameName].document.getElementById('mainFormId');
  	}
  	else
  	{
  		formElement = document.getElementById('mainFormId');
  	}

  // Action url
  formElement.action=actionUrl;
  // Form target-> frame name
  if(targetValue != "" && targetValue != null)
    formElement.target=targetValue; // refresh specified frame
  else
    formElement.target="_parent"; // refresh all
  // Action tag name
  formElement.event.value=event;
  formElement.referer.value=referer;
  // Finally do submit
  formElement.submit();
}


/* Save all form in 'allFormHistory' field of the form
@param name of the form to save
*/
function saveAllForm(formName){
  var allForm="";
  var searchForm = formName;
  for(i=0;i<searchForm.length;i++){
    var cur = +searchForm[i];
    if(searchForm[i].name != "")
      allForm += ("document.searchForm." + searchForm[i].name+".value=unescape('"+doReplaceQuote(searchForm[i].value)+"');");
    if(searchForm[i].type == 'radio' || searchForm[i].type == 'checkbox'){
      if(searchForm[i].checked)
        allForm += ("document.searchForm["+i+"].checked='"+searchForm[i].checked+"';");
      else
        allForm += ("document.searchForm["+i+"].checked='';");
    }
    if(searchForm[i].type == 'select-one'){
      allForm += ("document.searchForm["+i+"].selectedIndex=" +searchForm[i].selectedIndex + ";");
    }
  }
  searchForm.allFormHistory.value=allForm;
}

function doVoid()
{
}

//	TRAP F5
if (navigator.userAgent.toLowerCase().indexOf("safari") == -1 && navigator.userAgent.toLowerCase().indexOf("opera") == -1){
	function processKeyDown(evt){
		if(evt != null && evt.keyCode == 116) 
	    { // Capture and remap F5
				if(window.addEventListener)
					evt.preventDefault();
				else
					evt.keyCode = 505;
				if (top.frames["mainFrame"] != undefined)
				{
					top.frames["mainFrame"].location = top.frames["mainFrame"].document.URL
				}
				return false;
		}
	} 
    
	if(window.addEventListener){ // Mozilla, Netscape, Firefox
		window.addEventListener('keypress', processKeyDown, false);
	
	} else { // IE
		document.attachEvent('onkeydown', processKeyDown);
	}
}

//------------------------------------------------------------------------------
// Fonction de gestion du layer - Please wait

function doWaitSubmit(){
  displayWait()
  return true;
}

function displayWait(){
  setTimeout("displayWaitingLayer('centerLayer');",0) //setTimeout needed to get animation on gif
}

function displayWaitingLayer(id){
	var doc;
	var offset;
	var leftOffset;
	var bodyWidth;

	var docObj = null;

	if (window.name == "")
	{
		leftOffset = 160;
	}
	else
	{
		leftOffset = 0;
	}

	if (top.frames["main"] == undefined)
	{
		docObj = document;
	}
	else
	{
		docObj = top.frames["main"].document;
	}
	
	doc = docObj.getElementById(id);
	if (doc != null)
	{
		offset = docObj.body.clientHeight;
		bodyWidth = docObj.body.clientWidth;
		centerLayerFrameObj = docObj.getElementById(id+"Frame");
		doc.style.top=(offset - 106)/2;
		doc.style.left=(leftOffset + bodyWidth - 327)/2;
		if (centerLayerFrameObj)
		{
			centerLayerFrameObj.style.top=doc.style.top
			centerLayerFrameObj.style.left= doc.style.left
			centerLayerFrameObj.style.zIndex  = doc.style.zIndex -1;
			centerLayerFrameObj.style.visibility ='visible';
		}
		doc.style.visibility='visible';
	}
}

function hideWaitingLayer(id)
{
	if (id == undefined)
	{
		id = "centerLayer"
	}
	var doc;
	if(top.frames["main"] == undefined)
	{
		doc = document;
	}
	else
	{
		doc = top.frames["main"].document;
	}
	doc.getElementById(id).style.visibility='hidden';
	var frameObj = doc.getElementById(id+"Frame");
	if (frameObj != null)
	{
		frameObj.style.visibility='hidden';
	}
}



function calcul_temps(){
  var encore_toujours = new Date();
  return((encore_toujours.getTime() - Start)/1000);
}


// Fonction MM_preloadImages
function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
  var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
  if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}



function MM_findObj(n, d) { //v4.01


  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {


    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}


  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];


  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);


  if(!x && d.getElementById) x=d.getElementById(n); return x;


}


//------------------------------------------------------------------------------


// Fonction MM_swapImage


function MM_swapImage() { //v3.0


  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)


   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}


}




function isIE()
{
   var agt = navigator.userAgent.toLowerCase();
   return ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
}


//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
function openCenteredWindow(url, width, height, name)
{
	var id = Math.random();
	if (url.indexOf("?") == -1)
	{
		url = url + "?id="+id
	}
	else
	{
		url = url + "&id="+id
	}

	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width +",modal=yes,resizable=yes,scrollbars=yes,status=no"
	var win = window.open("popup.jsp?"+url, name, winParms);
	win.focus();

}

function openRightWindow(url, width, height, name)
{
	var id = Math.random();
	if (url.indexOf("?") == -1)
	{
		url = url + "?id="+id
	}
	else
	{
		url = url + "&id="+id
	}

	var left = Math.floor( (screen.width - width -40));
	var top = Math.floor( (screen.height - height) / 2);
	var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width +",modal=yes,resizable=yes,scrollbars=yes,status=no"
	var win = window.open("popup.jsp?"+url, name, winParms);
	win.focus();

}

// Fonction openCenteredModalWindow


function openCenteredModalWindow(url, width, height, name) {

	/* cannot use window.showModalDialog (texte not selectable, title in WIN local) */
	var id = Math.random();
	if (url.indexOf("?") == -1)
	{
		url = url + "?id="+id
	}
	else
	{
		url = url + "&id="+id
	}

		var left = Math.floor( (screen.width - width) / 2);
 		var top = Math.floor( (screen.height - height) / 2);
   		var winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width +",modal=yes,resizable=yes,scrollbars=no,status=no"
   		var win = window.open(url, name, winParms);
	    win.focus();
}


function openWindow(url, name)
{
	var win = window.open(url, name)
	win.focus()
}

function openHelpWindow(args){
  var winParms="";
  var params = args.split(",")
  if (params[1]!=null && params[2]!=null)
  {
	var width = params[1];
	var height = params[2];
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
    winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width +",modal=yes,resizable=yes,scrollbars=yes,status=no"
  }
   var win = window.open(params[0], 'help', winParms);
   win.focus();
}

function openHelpWindowFormBtn(url, width, height){
   var winParms="";
	var left = Math.floor( (screen.width - width) / 2);
	var top = Math.floor( (screen.height - height) / 2);
    winParms = "top=" + top + ",left=" + left + ",height=" + height + ",width=" + width +",modal=yes,resizable=yes,scrollbars=yes,status=no"
   var win = window.open(url, 'WIZARD_HELP', winParms);
   win.focus();
}


//------------------------------------------------------------------------------
// Fonction AutoScroll

function doAutoScroll()
{
	var scroller = document.getElementById("Search_scroller")
	scroller.height=50+document.body.scrollTop
}
 
function doInitAutoScroll()
{
	var agt=navigator.userAgent.toLowerCase();
	if (agt.indexOf("msie") != -1)
	{
		window.onscroll=doAutoScroll
	}
	else
	{
		window.addEventListener('scroll', doAutoScroll, false);
	}
}
//------------------------------------------------------------------------------

// Fonction trim


function trim(inputString) 

{

   // Removes leading and trailing spaces from the passed string. Also removes

   // consecutive spaces and replaces it with one space. If something besides

   // a string is passed in (null, custom object, etc.) then return the input.

   if (typeof inputString != "string") { return inputString; }

   var retValue = inputString;

   var ch = retValue.substring(0, 1);

   while (ch == " ") { // Check for spaces at the beginning of the string

      retValue = retValue.substring(1, retValue.length);

      ch = retValue.substring(0, 1);

   }

   ch = retValue.substring(retValue.length-1, retValue.length);

   while (ch == " ") { // Check for spaces at the end of the string

      retValue = retValue.substring(0, retValue.length-1);

      ch = retValue.substring(retValue.length-1, retValue.length);

   }

   while (retValue.indexOf("  ") != -1) { // Note that there are two spaces in the string - look for multiple spaces within the string

      retValue = retValue.substring(0, retValue.indexOf("  ")) + retValue.substring(retValue.indexOf("  ")+1, retValue.length); // Again, there are two spaces in each of the strings

   }

   return retValue; // Return the trimmed string back to the user

} // Ends the "trim" function


// This function replaces all instances of findStr in oldStr with repStr.

function replaceAll(oldStr,findStr,repStr) {
  var srchNdx = 0;  // srchNdx will keep track of where in the whole line
                    // of oldStr are we searching.
  var newStr = "";  // newStr will hold the altered version of oldStr.
  while (oldStr.indexOf(findStr,srchNdx) != -1)  
                    // As long as there are strings to replace, this loop
                    // will run. 
  {
    newStr += oldStr.substring(srchNdx,oldStr.indexOf(findStr,srchNdx));
                    // Put it all the unaltered text from one findStr to
                    // the next findStr into newStr.
    newStr += repStr;
                    // Instead of putting the old string, put in the
                    // new string instead. 
    srchNdx = (oldStr.indexOf(findStr,srchNdx) + findStr.length);
                    // Now jump to the next chunk of text till the next findStr.           
  }
  newStr += oldStr.substring(srchNdx,oldStr.length);
                    // Put whatever's left into newStr.             
  return newStr;
}

function URLDecode(psEncodeString, force) 
{
  var result;
  var unescaped = unescape(psEncodeString)

 if (force != true && psEncodeString == unescaped) {
	 //avoid removing + when URLDecode calles multiple times
	 result = unescaped
 }else{
	 // Create a regular expression to search all +s in the string
	  var lsRegExp = /\+/g;
	 result = unescape(String(psEncodeString).replace(lsRegExp, " ")); 
	}

  return result;
}
function doReplaceQuote(input)
{
	return replaceAll(input, "'", "\\'");
}
/*************************************************************************/

function getCookieVal(offset)
{
   var endstr=document.cookie.indexOf (";", offset);
   if (endstr==-1) endstr=document.cookie.length;
   return unescape(document.cookie.substring(offset, endstr));
}

function readCookie(nom)
{
   var arg=nom+"=";
   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 writeCookie(name, value)
{
   var argv=writeCookie.arguments;
   var argc=writeCookie.arguments.length;
   var expires=(argc > 2) ? argv[2] : null;
   var path=(argc > 3) ? argv[3] : null;
   var domain=(argc > 4) ? argv[4] : null;
   var secure=(argc > 5) ? argv[5] : false;
   document.cookie=name+"="+escape(value)+
      ((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
      ((path==null) ? "" : ("; path="+path))+
      ((domain==null) ? "" : ("; domain="+domain))+
      ((secure==true) ? "; secure" : "");
}

function eraseCookie(nom){
  date=new Date;
  date.setFullYear(date.getFullYear()-1);
  writeCookie(nom,null,date);
}

/* Change current url protocol.*/
function setUrl(url){
  var newUrl = url; // default
  if(url.indexOf("https") != -1)
    newUrl = url.replace("https", "http");
  else
    newUrl = url.replace("http", "https");
  top.location = newUrl;
}


function changeSelection(documentId, base, position) {
  var state = "0";
  var checkbox = document.getElementById("s"+documentId);
  if (checkbox.checked) {
    state = "1";
  }
  var xhr_object = null;   
  if(window.XMLHttpRequest)  {
   // Firefox
    xhr_object = new XMLHttpRequest();   
  } else if(window.ActiveXObject) { 
    // Internet Explorer 
    xhr_object = new ActiveXObject("Microsoft.XMLHTTP");   
  } else { // XMLHttpRequest non support? par le navigateur   
    alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");   
    return;   
  } 
  
  xhr_object.open("GET", "select?base=" + base + "&position=" + position + "&state=" + state + "&id=" + Math.random(), true);
  xhr_object.onreadystatechange = function() {   
    if(xhr_object.readyState == 4) { 
      if (xhr_object.status != "200") {
        if (checkbox.checked) {
          checkbox.checked = false;
        } else {
          checkbox.checked = true;
        }
      }
    }
  }     
  xhr_object.send(null);
}


///PROCESS LAYER

var maxnbLines = 200;
var on = false;
var interv = null;
	function displayPercent(max)
	{
		maxnbLines = max;
		displayWaitingLayer('processLayer')
		interv = window.setInterval("calc()",100)

	}

	function calc()
	{
		 var objTable = document.getElementById('Hitlist');
		 if (objTable != null)
		 {
			 var nbLines = objTable.rows.length;
			 disp( parseInt((nbLines/maxnbLines)*100)*0.75);
		 }
		 else {
			objTable = document.getElementById('tableFamily');
			if (objTable != null)
			{   
				var nbFam = document.extendedFamForm.rangeFam.value;
				disp( parseInt((nbFam/maxnbLines)*100)*0.75);
			}
		 }
	}

	function disp(width)
	{
		 var obj = document.getElementById('percentLayer');
		 obj.style.width = width + "%";

	}
	function hideProcessLayer()
	{
		disp(100);
		window.clearInterval(interv);
		hideWaitingLayer('processLayer');
	}

// ==================================================================================
// Shopping basket pour la commande de PDFs
// ==================================================================================

// Remplace l'icone PDF par la croix et maj le title	
function changeIconePDF(imgId, newtitle) {
	document.getElementById(imgId).src='images/pdf_rem.gif';
	document.getElementById(imgId).title=newtitle;
}

// Commande de PDF directe vers PDS pour mode "portfolio" (appel en mode asynchrone)
function directOrderToPDS(xpn, kind, imgId, newtitle, msginfo) {
  
  if (document.getElementById(imgId).title == newtitle) {	// icone d?j? chang?e ==> PDF venant juste d'?tre command? : ne pas rappeler PDS
        alert(msginfo);
        return;
  }

  var xhr_object = null;   
  if(window.XMLHttpRequest)  {
   // Firefox
    xhr_object = new XMLHttpRequest();   
  } else if(window.ActiveXObject) { 
    // Internet Explorer 
    xhr_object = new ActiveXObject("Microsoft.XMLHTTP");   
  } else { // XMLHttpRequest non support? par le navigateur   
    alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");   
    return;   
  } 
  
  var url = "directOrderToPDS.jsp?xpn=" + xpn + "&kind=" + kind + "&imgId=" + imgId;;
  //alert("url=" + url);

  xhr_object.open("GET", url , true);
  xhr_object.onreadystatechange = function() {   
    if(xhr_object.readyState == 4) { 	  // complete
      if (xhr_object.status == "200") {	  //OK : changer icone PDF par la croix et maj le title
        document.getElementById(imgId).src='images/pdf_rem.gif';
		document.getElementById(imgId).title=newtitle;
      }
    }
  }     
  xhr_object.send(null);
}

function getCookieValue(name){
    var cookieValue="";
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    //alert(document.cookie);
    for(var i=0;i < ca.length;i++){
        var c = ca[i];
        while (c.charAt(0)==' '){
          c = c.substring(1,c.length);
        }
        if (c != "undefined" && c.indexOf(nameEQ) == 0 ){
          cookieValue= c.substring(nameEQ.length,c.length);
        }
    }
    return cookieValue;
}

function getTime(){
  //var now = new Date(new Date().getTime() + new Date().getTimezoneOffset()*60*1000 + 3600*1000);
  var now = new Date();
  var gmt = new Date().getTimezoneOffset()/60*-1;
  if(gmt == 0){
    gmt = " (GMT)";
  }else{
    if(gmt > 0){
      gmt = " (GMT+"+gmt+")";
    }else{
      gmt = " (GMT"+gmt+")";
    }
  }
  var minutes = now.getMinutes();
  var seconds = now.getSeconds();
  var hours = now.getHours();
  if(minutes < 10)
    minutes = "0"+minutes;
  if(seconds < 10)
    seconds = "0"+seconds;
  if(hours < 10)
    hours = "0"+hours;
  return hours+":"+minutes+":"+ seconds +gmt;
}



