//	validate.js
//
//  Copyright 2003 empoweredtraining.com - A Division of
//  Empowered Training Center, LLC. All Rights Reserved.
//
//
// SUMMARY
//
// This is a set of JavaScript functions for validating input on 
// an HTML form.  Functions are provided to validate:
//

var regExpAlpha = new RegExp("[A-Za-z ]*");
var regExpNumeric = new RegExp("[0-9]*");
var regExpNameReplace = new RegExp("{name}", "g");
var date = new Date();
var autoPrint = true; // Flag for whether or not to automatically call the print function

function validateEmail(emailStr) {
/* The following pattern is used to check if the entered e-mail address
   fits the user@domain format.  It also is used to separate the username
   from the domain. */
var emailPat=/^(.+)@(.+)$/
/* The following string represents the pattern for matching all special
   characters.  We don't want to allow special characters in the address. 
   These characters include ( ) < > @ , ; : \ " . [ ]    */
var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"
/* The following string represents the range of characters allowed in a 
   username or domainname.  It really states which chars aren't allowed. */
var validChars="\[^\\s" + specialChars + "\]"
/* The following pattern applies if the "user" is a quoted string (in
   which case, there are no rules about which characters are allowed
   and which aren't; anything goes).  E.g. "jiminy cricket"@disney.com
   is a legal e-mail address. */
var quotedUser="(\"[^\"]*\")"
/* The following pattern applies for domains that are IP addresses,
   rather than symbolic names.  E.g. joe@[123.124.233.4] is a legal
   e-mail address. NOTE: The square brackets are required. */
var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/
/* The following string represents an atom (basically a series of
   non-special characters.) */
var atom=validChars + '+'
/* The following string represents one word in the typical username.
   For example, in john.doe@somewhere.com, john and doe are words.
   Basically, a word is either an atom or quoted string. */
var word="(" + atom + "|" + quotedUser + ")"
// The following pattern describes the structure of the user
var userPat=new RegExp("^" + word + "(\\." + word + ")*$")
/* The following pattern describes the structure of a normal symbolic
   domain, as opposed to ipDomainPat, shown above. */
var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")


/* Finally, let's start trying to figure out if the supplied address is
   valid. */

/* Begin with the coarse pattern to simply break up user@domain into
   different pieces that are easy to analyze. */
var matchArray=emailStr.match(emailPat)
if (matchArray==null) {
  /* Too many/few @'s or something; basically, this address doesn't
     even fit the general mould of a valid e-mail address. */
	alert("Please enter a complete email address in the form: yourname@yourdomain.com")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

// See if "user" is valid 
if (user.match(userPat)==null) {
    // user is not valid
    alert("The username doesn't seem to be valid.")
    return false
}

/* if the e-mail address is at an IP address (as opposed to a symbolic
   host name) make sure the IP address is valid. */
var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {
    // this is an IP address
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("Destination IP address is invalid!")
		return false
	    }
    }
    return true
}

// Domain is symbolic name
var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name doesn't seem to be valid.")
    return false
}

/* domain name seems valid, but now make sure that it ends in a
   three-letter word (like com, edu, gov) or a two-letter word,
   representing country (uk, nl), and that there's a hostname preceding 
   the domain or country. */

/* Now we need to break up the domain to get a count of how many atoms
   it consists of. */
var atomPat=new RegExp(atom,"g")
var domArr=domain.match(atomPat)
var len=domArr.length
if (domArr[domArr.length-1].length<2 || 
    domArr[domArr.length-1].length>3) {
   // the address must end in a two letter or three letter word.
   alert("The address must end in a three-letter domain, or two letter country.")
   return false
}

// Make sure there's a host name preceding the domain.
if (len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}

// If we've gotten this far, everything's valid!
return true;
}



function isEmpty(txt) {
    var str = txt.value;
	
	return str == null || str.length == 0;
}


function validateText(txt, name){
	var isError = isEmpty( txt );
	
	if ( isError ){
		var errorMsg = "{name} is blank. Please enter {name}.";
		
		showFieldError( errorMsg, txt, name );
	}
		
	return !isError;	
}



