// SFA JavaScript Functions

// Validate fields for the search form
function sfaformval() {		// validate the fields
	
	var inCity = document.getElementById('city');
	var inState = document.getElementById('st');
		
	if(inCity.value.length == 0 && inState.value.length == 0){  //if city and state not here
		alert('Please Enter a City and State');
		return false;
	}
	else if(inCity.value.length > 0 && inState.value.length == 0){   //if city but no state
		alert('Please Select a State');
		return false;
	}
	else if(inCity.value.length == 0 && inState.value.length > 0) {  // if state but no city
		alert('Please Enter a City');
		return false;
	}
	else { //is good city/state
		return true;
	}
}

function Init_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;
};


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



/**
 * popularCitiesSubmit - Performs popup that precedes redirect.  
 * @param win - target id (csgpopupc which contains spinner image.)
 * @param blk - target id (csgpopupb which is containing div for win)
 * @param city
 * @param state
 * @param dlv - directory level
 * @returns {Boolean}
 */
function displayCityURL(win, blk, url, dlv) {	
	_gaq.push(['_trackPageview', '/redirect/MNP']); // new way to do page tracking. In HLF the "pageTracker" variable was created for this purpose

	var dirup = "";
	for(dli=1;dli<dlv;dli++) dirup = dirup + "../";	
	var csgurl = dirup + 'citystategointer.php?dlv=' + dlv + '&url=' + url;

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



/**
 * popularCitiesSubmit - Performs popup that precedes redirect.  
 * @param win - target id (csgpopupc which contains spinner image.)
 * @param blk - target id (csgpopupb which is containing div for win)
 * @param city
 * @param state
 * @param dlv - directory level
 * @returns {Boolean}
 */
function displayCity(win, blk, city, state, dlv, affiliate) {	
	_gaq.push(['_trackPageview', '/redirect/MNP']); // new way to do page tracking. In HLF the "pageTracker" variable was created for this purpose
	var dirup = "";
	for(dli=1;dli<dlv;dli++) dirup = dirup + "../";	
	var csgurl = dirup + 'citystategointer.php?dlv=' + dlv + '&city=' + city + "&state=" + state + "&affiliate=" + affiliate;

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



/**
 * popularCitiesSubmit - Performs popup that precedes redirect.  
 * @param win - target id (csgpopupc which contains spinner image.)
 * @param blk - target id (csgpopupb which is containing div for win)
 * @param city
 * @param state
 * @param dlv - directory level
 * @returns {Boolean}
 */
function popularCitiesSubmit(win, blk, city, state, dlv) {	
	_gaq.push(['_trackPageview', '/redirect/MNP']); // new way to do page tracking. In HLF the "pageTracker" variable was created for this purpose
	var dirup = "";
	for(dli=1;dli<dlv;dli++) dirup = dirup + "../";	
	var csgurl = dirup + 'citystategointer.php?dlv=' + dlv + '&miniformcity=' + city + "&miniformstate=" + state;

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




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




//// MISC ////

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





