var nbsp = 160;		// non-breaking space char
var node_text = 3;	// DOM text node-type
var emptyString = /^\s*$/ ;
var global_valfield;	// retain valfield for timer thread
var ERRORCSSNAME = "error"; // error css name, define the rules in your styles.
var WARMCSSNAME = "warn"; // warn css name, define the rules in your styles.

// --------------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// --------------------------------------------

function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}

// --------------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// --------------------------------------------

function setFocusDelayed()
{
  global_valfield.focus();
}

function setfocus(valfield)
{
  // save valfield in global variable so value retained when routine exits
  global_valfield = valfield;
  setTimeout( 'setFocusDelayed()', 100 );
}

// --------------------------------------------
//                  msg
// Display warn/error message in HTML element.
// commonCheck routine must have previously been called
// --------------------------------------------

function msg(fld,     // id of element to display message in
             msgtype, // class to give element ("warn" or "error")
             message, // string to display
             tailormessage // string to display custom msg
             ) 
{
  // setting an empty string can give problems if later set to a 
  // non-empty string, so ensure a space present. (For Mozilla and Opera one could 
  // simply use a space, but IE demands something more, like a non-breaking space.)
   
  if (!emptyString.test(tailormessage)) {
    message = tailormessage;    
  }
  
  var elem = document.getElementById(fld);
  var dispmessage;
  if (emptyString.test(message)) {
    dispmessage = String.fromCharCode(nbsp);    
  }
  else{  
    dispmessage = message;
    elem.firstChild.nodeValue = dispmessage;  
    //elem.style.backgroundColor = "#ffefef";
    elem.style.display = "";
    elem.className = msgtype;   // set the CSS class to adjust appearance of message
  }
  //alert(dispmessage);
  
}

// --------------------------------------------
//            commonCheck
// Common code for all validation routines to:
// (a) check for older / less-equipped browsers
// (b) check if empty fields are required
// Returns true (validation passed), 
//         false (validation failed) or 
//         proceed (don't know yet)
// --------------------------------------------

var proceed = 2;  

function commonCheck    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required,   // true if required 
                         message
                         )  
{
  try 
  {  
      if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server
        
      var elemVal = document.getElementById(valfield);  
      var elem = document.getElementById(infofield);
      
      if (!elem.firstChild) return true;  // not available on this browser 
      if (elem.firstChild.nodeType != node_text) return true;  // infofield is wrong type of node  
     
      if (emptyString.test(elemVal.value)) {
        if (required) {
          msg (infofield, ERRORCSSNAME, "required" , message);  
          setfocus(elemVal);
          return false;
        }
        else {
          return true;  
        }
      }
      return proceed;
  }
  catch(e){
    //var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
    return true;
  }
}

// --------------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validatePresent(valfield,   // element to be validated
                         infofield,   // id of element to receive info/error msg
                            message ) // custom string to display
{

  var stat = commonCheck (valfield, infofield, true , message);
  if (stat != proceed) return stat;
  
  msg (infofield, WARMCSSNAME, "" , "");
  
  var elem = document.getElementById(infofield);
  elem.style.display = "none";  
  return true;
}

// --------------------------------------------
//            validateOptional
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validateOptional(valfield,   // element to be validated
                         infofield,   // id of element to receive info/error msg
                            message ) // custom string to display
{

  var stat = commonCheck (valfield, infofield, false , message);
  if (stat != proceed) return stat;
  
  msg (infofield, WARMCSSNAME, "" , "");
  
  var elem = document.getElementById(infofield);  
  elem.style.display = "none";  
  return true;
}

// --------------------------------------------
//            validateCompare
// Validate if something has been entered
// Returns true if so 
// --------------------------------------------