function validateCheckBox(CheckBox, name){
	var isChecked = CheckBox.checked;
	
	if ( !isChecked ){
		var errorMsg = "{name} checkbox is not checked. Please check {name} checkbox.";
		
		showFieldError( errorMsg, CheckBox, name );
	}
		
	return isChecked;	
}

function validateEmpty(txt, name ) {
	var isError = !isEmpty( txt );
	
	if ( isError ){
		var errorMsg = "Nothing should be entered for {name}.";
	
		showFieldError( errorMsg, txt, name );
	}
		
	return !isError;	
}

function getCheckedRadio( group ){
	for (var i = 0; i < group.length; i++ )
		if ( group[i].checked )
			return( group[i].checked );
		
	return null;
}

function validateRadio( group, name ) { 
	var isError = getCheckedRadio( group ) == null;
	
	if ( isError ){
		var errorMsg = "{name} is blank. Please enter {name}.";
	
		showFieldError( errorMsg, group[0], name );
	}
	
	return !isError;	
}

function validateQuestion( group, errorMsg ) {
	var isError = getCheckedRadio( group ) == null;
	
	if ( isError ){
		if ( errorMsg == null ) 
			errorMsg = "Please answer required questions.";
	
		showError( errorMsg );
	}
	
	return !isError;	
}

function validateAllQuestions( form, errorMsg ) {
	var isError = false;
	
	for ( var i = 0; i < form.elements.length && !isError; i++ ) {
		var elem = form.elements[i];
		
		if ( elem.type == "radio"  ) {
			var grp = eval( "form." + elem.name );
			isError = getCheckedRadio( grp ) == null;
		}
	}
	
	if ( isError ) {
		if ( errorMsg == null )
			errorMsg = "Please answer required questions."; 
		showError( errorMsg );
	}
	
	return !isError;
}


function validateSelect( mnu, name ){
    var isError = mnu.selectedIndex <= 0;
	if ( isError ){
		var errorMsg =  "{name} is blank. Please enter {name}.";
		
		showFieldError( errorMsg, mnu, name );
	}
		
	return !isError;	
}

function validateMultipleSelect( mnu, name ){
    var isError = mnu.selectedIndex < 0;
	if ( isError ) {
		showFieldError( "Please select { name }.", mnu, name );
	}
		
	return !isError;	
}

function validateInteger(txt, name){
    if ( !validateText(txt, name ) )
		return false;

    var val = parseInt( txt.value, 10 );		

	var isError = isNaN( val );	
	if ( !isError )
		// make sure there is nothing at the end that is not a number
		isError = val == parseInt( txt.value + "1", 10);
	
	if ( isError ) {
		var errorMsg = "Please enter a valid whole number for {name}.";
	  	showFieldError( errorMsg, txt, name );
    }
		
	return !isError;	
}

		
function validateIntegerInRange(txt, min, max){
    if ( !validateText(txt) )
		return false;

    var val = parseInt( txt.value, 10 );		
	var rangeError = "";
	var blnValid = true;
	
	if ( blnValid &&  min != null  ){
		blnValid = min <= val;
		if ( !blnValid )
			rangeError = "( minimum of " + min + ")"; 
	}
		
	if ( blnValid && max != null)	{
		blnValid =  val <= max;
		if ( !blnValid )
			rangeError = "( maximum of " + max + ")"; 
	}

	if ( !blnValid ) 
	  showFieldError( "Please enter a valid whole number " + rangeError + " for {name}.", txt, name);
		
	return blnValid;	
}

function isNumeric( txt ){
	var str = txt.value;
	var result = str.replace( regExpNumeric,"" );	

	return result.length == 0;	
}

function isAlpha( txt ){
	var str = txt.value;
	var result = str.replace( regExpAlpha ,"" );

	return result.length == 0;
}

function validateFixedNumeric( txt, length, name ){
	if ( !validateText( txt, name ) )
		return false;

	var isError = false;
	var errorMsg;
	
	isError = txt.value.length < length;
	if ( isError )
		errorMsg = "{name} does not contain enough characters. Please enter a valid {name}.";
	else {
		isError =  !isNumeric(txt);
		if ( isError )
			errorMsg =  "{name} contains invalid characters. Please enter a valid {name}.";		
	}
		
	if ( isError ) {
		showFieldError( errorMsg, txt, name );
	}
	
	return !isError;
}


