// *******************************************************************
// Check if focus has already been set, if not, sets it
function setFieldFocus(x) {
	if (fieldInFocus == "") {
		fieldInFocus = x;
		x.focus();
	}
}

// *******************************************************************
// places the focus on the first form field (text or password) on the page
function getFocus() {
	if (document.forms[0] != null) {
		for (i=0; i<document.forms[0].length; i++) {
			if (document.forms[0].elements[i].type == "text" || document.forms[0].elements[i].type == "password") {
				document.forms[0].elements[i].focus();
				break;
			}
		}
	}
}

// *******************************************************************
// Check that the number of characters in a string is between a max and a min
function isValidLength(string, min, max) {
	if (string.length < min || string.length > max)
		return false;
	else
		return true;
}

// *******************************************************************
// extracts the numerical part of a string
function extractNumber(someString) {	
	var digitString = "0123456789";
	var allowedChars = "$,. ";
	var newString = "";
	// remove the allowedChars first, so that we have a number for calculations purposes
	for (j=0; j<someString.length; j++) {
		if (allowedChars.indexOf(someString.charAt(j)) == -1) {
			newString += someString.charAt(j);
		} else if (someString.charAt(j) == '.') {
			// ignore everything after decimal space
			break;
		}
	}
	// now check if the remaining string is numeric
	for (i=0; i<newString.length; i++) {
		if (digitString.indexOf(newString.charAt(i)) == -1) return "";
	}
	return newString;
}

// *******************************************************************
// Check that a string contains only numbers
function isNumeric(someString) {
	var digitString = "0123456789";
	for (i=0; i<someString.length; i++) {
		if (digitString.indexOf(someString.charAt(i)) == -1) return false;
	}
	return (someString.length > 0);
}

// *******************************************************************
// Check that a US zip code is valid
function isValidZipcode(zipcode) {
	zipcode = removeSpaces(zipcode);
	if (!(zipcode.length == 5 || zipcode.length == 9 || zipcode.length == 10)) return false;
	if ((zipcode.length == 5 || zipcode.length == 9) && !isNumeric(zipcode)) return false;
	if (zipcode.length == 10 && zipcode.search && zipcode.search(/^\d{5}-\d{4}$/) == -1) return false;
	return true;
}

// *******************************************************************
// Check that a phone number is valid
function isValidPhoneNumber(phonenum) {
  	if (phonenum.length == 10) {
		var areacode = phonenum.substring(0, 3);
		var exchange = phonenum.substring(3, 6);
		var number   = phonenum.substring(6, 10);
		if (isNumeric(areacode) && isNumeric(exchange) && isNumeric(number)
			&& parseInt(areacode) >=100 && parseInt(areacode) <1000
			&& parseInt(exchange) >=100 && parseInt(exchange) <1000) {
			//alert("good phone");
			return true;
		}
	}
	//alert("bad phone");
	return false;
}

// *******************************************************************
// Remove all spaces from a string
function removeSpaces(string) {
	var newString = '';
	for (var i = 0; i < string.length; i++) {
		if (string.charAt(i) != ' ') newString += string.charAt(i);
	}
	return newString;
}

// *******************************************************************
// Check that a date is valid
function isValidDate(dateStr) {
	// Checks for the following valid date formats:
	// MM/DD/YY   MM/DD/YYYY   MM-DD-YY   MM-DD-YYYY
	// Also separates date into month, day, and year variables

	// To require a 2 or 4 digit year entry, use this line instead:
	//var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2}|\d{4})$/;

	// To require a 4 digit year entry, use this line instead:
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;

	var matchArray = dateStr.match(datePat); // is the format ok?
	if (matchArray == null) {
		//alert("Date is not in a valid format.")
		return false;
	}
	month = matchArray[1]; // parse date into variables
	day = matchArray[3];
	year = matchArray[4];
	if (month < 1 || month > 12) { // check month range
		//alert("Month must be between 1 and 12.");
		return false;
	}
	if (day < 1 || day > 31) {
		//alert("Day must be between 1 and 31.");
		return false;
	}
	if ((month==4 || month==6 || month==9 || month==11) && day==31) {
		//alert("Month "+month+" doesn't have 31 days!")
		return false
	}
	if (month == 2) { // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		if (day>29 || (day==29 && !isleap)) {
			//alert("February " + year + " doesn't have " + day + " days!");
			return false;
		}
	}
	//alert("good Date");
	return true;  // date is valid
}

// *******************************************************************
// Check that a SSN is valid
function isValidSSN(someSSN) {
	if (someSSN.length == 9) {
		var firstPart = someSSN.substring(0, 3);
		var middlePart = someSSN.substring(3, 5);
		var endPart = someSSN.substring(5, 9);
		if (isNumeric(firstPart) && isNumeric(middlePart) && isNumeric(endPart)
			&& parseInt(firstPart) != 666 && parseInt(firstPart) >= 1 && parseInt(firstPart) <= 728
			&& parseInt(middlePart) >= 1 && parseInt(middlePart) <= 99
			&& parseInt(endPart) >= 1 && parseInt(endPart) <= 9999) {
			//alert("good SSN");
			return true;
		}
	}
	//alert("bad SSN");
	return false;
}

