// FAH Common JS
// Clear default value for a form field
function clearDefault(input_text) {
  if (input_text.defaultValue==input_text.value) 
	input_text.value = "";
	input_text.style.borderColor= '#ADBCD1';
	input_text.style.color = '#444';
}

// Restore default value for a form field
function restoreDefault(input_text) {
	input_text.style.borderColor = '#999999';
	var re = /^\s{1,}$/g; //Match any white space including space, tab, form-feed, etc. Check null text field
	if ((input_text.value.length == 0) || (input_text.value == null) || ((input_text.value.search(re)) > -1)) {	
		input_text.value = input_text.defaultValue;	
		input_text.style.color = '#b3bac4';
	}
	else {
		input_text.style.color = '#555555';
	}
}

// Validate HLF user request form
function hlfsubval() {		// validate the fields
var msg="";
var errs=0;
var emerr=0;
var pherr=0;
ff = document.forms.LeadImporterForm;

if (!validateEmail(ff.Email, 'lab_Email', true)) {
  errs += 1;
  emerr+= 1;
//  var elem = document.getElementById('lab2_Email');
//  elem.innerHTML = "Please provide a valid email";   // set the CSS class to adjust appearance of message  
}
if (!validateSelected(ff.PurchaseState,  'lab_PurchaseState'))        errs += 1; 
if (!validateSelected(ff.price,  'lab_price'))        errs += 1; 
if (!validatePresent(ff.PurchaseCity,  'lab_PurchaseCity'))        errs += 1; 
if (!validateTelnr  (ff.PrimaryPhone, 'lab_PrimaryPhone', true)) {
  errs += 1;
  pherr+= 1;
//  var elem = document.getElementById('lab2_PrimaryPhone');
//  elem.innerHTML = "Please provide full phone # (xxx-xxx-xxxx)";   // set the CSS class to adjust appearance of message  
}
if (!validatePresent(ff.LastName,  'lab_LastName'))        errs += 1; 
if (!validatePresent(ff.FirstName,  'lab_FirstName'))        errs += 1; 

if (errs>0) {
	msg = "Please complete all required fields marked with a *.";
	if(pherr>0) {
		msg = msg + "  \nPlease give a valid telephone number.";
	}
	if (emerr>0) {
		msg = msg + "  \nPlease give a valid email address.";
	}
	alert(msg);
}
else {		// validation OK
	// Go populate the zip code field
	if (ff.ZipCode.value.length <= 0) {
		getdefzip(ff.PurchaseState.value, ff.PurchaseCity.value, ff.ZipCode);
	}
	// Send to HLF server so we can resolve errors.
 var req = Inint_AJAX();
	var parms;
	if (req) {
		parms = "postdata=" + escape(ff.PurchaseState.value + "|" + ff.PurchaseCity.value + "|" + ff.ZipCode.value + "|" + ff.LastName.value + "|" + ff.PrimaryPhone.value + "|" + ff.Email.value);
		/////req.open("GET", "http://localhost/hlf/hlfcheck.php?" + parms, false);
		req.open("GET", dirroot + "hlfcheck.php?" + parms, false);
		req.send(parms);
	}
}
return (errs==0);
}

// Validate HLF mini city-state-zip form
function hlfminiformval() {		// validate the fields

	var inZip = document.getElementById('mini_form_zip');
	
	if(inZip.value.length == 5){       //zip is proper length, go check character validity
	
		if(!CheckZip(inZip.value)) {  //error in zip validity - show label and throw error
				msg("lab_miniZip", "laberr", "ERROR: required");
				alert("Please Enter a Valid Zip (5 digits)");
				return false;
		}
		else {  //good zip goto form processing in backend
				
				msg("lab_miniCity", "lab", "");
				msg("lab_miniState", "lab", "");
				msg("lab_miniZip", "lab", "");
				msg("lab_miniformtitle", "lab", "");
				return true;
		}
	}
	
	else if(inZip.value.length == 0){  //no zip available - checking for city and state
		var inCity = document.getElementById('mini_form_city');
		var inState = document.getElementById('mini_form_state');
		
		if(inCity.value.length == 0 && inState.value.length == 0){  //if city and state not here
			msg("lab_miniformtitle", "laberr", "");
			return false;
		}
		else if(inCity.value.length > 0 && inState.value.length == 0){   //if city but no state
			msg("lab_miniState", "laberr", "");
			alert("Please Select a State");
			return false;
		}
		else if(inCity.value.length == 0 && inState.value.length > 0) {  // if state but no city
			msg("lab_miniCity", "laberr", "");
			alert("Please Enter a City");
			return false;
		}
		else { //is good city/state
			msg("lab_miniCity", "lab", "");
			msg("lab_miniState", "lab", "");
			msg("lab_miniZip", "lab", "");
			msg("lab_miniformtitle", "lab", "");
			return true;
		}
	}
	
	else{  // invalid number of digits entered for zip
			msg("lab_miniZip", "laberr", "ERROR: required");
			alert("Please Enter a Valid Zip (5 digits)");
			return false;
	}
	
}

