var digits = "0123456789";
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz";
var whitespace = " \t\n\r";
var decimalPointDelimiter = ".";
var phoneNumberDelimiters = "()- ";
var validUSPhoneChars = digits+phoneNumberDelimiters;
var validWorldPhoneChars = digits+phoneNumberDelimiters+"+";
var SSNDelimiters = "- ";
var validSSNChars = digits+SSNDelimiters;
var digitsInSocialSecurityNumber = 9;
var digitsInUSPhoneNumber = 10;
var ZIPCodeDelimiters = "-";
var ZIPCodeDelimeter = "-";
var validZIPCodeChars = digits+ZIPCodeDelimiters;
var digitsInZIPCode1 = 5;
var digitsInZIPCode2 = 9;
var creditCardDelimiters = " ";
// m is an abbreviation for "missing"
var mPrefix = "You did not enter a value into the ";
var mSuffix = " field. This is a required field. Please enter it now.";
// s is an abbreviation for "string"
var sLastName = "Last Name";
var sFirstName = "First Name";
var sUserName = "User Name";
var sWorldLastName = "Family Name";
var sWorldFirstName = "Given Name";
var sPassWord = "Password";
var sPassWordConfirm = "Password Confirm";
var sTitle = "Title";
var sCompanyName = "Company Name";
var sAddress1 = "Street Address";
var sWorldAddress = "Address";
var sCity = "City";
var sStateCode = "State Code";
var sWorldState = "State, Province, or Prefecture";
var sCountry = "Country";
var sZIPCode = "ZIP Code";
var sWorldPostalCode = "Postal Code";
var sPhone = "Phone Number";
var sFax = "Fax Number";
var sDateOfBirth = "Date of Birth";
var sExpirationDate = "Expiration Date";
var sEmail = "Email";
var sSSN = "Social Security Number";
var sCreditCardNumber = "Credit Card Number";
var sOtherInfo = "Other Information";
var sInputQuestion = "Question";
var sInputChoice = "Choice";
var sInputAnswer = "Answer";
var sRegistrationCode = "Registration Code";
var sHomeChurch = "Home Church";
var sDenomination = "Denomination";
var sFaithDeclaration = "Declaration of faith";
var sBibleVersion = "Bible Version";

// i is an abbreviation for "invalid"
var iStateCode = "This field must be a valid two character U.S. state abbreviation (like CA for California). Please reenter it now.";
var iZIPCode = "This field must be a 5 or 9 digit U.S. ZIP Code (like 94043). Please reenter it now.";
var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now.";
var iWorldPhone = "This field must be a valid international phone number. Please reenter it now.";
var iSSN = "This field must be a 9 digit U.S. social security number (like 123 45 6789). Please reenter it now.";
var iEmail = "This field must be a valid email address. Please reenter a valid email now.";
var iEmailGovMil = "Government or military email are not allowed. Please reenter a valid email now.";
var iCreditCardPrefix = "This is not a valid ";
var iCreditCardSuffix = " credit card number. (Click the link on this form to see a list of sample numbers.) Please reenter it now.";
var iDay = "This field must be a day number between 1 and 31.  Please reenter it now.";
var iMonth = "This field must be a month number between 1 and 12.  Please reenter it now.";
var iYear = "This field must be a 2 or 4 digit year number.  Please reenter it now.";
var iDatePrefix = "The Day, Month, and Year for ";
var iDateSuffix = " do not form a valid date.  Please reenter them now.";
var iStringBetween = "This field must be between the specified length.";
var iTerms = "Please read Condition and terms then click read. Thank you.";
var iInputQuestion = "This field must contain a question. Please enter a question.";
var iInputChoice = "Please fill in all possible choices.";
var iInputAnswer = "There must be one correct answer. Please select it now.";
var iBadUsername = "Valid user names can only contain letters and numbers with no spaces.";

// p is an abbreviation for "prompt"
var pEntryPrompt = "Please enter a ";
var pInputQuestion = "Please input the Question.";
var pInputChoice = "Please input a possible Answer.";
var pInputAnswer = "Please Select the correct Answer.";
var pStateCode = "2 character code (like AZ).";
var pZIPCode = "5 or 9 digit U.S. ZIP Code (like 85251).";
var pUSPhone = "10 digit U.S. phone number (like 415 555 1212).";
var pWorldPhone = "international phone number.";
var pSSN = "9 digit U.S. social security number (like 123 45 6789).";
var pEmail = "valid email address (like InHisName@HolyBibleTrivia.org).";
var pCreditCard = "valid credit card number.";
var pDay = "day number between 1 and 31.";
var pMonth = "month number between 1 and 12.";
var pYear = "2 or 4 digit year number.";
var pRegistrationCode = "If applicable please enter a registration code.";

