// Common JavaScript Routines
function setSubHeading(argSubHeadingText) {
	document.getElementById('SubHead').innerHTML = argSubHeadingText ;
}

/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function isInteger(s) {
	var i;
	for (i = 0; i < s.length; i++){   
		// Check that current character is number.
		var c = s.charAt(i);
		if (((c < "0") || (c > "9"))) return false;
	}
	// All characters are numbers.
	return true;
}

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30}
		if (i==2) {this[i] = 29}
   } 
   return this
}

function isDate(strDateLabel, dtStr){
	var msgs = ""
	var daysInMonth = DaysArray(12)
	var pos1=dtStr.indexOf(dtCh)
	var pos2=dtStr.indexOf(dtCh,pos1+1)
	var strMonth=dtStr.substring(0,pos1)
	var strDay=dtStr.substring(pos1+1,pos2)
	var strYear=dtStr.substring(pos2+1)
	strYr=strYear
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1)
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1)
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1)
	}
	month=parseInt(strMonth)
	day=parseInt(strDay)
	year=parseInt(strYr)
	if (pos1==-1 || pos2==-1){
		msgs += "The " + strDateLabel + " format should be : mm/dd/yyyy\n"
	}
	if (strMonth.length<1 || month<1 || month>12){
		msgs += "In " + strDateLabel + ", please enter a valid month\n"
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		msgs += "In " + strDateLabel + ", please enter a valid day\n"
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		msgs += "In " + strDateLabel + ", please enter a valid 4 digit year.\n"
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		msgs += "Please enter a valid " + strDateLabel + ".\n"
	}
	return msgs
}

function checkAMPM(strTimeValue)
{
    var d=strTimeValue.match(/^(\d{1,2}):(\d{1,2}) [AM|PM]{2}$/);
    if(!d || d[1]*1>12 || d[2]*1>59)
    {
	    return false;
    }
      return true;
}
// JavaScript Document


// Validates the argument to be alphabetic characters, plus a few punctuation chars
var letters="abcdefghijklmnopqrstuvwxyz.-,";
var LETTERS="ABCDEFGHIJKLMNOPQRSTUVWXYZ.-,";

function isAlpha(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isAlpha recursively for each character
		alpha=isAlpha(c.substring(j,j+1));
		if(!alpha) return alpha;
	  }
	  return alpha;
	}
	else {
	  // if c is alpha return true
	  if(letters.indexOf(c)>=0 || LETTERS.indexOf(c)>=0) return true;
	  return false;
	}
}

var EmailBadCharsMsgs, EmailAddressIsGood;
// Validates a string to contain valid email characters.
var ValidEmailAddressCharacters="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz@$_-.";
function CheckStringForValidEmailAddressCharacters(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isAlphaEmail recursively for each character
		valid = CheckStringForValidEmailAddressCharacters( c.substring(j,j+1) );
		if (EmailAddressIsGood && !valid) {
			EmailAddressIsGood = false;
		}
	  }
	  return EmailAddressIsGood;
	}
	else {
	  // if c is valid return true
	  if( ValidEmailAddressCharacters.indexOf(c) >= 0 ) {
	  	return true;
	  }
	  else {
	  	if (EmailBadCharsMsgs.length > 0) {
	  	  EmailBadCharsMsgs += ', '
		}
		if (c == ' ') {
		  EmailBadCharsMsgs += 'a space';
		}
	    else { 
		  EmailBadCharsMsgs +=  c;
		}
	     return false;
      }
	}
}

function isEmailAddressValid(c, addressType) {
	var posAtSign, posLastDot, allCharactersAreValid;
	EmailAddressIsGood = true; //optimistically assume the best
	
	var strC = new String(c);
	var probstringLength = valProblems.length;
	EmailBadCharsMsgs = '';
	posAtSign = strC.indexOf('@');
	posLastDot = -1;
	if (posAtSign >= 0) {
		posLastDot=strC.indexOf('.', posAtSign)
	}
	
    allCharactersAreValid = CheckStringForValidEmailAddressCharacters(c);
	if ( !allCharactersAreValid || posAtSign<0 || posLastDot<0 ) {
		valProblems += "\n\nThe " + addressType + " email address '" + c + "' is invalid.";
		if ( !allCharactersAreValid ) {
			valProblems +=  "\n >>>  The following illegal character";
			if ( EmailBadCharsMsgs.length > 1)
				valProblems += "s were found: ";
			else
				valProblems += " was found: " ;
			valProblems +=  EmailBadCharsMsgs;
		}
		if ( posAtSign < 0 ) 
			valProblems += "\n >>>  The '@' character is missing.";
		else
			if ( posLastDot < 0)
				valProblems += "\n >>>  There is no period following the '@', as in '.com' or '.army.mil'";
		if (probstringLength < valProblems.length) {
			valProblems += '\n';
		}
		return false;
	}
	else
		return true;
}

