//ACT javascript functions
//validation for CASMA registration 05/21/03 WDD
//added functions for ACT Store form 03/19/04 WDD
//added cookie functions for HR application 04/27/04 WDD
//added autotab function 08/10/04 WDD
//making more edits to deal with scripted store 12/26/04 WDD
//adding function for WK practice test 01/27/06 WDD

// Common functions used with forms
// We use this as a hash to track those elements validated on a per element
// basis that have formatting problems
validate = new Object();

// Takes a value, checks if it's an integer, and returns true or false
function isInteger ( value ) {
    return ( value == parseInt( value ) );
}

// Takes a value and a range, checks if the value is in the range, and
// returns true or false
function inRange ( value, low, high ) {
    return ( !( value < low ) && value <= high );
}

//ACT Store specific function : makes sure user has selected at least one item to order

function requireItem ( form, requiredValues ) {
    for ( var i = 0; i < requiredValues.length; i++ ) {
        element = requiredValues[i];
        if (form[element].selectedIndex >= 1) {
            return true;
        }
    }
    alert( "Please select at least one item to order." );
    return false;
}

//WorkKeys Practice Tests Specific Function : makes sure user has selected at least one item to order
function requireCheckedItem ( form, requiredValues ) {
    for ( var i = 0; i < requiredValues.length; i++ ) {
        element = requiredValues[i];
        if (form[element].checked) {
            return true;
        }
    }
    alert( "Please select at least one practice test to purchase." );
    return false;
}

// Takes a form and an array of element names; verifies that each has a value
function requireValues ( form, requiredValues ) {
    for ( var i = 0; i < requiredValues.length; i++ ) {
        element = requiredValues[i];
        if ( form[element].value == "" ) {
            alert( "You must complete all required fields on the form." );
            return false;
        }
    }
    return true;
}


// Takes a form and an array of element names; verifies that each has an
// option selected (other than the first; assumes that the first option in
// each select menu contains instructions)
function requireSelects ( form, requiredSelect ) {
    for ( var i = 0; i < requiredSelect.length; i++ ) {
        element = requiredSelect[i];
        if ( form[element].selectedIndex <= 0 ) {
            alert( "You must complete all required fields on the form." );
            return false;
        }
    }
    return true;
}

// Takes a form and an array of element names; verifies that each has a
// value checked
function requireRadios ( form, requiredRadio ) {
    for ( var i = 0; i < requiredRadio.length; i++ ) {
        element = requiredRadio[i];
        isChecked = false;
        for ( j = 0; j < form[element].length; j++ ) {
            if ( form[element][j].checked ) {
                isChecked = true;
            }
        }
        if ( ! isChecked ) {
            alert( "You must complete all required fields on the form." );
            return false;
        }
    }
    return true;
}

// Verify there aren't any uncorrected formatting problems with elements
// validated on a per element basis
function checkProblems () {
    for ( element in validate ) {
        if ( ! validate[element] ) {
            alert( "Please correct the format of " + element + "." );
            return false;
        }
    }
    return true;
}

//check email address  - not using currently
function checkemail( email ) {
var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
if (filter.test(email))
	return true;
else{
alert("Please input a valid email address.")
	return false;
}
}


//don't let the user submit more than once.
function oneSubmit ( form ) {
    form.disabled = true;  //to disable submit button after one submission
    return true;
}


function isalpha(ch){
	if (ch >= 65 && ch <= 90)
		return true;
	else if (ch >= 97 && ch <= 122)
		return true;
	else
		return false;
} //end isalpha()

function isDigit1(c)
{   return ((c >= "0001") && (c <= "9999"))
}//end isDigit1()

function isDigit2(c)
{   return ((c >= "01") && (c <= "12"))
} //end isDigit2()

function isDigit3(c)
{   return ((c >= "00") && (c <= "99"))
} //end isDigit3()

function isDigit4(c)
{   return ((c >= "01") && (c <= "31"))
} //end isDigit4()

function isDigit(c)
{   return ((c >= "0") && (c <= "9"))
} //end isDigit()

function isLetter(c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}  //end isLetter()

function any_blanks(str) {
/* checks a string to determine if the string contains any blanks */
/* RETURN VALUE: 0-no blanks, #>0 - the number of blanks found */
if (str == null)
	return true;

for(var i=0;i<str.length;i++){
	if (str[i]==' ')
		return true;
   }
return false;
} //end any_blanks()

function all_numbers(str) {
/* checks a string to determine if all chars are numeric */
/* RETURN VALUE: 0-not all numeric, 1-all chars numeric  */
for(var i=0;i<str.length;i++) {
	if (!isDigit(str.charAt(i)) && str.charAt(i) != ' ')
		return(false);
	}
return(true);
} //end all_numbers()

function any_numbers(str) {
/* checks a string to determine if all chars are numeric */
/* RETURN VALUE: 0-not all numeric, 1-all chars numeric  */
for(var i=0;i<str.length;i++){
	if (isDigit(str.charAt(i)))
		return(true);
	}
return(false);
} //end any_numbers()

function all_letters(str) {
/* checks a string to determine if all chars are alpha (or spaces) */
/* RETURN VALUE: 0-not all letters or spaces,                      */
/* 1-all chars are letters or spaces                               */
for(var i=0;i<str.length;i++) {
	if ( (str.charAt(i)!=' ') && !isLetter(str.charAt(i)) )
		return(false);
	}
return(true);
} //end all_letters()

function all_blanks(str) {
/* checks a string to determine if all chars are spaces */
/* RETURN VALUE: 0-not all spaces, 1-all spaces         */
if (str == null)
	return true;

for(var i=0;i<str.length;i++){
   if (str.charAt(i)!=' ')
		return(false);
   }
return(true);
} //end all_blanks()