var defaultEmptyOK = false;

// Attempting to make this library run on Navigator 2.0,
// so I'm supplying this array creation routine as per
// JavaScript 1.0 documentation.  If you're using 
// Navigator 3.0 or later, you don't need to do this;
// you can use the Array constructor instead.

function makeArray(n){
//*** BUG: If I put this line in, I get two error messages:
//(1) Window.length can't be set by assignment
//(2) daysInMonth has no property indexed by 4
//If I leave it out, the code works fine.
//   this.length = n;
   for (var i = 1; i <= n; i++){
      this[i] = 0;
   } 
   return this;
}

////////////////////////////jodys list
function isStrEqual ( theField, theField2, s ){	
	if( theField.value != theField2.value ){ 
		return warnInvalid (theField, s+" are not the same. Please reenter.");	
	}else{
		return true;
	}
}

/* FUNCTIONS TO INTERACTIVELY CHECK VARIOUS FIELDS. */
// checkString (TEXTFIELD theField, STRING s, [, BOOLEAN emptyOK==false])
// Check that string theField.value is not all whitespace.
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function checkString (theField, s, emptyOK){
	// Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if(checkString.arguments.length == 2){emptyOK = defaultEmptyOK;}
    if((emptyOK == true) && (isEmpty(theField.value))){return true;}
    if(isWhitespace(theField.value)){
       return warnEmpty (theField, s);
    }else{return true;}
}

//checkStringSize(form.elements["usrName"], "3", "10", sUserName)
function checkStringSize(theField, mi, ma, s){	
	if(isEmpty(theField.value)){
		return warnEmpty (theField, s);}

	if(!isBetweens (theField.value, mi, ma )){
		return warnInvalid (theField, iStringBetween);
	}else{
		return true;}

}

function isValidUserName(theField){	
	for (i = 0; i < theField.value.length; i++){   		
		var c = theField.value.charAt(i);
		if(!isLetterOrDigit(c)){
			return warnInvalid (theField, iBadUsername);}
	}

	return true;
}


// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
function checkEmail (theField, emptyOK){
	if(checkEmail.arguments.length == 1){emptyOK = defaultEmptyOK;}
	if((emptyOK == true) && (isEmpty(theField.value))){return true;}
	
	if(!isEmail(theField.value, false)){return warnInvalid (theField, iEmail);}
	
	if(!isValidEmailExt(theField.value)){return warnInvalid (theField, iEmailGovMil);
	}else{return true;}
}

//checkPassWord (form.elements["pWord"], form.elements["pWord2"], sPassWord )
function checkPassWord ( theField, theField2, mi, ma, s ){	
	if(isEmpty(theField.value)){return warnEmpty (theField, s);}
	if(isEmpty(theField2.value)){return warnEmpty (theField2, s);}
	if(!isBetweens (theField.value, mi, ma )){return warnInvalid (theField, iStringBetween);}
	
	if(theField.value != theField2.value){
		return warnInvalid (theField, "Passwords are not the same. Please reenter.");	
	}else{return true;}
}

//checkBoxSelected(form.elements["termsandconditions"], iTerms )
function checkBoxSelected(theField, s){
	if( !theField.checked ){
		return warnInvalid (theField, s);	
	}else{return true;}
}

//checkBoxSelected(form.elements["termsandconditions"], iTerms )
function checkRadioButton(radio, s){
	var checkvalue = "empty";
	for (i=0, n=radio.length; i<n; i++){
		if(radio[i].checked){
			checkvalue = radio[i].value;
			break;
		}
	}
	
	if( checkvalue == "empty" ){		
		//warnInvalid (radio, s);
		alert(mPrefix+s+mSuffix);
		return false;
	}else{return checkvalue;}
}

// Returns true if character c is an English letter 
function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) );
}

// Returns true if character c is a digit 
function isDigit (c){ return ((c >= "0") && (c <= "9"));}

