var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "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 = " "
var mPrefix = "You did not enter a value into the "
var mSuffix = " field. This is a required field. Please enter it now."
var iDatePrefix = "The Day (DD), Month(MM), and Year(YYYY) for "
var iDateSuffix = " do not form a valid date.  Please choose them now."
var iEmail = "This field must be a valid email address (like foo@bar.com). 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 iZIPCodeInt = "This field must be a digit/char zipcode (like 91293FG1). Please reenter it now."
var iStateUSA = "USA country selected, please choose a state you are in."
var iStateNonUSA = "States are only for USA country, leave state blank(--) if you are choosing different country"
var iMaleFemale = "Please choose gender."
var defaultEmptyOK = false

var login = "Login"
var first_name = "First Name"
var last_name = "Last Name"
var email = "Email"
var dateofbirth = "Birth Date"
var calldate = "Call Date";
var address = "Address"
var city = "City"


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
}

var daysInMonth = makeArray(12);
daysInMonth[1] = 31;
daysInMonth[2] = 29;   // must programmatically check this
daysInMonth[3] = 31;
daysInMonth[4] = 30;
daysInMonth[5] = 31;
daysInMonth[6] = 30;
daysInMonth[7] = 31;
daysInMonth[8] = 31;
daysInMonth[9] = 30;
daysInMonth[10] = 31;
daysInMonth[11] = 30;
daysInMonth[12] = 31;

// Added by PashTeT. START.
function privs_check(id_priv) {
	if (document.admin_rights.priv_13.checked && id_priv == '13') {
		if(confirm('Two more privilege will be set by setting this privilege, are you sure?')) {
			document.admin_rights.priv_9.checked = true;
			document.admin_rights.priv_1.checked = true;
                } else {
			document.admin_rights.priv_13.checked = false;
                	return 0;
                }
        } else {
/*	        if (document.admin_rights.priv_13.checked && (id_priv == '9' || id_priv == '1' ) && (document.admin_rights.priv_9.checked == false || document.admin_rights.priv_1.checked == false)) {
	                if(confirm('WARNING. This privilege must be set!')) {
				document.admin_rights.submit();
                        } else {
				document.admin_rights.priv_9.checked = true;
				document.admin_rights.priv_1.checked = true;
       	                	return 0;
                        }
		}*/
        }
	document.admin_rights.submit();
}

function check_mailinglist(id) {
	if (document.manage['mailing_'+id].checked && document.manage['remove_me'].checked) {
		document.manage['mailing_'+id].checked = false;
        }
}

function replace_mailinglist() {
	if (document.manage.remove_me.checked && confirm("Mailing list will be deleted. Are you sure?")) {
	                for (var i = 0; i < replace_mailinglist.arguments.length; i++) {
	                        if (document.manage['mailing_'+replace_mailinglist.arguments[i]].checked) {
	                                document.manage['mailing_'+replace_mailinglist.arguments[i]].checked = false;
	                        }
	                }
        } else {
	       	document.manage.remove_me.checked = false;
	}

}

// Added by PashTeT. END.


function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

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;
}


function stripZeroes (num) {
	var newTerm;
	while (num.charAt(0) == "0") {
		newTerm = num.substring(1, num.length);
		num = newTerm;
	}
	if (num == "")
	num = "0";
	return num;
}


// Removes all characters which appear in string bag from string s.

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++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}



// Removes all characters which do NOT appear in string bag
// from string s.

function stripCharsNotInBag (s, bag)

{   var i;
    var returnString = "";

    // Search through string's characters one by one.
    // If character is in bag, append to returnString.

    for (i = 0; i < s.length; i++)
    {
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) != -1) returnString += c;
    }

    return returnString;
}



// Removes all whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripWhitespace (s) {
	return stripCharsInBag (s, whitespace)
}

// Returns true if character c is an English letter
// (A .. Z, a..z).
//
// NOTE: Need i18n version to support European characters.
// This could be tricky due to different character
// sets and orderings for various languages and platforms.

function isLetter (c)
{   return ( ((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")) )
}



// Returns true if character c is a digit
// (0 .. 9).

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))
}



// Notify user that required field theField is empty.
// String s describes expected contents of theField.value.
// Put focus in theField and return false.

