// ----------------------------------------------------------------------------------------------
// Javascript Form Validations
// Author: Bradley Clampitt
// ----------------------------------------------------------------------------------------------
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.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", "ERROR: Required Field");  
      setfocus(valfield);
      return false;
    }
    else {
      msg (infofield, "info", "");   // OK
      return true;  
    }
  }
  return proceed;
}

// ----------------------------------------------------------------------------------------------
//            validatePresent
// Validate if something has been entered and return 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", "");  
	msg (infofield, "info", "Accepted (not verified)");
	return true;
}

// ----------------------------------------------------------------------------------------------
//            validateContent
// Validate if something is entered (like validatePresent  and return true if so
// ----------------------------------------------------------------------------------------------
function validateContent(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, "info", "Accepted");
	return true;
}
// ----------------------------------------------------------------------------------------------
//						validateCity
// Checking the City, State, Country and Zip Code
// ----------------------------------------------------------------------------------------------
function validateCity(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, "info", "Accepted (not verified)");
	return true;	
}

function validateStateDropdown(valfield,  // element to be validated
                               infofield )  // id of element to receive info/error msg
{

	if ((valfield == "") || (valfield == 0) || (!valfield))  {
		msg (infofield, "error", "State not chosen, please select or input!");
		return false;
	} else {
		msg (infofield, "info", "Approved");
		return true;
	}
	return true;
}

function validateZipCode(valfield,		// element to be validated
												 infofield, 	// id of element to receive info/error msg
												 required )		// true if required
{
	var stat = commonCheck (valfield, infofield, true);
	if (stat != proceed) return stat;
	
	var tfld = trim(valfield.value);	// Trims the baby fat off of it.
	var zipCode = /(^\d{5}$)|(^\d{5}-\d{4}$)/;
	
	if (zipCode.test(tfld)) {	// If the inputed value is a number then..
		msg (infofield, "info", "Accepted");
		return true;
	} else {
		msg (infofield, "error", "Invalid Zip Code");
		setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
		return false;
	}
  return true;
}

// ----------------------------------------------------------------------------------------------
//            validateSerialNumber
// Validate a serial number
// Returns true if so 
// ----------------------------------------------------------------------------------------------
function validateSerialNumber(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); // Trims the baby fat off of it.
	var serialNo = /^[0-9]+$/; 			 // Checks to see if this is just a number no letters/characters

	if (serialNo.test(tfld)) {  // If the inputed value is a number then...
		if (tfld.length == 5 || tfld.length == 11) {
			msg (infofield, "info", "Accepted (not yet verified with our records)");
			return true;
		} else if (tfld.length <= 4) {
			msg (infofield, "error", "Not Accepted (S/N's are 5 or 11 numbers)");
			setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
			return false;
		} else if (tfld.length >= 6 && tfld.length <= 10) {
			msg (infofield, "error", "Not Accepted (S/N's are 5 or 11 numbers)");
			setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
			return false;
		} else if (tfld.length >= 12) {
			msg (infofield, "error", "Not Accepted (S/N's are 5 or 11 numbers)");
			setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
			return false;
		}
	} else {
		msg (infofield, "error", "Not Accepted (S/N's are numbers only)");
		setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
		return false;
	}
  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", "Not Accepted: not a valid e-mail address");
    setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
    return false;
  }

  var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/  ;
  if (!email2.test(tfld)) {
    msg (infofield, "warn", "Unusual e-mail address - please double check");
 	}

	msg (infofield, "info", "Accepted Email Address");
	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 ()-]+[0-9]$/;
  if (!telnr.test(tfld)) {
    msg (infofield, "error", "Not Valid. Numbers, space ()- and leading + only permitted.");
    setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
    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, "error", "Not Valid: " + numdigits + " digits - too short");
    setfocus(valfield);  // Places the cursor back in the field to correct before moving on!
    return false;
  }

  if (numdigits>14) {
    msg (infofield, "warn", numdigits + " digits - check if correct");
  } else { 
    if (numdigits<10) {
      msg (infofield, "warn", "Only " + numdigits + " digits - check if correct");
    }
  }

	msg (infofield, "info", "Accepted Phone Number");
  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", "ERROR: not a valid age");
    setfocus(valfield);// Places the cursor back in the field to correct before moving on!
    return false;
  }

  if (tfld>=200) {
    msg (infofield, "error", "Not Valid: not an accurate age amount.");
    setfocus(valfield);// Places the cursor back in the field to correct before moving on!
    return false;
  }

  if (tfld>110) msg (infofield, "warn", "Older than 110: check correct");
  else {
    if (tfld<7) msg (infofield, "warn", "Bit young for this, aren't you?");
    else        msg (infofield, "warn", "");
  }
  msg (infofield, "info", "Accepted Age");
  return true;
}

