/*
'+---------------------------------------------------------------+
'| COPYRIGHT 2002 MACHROTECH, LLC                                |
'| http://www.machrotech.com                                     |
'|                                                               |
'| This software contains confidential information which is the  |
'| property of MachroTech, LLC. This entire software package is  |
'| protected by the copyright laws of the United States and      |
'| elsewhere. All rights are reserved. No part of this software  |
'| may be copied, transcribed or used without the express        |
'| written permission of MachroTech, LLC. This includes, but is  |
'| not limited to the source code, designs, concepts,            |
'| interfaces, and documentation that are associated with this   |
'| software and its development. Any violation of the copyright  |
'| laws and regulations of the United States and elsewhere will  |
'| be reported to the appropriate authorities and prosecuted.    |
'+---------------------------------------------------------------+ 
*/

/***************************** 
* Validate Email
******************************/

function validateEmail (emailStr) {

var emailPat=/^(.+)@(.+)$/

var specialChars="\\(\\)<>@,;:\\\\\\\"\\.\\[\\]"

var validChars="\[^\\s" + specialChars + "\]"

var firstChars=validChars

var quotedUser="(\"[^\"]*\")"

var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/

var atom="(" + firstChars + validChars + "*" + ")"

var word="(" + atom + "|" + quotedUser + ")"

var userPat=new RegExp("^" + word + "(\\." + word + ")*$")

var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$")

var matchArray=emailStr.match(emailPat)
if (matchArray==null) {  
	alert("Email address seems incorrect (check @ and .'s)")
	return false
}
var user=matchArray[1]
var domain=matchArray[2]

if (user.match(userPat)==null) {
    // user is not valid
    alert("The name part of the email address seems to be invalid.")
    return false
}

var IPArray=domain.match(ipDomainPat)
if (IPArray!=null) {    
	  for (var i=1;i<=4;i++) {
	    if (IPArray[i]>255) {
	        alert("The IP part of the email address is invalid!")
		return false
	    }
    }
    return true
}

var domainArray=domain.match(domainPat)
if (domainArray==null) {
	alert("The domain name of the email address doesn't seem to be valid.")
    return false
}

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 four letter word.
   alert("The email address must end in a three-letter or four-letter domain, or two letter country.")
   return false
}

if (domArr[domArr.length-1].length==3 && len<2) {
   var errStr="This address is missing a hostname!"
   alert(errStr)
   return false
}
// If we've gotten this far, everything's valid!
return true;
}

	
/**********************************
* Check a text field for a maximum length
* and trims it if necessary
***********************************/
function check_len(field, max)
{
	if(field.value.length > max)
	{
		field.value = field.value.substring(0, max - 1)
		alert("The length of this field cannot exceed " + max + " characters.\nIt has been truncated to this size.")
	}
}

	
	
/**********************************
* Trim Leading and Trailing Spaces
***********************************/
function trim(trimString)
{
	//trims the trimString and returns true if the resulting value is nullstring
	//or true otherwise

	if(trimString.length == 0)
		return false;

	//Triom leading spaces
	while(''+trimString.charAt(0)==' ')
		trimString=trimString.substring(1,trimString.length);

	if(trimString.length == 0)
	{
		return false;
	}

	//Trim trailing spaces
	while(trimString.charAt(trimString.length-1)==' ')
		trimString=trimString.substring(0,trimString.length-1);

	if(trimString.length == 0)
	{
		return false;
	}

	return true;
}

/**********************************
* Trim Leading and Trailing Spaces
***********************************/
function trimLT(trimString)
{
	//Triom leading spaces
	while(''+trimString.charAt(0)==' ')
		trimString=trimString.substring(1,trimString.length);	

	//Trim trailing spaces
	while(trimString.charAt(trimString.length-1)==' ')
		trimString=trimString.substring(0,trimString.length-1);	

	return trimString;
}


/**********************************
* Validate ZIP code
***********************************/

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;
}



/**********************************
* Validate phone number
***********************************/

// 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;
}

function handlespace(theField)
{
//**********************************************************************\
//the following is to remove " " and "-" in the phone number string
var Delimiters = " "
var Delimiters2 = "-"	
	
    var normalizedCCN = stripCharsInBag(theField, Delimiters)
    normalizedCCN = stripCharsInBag(normalizedCCN, Delimiters2)
    theField.value = normalizedCCN
    return true    
}