// Returns true if character c is a letter or digit.
function isLetterOrDigit (c){ return (isLetter(c) || isDigit(c));}

function isInteger (s)
{   var i;

    if(isEmpty(s)){
       if(isInteger.arguments.length == 1){return defaultEmptyOK;
       }else{return (isInteger.arguments[1] == true);}
    }

    // Search through string's characters one by one
    // until we find a non-numeric character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character is number.
        var c = s.charAt(i);
		//var c = s[i];

        if(!isDigit(c)){return false;}
    }

    // All characters are numbers.
    return true;
}

function isBetweens (s, mi, ma ){
	if((( s.length < mi ) || ( s.length > ma ))){return false;
	}else{return true;}
}

// For explanation of optional argument emptyOK,
// see comments of function isInteger.
function isIntegerInRange (s, a, b){
	if(isEmpty(s)){return false;}

    // Catch non-integer strings to avoid creating a NaN below,
    // which isn't available on JavaScript 1.0 for Windows.
    if(!isInteger(s, false)){return false;}

    // Now, explicitly change the type to integer via parseInt
    // so that the comparison code below will work both on 
    // JavaScript 1.2 (which typechecks in equality comparisons)
    // and JavaScript 1.1 and before (which doesn't).
    var num = parseInt (s);
    return ((num >= a) && (num <= b));
}

// Check whether string s is empty.
function isEmpty(s){
	return ((s == null) || (s.length == 0));
}

// Returns true if string s is empty or 
// whitespace characters only.
function isWhitespace (s){
	var i;
	// Is s empty?
	if(isEmpty(s)){return true;}
		// Search through string's characters one by one
		// until we find a non-whitespace character.
		// When we do, return false; if we don't, return true.
	
	for (i = 0; i < s.length; i++){   
		// Check that current character isn't whitespace.
		var c = s.charAt(i);
		if(whitespace.indexOf(c) == -1){return false;}
	}
	// All characters are whitespace.
	return true;
}

// isEmail (STRING s [, BOOLEAN emptyOK])
function isEmail (s){
	if(isEmpty(s)){ 
		if(isEmail.arguments.length == 1){return defaultEmptyOK;
		}else{return (isEmail.arguments[1] == true);}
	}
   
    if(isWhitespace(s)){return false;}    

    var i = 1;
    var sLength = s.length;

	//look for " "
	while ((i < sLength)){
		if(s.charAt(i) == " "){return false;
		}else{i++;}
    }	

	//reset to look for valid format
    i = 1;
    sLength = s.length;

    // look for @
    while ((i < sLength) && (s.charAt(i) != "@")){i++;}

    if((i >= sLength) || (s.charAt(i) != "@")){return false;
    }else{i += 2;}

    // look for .
    while ((i < sLength) && (s.charAt(i) != ".")){i++;}

	// there must be at least one character after the .
	if((i >= sLength - 1) || (s.charAt(i) != ".")){return false;
	}else{return true;}
}

// isValidEmailExt (STRING s )
function isValidEmailExt (text){
	if((text.indexOf(".gov") != -1) || (text.indexOf(".mil") != -1) ){				
		return false;
	}
	return true;
}

/* FUNCTIONS TO NOTIFY USER OF INPUT REQUIREMENTS OR MISTAKES. */

function prompt (s){
	window.status = s;
}

function promptEntry (s){
	window.status = pEntryPrompt+s;
}

function warnEmpty (theField, s){   
	theField.focus();
	alert(mPrefix+s+mSuffix);
	return false;
}

function warnInvalid (theField, s){   
	theField.focus();
	theField.select();
	alert(s);
	return false;
}

// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

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(dtStr){
	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){
		alert("The date format should be : mm/dd/yyyy");
		return false;
	}
	if(strMonth.length<1 || month<1 || month>12){
		alert("Please enter a valid month");
		return false;
	}
	if(strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
		alert("Please enter a valid day");
		return false;
	}
	if(strYear.length != 4 || year==0 || year<minYear || year>maxYear){
		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if(dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
		alert("Please enter a valid date");
		return false;
	}
return true;
}