function validateAlpha( txt, name ){
	if ( !validateText( txt, name ) )
		return false;

	var	isError =  !isAlpha(txt);
	if ( isError ){
		errorMsg =  "{name} contains invalid characters. Please enter {name} with alphabetic characters.";		
		showFieldError( errorMsg, txt, name );
	}
	
	return !isError;
}
	
function validateClassCd(txt) {
	return validateFixedNumeric( txt, 4, "Class Code" );
}


function validateMMDDYYYYDate(txt, name){
    if ( !validateText(txt) )
		return false;
		
	var str = txt.value;
	var isError = str.length != 10;
	if ( !isError ){
		month = str.substring(0,2) - 1;
		day = str.substring(3,5);
		year = str.substring(6,10);// - 1900;
		
		isError = !isDateOk( year, month, day );
	}	
	
	if ( isError ) {
		showFieldError( "Please enter a valid date ( mm/dd/yyyy ) for {name}.", txt, name);
	}
		
	return !isError;	
}

function isDateOk(year, month, day){
	var dt = new Date(year, month, day );
		
	//Netscape wants years entered to be 0 base not 1900		
	return  	getFullYear(dt) == year 
			&&  dt.getMonth()   == month 
			&&	dt.getDate()    == day;
}

function getFullYear( date ) {
	var year = date.getYear();
	
	if ( year < 1900 )
		year += 1900;
		
	return year;	
}

function getYearRange(date) {
    var year = date.getYear();
    if (year >2003) 
    {
       return " 2003-" + year +" ";
    } 
    else 
    {
       return " 2003 ";
    }
}    
function validateDate(yearField, monthField, dayField, name) {
	var yearOption = yearField[yearField.selectedIndex];
	var monthOption = monthField[monthField.selectedIndex];
	var dayOption = dayField[dayField.selectedIndex];

	if (   !validateSelect( monthField, name ) 
		|| !validateSelect( dayField, name )
		|| !validateSelect( yearField, name ) )		
		return false;
		
	var isOk = isDateOk( yearOption.value, monthOption.value - 1, dayOption.value );

	if (!isOk) {
		showError("The date entered is invalid. Please enter a valid date.", monthField);
	}

	return isOk;
}


function validateFloat(txt, name){
    if ( !validateText(txt) )
		return false;
		
	var isError = isNaN(parseFloat( txt.value ));	
	if ( !isError )
		isError = parseFloat( txt.value ) == parseFloat( txt.value + "1");
	
	if ( isError )
	  showFieldError( "Please enter a valid number for {name}.", txt, name);
		
	return !isError;	
}

function validateZIPCode(txt, name) {
	if ( !validateText( txt, name ) )
		return false;
		
	var isError = !isNumeric( txt ) || txt.value.length != 5;
    
    if (isError) {
		  var errorMsg = "{name} is invalid. Please enter a valid 5 digit US Zip Code.";
		
          showFieldError(errorMsg, txt, name );
	}

    return !isError;
}

/* Not used, instead use the validatePostalCodes function */
function validatePostalCode(txt, name){ 
	if ( !validateText( txt, name ) )
		return false;
		
	var isError = isNumeric( txt ) || !((txt.value.length == 6) || (txt.value.length == 7));
    
    if (isError) {
		  var errorMsg = "{name} is invalid. Please enter a 6 alpha-numeric Canada Postal Code, such as L8H 8J7 or L8H8J7. ";
		
          showFieldError(errorMsg, txt, name );
	}

    return !isError;
	
}

/**
 * Used to check for valid Canadian Postal Code.
 * Currently, validation does not strictly follow the Postal Code 
 * Conversion File (PCCF), Reference Guide. It only checks that 
 * the code entered follows the ANA NAN format, and does not check 
 * if the alpha character is valid.
 *
 * Refer to http://www.statcan.ca/english/freepub/92F0153GIE/92F0153GIE2006002.pdf for 
 * the PCCF.
 */
