// Generic Functions
// Copyright Guillaume Hérisson 2006
// By Guillaume Herisson - June 11th 2006 


/* Generic Browser Testing */
if(!document.all) {
	/* NS 4.7 and below */
	if(!document.getElementById) {
		var layerSwitch = 'document.layers';
		var formSwitch = 'document.forms';
		var flgNestedForm = true;
		var openBracketSwitch = '["';
		var closeLayerBracketSwitch = '"]';
		var closeFormBracketSwitch = '"]';
		var styleSwitch = '';
		var showSwitch = 'show';
		var hideSwitch = 'hide';
	/* NS 6.0 */
	} else {
		var layerSwitch = 'document.getElementById';
		var formSwitch = 'document.getElementsByName';
		var flgNestedForm = false;
		var openBracketSwitch = '("';
		var closeLayerBracketSwitch = '")';
		var closeFormBracketSwitch = '")[0]';
		var styleSwitch = '.style';
		var showSwitch = 'visible';
		var hideSwitch = 'hidden';
	}
/* IE 5.5 and below */
} else {
	var layerSwitch = 'document.all';
	var formSwitch = 'document.all';
	var flgNestedForm = false;
	var openBracketSwitch = '["';
	var closeLayerBracketSwitch = '"]';
	var closeFormBracketSwitch = '"]';
	var styleSwitch = '.style';
	var showSwitch = 'visible';
	var hideSwitch = 'hidden';
}

// Internet Explorer Specific
function isBrowserIE() {
	return (navigator.appVersion.indexOf("MSIE") != -1) ? true : false;
}

// Windows Specific
function isBrowserWindows() {
	return (navigator.appVersion.indexOf("Windows") != -1) ? true : false; // true if we're on windows
}

/* This function returns the object for the layer ID passed in. */
function getEltById(id) {
	return eval(layerSwitch + openBracketSwitch + id + closeLayerBracketSwitch);
}

/* This function returns the style of an object ID passed in.*/
function getEltStyleById(id,style){ 
  return eval(layerSwitch + openBracketSwitch + id + closeLayerBracketSwitch + styleSwitch + '.' + style);
}

/* This function set the style of an object ID passed in.*/
function setEltStyleById(id,style,value)
{
  var elt=eval(layerSwitch + openBracketSwitch + id + closeLayerBracketSwitch + styleSwitch);
  elt[style]=value;
}

/* This function hide an element id.*/
function showElt(id) {
  setEltStyleById(id,"display","block");
  //setEltStyleById(id,"display","inline"); 
  //setEltStyleById(id,"visibility","visible");
}

/* This function shows an element id.*/
function hideElt(id) {
  setEltStyleById(id,"display","none");
  //setEltStyleById(id,"visibility","hidden");
}

/* This function hide a table row.*/
function showTableRow(id) {
  if (isBrowserIE()) setEltStyleById(id,"display","block"); 
  else setEltStyleById(id,"display","table-row"); 
}

/* This function shows a table row.*/
function hideTableRow(id) {
  setEltStyleById(id,"display","none");
}

/* This function shows an element while hiding the other.*/
function switchEltDisplay(show,hide) {
 	showElt(show);
	hideElt(hide);
}

/* This function toggles the element visibility.*/
function layerToggleVisibility(id)
{
 if (getEltStyleById(id,"visibility")=="visible")
 {
  setEltStyleById(id,"visibility","hidden");
 }
 else 
 {
  setEltStyleById(id,"visibility","visible");
 }
}

/* This function returns the object for the form name passed in. */
function getForm(formName) {
	var theForm=eval(formSwitch + openBracketSwitch + formName + closeFormBracketSwitch);
	if (theForm==null) 
	{
	 alert("Error, form " + formName + " null !");
	 return false;
	}
	
	return theForm;
}


/* This function returns the field object for the form and field name passed in. */
function getFormField(formName,fieldName) {
	return eval(formSwitch + openBracketSwitch + formName + closeFormBracketSwitch + '.' + fieldName);
}

/* This function returns a string representing the object for a form(formName) nested in a layer(layerName).
	Use the eval() function on this string to get the form object. */
function getNestedForm(layerName, formName) {
	if (!flgNestedForm) {
		return getForm(formName);
	} else {
		return eval(layerSwitch + openBracketSwitch + id + closeLayerBracketSwitch + '.' + formSwitch + openBracketSwitch + formName + closeFormBracketSwitch);
	}
}