function embedded_blanks(str) {
/* checks a string to determine if there are embedded blanks */
/* RETURN VALUE: 0-no embedded blanks, 1-one or more embedded blanks */
var j=0;
while((str.charAt(j)==' ')&&(j<str.length))
	j++;

for(var i=j;i<str.length;i++) {
	if ( (str.charAt(i)==' ') && (str.charAt(i+1)!=' ') )
		return(true);
   }
return(false);
} //end embedded_blanks()

function valid_digits(str,len,require)	{
	if (all_blanks(str)) {	
		if (require)
			return "Field cannot be blank.";
		else
			return null;
	}
	else if (len == 0)	{
		if ( (!all_numbers(str)) || (embedded_blanks(str)) )
			return "Only numbers are valid for this field.  Do not enter spaces or any other character."; 
		}	
	else {
		if ( (str.length < len) || (!all_numbers(str)) || (any_blanks(str)) )
			return "Only numbers are valid for this field.  Do not enter spaces or any other character.  This field must be "+len+" digits in length.";
	    }
	return null;	
} //end valid_digits()

function check_embedded(str) {
var blank = 0;
var embedded = 0;

if(all_blanks(str))
	return false;
	
	for(var i=0;i<str.length;i++){
   		if (str.charAt(i)==' ')
		blank++;
   	}
	
	var j=0;
	while((str.charAt(j)==' ')&&(j<str.length))
		j++;

	for(var i=j;i<str.length;i++) {
		if ( (str.charAt(i)==' ') && (str.charAt(i+1)!=' ') )
			embedded++;
   	}

if (blank != embedded)
	return false;

return true;
} //end check_embedded()
	


function valid_cc(value) {
    var len = value.length;	
	var type1 = document.casma.card_type[0].value;
	var type2 = document.casma.card_type[1].value;
    var c1 = value.charAt(0);
	
   if (all_blanks(value))  // this should never happen, but check nonetheless
        return "You must provide a credit card number.";

	if ( ((c1 != "4") && (c1 != "5")) || (valid_digits(value,13,true) != null) ) {
		return "You have entered an invalid credit card number.  Only VISA and MasterCard are accepted.  Only numbers are valid for this field.  Do not enter spaces or any other character.";
	}

    if (((c1 == "4") && (type1 != "VISA")) || ((c1 == "5") && (type2 != "MasterCard"))) {
       return "The credit card number you have entered does not match the credit card type you have selected.";
    }

    var sum = 0;
    var tmp = 0;
    var mul = 1;
    if(len%2 == 0) {
      mul = 2;
    }
    for (i = 0; i < len; i++) {
      tmp = mul * ( 0 - 0 + value.charAt(i));
      if(tmp > 9) {
        tmp -= 9;
      }
      mul = (mul == 2)?1:2;
      sum += tmp;
    }

    if(sum%10 != 0) {
      return "You have entered an invalid credit card number.  Only VISA and MasterCard are accepted.  Only numbers are valid for this field.  Do not enter spaces or any other character.";
    }
    // pass the test
    return null;
} //end valid_cc()

today=new Date();
var mnth1 = today.getMonth();
var day = today.getDay();
var mnth = mnth1 + 1;

function getFullYear() { // d is a date object
 var yr = "";
 	if (today.getYear() < 100) yr = "19" + today.getYear();
	if (today.getYear() >= 2001) yr = today.getYear();
	else yr = 1900 + today.getYear();
 return yr;
} //end getFullYear()

function findCharsInBag (s, bag) { 
for (var i=0; i < s.length; i++) {
  var c = s.charAt(i);
   if (bag.indexOf(c) == -1){
	return false;
	}
 }
return true;
} //end findCharsInBag()

function emailCheck (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("Email address seems incorrect (check @ and .'s)")
	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>4) {
   // 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!
//alert("Testing email check.");
return true;
}
//end emailCheck()

// Cookie setting functions 
// Function to create a cookie and set its value
function setCookie(name, value, expires) {
    document.cookie = escape(name) + "=" + escape(value) + "; path=/" + 
        ((expires == null) ? "" : "; expires=" + expires.toGMTString(  ));
}

// Function to retrieve a cookie's value
function getCookie(name) {
    var cookiename = name + "=";
    var dc = document.cookie;
    var begin, end;

    if (dc.length > 0) {
        begin = dc.indexOf(cookiename);
        if (begin != -1) {
            begin += cookiename.length;
            end = dc.indexOf(";", begin);
            if (end == -1) {
                end = dc.length;
            }
            return unescape(dc.substring(begin, end));
        } 
    }
    return null;
}

// Function to delete a cookie
function deleteCookie(name) {
    document.cookie = name + "=; expires=Thu, 01-Jan-70 00:00:01 GMT" +  
        "; path=/";
}

//end Cookie setting functions

// -------------------------------------------------------------------
// TabNext()
// Function to auto-tab phone field
// Arguments:
//   obj :  The input object (this)
//   event: Either 'up' or 'down' depending on the keypress event
//   len  : Max length of field - tab when input reaches this length
//   next_field: input object to get focus after this one

// example code:
// <input type="text" name="hp_area" size="3" maxlength="3" nKeyDown="TabNext(this,'down',3)" onKeyUp="TabNext(this,'up',3,this.form.hp_3)">

// -------------------------------------------------------------------
var phone_field_length=0;
function TabNext(obj,event,len,next_field) {
	if (event == "down") {
		phone_field_length=obj.value.length;
		}
	else if (event == "up") {
		if (obj.value.length != phone_field_length) {
			phone_field_length=obj.value.length;
			if (phone_field_length == len) {
				next_field.focus();
				}
			}
		}
	}

