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	
// 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
{
  // 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.)
  var dispmessage;
  if (emptyString.test(message)) 
    dispmessage = String.fromCharCode(nbsp);    
  else  
    dispmessage = message;

  var elem = document.getElementById(fld);
  elem.firstChild.nodeValue = dispmessage;  
  
  elem.className = msgtype;   // set the CSS class to adjust appearance of message
}

// --------------------------------------------
//            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
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(infofield);
  if (elem == null || !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, "error", "Required");  
		$('#' + infofield).show();
      // setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "warn", "");   // OK
		$('#' + infofield).hide();
      return true;  
    }
  }
  $('#' + infofield).hide();
  return proceed;
}

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

  msg (infofield, "warn", "");  
  $('#' + infofield).show();
  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
{
  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, "error", "Invalid email");
    $('#' + infofield).show();
    // 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, "warn", "Malformed email");
    $('#' + infofield).show();
  } else {
    msg (infofield, "warn", "");
  }
  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 phone1 = /^\+?[0-9 .()-]+[0-9]$/  ;
  if (!phone1.test(tfld)) {
    msg (infofield, "error", "Invalid phone");
    $('#' + infofield).show();
    // 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<7) {
    msg (infofield, "error", "Only " + numdigits + " digits: please correct.");
    $('#' + infofield).show();
    // setfocus(valfield);
    return false;
  }

  if (numdigits>14) {
    msg (infofield, "warn", numdigits + " digits?");
    $('#' + infofield).show();
  } else { 
    if (numdigits<10) {
      msg (infofield, "warn", numdigits + " digits: no area code?");
      $('#' + infofield).show();
    } else {
      msg (infofield, "warn", "");
      $('#' + infofield).hide();
	 }
  }

	var areacodes = {"201":"NJ","202":"DC","203":"CT","204":"MB","205":"AL","206":"WA","207":"ME","208":"ID","209":"CA","210":"TX","212":"NY","213":"CA","214":"TX","215":"PA","216":"OH","217":"IL","218":"MN","219":"IN","224":"IL","225":"LA","226":"ON","228":"MS","229":"GA","231":"MI","234":"OH","236":"VA","239":"FL","240":"MD","248":"MI","250":"BC","251":"AL","252":"NC","253":"WA","254":"TX","256":"AL","260":"IN","262":"WI","267":"PA","269":"MI","270":"KY","276":"VA","278":"MI","281":"TX","283":"OH","289":"ON","301":"MD","302":"DE","303":"CO","304":"WV","305":"FL","306":"SK","307":"WY","308":"NE","309":"IL","310":"CA","312":"IL","313":"MI","314":"MO","315":"NY","316":"KS","317":"IN","318":"LA","319":"IA","320":"MN","321":"FL","323":"CA","325":"TX","330":"OH","331":"IL","334":"AL","336":"NC","337":"LA","339":"MA","340":"VI","341":"CA","347":"NY","351":"MA","352":"FL","360":"WA","361":"TX","369":"CA","380":"OH","385":"UT","386":"FL","401":"RI","402":"NE","403":"AB","404":"GA","405":"OK","406":"MT","407":"FL","408":"CA","409":"TX","410":"MD","412":"PA","413":"MA","414":"WI","415":"CA","416":"ON","417":"MO","418":"QC","419":"OH","423":"TN","424":"CA","425":"WA","430":"TX","432":"TX","434":"VA","435":"UT","438":"QC","440":"OH","442":"CA","443":"MD","450":"QC","464":"IL","469":"TX","470":"GA","475":"CT","478":"GA","479":"AR","480":"AZ","484":"PA","501":"AR","502":"KY","503":"OR","504":"LA","505":"NM","506":"NB","507":"MN","508":"MA","509":"WA","510":"CA","512":"TX","513":"OH","514":"QC","515":"IA","516":"NY","517":"MI","518":"NY","519":"ON","520":"AZ","530":"CA","540":"VA","541":"OR","551":"NJ","557":"MO","559":"CA","561":"FL","562":"CA","563":"IA","564":"WA","567":"OH","570":"PA","571":"VA","573":"MO","574":"IN","580":"OK","585":"NY","586":"MI","601":"MS","602":"AZ","603":"NH","604":"BC","605":"SD","606":"KY","607":"NY","608":"WI","609":"NJ","610":"PA","612":"MN","613":"ON","614":"OH","615":"TN","616":"MI","617":"MA","618":"IL","619":"CA","620":"KS","623":"AZ","626":"CA","627":"CA","628":"CA","630":"IL","631":"NY","636":"MO","641":"IA","646":"NY","647":"ON","650":"CA","651":"MN","660":"MO","661":"CA","662":"MS","669":"CA","670":"MP","671":"GU","678":"GA","679":"MI","682":"TX","689":"FL","701":"ND","702":"NV","703":"VA","704":"NC","705":"ON","706":"GA","707":"CA","708":"IL","709":"NL","712":"IA","713":"TX","714":"CA","715":"WI","716":"NY","717":"PA","718":"NY","719":"CO","720":"CO","724":"PA","727":"FL","731":"TN","732":"NJ","734":"MI","737":"TX","740":"OH","747":"CA","754":"FL","757":"VA","760":"CA","762":"GA","763":"MN","764":"CA","765":"IN","769":"MS","770":"GA","772":"FL","773":"IL","774":"MA","775":"NV","778":"BC","779":"IL","780":"AB","781":"MA","785":"KS","786":"FL","787":"PR","801":"UT","802":"VT","803":"SC","804":"VA","805":"CA","806":"TX","807":"ON","808":"HI","810":"MI","812":"IN","813":"FL","814":"PA","815":"IL","816":"MO","817":"TX","818":"CA","819":"QC","828":"NC","830":"TX","831":"CA","832":"TX","835":"PA","843":"SC","845":"NY","847":"IL","848":"NJ","850":"FL","856":"NJ","857":"MA","858":"CA","859":"KY","860":"CT","862":"NJ","863":"FL","864":"SC","865":"TN","867":"YT","870":"AR","872":"IL","878":"PA","901":"TN","902":"NS","903":"TX","904":"FL","905":"ON","906":"MI","907":"AK","908":"NJ","909":"CA","910":"NC","912":"GA","913":"KS","914":"NY","915":"TX","916":"CA","917":"NY","918":"OK","919":"NC","920":"WI","925":"CA","927":"FL","928":"AZ","931":"TN","935":"CA","936":"TX","937":"OH","939":"PR","940":"TX","941":"FL","947":"MI","949":"CA","951":"CA","952":"MN","954":"FL","956":"TX","957":"NM","959":"CT","970":"CO","971":"OR","972":"TX","973":"NJ","975":"MO","978":"MA","979":"TX","980":"NC","984":"NC","985":"LA","989":"MI"};
	var states = {"AL":"Alabama","AK":"Alaska","AS":"American Samoa","AZ":"Arizona","AR":"Arkansas","CA":"California","CO":"Colorado","CT":"Connecticut","DE":"Delaware","DC":"District Of Columbia","FM":"Federated States Of Micronesia","FL":"Florida","GA":"Georgia","GU":"Guam","HI":"Hawaii","ID":"Idaho","IL":"Illinois","IN":"Indiana","IA":"Iowa","KS":"Kansas","KY":"Kentucky","LA":"Louisiana","ME":"Maine","MH":"Marshall Islands","MD":"Maryland","MA":"Massachusetts","MI":"Michigan","MN":"Minnesota","MS":"Mississippi","MO":"Missouri","MT":"Montana","NE":"Nebraska","NV":"Nevada","NH":"New Hampshire","NJ":"New Jersey","NM":"New Mexico","NY":"New York","NC":"North Carolina","ND":"North Dakota","MP":"Northern Mariana Islands","OH":"Ohio","OK":"Oklahoma","OR":"Oregon","PW":"Palau","PA":"Pennsylvania","PR":"Puerto Rico","RI":"Rhode Island","SC":"South Carolina","SD":"South Dakota","TN":"Tennessee","TX":"Texas","UT":"Utah","VT":"Vermont","VI":"Virgin Islands","VA":"Virginia","WA":"Washington","WV":"West Virginia","WI":"Wisconsin","WY":"Wyoming"};

	var re = /\(?(\d{3})\)?[-\/\. ]\d{3}[-\/\. ]\d{4}/;
	var OK = re.exec(tfld);
	if (OK && areacodes[OK[1]]) {
		document.forms.assessmentForm.state.value = states[areacodes[OK[1]]];
	} 
  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, "error", "Invalid age");
    $('#' + infofield).show();
    // setfocus(valfield);
    return false;
  }

  if (tfld>=200) {
    msg (infofield, "error", "Invalid age...");
    $('#' + infofield).show();
    // setfocus(valfield);
    return false;
  }

  if (tfld>75) {
	 msg (infofield, "warn", "Over 75 years?");
    $('#' + infofield).show();
  } else {
    if (tfld<12) {
		 msg (infofield, "warn", "Must be over 13.");
       $('#' + infofield).show();
	 } else {
		 msg (infofield, "warn", "");
       $('#' + infofield).hide();
	 }
  }
  return true;
}