/* begin functions for rollovers */
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_findObj(n, d) { //v3.0
  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); return x;
}

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 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;
}
/* end functions for rollovers */

/* begin global functions */

/* Opens a new browser window
		page: the URL of the page to load in the new window
		windowName: a name given to the window
		winWidth, winHeight: the width and height of the new window
*/
function openWindow(page, windowName, winWidth, winHeight, winSpec, flgReturnObj) {
    var sizeSpec;
	if (!winSpec) {
		sizeSpec='toolbar=0,location=0,directories=0,left=10,top=10,status=no,menubar=0,scrollbars=1,resizable=yes,width='+winWidth+',height='+winHeight;
	} else {
		sizeSpec=winSpec+',width='+winWidth+',height='+winHeight;
	}
    var windowObject;
	windowObject=window.open(page,windowName,sizeSpec);
	if (flgReturnObj) return windowObject;
}

/*  Changes the text in the status bar
		statusText: the text to display
*/
function winStat(statusText) {
	window.status=statusText;
	return true;
}

/* end global functions */

/* begin generic functions */

/*
 * Generic Form Check Functions
 */
function getArticle(name) {
	if (name.charAt(0)=='a' || name.charAt(0)=='A' ||
	    name.charAt(0)=='e' || name.charAt(0)=='E' ||
		name.charAt(0)=='i' || name.charAt(0)=='I' ||
		name.charAt(0)=='o' || name.charAt(0)=='O' ||
		name.charAt(0)=='u' || name.charAt(0)=='U') return 'an ' + name;
	 return 'a ' + name;
}

/* Check if a field contains a text */
function checkStrField(theField,name) {
	if (trimStr(theField.value)=="")
	{
	 alert("Please enter " + getArticle(name) + '!');
	 theField.focus();
	 return false;
	}
	return true;
}

/* Check if a field contains an integer */
function checkIntField(theField,name) {
	if (!checkStrField(theField,name)) return false;
	if (!isInteger(trimStr(theField.value)))
	{
	 alert("Please enter an integer for the " + name + '!');
	 theField.focus();
	 return false;
	} 
	return true;
}

/* Check if a field contains a number */
function checkFloatField(theField,name) {
	if (!checkStrField(theField,name)) return false;
	if (!isNumber(trimStr(theField.value)))
	{
	 alert("Please enter a valid number for the " + name + '!');
	 theField.focus();
	 return false;
	} 
	return true;
}

/* Clears the text in a text input
		formName: the name of the form that contains the input
		inputName: the name of the input to clear
		defaultText: the text that should be cleared
*/
function clearField(formName, inputName, defaultText) {
	var field = getFormField(formName,inputName);
	if (field.value == defaultText) {
		field.value = '';
	}
	return true;
}

/* Trim string */
function trimStr(str) {
	var strObj = new String(str);
	while(strObj.charAt(0)==' '||strObj.charAt(0)=='\t'||strObj.charAt(0)=='\n') {
		strObj=strObj.substring(1,strObj.length);
	}
	while(strObj.charAt(strObj.length-1)==' '||strObj.charAt(strObj.length-1)=='\t'||strObj.charAt(strObj.length-1)=='\n') {
		strObj=strObj.substring(0,strObj.length-1);
	}
	
	return strObj;
}

/* Compare string */
function cmpStr(str1,str2) {
	return str1.toString()==str2.toString();
}

/* Compare no case string */
function cmpStrNoCase(str1,str2) {
	return str1.toString().toLowerCase()==str2.toString().toLowerCase();
}

/* Replaces text s1 with s2 in string str*/
function replaceStr(str,s1,s2) 
{
	var strObj = new String(str);
	var s1Obj = new String(s1);
	var s2Obj = new String(s2);
	var newstr = new String('');
	
    if ((strObj.length == 0) || (s1Obj.length == 0)) return str;
	for (i=0;i<strObj.length;++i)
	{
	 if (s1Obj == strObj.substring(i,i+s1Obj.length))
	 {
	  i+=s1Obj.length-1;
	  newstr+=s2Obj;
	 }
	 else
	 {
	  newstr+=strObj.charAt(i);
	 }
	}
    return newstr;
}

/* Checks if a string is a valid email address
				begins with letter or digit, contains letters, digits, or any ".-"
				followed by an "@" followed by letters, digits, or any ".-" followed by two or three letters
		email: the string to test
*/
function isEmail(email) {
        if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
           return true ;

        return false;
}