function CheckPhoneNumber(TheNumber) {
	var valid = true
	var GoodChars = "0123456789()-+ "
	var i = 0
	//var bool=handlespace(TheNumber)
	if (TheNumber=="") {
		// Return false if number is empty
		//alert("Please enter a valid phone number.")
		valid = false
	}
	for (i =0; i <= TheNumber.length -1; i++) {
		if (GoodChars.indexOf(TheNumber.charAt(i)) == -1) {

		 //alert("Please enter a valid phone number.")
			valid = false
		} // End if statement
	} // End for loop
	return valid
}



/*  ================================================================
    FUNCTION:  isCreditCard(st)
 
    INPUT:     st - a string representing a credit card number

    RETURNS:  true, if the credit card number passes the Luhn Mod-10
		    test.
	      false, otherwise
    ================================================================ */

function isCreditCard(st) {
  // Encoding only works on cards with less than 19 digits
  if (st.length > 19 || st.length < 15)
    return (false);

  sum = 0; mul = 1; l = st.length;
  for (i = 0; i < l; i++) {
    digit = st.substring(l-i-1,l-i);
    tproduct = parseInt(digit ,10)*mul;
    if (tproduct >= 10)
      sum += (tproduct % 10) + 1;
    else
      sum += tproduct;
    if (mul == 1)
      mul++;
    else
      mul--;
  }
// Uncomment the following line to help create credit card numbers
// 1. Create a dummy number with a 0 as the last digit
// 2. Examine the sum written out
// 3. Replace the last digit with the difference between the sum and
//    the next multiple of 10.

//  document.writeln("<BR>Sum      = ",sum,"<BR>");
//  alert("Sum      = " + sum);

  if ((sum % 10) == 0)
    return (true);
  else
    return (false);

} // END FUNCTION isCreditCard()

var defaultEmptyOK = false;

var phoneNumberDelimiters = "()- ";

var validUSPhoneChars = digits + phoneNumberDelimiters;

var digits = "0123456789";
var validWorldPhoneChars = digits + phoneNumberDelimiters + "+";

var digitsInUSPhoneNumber = 10;

var iUSPhone = "This field must be a 10 digit U.S. phone number (like 415 555 1212). Please reenter it now."
var pUSPhone = "10 digit U.S. phone number (like 415 555 1212)."
var pWorldPhone = "international phone number."

var reInteger = /^\d+$/

function isUSPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isUSPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isUSPhoneNumber.arguments[1] == true);
    return (isInteger(s) && s.length == digitsInUSPhoneNumber)
}

function isInternationalPhoneNumber (s)
{   if (isEmpty(s)) 
       if (isInternationalPhoneNumber.arguments.length == 1) return defaultEmptyOK;
       else return (isInternationalPhoneNumber.arguments[1] == true);
    return (isPositiveInteger(s))
}

function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}


function checkUSPhone (theField, emptyOK)
{   if (checkUSPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  var normalizedPhone = stripCharsInBag(theField.value, phoneNumberDelimiters)
       if (!isUSPhoneNumber(normalizedPhone, false)) 
          return warnInvalid (theField, iUSPhone);
       else 
       {  // if you don't want to reformat as (123) 456-789, comment next line out
          theField.value = reformatUSPhone(normalizedPhone)
          return true;
       }
    }
}

function checkInternationalPhone (theField, emptyOK)
{   if (checkInternationalPhone.arguments.length == 1) emptyOK = defaultEmptyOK;
    if ((emptyOK == true) && (isEmpty(theField.value))) return true;
    else
    {  if (!isInternationalPhoneNumber(theField.value, false)) 
          return warnInvalid (theField, iWorldPhone);
       else 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++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }

    return returnString;
}


function isEmpty(s)
{   return ((s == null) || (s.length == 0))
}

function isInteger (s)

{   var i;

    if (isEmpty(s)) 
       if (isInteger.arguments.length == 1) return defaultEmptyOK;
       else return (isInteger.arguments[1] == true);

    return reInteger.test(s)
}

function warnInvalid (theField, s)
{   theField.focus()
    theField.select()
    alert(s)
    return false
}