function warnEmpty (theField, s)
{   theField.focus()
    alert(mPrefix + s + mSuffix)
    return false
}



// Notify user that contents of field theField are invalid.
// String s describes expected contents of theField.value.
// Put select theField, pu focus in it, and return false.

function warnInvalid (theField, s)
{   
	theField.focus()
	if (theField.tagName=='SELECT' || theField.type=='RADIO') {
    	theField.select()
	}
    alert(s)
    return false
}

// 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;
}


// checkEmail (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid Email.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkEmail (theField, emptyOK)
{   if (checkEmail.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else if (!isEmail(theField.value, false))
	{
		return warnInvalid (theField, iEmail);
	}
    else return true;
}

// isEmail (STRING s [, BOOLEAN emptyOK])
//
// Email address must be of form a@b.c -- in other words:
// * there must be at least one character before the @
// * there must be at least one character before and after the .
// * the characters @ and . are both required
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isEmail (s)
{   if (isEmpty(s))
       if (isEmail.arguments.length == 1) return defaultEmptyOK;
       else return (isEmail.arguments[1] == true);

    // is s whitespace?
    if (isWhitespace(s)) return false;

    // there must be >= 1 character before @, so we
    // start looking at character position 1
    // (i.e. second character)
    var i = 1;
    var 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;
}

// isYear (STRING s [, BOOLEAN emptyOK])
//
// isYear returns true if string s is a valid
// Year number.  Must be 2 or 4 digits only.
//
// For Year 2000 compliance, you are advised
// to use 4-digit year numbers everywhere.
//
// And yes, this function is not Year 10000 compliant, but
// because I am giving you 8003 years of advance notice,
// I don't feel very guilty about this ...
//
// For B.C. compliance, write your own function. ;->
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isYear (s)
{   if (isEmpty(s))
       if (isYear.arguments.length == 1) {return defaultEmptyOK;}
       else return (isYear.arguments[1] == true);
    if (!isNonnegativeInteger(s)) {return false;}
    //return ((s.length == 2) || (s.length == 4));
    return (s.length == 4);
}

function isMyYear (s) {
	if (isEmpty(s)) {
		if (isYear.arguments.length != 4) return defaultEmptyOK;
	} else {
		if (!isNonnegativeInteger(s)) {return false;}
	}
	return (s.length == 4);
}

// isMonth (STRING s [, BOOLEAN emptyOK])
//
// isMonth returns true if string s is a valid
// month number between 1 and 12.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isMonth (s)
{   if (isEmpty(s))
       if (isMonth.arguments.length == 1) return defaultEmptyOK;
       else return (isMonth.arguments[1] == true);
    return isIntegerInRange (s, 1, 12);
}

// isDay (STRING s [, BOOLEAN emptyOK])
//
// isDay returns true if string s is a valid
// day number between 1 and 31.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isDay (s)
{   if (isEmpty(s))
       if (isDay.arguments.length == 1) return defaultEmptyOK;
       else return (isDay.arguments[1] == true);
    return isIntegerInRange (s, 1, 31);
}



// daysInFebruary (INTEGER year)
//
// Given integer argument year,
// returns number of days in February of that year.

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 );
}

// isDate (STRING year, STRING month, STRING day)
//
// isDate returns true if string arguments year, month, and day
// form a valid date.
//

function isDate (year, month, day)
{   // catch invalid years (not 2- or 4-digit) and invalid months and days.

    // if (!(isYear(intYear, false) && isMonth(intMonth, false) && isDay(intDay, false))) return false;

    if (!(isYear(stripZeroes(year), false) && isMonth(stripZeroes(month), false) && isDay(stripZeroes(day), false))) return false;
    // Explicitly change type to integer to make code work in both
    // JavaScript 1.1 and JavaScript 1.2.

    var intYear = parseInt(stripZeroes(year));
    var intMonth = parseInt(stripZeroes(month));
    var intDay = parseInt(stripZeroes(day));

    // catch invalid days, except for February
    if (intDay > daysInMonth[intMonth]) return false;
    if ((intMonth == 2) && (intDay > daysInFebruary(intYear))) return false;
    return true;
}