function validateUserAddressForm(form){			
	//check first name
	if(!checkString(form.elements["pFirstName"], sFirstName)){
		return false;	
	}
	
	//check last name
	if(!checkString(form.elements["pLastName"], sLastName)){
		return false;	
	}
	
	//check address
	if(!checkString(form.elements["pAddress1"], sAddress1)){
		return false;	
	}
	
	//country
	if(!checkString(form.elements["pCountry"], sCountry)){
		return false;	
	}
	
	return true;
}

function validateChangePasswordForm(form){			
	var bOK = true;
	
	bOK = checkPassWord (form.elements["pPassWord"], form.elements["pPassWord2"], 3, 24, sPassWord );
	
	return bOK;
}

function validateAuthorRequestForm(form){			
	var bOK = true;
	if(!checkString(form.elements["pDenomination"], sDenomination)){return false;}	
	if(!checkString(form.elements["pFaithDeclaration"], sFaithDeclaration)){return false;}
	return bOK;
}

function isValidFeedback(form){			
	var bOK = true;
	if(bOK){bOK = checkEmail (form.elements["pEmail"]);}	
	return bOK;
}

function validateUserProfileForm(form, catmax){				
	var bOK = true;
	var bCatChecked = true;//false jody make false when category is required.
	var dt = document.fProfileUpdater.pDob;	

	//check for one bibleVersion checked
	if (!(form.bibleVersionAll.checked || form.bibleVersion0.checked || form.bibleVersion1.checked || form.bibleVersion2.checked || form.bibleVersion3.checked || form.bibleVersion4.checked || form.bibleVersion5.checked)) {
		warnInvalid (form.elements["bibleVersionAll"], "Please select at least one Bible version");
		bOK = false;
	}
	
	if(bOK){
		for ( j=1; j < catmax; j++ ){
			var cat = "cat"+j;
			if( form.elements[cat].checked ){				
				bCatChecked = true;
			}
		}
		if(!bCatChecked){
			warnInvalid (form.elements["cat1"], "Please select at least one category");
			bOK = false;
		}
	}
	if(bOK){bOK = checkEmail (form.elements["pEmail"]);}

	//check Date of Birth if not null
	if(bOK){
		if(!isEmpty(dt.value)){
			if(!isDate(dt.value)){
				dt.focus();
				bOK = false;
			}
		}
	}	
	
	//Level Desired
	for (j=0; j<form.pDesiredLevel.options.length; j++){
		if(form.pDesiredLevel.options[j].selected){
			if(form.pDesiredLevel.options[j].value == "0"){
				alert ("Please select the desired playing level.");
				return false;
			}
		}
	}	
	
	return bOK;		
}

function popUpScriptRef(URL){
	day = new Date();
	id = day.getTime();
	var popW = window.open(URL, 'scriptRefPage', 'alwaysRaised=1, dependent=1, toolbar=0, scrollbars=1, location=0, statusbar=0, menubar=0, resizable=1, width=800, height=445, left=110, top=50');
	//eval("page" + id + " = window.open(URL, 'scriptRefPage', 'alwaysRaised=1, dependent=1, toolbar=0, scrollbars=1, location=0, statusbar=0, menubar=0, resizable=1, width=800, height=445, left=110, top=50');");
	if (window.focus){popW.focus();}
}

function popUpExternalSite(URL){
	day = new Date();
	id = day.getTime();
	eval("page"+id+" = window.open(URL, '"+id+"', 'toolbar=1, scrollbars=1, location=1, statusbar=1, menubar=1, resizable=1, width=750, height=500, left=220, top=50');");
}

function popUpMisc(URL){
	day = new Date();
	id = day.getTime();
	eval("page"+id+" = window.open(URL, '"+id+"', 'toolbar=0, scrollbars=1, location=1, statusbar=1, menubar=0, resizable=1, width=750, height=600, left=220, top=50');");
}

function popUpHelp(URL){
	day = new Date();
	id = day.getTime();
	eval("page" + id + " = window.open(URL, 'helpPage', 'alwaysRaised=1, dependent=1, toolbar=0, scrollbars=1, location=0, statusbar=0, menubar=0, resizable=1, width=500, height=600, left=20,  top=50');");
}

function popUpQuestioin(URL){
	day = new Date();
	id = day.getTime();
	eval("page"+id+" = window.open(URL, '"+id+"', 'toolbar=0,scrollbars=1,location=0,statusbar=1,menubar=0,resizable=1,width=400,height=500,left = 20,top = 50');");
}