function validateCompare(valfield,   // element to be validated
                         valfieldCompare,   // element to compare  
                         infofield,   // id of element to receive info/error msg
                            message ) // custom string to display
{
    try 
    {
      var elemVal = document.getElementById(valfield);  
      var elemValCompare = document.getElementById(valfieldCompare);  

      var stat = compareValues (elemVal.value, elemValCompare.value);
      if (stat == false) {
        msg (infofield, ERRORCSSNAME, "required" , message);  
        setfocus(elemVal);
        return stat;
      }
      //var elem = document.getElementById(infofield);  
      //elem.style.display = "none";
      return true;
    } 
    catch(e){
    //var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
    return true;
    }
}

function compareValues(val1,val2)
{
   return (val1 == val2);
}

// --------------------------------------------
//            validateSelected
// Validate if something has been selected
// Returns true if so 
// --------------------------------------------

function validateSelected(valfield,   // element to be validated
                         infofield,   // id of element to receive info/error msg
                         message      // custom string to display
                         ) 
{ 
    try 
    {   
        var elemVal = document.getElementById(valfield);  
        var elem = document.getElementById(infofield);

        var myindex  = elemVal.selectedIndex
        var selValue = elemVal.options[myindex].value

        if (emptyString.test(selValue) || selValue == "0") {
            msg (infofield, ERRORCSSNAME, "required",message);  
            setfocus(elemVal);
            return false;
        } else{    
            elem.style.display = "none";  
        }
        return true;
    } catch(e){
    //var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
    return true;
    }
}
// --------------------------------------------
//               validateEmail
// Validate if e-mail address
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateEmail  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required,    // true if required
                         message      // custom string to display
                         )   
{
    try 
    {
      var stat = commonCheck (valfield, infofield, required, message);
      if (stat != proceed) return stat;

      var elem = document.getElementById(infofield);
      var elemVal = document.getElementById(valfield);

      var tfld = trim(elemVal.value);  // value of field with whitespace trimmed off
      var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;

      if (emptyString.test(elemVal.value) && required) {
        msg (infofield, ERRORCSSNAME, "",message);
        setfocus(elemVal);
        return false;
      }  
        
      if (!email.test(tfld)) {
        msg (infofield, ERRORCSSNAME, "Not a valid e-mail address","");
        setfocus(elemVal);
        return false;
      }
      
      var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
      if (!email2.test(tfld)) 
        msg (infofield, WARMCSSNAME, "Unusual e-mail address - check if correct","");
      else
        msg (infofield, WARMCSSNAME, "", message);
      
      elem.style.backgroundColor = "";
      elem.style.display = "none";
      return true;
    } catch(e){
    //var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
    return true;
    }
}


// --------------------------------------------
//            validateTelnr
// Validate telephone number
// Returns true if so (and also if could not be executed because of old browser)
// Permits spaces, hyphens, brackets and leading +
// --------------------------------------------

function validateTelnr  (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/;
  if (!telnr.test(tfld)) {
    msg (infofield, ERRORCSSNAME, "Not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(valfield);
    return false;
  }

  var numdigits = 0;
  for (var j=0; j<tfld.length; j++)
    if (tfld.charAt(j)>='0' && tfld.charAt(j)<='9') numdigits++;

  if (numdigits<6) {
    msg (infofield, ERRORCSSNAME, " " + numdigits + " digits - too short");
    setfocus(valfield);
    return false;
  }

  if (numdigits>14)
    msg (infofield, WARMCSSNAME, numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (infofield, WARMCSSNAME, "Only " + numdigits + " digits - check if correct");
    else
      msg (infofield, "warn", "");
  }
  return true;
}

// --------------------------------------------
//             validateAge
// Validate person's age
// Returns true if OK 
// --------------------------------------------

function validateAge    (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required)   // true if required
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);
  var ageRE = /^[0-9]{1,3}$/;
  if (!ageRE.test(tfld)) {
    msg (infofield, ERRORCSSNAME, "not a valid age");
    setfocus(valfield);
    return false;
  }

  if (tfld>=200) {
    msg (infofield, ERRORCSSNAME, "not a valid age");
    setfocus(valfield);
    return false;
  }

  if (tfld>110) msg (infofield, WARMCSSNAME, "Older than 110: check correct");
  else {
    if (tfld<7) msg (infofield, WARMCSSNAME, "Bit young for this, aren't you?");
    else        msg (infofield, WARMCSSNAME, "");
  }
  return true;
}