// *** --------------------------------------------
//             validateLastName
// Validate the selection tag for LastName
// Returns true if OK
// --------------------------------------------

function validateLastName(valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required  )
{
  var stat = commonCheck (valfield, infofield, required);
  if (stat != proceed) return stat;
  msg (infofield, "warn", "");
  $('#' + infofield).hide();
  return true;
}

// --------------------------------------------
//             validatePhoneType
// Validate the selection tag for Phone Type
// Returns true if OK
// --------------------------------------------

function validatePhoneType(valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required  )
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;
  msg (infofield, "warn", "");
  $('#' + infofield).hide();
  return true;
}

// *** --------------------------------------------
//             validateState
// Validate the selection tag for State
// Returns true if OK
// --------------------------------------------

function validateState(valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required  )
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;
  msg (infofield, "warn", "");
  $('#' + infofield).hide();
  return true;
}

// *** --------------------------------------------
//             validateFirstName
// Validate the input tag for FirstName
// Returns true if OK
// --------------------------------------------

function validateFirstName(valfield,   // element to be validated
                         infofield,  // id of element to receive info/error msg
                         required  )
{
  var stat = commonCheck (valfield, infofield, true);
  if (stat != proceed) return stat;

    var pt = trim(valfield.value);
    var ptl=pt.length;
    if(ptl < 3) {
     msg(infofield,"error", "At least 3 char");
     $('#' + infofield).show();
     // setfocus(valfield);
     return false;
    } else {
		msg (infofield, "warn", "");
		$('#' + infofield).hide();
		return true;
    }
  msg (infofield, "warn", "");
  $('#' + infofield).hide();
  return true;
}

// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley

function validateOnSubmit() {
	var elem;
	var errs=0;
	// execute all element validations in reverse order, so focus gets
	// set to the first one in error.
	if (!validateAge (document.forms.assessmentForm.age,   'inf_age',  false)) errs += 1;
	if (!validateTelnr (document.forms.assessmentForm.phone1, 'inf_phone1', true)) errs += 1;
	if (!validateEmail (document.forms.assessmentForm.emailAddress, 'inf_email', true)) errs += 1;
	if (!validatePresent (document.forms.assessmentForm.firstName,  'inf_from1')) errs += 1;
	if (!validateLastName (document.forms.assessmentForm.lastName,   'inf_from2',  false)) errs += 1;
	if (!validateState (document.forms.assessmentForm.state,  'inf_state')) errs += 1;

	if (errs>1)  alert('There are fields which need correction before sending');
	if (errs==1) alert('There is a field which needs correction before sending');

	return (errs==0);
};
  
// SHOWHIDE TBODY FOR COMMENTS ON RADIO SELECT
function show(id) {
	if (document.getElementById(id).style.display == 'none') {
		document.getElementById(id).style.display = '';
	}
}

function hide(id) {
	document.getElementById(id).style.display = 'none';
}

// SHOWHIDE DIV TEXT

function showhideDiv(ID) {
	var divID = document.getElementById(ID).style;
	if (divID.display == 'block') {
		divID.display = 'none';
	} else {
		divID.display = 'block';
	}
}

// SWAP TBODY IN CONTACT FORM

var tbods = {
	'legal': 'Legal' ,
	'family': 'Family' ,
	'family': 'Family' ,
	'friend': 'Friend' ,
	'coworker': 'Coworker' ,
	'other': 'Other'
}

if (navigator.userAgent.indexOf("Firefox")!=-1) {
	function showhide(obj) {
		var mc, v = obj.options[obj.selectedIndex].value;
		for (var opt in tbods)
		if (mc = document.getElementById(tbods[opt]))
			mc.style.display = (opt != v) ? 'none' : 'table-row-group';
	}
}

if (navigator.userAgent.indexOf("MSIE")!=-1) {
	function showhide(obj) {
		var mc, v = obj.options[obj.selectedIndex].value;
		for (var opt in tbods)
		if (mc = document.getElementById(tbods[opt]))
			mc.style.display = (opt != v) ? 'none' : 'block';
	}
}

document.onload = function() {
	document.getElementById('inquiringAbout').onchange();
}