/* Checks if a string is a valid credit card
		ccno: the string to test
*/
function isCCNumber(ccno) {
	    var creditCardPattern = /[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]/;
	
		if (ccno == "" || creditCardPattern.exec(ccno) == null) return false;

        return true;
}

/*  Checks if a string is alphanumeric
				begins with letter or digit, contains letters, digits, or any ".-"
				followed by an "@" followed by letters, digits, or any ".-" followed by two or three letters
		email: the string to test
*/
// Test Letter
// listas de caracteres

function isLetter(c)
{
    return (((c >= "a") && (c <= "z"))||((c >= "A") && (c <= "Z")));
}

// Test Digit
function isDigit(c)
{   
 return ((c >= "0") && (c <= "9"))
}


function isUserName(s) 
{
    var i;
	var c;
	
    if (s.length==0) return false;

    c = s.charAt(0);
	
	if (! (isLetter(c) || isDigit(c))) return false;
	
    for (i = 0; i < s.length; ++i)
    {   
        c = s.charAt(i);
        if (! (isLetter(c) || isDigit(c) || c=="@" || c=="." || c=="-") )
        return false;
    }

    return true;
}


function isPassword(s) 
{
    var i;
	var c;
    if (s.length==0) return false;

    return true;
}

function isCode(s) 
{
    var i;
	var c;
	
    if (s.length==0) return false;
	
    for (i = 0; i < s.length; ++i)
    {   
        c = s.charAt(i);
		if (!isLetter(c) && !isDigit(c)) return false;
    }

    return true;
}

function isPath(s) 
{
    var i;
	var c;
	
    if (s.length==0) return false;
	
    for (i = 0; i < s.length; ++i)
    {   
        c = s.charAt(i);
		if (!isLetter(c) && !isDigit(c) && c!='/') return false;
    }

    return true;
}



/* Checks if a string is a number
				the valid formats are:
					123, 1.3, 0.323, 00.12
		email: the string to test
*/
function isNumber(number) {
	// 123, 1.3, 0.323, 00.12
	var numberExp = /(^\d+$)|(^\d+\.\d+$)/
	// +123, -123, .123, 123, -12.3, +12.3, 1.23, 2.
	//var numberExp = /^[+-\.]?\d+|^[+-]?\d+[\.]\d*/;

	return numberExp.test(number);
}

/* Checks if a string is an integer
				the valid formats are:
					+123, -123, 123
		email: the string to test
^[+-]?
*/
function isInteger(integer) {
	var integerExp = /^\d+$/;

	return integerExp.test(integer);
}

/* Checks if a form text field contains an integer
		formName: the name of the form that contains the input
		inputName: the name of the input to test
		errorText: (optional) the name of the input to display in the error message
*/
function validateInteger(formName, inputName, errorText) {
	var inputField = getFormField(formName,inputName);
	var retVal = isInteger(inputField.value);

	if (!retVal && errorText) 
	{
     if (getCookieValue("language")=="fr")
        alert("S'il vous plait, entrez un " + errorText + "valide");
	 else
		alert("Please enter a valid " + errorText);
		inputField.focus();
	}
	
	return retVal;
}

/* Checks if a form text field contains a number
		formName: the name of the form that contains the input
		inputName: the name of the input to test
		errorText: (optional) the name of the input to display in the error message
*/
function validateNumber(formName, inputName, errorText) {
	var inputField = getFormField(formName,inputName);
	var retVal = isNumber(inputField.value);
	
	if (!retVal && errorText) 
	{
     if (getCookieValue("language")=="fr")
        alert("S'il vous plait, entrez un " + errorText + "valide");
	 else
		alert("Please enter a valid " + errorText);
	 inputField.focus();
	}
	
	return retVal;
}

/* Checks if a form text field contains a valid email address
		formName: the name of the form that contains the input
		inputName: the name of the input to test
		errorText: (optional) the name of the input to display in the error message
*/
function validateEmail(formName, inputName, errorText) {
	var inputField = getFormField(formName,inputName);
	var retVal = isEmail(inputField.value);

	if (!retVal && errorText) 
	{
     if (getCookieValue("language")=="fr")
        alert("S'il vous plait, entrez un " + errorText + "valide");
	 else
		alert("Please enter a valid " + errorText);
		inputField.focus();
	}
	
	return retVal;
}