// ----------------------------------------------------------------------------------------------
// 							Validate Password
// This will check the results of two fields that are for passwords
// ----------------------------------------------------------------------------------------------
function verifynotify(field1, field2, result_id, match_html, nomatch_html, blankmatch_html) {
 this.field1 = field1;
 this.field2 = field2;
 this.result_id = result_id;
 this.match_html = match_html;
 this.nomatch_html = nomatch_html;
 this.blankmatch_html = blankmatch_html;

 this.check = function() {

   // Make sure we don't cause an error
   // for browsers that do not support getElementById
   if (!this.result_id) { return false; }
   if (!document.getElementById){ return false; }
   r = document.getElementById(this.result_id);
   if (!r){ return false; }

   if (this.field1.value != "" && this.field1.value == this.field2.value) {
     r.innerHTML = this.match_html;
   } else if ((this.field1.value == "" && this.field2.value == "") || (this.field2.value =="")) {
   		r.innerHTML = this.blankmatch_html;
   } else {
     r.innerHTML = this.nomatch_html;
   }
 }
}

// ----------------------------------------------------------------------------------------------
// Calendar - Javascript
// ----------------------------------------------------------------------------------------------
var monthtext = ['January','February','March','April','May','June','July','August','September','October','November','December'];

function populatedropdown(dayfield, monthfield, yearfield){
	var today = new Date()
	var dayfield = document.getElementById(dayfield)
	var monthfield = document.getElementById(monthfield)
	var yearfield = document.getElementById(yearfield)
	
	for (var i=0; i<31; i++)
	dayfield.options[i]=new Option(i, i+1)
	dayfield.options[today.getDate()]=new Option(today.getDate(), today.getDate(), true, true) //select today's day

	for (var m=0; m<12; m++)
	monthfield.options[m]=new Option(monthtext[m], monthtext[m])
	monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], monthtext[today.getMonth()], true, true) //select today's month
			
	var thisyear=today.getFullYear()
			
	for (var y=0; y<10; y++) {
		yearfield.options[y]=new Option(thisyear, thisyear)
		thisyear-=1
	}
	// $purchase_date
	yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true) //select today's year
}

// Secondary Password checker for the User Control Panel
function chkpassword() {
 
        var p1 = document.getElementById("pass1").value;
        var p2 = document.getElementById("pass2").value;
 
        if(p1.length>5) {
            document.getElementById("passwordAlert").style.display = 'none';
 
            if(p1===p2){
                document.getElementById("passwordAlert").style.display = 'none';
                validpass="yes";
            } else {
                validpass="no";
                document.getElementById("passwordAlert").style.display = 'block';
                document.getElementById("passwordAlert").innerHTML = "Both passwords must match to change your password.";
            }
 
        } else{
            document.getElementById("passwordAlert").style.display = 'block';
            document.getElementById("passwordAlert").innerHTML = "For security purposes, the password must be at least 6 characters long.";
        }
}
// Custom Email Checker for the User Control Panel's Email Changer
function chkemailchange() {
	var e1 = document.getElementById("email1").value;
	var e2 = document.getElementById("email2").value;
	var email = /^[^@]+@[^@.]+\.[^@]*\w\w$/;
	var email2 = /^[A-Za-z][\w.-]+@\w[\w.-]+\.[\w.-]*[A-Za-z][A-Za-z]$/;
	
	if (e1===e2) {
    document.getElementById("passwordAlert").style.display = 'none';
    validpass="yes";
	} else {
		validpass="no";
		document.getElementById("passwordAlert").style.display = 'block';
		document.getElementById("passwordAlert").innerHTML = "Your Entered Email Address and Confirmation Address do not match.";
	}
	if (email.test(e1) == false) {
		validpass="no";
		document.getElementById("passwordAlert").style.display = 'block';
		document.getElementById("passwordAlert").innerHTML = "Not Accepted: not a valid e-mail address";
	}
	if (email2.test(e1) == false) {
		validpass="no";
		document.getElementById("passwordAlert").style.display = 'block';
		document.getElementById("passwordAlert").innerHTML = "Unusual e-mail address - please double check.";
	}
}