function checkDate (yearField, monthField, dayField, labelString, OKtoOmitDay)
{   // Next line is needed on NN3 to avoid "undefined is not a number" error
    // in equality comparison below.
    if (checkDate.arguments.length == 4) OKtoOmitDay = false;
    //if (!isYear(yearField.value)) return warnInvalid (yearField, iYear);
    //if (!isYear(yearField.options[yearField.selectedIndex].value)) return warnInvalid (yearField, iYear);
    //if (!isMonth(monthField.options[monthField.selectedIndex].value)) return warnInvalid (monthField, iMonth);
    //if ( (OKtoOmitDay == true) && isEmpty(dayField.options[dayField.selectedIndex].value) ) return true;
    //else if (!isDay(dayField.options[dayField.selectedIndex].value))
    //   return warnInvalid (dayField, iDay);

    // if (yearField.options[yearField.selectedIndex].value == '' && monthField.options[monthField.selectedIndex].value == '' && dayField.options[dayField.selectedIndex].value == '') {return true;}
    // if (isDate (yearField.options[yearField.selectedIndex].value, monthField.options[monthField.selectedIndex].value, dayField.options[dayField.selectedIndex].value))
    if (yearField.value == '' && monthField.value == '' && dayField.value == '') {return true;}
    
    if (isDate (yearField.value, monthField.value, dayField.value))
       return true;
    alert (iDatePrefix + labelString + iDateSuffix)
    return false
}

function isChecked (radioField) {
	var t;
	for (t = 0; t < radioField.length; t++) {
		if (radioField[t].checked) {return true;}
	}
	return false;
}

function checkRadio (radioField, labelString, emptyOK) {
	if (checkRadio.arguments.length == 1) emptyOK = defaultEmptyOK;
	if (isChecked(radioField)) {
		return true;
	} else {
		if (emptyOK == true) {return true;}
	}
	alert (labelString);
	radioField[1].focus();
	return false;
}

// isNonnegativeInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if string s is an integer >= 0.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isNonnegativeInteger (s)
{   var secondArg = defaultEmptyOK;

    if (isNonnegativeInteger.arguments.length > 1)
        secondArg = isNonnegativeInteger.arguments[1];

    // The next line is a bit byzantine.  What it means is:
    // a) s must be a signed integer, AND
    // b) one of the following must be true:
    //    i)  s is empty and we are supposed to return true for
    //        empty strings
    //    ii) this is a number >= 0

    return (isSignedInteger(s, secondArg)
         && ( (isEmpty(s) && secondArg)  || (parseInt (s) >= 0) ) );
}


// isIntegerInRange (STRING s, INTEGER a, INTEGER b [, BOOLEAN emptyOK])
//
// isIntegerInRange returns true if string s is an integer
// within the range of integer arguments a and b, inclusive.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.


function isIntegerInRange (s, a, b)
{   if (isEmpty(s))
       if (isIntegerInRange.arguments.length == 1) return defaultEmptyOK;
       else return (isIntegerInRange.arguments[1] == true);

    // 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));
}


// isSignedInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters are numbers;
// first character is allowed to be + or - as well.
//
// Does not accept floating point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.
//
// EXAMPLE FUNCTION CALL:          RESULT:
// isSignedInteger ("5")           true
// isSignedInteger ("")            defaultEmptyOK
// isSignedInteger ("-5")          true
// isSignedInteger ("+5")          true
// isSignedInteger ("", false)     false
// isSignedInteger ("", true)      true

function isSignedInteger (s)

{   if (isEmpty(s))
       if (isSignedInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isSignedInteger.arguments[1] == true);

    else {
        var startPos = 0;
        var secondArg = defaultEmptyOK;

        if (isSignedInteger.arguments.length > 1)
            secondArg = isSignedInteger.arguments[1];

        // skip leading + or -
        if ( (s.charAt(0) == "-") || (s.charAt(0) == "+") )
           startPos = 1;
        return (isInteger(s.substring(startPos, s.length), secondArg))
    }
}