function reformatUSPhone (USPhone)
{   return (reformat (USPhone, "(", 3, ") ", 3, "-", 4))
}

function reformat (s)

{   var arg;
    var sPos = 0;
    var resultString = "";

    for (var i = 1; i < reformat.arguments.length; i++) {
       arg = reformat.arguments[i];
       if (i % 2 == 1) resultString += arg;
       else {
           resultString += s.substring(sPos, sPos + arg);
           sPos += arg;
       }
    }
    return resultString;
}

function validate_date(date_field, desc) {
        if (!date_field.value)  
                return true;
        var in_date = stripCharString(date_field.value," ");
        in_date = in_date.toUpperCase();
        var date_is_bad = 0;  
        if (!allowInString(in_date,"/0123456789T+-"))
                date_is_bad = 1; // invalid characters in date
        if (!date_is_bad) { 
                var has_rdi = 0;
                if (in_date.indexOf("T") >= 0){ 
                        has_rdi = 1;
                }
                if (!date_is_bad && has_rdi && (in_date.indexOf("T") != 0)) { 
                        date_is_bad = 2; // relative date index character is not in first position
                }
                if (!date_is_bad && has_rdi && (in_date.length == 1)) { 
                        var d = new Date();
						var return_month = parseInt(d.getMonth() + 1).toString();
						return_month = (return_month.length==1 ? "0" : "") + return_month; 
						var return_date =  parseInt(d.getDate()).toString();
						return_date = (return_date.length==1 ? "0" : "") + return_date; 
				        in_date = return_month + "/" + return_date + "/" + get_full_year(d);		
                        has_rdi = 0; // date doesn't have rdi char anymore (will also cause failure of add'l rdi checks, which is a good thing)
                }
                if (!date_is_bad && has_rdi && (in_date.length > 1) && !(in_date.charAt(1) == "+" || in_date.charAt(1) == "-")) {
                        date_is_bad = 3; // length of rdi string is greater than 1 but second char is not "+" or "-"
                }
                if (!date_is_bad && has_rdi && isNaN(parseInt(in_date.substring(2,in_date.length),10))) {
                        date_is_bad = 4; // rdi value is not a number
                }
                if (!date_is_bad && has_rdi && (parseInt(in_date.substring(2,in_date.length),10) < 0)) {
                        date_is_bad = 5; // rdi value is not a positive integer
                }
                if (!date_is_bad && has_rdi) {
                        var d = new Date();
                        ms = d.getTime();
                        offset = parseInt(in_date.substring(2,in_date.length),10);
                        if(in_date.charAt(1) == "+") {
                                ms += (86400000 * offset);
                        } else {
                                ms -= (86400000 * offset);
                        }
                        d.setTime(ms);
						var return_month = parseInt(d.getMonth() + 1).toString();
						return_month = (return_month.length==1 ? "0" : "") + return_month; 
						var return_date =  parseInt(d.getDate()).toString();
						return_date = (return_date.length==1 ? "0" : "") + return_date; 
				        in_date = return_month + "/" + return_date + "/" + get_full_year(d);	
                        has_rdi = 0;
                }
        } 
        if (!date_is_bad) {
                var date_pieces = new Array();
                date_pieces = in_date.split("/");
                if (date_pieces.length == 2) {
                        var d = new Date();
                        in_date = in_date + "/" + get_full_year(d);
                        date_pieces = in_date.split("/");
                }
                if (date_pieces.length != 3 || parseInt(date_pieces[0],10) < 1 || parseInt(date_pieces[0],10) > 12 
                                || parseInt(date_pieces[1],10) < 1 || parseInt(date_pieces[1],10) > 31 
                                || (date_pieces[2].length != 2 && date_pieces[2].length != 4)) {
                        date_is_bad = 6;  // date is not in format of m[m]/d[d]/yy[yy]
                }
        }
        if (date_is_bad) {
                alert(desc + " must be in the format of mm/dd/yy, mm/dd/yyyy");
                date_field.focus();
                return (false);
        }
        
        var ms = Date.parse(in_date);
        var d = new Date();
        d.setTime(ms);
		var return_date = d.toLocaleString();
		var return_month = parseInt(d.getMonth() + 1).toString();
		return_month = (return_month.length==1 ? "0" : "") + return_month; 
		var return_date =  parseInt(d.getDate()).toString();
		return_date = (return_date.length==1 ? "0" : "") + return_date; 
        return_date = return_month + "/" + return_date + "/" + get_full_year(d);
        date_field.value = return_date;
        return true;
}       // normalize the year to yyyy
function get_full_year(d) {
		var y = ""
		if (d.getFullYear() != null)
		{
			y = d.getFullYear();
			if (y < 1970) y+= 100;		
		} else
		{	
	        y = d.getYear();
	        if (y > 69  && y < 100) y += 1900;
	        if (y < 1000) y += 2000;
		}
        return y;
}
// The following functions were written by Gordon McComb
// More information can be found here: http://www.javaworld.com/javaworld/jw-02-1997/jw-02-javascript.html
function stripCharString (InString, CharString)  {
        var OutString="";
   for (var Count=0; Count < InString.length; Count++)  {
        var TempChar=InString.substring (Count, Count+1);
      var Strip = false;
      for (var Countx = 0; Countx < CharString.length; Countx++) {
        var StripThis = CharString.substring(Countx, Countx+1)
         if (TempChar == StripThis) {
                Strip = true;
            break;
         }
      }
      if (!Strip)
        OutString=OutString+TempChar;
   }
        return (OutString);
}
function allowInString (InString, RefString)  {
        if(InString.length==0) return (false);
        for (var Count=0; Count < InString.length; Count++)  {
        var TempChar= InString.substring (Count, Count+1);
      if (RefString.indexOf (TempChar, 0)==-1)  
        return (false);
   }
   return (true);
}

