// HLF JavaScript Functions

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

// Do the citystatego function from the mini-form
function csgsubmit(f, win, blk, dlv) {
	if (!hlfminiformval()) return false;	// do edits
	var cf = f.miniformcity;
	var c;
	if (null==cf) c="";
	else c = escape(cf.value);
	var ff = f.miniformstate;
	var s;
	if (null==ff) s="";
	else s = ff.options[ff.selectedIndex].value;
	var zf = f.miniformzip;
	var z;
	if (null==zf) z="";
	else z = escape(zf.value);
	var dirup = "";
	for(dli=1;dli<dlv;dli++) dirup = dirup + "../";
	var csgurl = dirup + 'citystategointer.php?dlv=' + dlv + '&miniformcity=' + c + "&miniformstate=" + s + "&miniformzip=" + z;
	var os = f.originalState;
	if (os) {
		csgurl = csgurl + "&originalState=" + os.value;
	}
	// Get the window contents using ajax if possible
	var req = Inint_AJAX();
	if (req) {
		req.open("GET", csgurl, 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 = req.responseText;
			if (r.length > 20) {
				csspopup(win, blk, 0, r, 500, 400);
				csgdolink();	// fire the link
				return false;
			}
		}
	}
	// AJAX failed, just load it. 
	window.location = csgurl;
	return false;
}
// Do citystatego function for a city link
function csglink(c, s, z, n, win, blk, dlv) {
	var dirup = "";
	for(dli=1;dli<dlv;dli++) dirup = dirup + "../";
	var csgurl = dirup + 'citystategointer.php?dlv=' + dlv + '&miniformcity=' + c + "&miniformstate=" + s + "&miniformzip=" + z + "&nbhd=" + n;
	// Get the window contents using ajax if possible
	var req = Inint_AJAX();
	if (req) {
		req.open("GET", csgurl, 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 = req.responseText;
			if (r.length > 20) {
				csspopup(win, blk, 0, r, 500, 400);
				csgdolink();	// fire the link
				return false;
			}
		}
	}
	// AJAX failed, just load it
	window.location = csgurl;
	return false;
}
// Initiate link for csg popup.  Uses flag/link in hidden div.
function csgdolink() {
	var dc = document.getElementById('csgcountdown');
	if (dc) c = dc.innerHTML;	// get countdown
	else c=0;
	var dk = document.getElementById('csglinkurl');
	if (dk) k = dk.innerHTML;	// get url
	// JRE 6/18 k = k.replace('&amp;', '&');	// Fix FF escapes
	k = k.replace(/\&amp;/g, '&');	// Fix FF escapes
	if (c <= 0) {	
		window.location = k;	// link out now
	}
	else {
		setTimeout('redirtocsglink(c, k)', 1000);	// start countdown
	}
}
// Handle countdown for csg interstitial
function redirtocsglink(c, k) {
	cc = c - 1;
	if (cc == 2) {		// ready now
		window.location = k;	// go to partner
	}
	if (cc >= 0) {
		setTimeout('redirtocsglink(cc, k)', 1000);		// come back in 1 second
		document.getElementById('csgcountdown').innerHTML = c;
	}
}

// Manage a CSS popup window
function popup_window_pos(win) {
  var x = 0;
  var y = 0;
  if( typeof( window.pageYOffset ) == 'number' )
  {
      x = window.pageXOffset;
      y = window.pageYOffset;
  }
  else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) )
  {
      x = document.documentElement.scrollLeft;
      y = document.documentElement.scrollTop;
  }
  else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) )
  {
      x = document.body.scrollLeft;
      y = document.body.scrollTop;
  }
  x = x+80;
  y = y+20;
	var popUpDiv = document.getElementById(win);
	popUpDiv.style.position = "absolute";
	popUpDiv.style.left = x + 'px';
	popUpDiv.style.top = y + 'px';
}
function popup_close(win, blk, erase) {
	var fc = document.getElementById(win);
	var fb = document.getElementById(blk);
	if (null != fb) fb.style.display = 'none';
	if (null != fc) {
		fc.style.display = 'none';
		if (erase) fc.innerHTML="";
	}
	return false;
}
function csspopup(win, blk, type, url, w, h) {
	var fc = document.getElementById(win);
	var fb = document.getElementById(blk);
	if (type==1) {	// iFrame URL
		ct = "<iframe scrolling='no' marginheight='0' marginwidth='0' src='" + url + "' width='" + w + "' height='" + h + "' border='0' frameborder='0'></iframe>";
	}
	else {	// assume fill with text
		ct = url;
	}
	fc.innerHTML = ct;
	fb.style.display = 'block';
	fc.style.display = 'block';
	popup_window_pos(blk);
}

// Go to a city from a metro dropdown
function hlfmetroform(fm, fs, st) {
	var fso = document.getElementById(fs);	// get select
	if (fso != null) {
		var city = fso.options[fso.selectedIndex].value;
		return csglink(city, st, '', '', 'csgpopupc', 'csgpopupb', '1');
	}
	return false;
}

// 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", "");
				pageTracker._trackPageview("/form/miniform_ZipCode.html"); //google tracking  code
				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", "");
			pageTracker._trackPageview("/form/miniform_CitySt.html"); //google tracking  code
			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;
	}
}

// Validate HLF advertising inquiry form
function advertiseformval() {		// validate the fields
	var inCity = document.getElementById('adv_form_city');
	var inState = document.getElementById('adv_form_state');
	var inName = document.getElementById('adv_form_name');
	var inPhone = document.getElementById('adv_form_phone');
	var inEmail = document.getElementById('adv_form_email');
	var ff = document.forms.AdvertiseForm;

	msg("lab_advCity", "lab", "");
	msg("lab_advName", "lab", "");
	msg("lab_advPhone", "lab", "");
	msg("lab_advEmail", "lab", "");
	msg("lab_advState", "lab", "");
	msg("lab_advZip", "lab", "");
	msg("lab_advformtitle", "lab", "");
	if(inName.value.length == 0) {  // if no name
		msg("lab_advName", "laberr", "");
		alert("Please Enter Your Full Name");
		setfocus(inName);
 		return false;
	}
	else if (!validateTelnr  (ff.advformphone, 'adv_form_phone', true)) {
		msg("lab_advPhone", "laberr", "");
		//alert("Please Enter a Phone");
		return false;
	}
	else if(!validateEmail(ff.advformemail, 'adv_form_email', true)) {  // if no email
		msg("lab_advEmail", "laberr", "");
		//alert("Please Enter Your Email Address");
		return false;
	}
	else if(inCity.value.length == 0 && inState.value.length == 0){  //if city and state not here
		msg("lab_advformtitle", "laberr", "");
		alert("Please Provide a City and State");
		setfocus(inCity);
		return false;
	}
	else if(inCity.value.length > 0 && inState.value.length == 0){   //if city but no state
		msg("lab_advState", "laberr", "");
		alert("Please Select a State");
		setfocus(inState);
		return false;
	}
	pageTracker._trackPageview("/form/advform_Inquiry.html"); //google tracking  code
	return true;
}

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
{
	if (message.length > 0) {
		alert(message);
	}
//  var elem = document.getElementById(fld);
//  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<10) {
    msg (infofield, "laberr", "Phone number must be at least 10 digits");
    setfocus(valfield);
    return false;
  }

  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";
	}
}