function CheckZip(Zip)  //checks the zip field to see if we have properly inputted zip
{
   var ValidChars = "0123456789";
   var IsGoodZip=true;
   var Char;
 
   for (i = 0; i < Zip.length; i++) 
      { 
      Char = Zip.charAt(i); 
      if (ValidChars.indexOf(Char) == -1) 
         {
         	IsGoodZip = false;
         }
      }
   return IsGoodZip;
}

function Inint_AJAX() {
try { return new ActiveXObject("Msxml2.XMLHTTP");  } catch(e) {} //IE
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {} //IE
try { return new XMLHttpRequest();          } catch(e) {} //Native Javascript
////////alert("XMLHttpRequest not supported");
return null;
};


// Get a default zip code
function getdefzip(st, city, src) {
 var req = Inint_AJAX();

 req.open("GET", dirroot+"getdefzip.php?st="+st+"&city="+city, false); //open connection
 req.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=tis-620"); // set Header
 req.send(null);
 if (req.status==200) {	// got it, trim extra chars and return
  var r;
  r = req.responseText.replace(" ", "");
  r = r.replace("\n", "");
  r = r.replace("\r", "");
  r = r.replace("\t", "");
  src.value=r;	// set in field
 }
}

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

// Trim leading/trailing whitespace off string
function trim(str)
{
  return str.replace(/^\s+|\s+$/g, '');
}


// 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 );
}


// 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
{
  var elem = document.getElementById(fld);
  if (null != elem)  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// 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
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem) return true;							// label field does not exist, assume no label and no editing needed
  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(valfield.value)) {
    if (required) {
      msg (infofield, "laberr", "ERROR: required");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "labwarn", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// Validate if something has been entered
function validatePresent(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;

  msg (infofield, "lab", "");  
  return true;
}

// Validate if something has been selected
function validateSelected(valfield,   // element to be validated
                         infofield ) // id of element to receive info/error msg
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (!elem) return true;							// label field does not exist, assume no label and no editing needed
  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 (valfield.selectedIndex <= 0) {
		msg(infofield, "laberr", "ERROR: required");
    setfocus(valfield);
    return false;
	}		

  msg (infofield, "lab", "");  
  return true;
}

// 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
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;

  var tfld = trim(valfield.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/  ;
  if (!email.test(tfld)) {
    msg (infofield, "laberr", "ERROR: not a valid e-mail address");
    setfocus(valfield);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) 
    msg (infofield, "labwarn", "Unusual e-mail address - check if correct");
  else
    msg (infofield, "lab", "");
  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 ()-xX]+[0-9]$/  ;
  if (!telnr.test(tfld)) {
    msg (infofield, "laberr", "ERROR: 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, "laberr", "ERROR: " + numdigits + " digits - too short");
    setfocus(valfield);
    return false;
  }

  if (numdigits>15) {
    msg (infofield, "labwarn", numdigits + " digits - check if correct");
    setfocus(valfield);
    return false;
  }
  else { 
    if (numdigits<10){
      msg (infofield, "labwarn", "Only " + numdigits + " digits - check if correct");
	    setfocus(valfield);
		  return false;
    }
    else {
      msg (infofield, "lab", "");
    }
  }
  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, "laberr", "ERROR: not a valid age");
    setfocus(valfield);
    return false;
  }

  if (tfld>=200) {
    msg (infofield, "laberr", "ERROR: not a valid age");
    setfocus(valfield);
    return false;
  }

  if (tfld>110) msg (infofield, "labwarn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (infofield, "labwarn", "Bit young for this, aren't you?");
    else        msg (infofield, "labwarn", "");
  }
  return true;
}

function togglecustomdate (datetype)
{
	if(datetype=="showform")
	{
		document.getElementById("customdatefields").style.display = "block";
	}
	else
	{
		document.getElementById("customdatefields").style.display = "none";
	}
}