function validatePostalCodes(txt, name) {
	//strlen = txtbox.value.length; 
	var isError = true;
	var code = txt.value;
	if (code.length != 6){
		isError = true;
	}else{
	    isError = false;
	}

	code = code.toUpperCase();   
	
	// Check for legal characters in string - note index starts at zero
	if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(code.charAt(0)) < 0) {
		isError = true;
	}
	if ('0123456789'.indexOf(code.charAt(1)) < 0) {
		isError = true;
	}
	if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(code.charAt(2)) < 0) {
		isError = true;
	}
	if ('0123456789'.indexOf(code.charAt(3)) < 0) {
		isError = true;
	}
	if ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'.indexOf(code.charAt(4)) < 0) {
		isError = true;
	}
	if ('0123456789'.indexOf(code.charAt(5)) < 0) {
		isError = true;
	}
	
	if (isError) {
		var errorMsg = "{name} is invalid. Please enter a valid 6 digit Canada Postal Code.";
		showFieldError(errorMsg, txt, name );
	}

	return !isError;
}

function checkRadios( form, matchvalue ) {
	for ( var i = 0; i < form.elements.length; i++ ) {
		var elem = form.elements[i];
		
		if ( elem.type == "radio" && elem.value.toUpperCase() == matchvalue.toUpperCase() )
			elem.checked = true;
	}
}

function confirmInput( field, clearOnCancel ) {
	var msg = "Press OK if " + field.value + " for " + field.name + " is correct ";
	
	var ok = confirm( msg );
	if ( !ok && clearOnCancel ) {
		if ( field.type == "radio" ) 
			field.checked = false;
		else if ( field.type == "text" ) 
			field.value = null;  // not tested			
	}
	
	return ok;
}


function showFieldError( errorMsg, field, name ){
	if ( name == null ) 
		name = getPrettyName(field.name);

	// replace is JS4.0+
	errorMsg = 	errorMsg.replace( regExpNameReplace, name );	
	
	showError( errorMsg, field );
}

function showError( strError, field ){
	alert( strError );
	
	if ( field != null && field.type != "hidden" ) 
		field.focus();	
}

function getPrettyName( name ){
	var pretty = "";
	
	for ( var i = 0; i < name.length; i++ ) {
		var ch = name.charAt(i); 
		
		if ( i == 0 ){
			pretty +=  ch.toUpperCase();
		} else {
			if ( ch == ch.toUpperCase() )
				pretty += ' ';
			pretty += ch;
		}	
	}
	return pretty;
}	


function isValidEmail(email) {
	invalidChars = " /:,;";
	
	if (email == "") {						// cannot be empty
		return false;
	}
	for (i=0; i<invalidChars.length; i++) {	// does it contain any invalid characters?
		badChar = invalidChars.charAt(i);
		if (email.indexOf(badChar,0) > -1) {
			return false;
		}
	}
	atPos = email.indexOf("@",1);			// there must be one "@" symbol
	if (atPos == -1) {
		return false;
	}
	if (email.indexOf("@",atPos+1) != -1) {	// and only one "@" symbol
		return false;
	}
	periodPos = email.indexOf(".",atPos)
	if (periodPos == -1) {					// and at least one "." after the "@"
		return false;
	}
	if (periodPos+3 > email.length)	{		// must be at least 2 characters after the "."
		return false;
	}
	return true;
}

function isEmailAddr(email)
{
  var result = false;
  var theStr = new String(email);
  var index = theStr.indexOf("@");
  if (index > 0)
  {
    var pindex = theStr.indexOf(".",index);
    if ((pindex > index+1) && (theStr.length > pindex+1))
  result = true;
  }

  return result;
}

function validRequired(formField,fieldLabel)
{
  var result = true;
  
  if (formField.value == "")
  {
    alert('Please enter a value for the "' + fieldLabel +'" field.');
    formField.focus();
    result = false;
  }
  
  return result;
}