// --------------------------------------------
//             Util JS
// Auto functions
// --------------------------------------------

function isNumericChar(ch){
    var charCode=ch.charCodeAt(0);
    if( charCode>=48 && charCode<=57 )return true;
    else return false;
 }
  
 function isAutoPhoneFormat(ctr) {
    
    if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server
        
        
    var p1;				//conversion phone number
    var p2 = ""; 		//conversion phone text
    var p3 = "";
    var strChar;
    var mask = "() -"; 	//this is what phone numbers look like
    var oldvalue = ""; 	//the last thing in phonetxt
	var inputctrl = document.getElementById(ctr);
    p1 = inputctrl.value;
		    p1 = p1.replace("(","");
		    p1 = p1.replace(")","");
		    p1 = p1.replace("-","");
		    while (p1.search(" ") != -1){
    			    p1 = p1.replace(" ","");
    	    }
		    //frmPhone.phone.value = p1;
		    for (var i = 0; i <= p1.length; i++) 
            { 
                strChar = p1.charAt(i); 
                if (isNumericChar(strChar)){ 
                    p3 = p3 + strChar;    
                } 
            } 
            p1 = p3;
           
		    if (p1.length < 4 ) {
		        //alert(p1.length);
		        if(p1.length != 1 && p1.length != 2){
				    p2 = mask.substring(p1.length + 1,13);
				    inputctrl.value = "(" + p1 + p2;
				 }   
		    } else {
			    if (p1.length < 7){
				    p2 = mask.substring(p1.length + 2,13);
				    inputctrl.value = "(" + p1.substring(0,3) + ") " + p1.substring(3,6) + p2;
			    } 
			    else {
				    p2 = mask.substring(p1.length + 3,13)
				    inputctrl.value = "(" + p1.substring(0,3) + ") " + p1.substring(3,6) + "-" + p1.substring(6,10) + p2;
			    }
		    }
	//clean up	    
    if(inputctrl.value == "() -"){
        inputctrl.value = "";
    }    		    
}
function isAutoZipFormat(ctr) {

    if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server

    var inputctrl = document.getElementById(ctr);
    var p1 = inputctrl.value;
    var p2 = "";
    for (var i=0;i<p1.length;i++){
        if(isNumericChar(p1.charAt(i))){
            p2 += p1.charAt(i);
            //alert("Only numbers are allowed for " + fieldname + " field");
            //return false;
        }
    }
    inputctrl.value = p2;
 }
 
 /************************************************
DESCRIPTION: Validates that a string a United
  States zip code in 5 digit format or zip+4
  format. 99999 

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.

*************************************************/
 function validateUSZip( valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required
                         ) {

    if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server

    var objRegExp  = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
    var elem = document.getElementById(infofield);
    var elemVal = document.getElementById(valfield);

      //check for valid US Zipcode
      if(!objRegExp.test(elemVal.value)){
         msg (infofield, ERRORCSSNAME, "Not a valid zipcode.","");
         setfocus(elemVal);
         return false;   
      }
  return true;
}
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
/************************************************
DESCRIPTION: Validates that a string contains valid
  US phone pattern.
  Ex. (999) 999-9999 or (999)999-9999

PARAMETERS:
   strValue - String to be tested for validity

RETURNS:
   True if valid, otherwise false.
*************************************************/
function isUSPhone( strValue ) 
{  
  return /^\([1-9]\d{2}\)\s?\d{3}\-\d{4}$/.test(strValue);
}

