// ++ Cette fonction renvoie true si la chaine est vide
function isEmptyString(chaine) 
{
  if ((chaine == null) || (chaine.length == 0)) return true;
  return false;
}

// ++ Vérification de l'email. NB: la compilation de RegExp semble etre boguée sous IE5...
function isEmail (email) 
{
  if (! email) return false;
  if (email.length > 255) {
  	return false;
  }
  eml = email.trim();
  return ( eml.search(/^[a-zA-Z0-9_'\.\-]+\@[a-zA-Z0-9\.\-]*[a-zA-Z0-9\-]{1}\.[a-zA-Z0-9]{2,6}$/) >=0);
}

// ++ Convertit en nombre. NaN si vide ou invalide'
function toNumber(num,repl)
{
 if (num == null || num == "" || isNaN(num)) 
   return (repl==null? NaN :repl);
 return parseInt( num.trim(), 10);  
}

// ++ true si non vide et nombre valide 
function isNumber(num, allowEmpty) 
{
 if (allowEmpty && (num == null || num == ""))
   return true;
 return (! isNaN(toNumber(num)) );
}

// ++ Renvoie la valeur entre inf et sup comprises, ou NaN
function toNumberMinMax(num, inf,sup)
{
 n = toNumber(num);
 if ( (! isNaN(n)) && n>=inf && n<=sup ) 
  return n;
 return NaN;
}

function maxlength(frm, inputName, maxLength) {
	var inputValue = getGenericValue(frm, inputName);
	return inputValue.length < maxLength;
}

// ++ Checks that the parameter matchs the regular expression \[a-zA-Z0-9"-@_"]+\.
function checkValidLoginOrPass(value) 
{
 return ( value.search(/^[a-zA-Z0-9_\@\.\-]+$/) >=0 );
}

// ++ Cette fonction renvoie true si numéro de tel fixe francais valide. Conseil: normPhoneNumber() avant 
function isFrenchPhone(num) 
{
 return ( num.search(/^(\+33|33|0)[1-58]\d{8}$/) >= 0 );
}

// phone related
function formatPhoneNumber(num, separator)
{
  if (isEmptyString(num))
    return "";
  num = normPhoneNumber(num);
  res = "";
  for (i = 0; i < num.length; i+=2) 
  {
    res+=(num.substr(i,2)+separator);
  }
  return res;
}

/**
 * phone related
 * maj de formatPhoneNumber pour formater plusieurs numéro de téléphone
 * séparés par une chaine ("01 02 03 04 05 ou 06 07 08 09 10")
 */
function formatPhoneNumbers(num, separator) {
    // alert("formatPhoneNumber");
    if (isEmptyString(num)) {
        return "";
    }

    res = "";
    cpt = 0; // compte le nombre de chiffre qui se suivent
    for (i = 0; i < num.length; i++) {
        // alert("cpt : "+cpt);
        if (num.charAt(i) != separator) {
            if(! isNaN(parseInt(num.charAt(i))) && ++cpt == 3) {
                res+= " "+num.charAt(i);
                cpt = 1;
            } else {
                res+= num.charAt(i);
            }
        } else {
            res+= num.charAt(i);
            cpt = 0;
        }
    }

    // alert("res : "+res);
    return res;
}
    
    

// ++ Mobile phone related
function normPhoneNumber(num)
{
 return num.replace(/[^0-9]*/g,"");
}

// ++ Mobile phone related
function normMobileNumber(num)
{
 return num.replace(/[^\+0-9]*/g,"");
}
function isFrenchMobile(num)
{
  return ( num.search(/^\+336\d{8}$/) >= 0 );
}

// ++ Desactivation du double-click
CF_alreadySubmitted=false;
function isDoubleClick()
{ 
 return CF_alreadySubmitted; 
}
function noDoubleClickNow(tt)
{
 if (!tt) tt=20000;
 CF_alreadySubmitted=true;
 setTimeout('CF_alreadySubmitted=false', tt);
}

// ++ Administrateur ou createur
function isAdministrator( isLoggedMember, memXEventRole )
{
  return ( isLoggedMember && (memXEventRole == 1 || memXEventRole == 4));
}

// ++ True si un des radio-buttons est checked  
function checkRadio(radio)
{
 if (!radio)  return false;
 if (! radio.length) 
   return radio.checked;
 for(i=0; i < radio.length; i++)
 {
   if (radio[i].checked) 
     return true;
 }
 return false;
}

// ++ retourne la valeur checkee d un radio button
function radioCheckedValue(radio)
{
 if (!radio) return "";
 if (! radio.length)
   return (radio.checked? radio.value : "");
 for(i=0; i < radio.length; i++)
 {
   if (radio[i].checked) 
     return radio[i].value;
 }
 return "";
}

// ++ 
function forceCheckRadio(frm, elementName, testedValue)
{
//  alert('checking radio button '+elementName+' with '+testedValue);
  radio = frm.elements[elementName];
  if (!radio) return false;
  result=false;
  if (! radio.length)
  {
    radio.checked = (radio.value == testedValue);
    result = result || radio.checked;
//    alert('checking unique radio button :'+radio.checked);
    return result;
  }
  for(i=radio.length-1; i >= 0; i--)
  {
    radio[i].checked = (radio[i].value == testedValue);
    result = result || radio[i].checked;
//    alert('checking radio button '+i+' :'+radio[i].checked);
  }
  return result;
}

// ++
function disableRadio(frm, elementName, onOff)
{
  radio = frm.elements[elementName];
  if (!radio) return;

  if (! radio.length)
  {
    radio.disabled = onOff;
    return;
  }
  for(i=radio.length-1; i >= 0; i--)
    radio[i].disabled = onOff;
}

// ++
function forceSelectOption(frm, elementName, testedValue)
{
//  alert('selecting '+testedValue+' in '+elementName);
  selectList = frm.elements[elementName];
  if (!selectList) return false;
  for(i=selectList.options.length-1; i >= 0; i--)
  {
    if (selectList.options[i].value == testedValue)
    {
      selectList.selectedIndex = i;
      return true;
    }
  }
  return false;
}

function forceSelectOptionByText(frm, elementName, testedValue)
{
//  alert('selecting '+testedValue+' in '+elementName);
  selectList = frm.elements[elementName];
  if (!selectList) return false;
  for(i=selectList.options.length-1; i >= 0; i--)
  {
    if (selectList.options[i].text == testedValue)
    {
      selectList.selectedIndex = i;
      return true;
    }
  }
  return false;
}

// ++
function selectedValue(frm, elementName)
{
  selectList = frm.elements[elementName];
  if (!selectList || !selectList.options || selectList.options.length==0 || selectList.selectedIndex < 0) 
    return "";
  return selectList.options[selectList.selectedIndex].value;
}


function getSelectText(frm, selectName) {
	selectList = frm.elements[selectName];
	if (!selectList || !selectList.options || selectList.options.length==0 || selectList.selectedIndex < 0) { 
		return "";
   }
	return selectList.options[selectList.selectedIndex].text;
}

function setSelectText(frm, selectName, newText) {
	selectList = frm.elements[selectName];
	if (selectList && selectList.options && selectList.options.length && selectList.selectedIndex > 0) {
		selectList.options[selectList.selectedIndex].text = newText;
	}
}

//retourne true si une checkBox de nom checkBoxName est cochée
//false sinon
function isCheckedCheckBox(frm, checkboxName)
{
  elts = frm.elements[checkboxName];
  if (!elts)
  {
    //alert('elts introuvable');
    return false;
  }
  if(! elts.length)
    return elts.checked;
  for(i=elts.length-1; i >= 0; i--)
  {
    if (elts[i].checked)
    {
      //alert("elt "+i+" checked");
      return true;
    }
  }
  //alert('no elt checked');
  return false;
}

// ++
function disableCollectCheckBox(frm, elementName, onOff)
{
  items = frm.elements[elementName];
  if (!items) return;

  if (! items.length && (items.type.toLowerCase()=="checkbox"))
  {
    items.disabled = onOff;
    return;
  }
  else if ( 2 > items.length)
  {
    if (items.type && (items.type.toLowerCase()=="checkbox"))
      items.disabled = onOff;
    return;
  }
  for(i=items.length-1; i >= 0; i--)
  {
    if (items[i].type && (items[i].type.toLowerCase() =="checkbox"))
      items[i].disabled = onOff;
  }
}

// ++ Return true if at least one is checked
function isCheckedCollectCheckBox(frm, elementName)
{
  items = frm.elements[elementName];
  if (!items && ! startsWith(elementName, "ffcbc"))
    elementName = "ffcbc"+elementName;
  if (!items) return false;
  if ( 2 > items.length)
  {
    if (items.type && (items.type.toLowerCase()=="checkbox"))
      return items.checked;
  }
  for(i=items.length-1; i >= 0; i--)
  {
    if (items[i].type && (items[i].type.toLowerCase() =="checkbox") && items[i].checked)
      return true;
  }
  return false;
}

// ++
function checkCollectCheckBox(frm, elementName, onOff)
{
  items = frm.elements[elementName];
  if (!items && ! startsWith(elementName, "ffcbc"))
    elementName = "ffcbc"+elementName;
  if (!items) return false;
  if ( 2 > items.length)
  {
    if (items.type && (items.type.toLowerCase()=="checkbox"))
      items.checked = onOff;
  }
  for(i=items.length-1; i >= 0; i--)
  {
    if (items[i].type && (items[i].type.toLowerCase() =="checkbox"))
      items[i].checked = onOff;
  }
}

// ++ Return the value of any input. Return null if element not found.
//    WARNING: return only the first value on collectCheckBoxes !!
function getGenericValue(frm, elementName)
{
  var obj = frm.elements[elementName];
  if (! obj) 
  { obj = frm.elements["ffcbc"+elementName]; if (! obj) return null; }
  if (obj.options) return selectedValue(frm,elementName);
  if (! obj.length)
  {
    var typ = obj.type.toLowerCase();
    if (! typ || typ == "") return null;
    else if (typ == "radio" || typ == "checkbox") return radioCheckedValue(obj);
    else return obj.value;
  }
  else  // Array here
  {
    var typ = obj[0].type.toLowerCase();
    if (! typ || typ == "") return null;
    else if (typ == "radio" || typ == "checkbox") return radioCheckedValue(obj);
    else return (obj.value ? obj.value : (obj[0].value ? obj[0].value : null));
  }
  return null;
}

// ++ Set the value of any input. Return null if element not found.
//    WARNING: set only the first value on collectCheckBoxes ! (a vérifier)
function setGenericValue(frm, elementName, val)
{
  //alert("setGenericValue(frm, "+elementName+", "+val+")");
  var obj = frm.elements[elementName];
  if (! obj) 
  { obj = frm.elements["ffcbc"+elementName]; if (! obj) return; }
  if (obj.options) return forceSelectOption(frm, elementName, val);
  if (! obj.length)
  {
    var typ = obj.type.toLowerCase();
    if (! typ || typ == "") return;
    else if (typ == "radio" || typ == "checkbox") forceCheckRadio(frm, elementName, val);
    else obj.value = val;
  }
  else  // Array here
  {
    for (var i = 0; i < obj.length; i++) 
    {
      var typ = obj[i].type.toLowerCase();
      if (! typ || typ == "") return;
      else if (typ == "radio" || typ == "checkbox")  // Apl plusieurs fois car peut avoir des input hidden!
        forceCheckRadio(frm, elementName, val);
      else if (obj[i]) obj[0].value = val;
    }
  }
  return;
}

function setFocus(frm, elementName) {
	// Check if an setFocus funstion exist for the field
	if (isset('window.setFocus_' + elementName)) {
		// Execute custom setFocus function
		eval('window.setFocus_' + elementName + '(frm)');
	} else {
		// Get field object
		var obj = frm.elements[elementName];
		if (! obj) {
			obj = frm.elements["ffcbc"+elementName];
		}

  		try {
			obj.focus();
		} catch(e) {
			try {
				obj[0].focus();
			} catch(ex) { }
		}
	}
}

/**
 * Check qu'un group de select box (param SelboxGroup => Array of select names)
 * ne possède pas la même valeur selected
 
  var SEL_BOX_GROUP = new Array("ff3t1037781", "ff3t1037782", "ff3t1037783");
  var ALERT_ALREADY_SEL = 'Vous avez déjà sélectionné ce choix';
  
  Sur chaque select box à controler :
  onChange="javascript: checkUniqueSelected(this.form, this, SEL_BOX_GROUP, ALERT_ALREADY_SEL);
 */
function checkUniqueSelected(frm, obj, SelboxGroup, alertAlreadySel, valueNothingSel) {
  //alert('checkSelectboxGroup');
  objName = obj.name;
  if (valueNothingSel == null) {
    valueNothingSel = '';
  }
  idx = -1;
  for(i=0; i<SelboxGroup.length; i++) {
    if (SelboxGroup[i] == objName) {
      idx = i;
      break;
    }
  }
  if (idx < 0) {
    return false;
  }
  
  selectedVal = getGenericValue(frm, SelboxGroup[idx]);
  //alert(selectedVal);
  if (selectedVal != valueNothingSel) {
    for(i=0; i<SelboxGroup.length; i++) {
      if (i != idx) {
        otherVal = getGenericValue(frm, SelboxGroup[i]);
        if (selectedVal == otherVal) {
          alert(alertAlreadySel);
          forceSelectOption(frm, SelboxGroup[idx], valueNothingSel);
          return false;
        }
      }
    }
  }
}

function keepOption(frm, elementName, testedValue) {
  selectList = frm.elements[elementName];
  if (!selectList) {
    return false;
  }
  var validIndex = 0;
  for(i = 0; i <selectList.options.length; i++) {
    if (selectList.options[i].value && !testedValue[selectList.options[i].value]) {
      // skip value
      // alert('removing '+selectList.options[i].value+' from '+elementName);
    } else {
      // alert('keeping '+selectList.options[i].value+' in '+elementName);
      selectList.options[validIndex].value=selectList.options[i].value;
      selectList.options[validIndex].text=selectList.options[i].text;
      selectList.options[validIndex].selected=selectList.options[i].selected;
      validIndex++;
    }
  }
  selectList.options.length=validIndex;
  // alert('valid: '+validIndex);
}

// ++
YES_CHARACTERS = "yY1tTvVoO";
function isParameterYes(val)
{
  if (isEmptyString(val))
    return false;
  return (YES_CHARACTERS.indexOf( val.charAt(0) ) >= 0);
}

// ++ pour passer du HTML complet (avec commentaires, etc.) de Java en JS 
function unEscapeHtml(text)
{
 text=text.replace(/&quot;/g,'"');
 text=text.replace(/&lt;/g,"<");
 text=text.replace(/&gt;/g,">");
 text=text.replace(/&#39;/g,"'");
 text=text.replace(/&amp;/g,"&");
 return text;
};

//remplace les caracteres de la source avec les codes unicode associés à ces caracteres (HTML) e.g. -> &#0000
function encodeUnicode(source)
{
  result = '';
  for (i=0; i<source.length; i++) 
    result += '&#' + source.charCodeAt(i) + ';'; 
  return result;
}

//remplace les codes unicodes contenus dans la source avec les caracteres associees à ces codes (HTML)
function decodeUnicode(source)
{
  strRet = "";
  //si rien à décoder
  if (source.indexOf("&#")<0)
    return source;
  for (i = 0; i < source.length; i++)
  {
    if (source.charAt(i) == '&' && source.charAt(i + 1) == '#')
    {
      tmp = source.substring(source.indexOf("&#",i)+2, source.indexOf(";",i));
      strRet += String.fromCharCode(tmp);
      i = i + tmp.length + 2;
    }
  }
  return (strRet);
}
//remplace les caracteres de la source avec les codes unicode associés à ces caracteres (URL) -> %00%00
function utf8UrlEscape(theString) {
 	var utftext = "";

	for (var n = 0; n < theString.length; n++) {
		var c = theString.charCodeAt(n);
		if (c < 128) {
			utftext += String.fromCharCode(c);
		} else if((c > 127) && (c < 2048)) {
			utftext += String.fromCharCode((c >> 6) | 192);
			utftext += String.fromCharCode((c & 63) | 128);
		} else {
			utftext += String.fromCharCode((c >> 12) | 224);
			utftext += String.fromCharCode(((c >> 6) & 63) | 128);
 			utftext += String.fromCharCode((c & 63) | 128);
		}
	}
	return utftext;
}