/* Checks if a form text field is not empty
		formName: the name of the form that contains the input
		inputName: the name of the input to test
		errorText: (optional) the name of the input to display in the error message
*/
function validateText(formName, inputName, errorText) {
	var inputField = getFormField(formName,inputName);
	var retVal = true;
	
	if (!inputField.value.length) {
		if (errorText) 
		{
          if (getCookieValue("language")=="fr")
            alert("S'il vous plait, entrez " + errorText);
          else
			alert("Please enter " + errorText);
		 inputField.focus();
		}
		retVal = false;
	}
	
	return retVal
}

/* Checks if a form text field does not contain a certain string
		formName: the name of the form that contains the input
		inputName: the name of the input to test
		defaultText: the string to test for
		errorText: (optional) the name of the input to display in the error message
*/
function validateDefaultText(formName, inputName, defaultText, errorText) {
	var inputField = getFormField(formName,inputName);
	var retVal = true;
	
	if (inputField.value == defaultText) {
		if (errorText) {
			alert("Please enter " + errorText);
			inputField.focus();
		}
		retVal = false;
	}
	
	return retVal
}

/* Checks the number of checked checkboxes in a group of checkboxes 
		formName: the name of the form that contains the input
		inputName: the name of the input to test
*/
function validateCheckbox(formName, inputName) 
{
	var theForm = getForm(formName);
	var nb=0;
	
	for (i = 0; i < theForm.elements.length; i++) 
	{
		if (theForm.elements[i].type=='checkbox' && 
		    theForm.elements[i].name==inputName ) 
		{
			if (theForm.elements[i].checked) ++nb;
		}
	}

	return nb;
}

/* Checks if a valid selection has been made in a form selectbox field
				A valid selection is any item except for the first item in the list
		formName: the name of the form that contains the input
		inputName: the name of the input to test
		errorText: (optional) the name of the input to display in the error message
*/
function validateSelect(formName, inputName, errorText) 
{
	var inputField = getFormField(formName,inputName);
	var retVal = true;
	
	if (!inputField)
	{
	 alert("Unable to get field!");
	 return false;
	}
	retVal=inputField.selectedIndex;
	if (inputField.selectedIndex <= 0) 
	{
		if (errorText) 
		{
			alert(errorText);
			inputField.focus();
		}
		retVal = false;
	}

	return retVal;
}

/* Obtain the selected index of a SELECT 
		formName: the name of the form that contains the input
		inputName: the name of the field 
*/
function getSelectIndex(formName,inputName) {
	var inputField = getFormField(formName,inputName);
	return inputField.selectedIndex;
}

/* Obtain the selected value of a SELECT 
		formName: the name of the form that contains the input
		inputName: the name of the field 
*/
function getSelectValue(formName,inputName) {
	var inputField = getFormField(formName,inputName);
	
	return inputField.options[inputField.selectedIndex].value;
}


/* Get the selected value of a radio 
		formName: the name of the form that contains the input
		inputName: the name of the field 
*/
function getRadioValue(formName,inputName) {
	var inputField = getFormField(formName,inputName);
	
 	for( i=0; i < inputField.length; i++ ) {
		if (inputField[i].checked == true)
		return inputField[i].value;
	}
	
	return "";
}

/* Check the selected value of a radio 
		formName: the name of the form that contains the input
		inputName: the name of the field   
		value: the value of the field
*/                                                
function checkRadioValue(formName,inputName,value) {
	var inputField = getFormField(formName,inputName);
	
 	for( i=0; i < inputField.length; i++ ) {
		if (inputField[i].value == value) {
			inputField[i].checked = true;
		}
		else {
			inputField[i].checked = false;
		}	
	}
}

function isChecked(formName,inputName) {
	var inputField = getFormField(formName,inputName);
	return inputField.checked
}

/* Check checkbox 
		formName: the name of the form that contains the input
		inputName: the name of the checkbox to check
		checked: true or false
*/

function selectCheckBoxes(formName,inputName,val)
{
	var theForm = getForm(formName);
	if (!theForm) return;
	
 	for( i=0; i < theForm.elements.length; i++ ) 
 	{
 	 if (theForm.elements[i].type=='checkbox' && theForm.elements[i].name==inputName)
 	 {
 	  theForm.elements[i].checked = val;
 	 }
 	}
}