function validate_CURRENCY(obj, sFieldName)
{
	obj.value = obj.value.replace("$", "")
	//obj.value = obj.value.replace(",", "")
	obj.value = strReplace(obj.value,",","")
	
	if (validate_DOUBLE(obj, sFieldName))
		if (obj.value < 0)
		{
			alert("Please enter a number greater or equal to zero for the " + sFieldName)
			obj.focus();	
			return false
		}
		else
		{
			obj.value = parseInt((parseFloat(obj.value) + 0.005) * 100) / 100
			return true
		}
	else
		return false		
}	

function validate_INTEGER(obj, sFieldName)
{
	var val
	
	if (parseInt(obj.value)<0)
		val = parseInt(parseInt(obj.value) - 0.5)
	else if(parseInt(obj.value)==0)
		val = 0
	else
		val = parseInt(parseInt(obj.value) + 0.5)
	
	if (isNaN(val) || obj.value == "")
	{
		alert("Please enter a numeric " + sFieldName + " value")
		obj.focus();	
		return false
	}
	else
	{
		obj.value = val
		return true
	}
}

function validate_DOUBLE(obj, sFieldName)
{
	var val = parseFloat(strReplace(obj.value,",",""))
	
	if (isNaN(val) || obj.value == "")
	{
		alert("Please enter a numeric value for the " + sFieldName)
		obj.focus();	
		return false
	}
	obj.value = val
	return true
}

function strReplace(strVal,strFrom,strTo)
{
	var i;
	var strRes='';
	for(i=0;i<strVal.length;i++)
	{
		ch=strVal.substring(i,i+1);
		strRes+=ch==strFrom?strTo:ch
	}
	return strRes;
}

function validate_TEXTAREA(obj, maxlen)
{
	if (validate_TEXT(obj))
		if (obj.value.length > parseInt(maxlen))
		{
			alert("The maximum length for this text field is " + maxlen + " characters.\nPlease shorten the amount of text you entered.")
			obj.focus();
			return false
		}
		else
			return true
	else
		return false
}

function validate_DROPDOWN(obj, sFieldName)
{	
	if (obj.selectedIndex == 0)
	{
		alert("Please select an option for the " + sFieldName)
		obj.focus();
		return false
	}
	
	return true
}

function validate_TEXT(obj, sFieldName)
{
	//Commented for Netscape Crash Error - Have to be replaced
	var exp = /^(\S|\s)+$/
	return checkExp(exp, obj, "The " + sFieldName + " must be filled out")
	return true;
}
function checkExp(exp, obj, message)
{
	if (!exp.exec(trim(obj.value)))
	{
		alert(message);
		obj.focus();
		return false;
	}		
	return true;
}

