// ----------------------------------------------------------------------
// Javascript form validation routines.
// Author: Stephen Poley
//
// http://www.xs4all.nl/~sbpoley/webmatters/formval.html
//
// Simple routines to quickly pick up obvious typos.
// All validation routines return true if executed by an older browser:
// in this case validation must be left to the server.
//
// Update Aug 2004: have tested that IE 5.0 and IE 5.5 both support DOM model
// sufficiently well, so innerHTML option removed (redundant).
//
// Update Jun 2005: discovered that reason IE wasn't setting focus was
// due to an IE timing bug. Added 0.1 sec delay to fix.
//
// Update Oct 2005: minor tidy-up: unused parameter removed
// ----------------------------------------------------------------------

var nbsp = 160;    // non-breaking space char
var node_text = 3; // DOM text node-type
var emptyString = /^\s*$/
var glb_vfld;      // retain vfld for timer thread

// -----------------------------------------
//                  trim
// Trim leading/trailing whitespace off string
// -----------------------------------------

function trim(str)
{
 	return str.replace(/^\s+|\s+$/g, '')
}

function filterNum(str) {
	re = /^\$|,/g;
	// remove "$" and ","
	return str.replace(re, "");
}

function formatCurrency(num) {
	num = num.toString().replace(/\$|\,/g,'');
	if(isNaN(num))
	num = "0";
	sign = (num == (num = Math.abs(num)));
	num = Math.floor(num*100+0.50000000001);
	cents = num%100;
	num = Math.floor(num/100).toString();
	if(cents<10)
	cents = "0" + cents;
	for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
	num = num.substring(0,num.length-(4*i+3))+','+
	num.substring(num.length-(4*i+3));
	return (((sign)?'':'-') + '$' + num + '.' + cents);
}




// -----------------------------------------
//                  setfocus
// Delayed focus setting to get around IE bug
// -----------------------------------------

function setFocusDelayed()
{
  glb_vfld.focus()
}

function setfocus(vfld)
{
  // save vfld in global variable so value retained when routine exits
  glb_vfld = vfld;
  setTimeout( 'setFocusDelayed()', 100 );
}


// -----------------------------------------
//                  msg
// Display good/bad 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 ("good" or "bad")
             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
}

function changecss(fld,     // id of element to change css of
                    msgtype)       // class to give element (defined in CSS)
{
	if( document.getElementById(fld) ) {
	  var elem = document.getElementById(fld);
	  elem.className = msgtype;   // set the CSS class to adjust appearance of message
	} else {
		// alert( fld ); // For Debugging changecss errors, uncomment this line.
	}
}


// -----------------------------------------
//            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    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/bad msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  

  if (emptyString.test(vfld.value)) {
    if (reqd) {
      msg (ifld, "bad", "ERROR: required");  
      setfocus(vfld);
      return false;
    }
    else {
      msg (ifld, "good", "");   // OK
      return true;  
    }
  }
  return proceed;
}




function commonCheckBull    (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  if (!document.getElementById) 
    return true;  // not available on this browser - leave validation to the server
  var elem = document.getElementById(ifld);
  if (!elem.firstChild)
    return true;  // not available on this browser 
  if (elem.firstChild.nodeType != node_text)
    return true;  // ifld is wrong type of node  

  if (emptyString.test(vfld.value)) {
    if (reqd) {
      changecss (ifld, "bad" );  
      setfocus(vfld);
      return false;
    }
    else {
      changecss (ifld, "good" );   // OK
      return true;  
    }
  }
  return proceed;
}

// -----------------------------------------
//            validatePresent
// Validate if something has been entered
// Returns true if so 
// -----------------------------------------

function validatePresent(vfld,   // element to be validated
                         ifld )  // id of element to receive info/error msg
{
  var stat = commonCheck (vfld, ifld, true);
  if (stat != proceed) return stat;

  msg (ifld, "good", "");  
  return true;
}



function validatePresentBull(vfld,   // element to be validated
                              ifld )  // id of element to receive info/error msg
{
  var stat = commonCheckBull (vfld, ifld, true);
  if (stat != proceed) return stat;

  changecss (ifld, "good" );  
  return true;
}