// *******************************************************************
// Check that a Driver's License is valid
function isValidLicense(license) {
	if (isValidLength(license, 2, 24) && license.search) {
		if (license.search(/[\w\s-\.]/) != -1) return true;
	}
	return false;
}

// *******************************************************************
// Check that an email address is valid based on RFC 821 (?)
function isValidEmail(address) {
	if (address != '' && address.search) {
		if (address.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) return true;
		else return false;
	}
	
	// allow empty strings to return true - screen these with either a 'required' test or a 'length' test
	else return true;
}

// *******************************************************************
function validateEmail(emailAddress) {
	if (/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(emailAddress)){
		// alert("Good email");
		return true;
	}
	alert("Invalid E-mail Address! Please re-enter.")
	return false;
}

// *******************************************************************
// Check that an email address has the form something@something.something
// This is a stricter standard than RFC 821 (?) which allows addresses like postmaster@localhost
function isValidEmailStrict(address) {
	if (isValidEmail(address) == false) return false;
	var domain = address.substring(address.indexOf('@') + 1);
	if (domain.indexOf('.') == -1) return false;
	if (domain.indexOf('.') == 0 || domain.indexOf('.') == domain.length - 1) return false;
	//alert("good email");
	return true;
}

// *******************************************************************
// Check that a string contains only letters and numbers
function isAlphanumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}

// *******************************************************************
// Check that a string contains only letters
function isAlphabetic(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) return false;
	}
	return true;
}

// *******************************************************************
function trim(item) {
	var tmp = "";
	var item_length = item.value.length;
	var item_length_minus_1 = item.value.length - 1;
	for (index = 0; index < item_length; index++) {
		if (item.value.charAt(index) != ' ') {
			tmp += item.value.charAt(index);
		} else {
			if (tmp.length > 0) {
				if (item.value.charAt(index+1) != ' ' && index != item_length_minus_1) {
					tmp += item.value.charAt(index);
				}
			}
		}
	}
	item.value = tmp;
}

// *******************************************************************
function validateZIP(field) {
	var valid = "0123456789-";
	var hyphencount = 0;
	if (field.length!=5 && field.length!=10) {
		alert("Please enter your 5 digit or 5 digit+4 zip code.");
			return false;
	}
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
		}
	}
	return true;
}

// *******************************************************************
function CountWords (this_field, show_word_count, show_char_count) {
	if (show_word_count == null) {
		show_word_count = true;
	}
	if (show_char_count == null) {
		show_char_count = false;
	}
	var char_count = this_field.value.length;
	var fullStr = this_field.value + " ";
	var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
	var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
	var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
	var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
	var splitString = cleanedStr.split(" ");
	var word_count = splitString.length -1;
	if (fullStr.length <2) {
		word_count = 0;
	}
	if (word_count == 1) {
		wordOrWords = " word";
	}
	else {
		wordOrWords = " words";
	}
	if (char_count == 1) {
		charOrChars = " character";
	} else {
		charOrChars = " characters";
	}
	if (show_word_count & show_char_count) {
		alert ("Word Count for " + this_field.name + ":\n" + "    " + word_count + wordOrWords + "\n" + "    " + char_count + charOrChars);
	}
	else {
		if (show_word_count) {
			alert ("Word Count for " + this_field.name + ":  " + word_count + wordOrWords);
		}
		else {
			if (show_char_count) {
				alert ("Character Count for " + this_field.name + ":  " + char_count + charOrChars);
			}
		}
	}
	return word_count;
}

// *******************************************************************
// removes given string
function removeSubstr(sValue,sSubstr)
{
    var sEmpty = "";
    var tmp = new String(sValue);
    while( tmp.indexOf(sSubstr) > -1 ) { tmp = tmp.replace(sSubstr,sEmpty); }
  return tmp;
}

// *******************************************************************
// checks if passed field is empty
function fieldNotEmpty(field,fieldDescr)
{
	var tmp = new String(field.value);
    tmp = removeSubstr(tmp," ");
    if( tmp.length == 0 ) {
        alert("Please enter " + fieldDescr);
        field.focus();
        return false;
    }
    return true;    
}

//Opens a new popup window with specific window properties
function popup(url) {
   	sealWin=window.open(url,"win",'toolbar=1,location=0,directories=0,status=1,menubar=1,scrollbars=1,resizable=1,width=720,height=480');
   	self.name = "mainWin";
}

//Opens a new popup window without ctrls
// The recommended way for all myuhc popUps
// Nithya S
function popupWoutCtrls(url,height,width) {
	if (height == null)
	height=480 ;
	if (width == null)
	width = 720 ;
	sealWin=window.open(url,"_blank",'toolbar=0,location=0,left=20,top=20,directories=0,status=0,menubar=0,scrollbars=1,resizable=1,width='+width+',height='+height);
   	self.name = "mainWin";
}

//Function to write out the link used to open a popup window
//This function should be used in conjunction with a noscript tag.
function writePopupLink(url,text) {
	document.write('<a href="javascript:popup(');
	document.write("'"+url+"'");
	document.write(')" class="bodylinks">'+text+'</a>');
}