function validateForm(formname) 
{
	var theForm = getForm(formname);
	if (!theForm) return false;
	
	theForm.bJavaScript.value=1;
	
	if (theForm.vLogin && !isUserName(theForm.vLogin.value))
	{
     if (getCookieValue("language")=="fr")
      alert("Entrez un identifiant valide.");
     else
	  alert("Please enter a valid user name.");
	 theForm.vLogin.focus();
	 return false;
	}
	if (theForm.vNickname && !isUserName(theForm.vNickname.value))
	{
     if (getCookieValue("language")=="fr")
      alert("Entrez un pseudo valide.");
     else
	  alert("Please enter a valid nickname.");
	 theForm.vNickname.focus();
	 return false;
	}
	if (theForm.vPassword && !isPassword(theForm.vPassword.value))
	{
     if (getCookieValue("language")=="fr")
      alert("Entrez un mot de passe.");
     else
	  alert("Please enter a password.");
	 theForm.vPassword.focus();
	 return false;
	}
	if (theForm.vPassword && theForm.vRepeatPassword && theForm.vPassword.value!=theForm.vRepeatPassword.value)
	{
     if (getCookieValue("language")=="fr")
      alert("Entrez deux mots de passe identiques.");
     else
	  alert("Please enter the same repeat password than password.");
	 theForm.vPassword.focus();
	 return false;
	}
	if (theForm.vEmail && !isEmail(theForm.vEmail.value))
	{
     if (getCookieValue("language")=="fr")
      alert("Entrez une adresse e-mail valide.");
     else
	  alert("Please enter a valid email address.");
	 theForm.vEmail.focus();
	 return false;
	}
	if (theForm.vEmail && theForm.vRepeatEmail && theForm.vEmail.value!=theForm.vRepeatEmail.value)
	{
     if (getCookieValue("language")=="fr")
      alert("Entrez deux adresses e-mail identiques.");
     else
	  alert("Please enter the same repeat email address than email address.");
	 theForm.vEmail.focus();
	 return false;
	}
	if (theForm.iGroupID && !validateSelect(formname,'iGroupID','Please select your current group')) return false;
	
	return true;
}

function submitForm(formname) 
{
	if (validateForm(formname)) {
		var theForm = getForm(formname);
		if (!theForm) return;
		theForm.submit();
	}
}


function justSubmitForm(formname) 
{
	var theForm = getForm(formname);
	if (!theForm) return;
	theForm.submit();
}

function submitAction(formname, action) 
{
	var theForm = getForm(formname);
	if (!theForm) return;
	
	theForm.action.value=action;
	
	if (validateForm(formname)) theForm.submit();
}

function submitBack(formname) 
{
	var theForm = getForm(formname);
	if (!theForm) return;
	
	theForm.bJavaScript.value=1;
	theForm.action.value=theForm.lastAction.value;
	theForm.submit();
}

function submitSearch(formname,defaultText,ret) 
{
 var searchForm = getForm(formname);
 if ((trimStr(searchForm.query.value)=="") ||
     (trimStr(searchForm.query.value)==defaultText))
 {
  if (getCookieValue("language")=="fr")
   alert("Entrez un ou plusieurs mot-clefs.");
  else
   alert("Please enter a search keyword.");
  searchForm.query.focus();
  if (ret) return false;
  else return;
 } 
 
 if (!ret) searchForm.submit();
 
 if (ret) return true;
}

function AlertDelete(message)
{
 if (getCookieValue("language")=="fr")
  return confirm("Voulez-vous supprimer " + message + " ?");
 else
  return confirm("Are you sure you want to delete this " + message + " ?");
}

function AlertCreate(message)
{
 if (getCookieValue("language")=="fr")
  return confirm("Voulez-vous ajouter un nouvel enregistrement " + message + "?");
 else
  return confirm("Do you want to create a new  " + message + " record ?");
}

function LoadPage(url)
{
 window.location=url;
}

function ReloadPage()
{
 window.location.reload();
}

function SetLanguage(language)
{
 writePersistentCookie ("language", language, "years", 1);
 ReloadPage();
}


/*
 * Generic Set Action
 */
function setActionValue(formname,value) {
	var theForm = getForm(formname);
	if (!theForm) return;
	theForm.action.value=value;
	theForm.submit();
}

/* Convert Square Foot to m2, with 1 digit precision */
function convertFt2ToMt2(n) {
	return Math.round(n*0.0929*10)/10;
} 

/* Convert m2 to Square Foot  with 0 digit precision */
function convertMt2ToFt2(n) {
	return Math.round(n*10.76391);
}
/* end generic functions */