function validatePresentButNotZeroBull(vfld,   // element to be validated
                              ifld )  // id of element to receive info/error msg
{
  var stat = commonCheckBull (vfld, ifld, true);
  if (stat != proceed) return stat;
  if (vfld.value == "$0.00") {
      changecss (ifld, "bad" );
	  return false;
	  } else {
  changecss (ifld, "good" );  
  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  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/
  if (!email.test(tfld)) {
    msg (ifld, "bad", "ERROR: not a valid e-mail address");
    setfocus(vfld);
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/
  if (!email2.test(tfld)) 
    msg (ifld, "good", "Unusual e-mail address - check if correct");
  else
    msg (ifld, "good", "");
  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  (vfld,   // element to be validated
                         ifld,   // id of element to receive info/error msg
                         reqd)   // true if required
{
  var stat = commonCheck (vfld, ifld, reqd);
  if (stat != proceed) return stat;

  var tfld = trim(vfld.value);  // value of field with whitespace trimmed off
  var telnr = /^\+?[0-9 ()-]+[0-9]$/
  if (!telnr.test(tfld)) {
    msg (ifld, "bad", "ERROR: not a valid telephone number. Characters permitted are digits, space ()- and leading +");
    setfocus(vfld);
    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 (ifld, "bad", "ERROR: " + numdigits + " digits - too short");
    setfocus(vfld);
    return false;
  }

  if (numdigits>14)
    msg (ifld, "good", numdigits + " digits - check if correct");
  else { 
    if (numdigits<10)
      msg (ifld, "good", "Only " + numdigits + " digits - check if correct");
    else
      msg (ifld, "good", "");
  }
  return true;
}


// My own version of the telephone number check & post-formating
function validate_phone( field_id, show_alert ) {
	var tphone_pre = trim(field_id.value);
	// var tphone_pre = field_id.value.replace(/^\s+|\s+$/g, '')
	var tphone_mid = '';
	var tphone_post = '';
	for (var i=0; i<tphone_pre.length; i++) {
    	if (tphone_pre.charAt(i)>='0' && tphone_pre.charAt(i)<='9') tphone_mid += tphone_pre.charAt(i); }
	if( field_id.value == '' ) return false;
	if( tphone_mid.length != 10 ||
	   	tphone_mid.charAt(0) == '0' ||  // no valid area codes start with 0 or 1
	   	tphone_mid.charAt(0) == '1' ||
	   	tphone_mid == '2222222222' ||
	   	tphone_mid == '3333333333' ||
	   	tphone_mid == '4444444444' ||
	   	tphone_mid == '5555555555' ||
	   	tphone_mid == '6666666666' ||
	   	tphone_mid == '7777777777' ||
	   	tphone_mid == '8888888888' ||
	   	tphone_mid == '9999999999'
	) {
		if( show_alert ) {
			alert( 'Invalid phone number entry.\nPlease enter valid 10-digit phone number:\nex: (817) 555-4321 or 817-555-4321' );
		}
		// field_id.value = '';
		// Don't blank phone field here. Do so in the calling process script.
		return false;
	}
	tphone_post = "(" + tphone_mid.substr(0,3) + ") " + tphone_mid.substr(3,3) + "-" + tphone_mid.substr(6,4);
	field_id.value = tphone_post;
	return true;
}


// Div Hide/Show Code
function hidediv(idref) {
	if( idref ) {
		if (document.getElementById) { // DOM3 = IE5, NS6
			if( document.getElementById(idref) ) {
				document.getElementById(idref).style.visibility = 'hidden';
				document.getElementById(idref).style.display = 'none';
			}
		} 
		else { 
			if (document.layers) { // Netscape 4
				if( document.layers[idref]) {
					document.layers[idref].visibility = 'hidden';
					document.layers[idref].display = 'none';
				}
			} 
			else { // IE 4
				if( document.all[idref] ) {
					document.all[idref].style.visibility = 'hidden';
					document.all[idref].style.display = 'none';
				}
			}
		}
	}
}

function showdiv(idref) {
	if( idref ) {
		if (document.getElementById) { // DOM3 = IE5, NS6
			if( document.getElementById(idref) ) {
				document.getElementById(idref).style.visibility = 'visible';
				document.getElementById(idref).style.display = 'block';
			}
		} 
		else { 
			if (document.layers) { // Netscape 4 
				if( document.layers[idref]) {
					document.layers[idref].visibility = 'visible';
					document.layers[idref].display = 'block';
				}
			} 
			else { // IE 4
				if( document.all[idref] ) {
					document.all[idref].style.visibility = 'visible';
					document.all[idref].style.display = 'block';
				}
			}
		}
	}
}