function validEmail(formField,fieldLabel,required)
{
  var result = true;
  
  if (required && !validRequired(formField,fieldLabel))
    result = false;

  if (result && ((formField.value.length < 3) || !isEmailAddr(formField.value)) )
  {
    alert("Please enter a complete email address in the form: yourname@yourdomain.com");
    formField.focus();
    result = false;
  }
   
  return result;

}

 function printChartReport(id, title)
 {
 	if (document.getElementById != null)
 	{
 		var html = '<HTML>\n<HEAD>\n';

 		if (document.getElementsByTagName != null)
 		{
 			var headTags = document.getElementsByTagName("head");
 			if (headTags.length > 0)
 				html += headTags[0].innerHTML;
 		}

 		html += '\n</HEAD>\n<BODY bgcolor="E4E8EE">\n';
 		
 		if (title=="Course Schedule") {
			html +='\n<div align="center"><strong>Course Schedule</strong></div>\n';
		} else if (title=="Course Transcript") {
			html +='\n<div align="center"><strong>Course Transcript</strong></div>\n';
		} else if (title=="Monthly Revenue Report") {
		    html +='\n<div align="center"><strong>Monthly Revenue Report</strong></div>\n';
		} else if (title=="Monthly Learner Enrolled Info") {
		    html +='\n<div align="center"><strong>Monthly Course Enroll Info Report</strong></div>\n';
		}
		
        html +='\n<br><br>\n';
        
        if (title == "Course Schedule" || title =="Course Transcript") {
        	html +='\n<div align="left">\n';
        	html += document.getElementById(id+1).innerHTML; 
        	html +='\n<br>';
        	html += document.getElementById(id+2).innerHTML; 
        	html +='\n<br>';
        	html += document.getElementById(id+3).innerHTML; 
        	html +='\n<br>';
        	html += document.getElementById(id+4).innerHTML; 
        	html +='\n<br><br>\n';
        	html += document.getElementById(id+5).innerHTML; 
        	html +='\n</div><br><br>\n';		
		} else if ( title == "Monthly Revenue Report" || title=="Monthly Learner Enrolled Info") {
        	html +='\n<div align="left">\n';
        	html += document.getElementById(id+1).innerHTML; 
        	html +='\n<br>';
        	html += document.getElementById(id+2).innerHTML;  
        	html +='\n</div><br><br>\n';
		}
        
        html +='\n<div align="center">\n';
 		var chartSection = document.getElementById(id); 	
 		if (chartSection != null)
 		{ 				
 				html += chartSection.innerHTML;
 		}
 		else
 		{
 			alert("Could not find the printReady section in the HTML");
 			return;
 		}
 		
        html += '<br><br><br><br>Copyright &copy; ';

  		html +=  getYearRange(date) + ' empoweredtraining.com - A Division of Empowered Training Centre, LLC. All Rights Reserved.</br></br></br></br>';
  		html +='\n</div>\n';
 		html += '\n</BO' + 'DY>\n</HT' + 'ML>';

 		var printWin = window.open("","printSpecial");
 		printWin.document.open();
 		printWin.document.write(html);
 		printWin.document.close();
 		if (autoPrint)
 			printWin.print();
 			 			
 	}
 	else
 	{
 		alert("Sorry, the print ready feature is only available in modern browsers.");
 	}
 }
 
  function printLiveInfo(id, title)
 {
 	if (document.getElementById != null)
 	{
 		var html = '<HTML>\n<HEAD>\n';

 		if (document.getElementsByTagName != null)
 		{
 			var headTags = document.getElementsByTagName("head");
 			if (headTags.length > 0)
 				html += headTags[0].innerHTML;
 		}

 		html += '\n</HEAD>\n<BODY bgcolor="E4E8EE">\n';
		
        html +='\n<br><br>\n';
        
        html +='\n<div align="center">\n';
 		var chartSection = document.getElementById(id); 	
 		if (chartSection != null)
 		{ 				
 				html += chartSection.innerHTML;
 		}
 		else
 		{
 			alert("Could not find the printReady section in the HTML");
 			return;
 		}
 
   		html +='\n</div>\n';
 		html += '\n</BO' + 'DY>\n</HT' + 'ML>';

 		var printWin = window.open("","printSpecial");
 		printWin.document.open();
 		printWin.document.write(html);
 		printWin.document.close();
 		if (autoPrint)
 			printWin.print();
 			 			
 	}
 	else
 	{
 		alert("Sorry, the print ready feature is only available in modern browsers.");
 	}
 }
 
 