// Validates a string to contain valid decimal numeric characters.
var Numbers="0123456789";
function isNumeric(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isNumeric recursively for each character
		numeric=isNumeric(c.substring(j,j+1));
		if(!numeric) return numeric;
	  }
	  return numeric;
	}
	else {
	  // if c is numeric return true
	  if(Numbers.indexOf(c)>=0) return true;
	  return false;
	}
}


// Validates a string to contain valid zipcode characters.
var NumbersPlusDash="0123456789-";
function isZipCode(c) {
	// is c a String or a character?
	if(c.length>1) {
	  for(j=0;j<c.length;j++) {
		// call isNumeric recursively for each character
		numeric=isZipCode(c.substring(j,j+1));
		if(!numeric) return numeric;
	  }
	  return numeric;
	}
	else {
	  // if c is numeric or a dash return true
	  if(NumbersPlusDash.indexOf(c)>=0) return true;
	  return false;
	}
}

function IsZipCode(c) {
	return isZipCode(c) ;
}


function RemoveThisClassFromObject(strClassToRemove, strID) {
//alert("got to RemoveThisClassFromObject(" + strClassToRemove + ", " + strID + ")");
	var lengthOfClassToRemove = strID.length;
	var lengthOfOriginalClassString = document.getElementById(strID).className.length;
    var posOfClassToRemove =  document.getElementById(strID).className.indexOf(strClassToRemove);

//alert("1\n\nClass to remove: '" + strClassToRemove + "'" +
//	   "\nClass string from which to remove it: '" + document.getElementById(strID).className +"'" +
//	   "\nlengthOfClassToRemove = " + lengthOfClassToRemove +
 //      "\nlengthOfOriginalClassString = " + lengthOfOriginalClassString +
//	   "\nposOfClassToRemove = " + posOfClassToRemove);
	var strNewClassSet;
	if (posOfClassToRemove == -1) {
		//alert('1');

		//alert('The resulting Class setting for object of ID=' + strID + ' is now\n' +
//"'" + document.getElementById(strID).className + "', whose length is now " + 
//document.getElementById(strID).className.length); 

		return;  //not there, so we can't remove it.
	}
	if ( posOfClassToRemove == 0 ) {		
		//the class name we wish to remove resides at the beginning of the class string
		//Maybe the one we want to remove is the only one there. If so, just null the
		//string
		//alert('2');
		if (document.getElementById(strID).className == strClassToRemove) {
			//alert('3');
			document.getElementById(strID).className = "";
			//alert('4');
			return;
		}
		else {
			//alert('5');
			//it's the first class name in there, but not the only one, so
			//reset the string to it's present content with the undesired 
			//class name trimmed off.
			document.getElementById(strID).className = 
				document.getElementById(strID).className.substr(lengthOfClass+1);
			//alert('6');
			return;
		}	
	}
	
	//So, the class name isn't at the front of the string.  Build up a string 
	//thoat omits it from the current class, then assign that back in.
	//This gets the part before the one to be omitted.
//alert('7');
	strNewClassSet =  document.getElementById(strID).className.substr(0, posOfClassToRemove-1);
//alert('8');
	if ( posOfClassToRemove + lengthOfClassToRemove - 1 == lengthOfOriginalClassString) {
//alert('9');
		//if true, the class to remove is at the end of the string, so the new
		//class set is just everything up to, and not including the one to be
		//removed.
		strNewClassSet =  document.getElementById(strID).className.substr(0, posOfClassToRemove-1);
//alert('10');
	}
	else {
		//there's more stuff following the part we're removing, so we have to
		//join together the part before it and the part after it.
		//This gets the part before:
//alert('11');
		strNewClassSet =  document.getElementById(strID).className.substr(0, posOfClassToRemove-1);
		//This gets the part after:
//alert('12');
		strNewClassSet += " " +
			document.getElementById(strID).className.substr(
			   posOfClassToRemove+lengthOfClassToRemove, 
			   lengthOfOriginalClassString-(posOfClassToRemove+lengthOfClassToRemove) );
	}
	//alert("class string before mod was:" + document.getElementById(strID).className + "\nand after, it will be:" + strNewClassSet);
	document.getElementById(strID).className = strNewClassSet;
//alert('13 - made it all the way through');
}