function validateUSPhone( valfield , infofield , message ) 
{
     try{
        
        if (!document.getElementById) 
            return true;  // not available on this browser - leave validation to the server
        
        var elemVal = document.getElementById(valfield);            
        var elem = document.getElementById(infofield);
                 
        if (!isUSPhone(elemVal.value))
        {
            msg (infofield, ERRORCSSNAME, "required",message);  
            setfocus(elemVal);
            return false;	
        }
        else
        {
            elem.style.display = "none";          
        }
        return true;         
    }
    catch(e){
        var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
        return true;
    }
}

// --------------------------------------------
//               isRadioChecked
// Validate 
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function TextBoxValueEntered (valfield,   // element to be validated
                         valuetocheck      // custom string to display
                         )  
{

    if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server

    var elemVal = document.getElementById(valfield);
    
    if (emptyString.test(elemVal.value)) {
        return true;
    } else {
        if (elemVal.value == valuetocheck && valuetocheck != emptyString) {
            return true;
        } 
    }
    return false;
}

// --------------------------------------------
//               RadioSelect
// Validate 
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function RadioSelect (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg                         
                         valuetocheck      // custom string to display
                         )  
{
    if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server

    var elem = document.getElementById(infofield);
    var elemVal = document.getElementById(valfield);
    
    
    if (!elemVal.checked) {
        return false;
    } else{    
        elem.style.display = "none";  
    }
    return true;
}

// --------------------------------------------
//               validateRadioButtonList
// Validate 
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateRadioButtonList (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required,    // true if required
                         message      // custom string to display
                         )  
{
    try{
    
        if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server
        
        var elem = document.getElementById(infofield);
        var elemVal = document.getElementsByName(valfield);
        var isChecked = false;
        
        for ( var i = 0; i < elemVal.length; i++ ) {
            if (elemVal[i].checked == true) {
                elem.style.display = "none"; 
                return true;
                break;
                }
        }
        if (!isChecked) {
            msg (infofield, ERRORCSSNAME, "required",message);  
            setfocus(elemVal[0]);
            return false;
        } else{    
            elem.style.display = "none";  
        }
        return true;
  }
  catch(e){
    //var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
    return true;
  }
}

// --------------------------------------------
//               validateFileUpload
// Validate 
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------

function validateFileUpload (valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         objRegExp,    // file expression to check
                         message      // custom string to display
                         )  
{
    try{
        if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server
        //var objRegExp  = /^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$/;
        var elemVal = document.getElementById(valfield);            
        var elem = document.getElementById(infofield);        
        if (!objRegExp.test(elemVal.value)){
            msg (infofield, ERRORCSSNAME, "required",message);  
            setfocus(elemVal);
            return false;	
        }
        elem.style.display = "none";  
        return true;	        
    }
    catch(e){
        var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
        return true;
    }
}
// --------------------------------------------
//               validateOptins
// Validate 
// Returns true if so (and also if could not be executed because of old browser)
// --------------------------------------------
function validateOptins (optinList, infofield , message )
{
    try{
        if (!document.getElementById) 
        return true;  // not available on this browser - leave validation to the server
        
        var elem = document.getElementById(infofield);        
        
        for ( var a = 0; a < optinList.elements; a++ ) 
        {
           if(optinList.isItemMandatory(a) == true && document.getElementById(optinList.getItemName(a)).checked != true) /*its mandatory and its not checked, flag the user*/
            {                
                message = message + " \"" + striphtml(document.getElementById(optinList.getItemText(a)).innerHTML) + "\"";
                msg (infofield, ERRORCSSNAME, "required",message);
                document.getElementsByName(optinList.getItemName(a))[0].focus();
                return false;                                
                break;
            }
        }
        elem.style.display = "none";  
        return true;    
    }
    catch(e){
        var ee = e.message || 0; alert('Error: \n\n'+e+'\n'+ee);
        return true;
    }
}


function striphtml(value)
{
    return value.replace(/(<([^>]+)>)/ig,""); 
}