// isInteger (STRING s [, BOOLEAN emptyOK])
//
// Returns true if all characters in string s are numbers.
//
// Accepts non-signed integers only. Does not accept floating
// point, exponential notation, etc.
//
// We don't use parseInt because that would accept a string
// with trailing non-numeric characters.
//
// By default, returns defaultEmptyOK if s is empty.
// There is an optional second argument called emptyOK.
// emptyOK is used to override for a single function call
//      the default behavior which is specified globally by
//      defaultEmptyOK.
// If emptyOK is false (or any value other than true),
//      the function will return false if s is empty.
// If emptyOK is true, the function will return true if s is empty.
//
// EXAMPLE FUNCTION CALL:     RESULT:
// isInteger ("5")            true
// isInteger ("")             defaultEmptyOK
// isInteger ("-5")           false
// isInteger ("", true)       true
// isInteger ("", false)      false
// isInteger ("5", false)     true

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);

        if (!isDigit(c)) return false;
    }

    // All characters are numbers.
    return true;
}

// checkZIPCode (TEXTFIELD theField [, BOOLEAN emptyOK==false])
//
// Check that string theField.value is a valid ZIP code.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function checkZIPCode (theField, countryField, emptyOK) {
	if (checkZIPCode.arguments.length == 2) emptyOK = defaultEmptyOK;
	if ((emptyOK == true) && (isEmpty(theField.value))) {
    			return true;
 	}
	if (countryField.value == 218) {
    		var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
      		if (!isZIPCode(normalizedZIP, false)) {
        	 	return warnInvalid (theField, iZIPCode);
        	 } else {
         		return true;
      		}
    	} else {
    		var normalizedZIP = stripCharsInBag(theField.value, ZIPCodeDelimiters)
    		for (i = 0; i < normalizedZIP.length; i++) {

			if (isLetterOrDigit(normalizedZIP.charAt(i)) == false) {return warnInvalid (theField, iZIPCodeInt);}
    		// if (!isInteger(normalizedZIP)) {
    		// 	return warnInvalid (theField, iZIPCodeInt);
    		}
    		return true;
    	}
}

// isZIPCode (STRING s [, BOOLEAN emptyOK])
//
// isZIPCode returns true if string s is a valid
// U.S. ZIP code.  Must be 5 or 9 digits only.
//
// NOTE: Strip out any delimiters (spaces, hyphens, etc.)
// from string s before calling this function.
//
// For explanation of optional argument emptyOK,
// see comments of function isInteger.

function isZIPCode (s)
{  if (isEmpty(s))
       if (isZIPCode.arguments.length == 1) return defaultEmptyOK;
       else return (isZIPCode.arguments[1] == true);
   return (isInteger(s) &&
            ((s.length == digitsInZIPCode1) ||
             (s.length == digitsInZIPCode2)))
}


function checkState (theField, countryField, emptyOK) {
	if (checkState.arguments.length == 2) emptyOK = defaultEmptyOK;
	if (countryField.options[countryField.selectedIndex].value == 218) {
		// usa selected, so user must provide a state
		if (!isEmpty(theField.options[theField.selectedIndex].value)) {
			return true;
		} else {
			if (emptyOK) {return true;}
			alert (iStateUSA);
		}
	} else {
		// not a usa country, state field must be unselected
		if (isEmpty(theField.options[theField.selectedIndex].value)) {
			return true;
		} else {
			alert (iStateNonUSA);
		}
	}
	return false;
}


function set_clear (theField) {
	if (theField.name.substring(7, 12) == 'clear') {
		// clear changed
		var id = theField.name.substring(13, theField.name.length);
		if (isInteger(id)) {
			if (theField.checked) {
				document.form['chkbox_set_'+id].checked = false;
			} else {
				document.form['chkbox_set_'+id].checked = true;
			}
		} else {
			alert('Checkbox ID is not a number, contact your system administrator before doing any changes...');
			return false;
		}
	} else if (theField.name.substring(7, 10) == 'set') {
		// set changed
		var id = theField.name.substring(11, theField.name.length);
		if (isInteger(id)) {
			if (theField.checked) {
				document.form['chkbox_clear_'+id].checked = false;
			} else {
				document.form['chkbox_clear_'+id].checked = true;
			}
		} else {
			alert('Checkbox ID: '+id+' is not a number, contact your system administrator before doing any changes...');
			return false;
		}
	} else {
		// wrong checkbox name

	}
	return true;
}