function AddThisClassToObject(strClassToAdd, strID) { 
	var identity
	identity = document.getElementById(strID);

//alert('in AddThisClassToObject("' +strClassToAdd+'", "' + strID + '") and classname contains "' + identity.className + '"');
	if ( identity.className.indexOf(strClassToAdd) == -1 ) {
		if (identity.className.length == 0) {
		    //if it's the first class name in the string, don't include 
			//separator space.
//alert('determined that ' + strClassToAdd +' wasn\'t there already' + '\nthe classname length is ' + identity.className.length);
			
			identity.className += strClassToAdd;
		}
		else {
			//if other classes are present, include a space before the 
			//additional class name
			identity.className += " " + strClassToAdd;
		}
	}
//alert('The resulting Class setting for object of ID=' + strID + ' is now\n' + "'" + identity.className + "', whose length is now " + identity.className.length); 
}

function MarkAsIncorrect(strID) {
	AddThisClassToObject( "InError", strID );
}

function MarkAsCorrect(strID) {
	RemoveThisClassFromObject( "InError", strID );
}
	
				
function HighlightInYellow(strID) {
	AddThisClassToObject( "InError", strID );
}

function RemoveHighlight(strID) {
	RemoveThisClassFromObject( "InError", strID );
}

function trim(stringToTrim) {
	return stringToTrim.replace(/^\s+|\s+$/g,"");
}
function ltrim(stringToTrim) {
	return stringToTrim.replace(/^\s+/,"");
}
function rtrim(stringToTrim) {
	return stringToTrim.replace(/\s+$/,"");
}

function emailCheck (emailStr) {
	/* The following variable tells the rest of the function whether or not
	to verify that the address ends in a two-letter country or well-known
	TLD.  1 means check it, 0 means don't. */
	
	var checkTLD=1;
	
	/* The following is the list of known TLDs that an e-mail address must end with. */
	
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	
	/* 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. */
	
		valProblems += "Email address seems incorrect (check @ and .'s)\n";
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	
	// Start by checking that only basic ASCII characters are in the strings (0-127).
	
	for (i=0; i<user.length; i++) {
	if (user.charCodeAt(i)>127) {
		valProblems += "The username contains invalid characters.\n";
		return false;
	 }
	}
	for (i=0; i<domain.length; i++) {
	if (domain.charCodeAt(i)>127) {
	valProblems += "The domain name contains invalid characters.\n";
	return false;
		 }
	}
	
	// See if "user" is valid 
	
	if (user.match(userPat)==null) {
	
	// user is not valid
	
	valProblems += "The username doesn't seem to be valid.\n";
	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) {
	valProblems += "Destination IP address is invalid!\n";
	return false;
		 }
	}
	return true;
	}
	
	// Domain is symbolic name.  Check if it's valid.
	 
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
	valProblems += "The domain name does not seem to be valid.\n";
	return false;
		 }
	}
	
	/* domain name seems valid, but now make sure that it ends in a
	known top-level domain (like com, edu, gov) or a two-letter word,
	representing country (uk, nl), and that there's a hostname preceding 
	the domain or country. */
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
	domArr[domArr.length-1].search(knownDomsPat)==-1) {
	valProblems += "The address must end in a well-known domain or two letter " + "country.\n";
	return false;
	}
	
	// Make sure there's a host name preceding the domain.
	
	if (len<2) {
	valProblems += "This address is missing a hostname!\n";
	return false;
	}
	
	// If we've gotten this far, everything's valid!
	return true;
}
