/*=====================================================================
 Filename: pp_form_utils.js -- Written by ndelmedico@waca.com
 Created: 7/14/2002 -- Last Updated: 7/31/2003
 This file contains client-side functions for Protection Plus forms
======================================================================*/
var sAlpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-_ ";
var sNumeric = "1234567890";
var sPostal = ""; var sEmail = "";

/*=====================================================================
Description: Sets the checked property of all checkboxes in a form
Parameters: Form ID to walk, boolean checked or unchecked
======================================================================*/
function setAllCheckboxes(sFormID, bCheck) {
    var oForm = document.getElementById(sFormID);
    if (oForm) {
        var aBoxes = oForm.getElementsByTagName("input");
        if (aBoxes && aBoxes.length > 0) {
            for (var i = 0; i < aBoxes.length; i++) {
                if (aBoxes[i].type == "checkbox") {aBoxes[i].checked = bCheck;}
            }
        }
    }
}

/*=====================================================================
Description: Trims whitespace from beginning and end of strings
Parameters: The string that needs whitespace trimmed
Returns: String with the excess white space removed (left, right, both)
======================================================================*/
function LTrim(str) {
    for (var i=0; str.charAt(i)==" "; i++);
    return str.substring(i,str.length);
}

function RTrim(str) {
    for (var i=str.length-1; str.charAt(i)==" "; i--);
    return str.substring(0,i+1);
}

function Trim(str) {
    return LTrim(RTrim(str));
}

/*=====================================================================
Description: Checks if a given character or string is numeric or money
Parameters: The string to check (sVal) / The char to check (iNum)
Returns: True if numeric / False if not
======================================================================*/
function isNumeric(sVal) {
    for (var i = 0; i < sVal.length; i++) {
        if (!isDigit(sVal.charAt(i))) {return false;}
    }
    return true;
}

function isMoney(sVal) {
    var bDP = false;
    for (var i = 0; i < sVal.length; i++) {
        if (!isDigit(sVal.charAt(i))) {
            if (sVal.charAt(i) == '.') {
                if (bDP == true) {return false;} else {bDP = true;}
            } else {
                return false;
            }
        }
    }
    return true;
}

function isDigit(iNum) {
    if (sNumeric.indexOf(iNum) != -1) {return true;}
    return false;
}

/*=====================================================================
Description: Removes specified pattern from a string
======================================================================*/
function removeChars(sValue, sPattern) {
    var oRegExp =  new RegExp(sPattern, 'gi');
    return sValue.replace(oRegExp, '');
}

/*=====================================================================
Description: Checks if a string contains any invalid chars
Parameters: Value to check (sVal), String of valid chars (sValidChars)
Returns: True if valid / False if not
======================================================================*/
function isValidChar(sVal, sValidChars) {
    for (var i = 0; i < sVal.length; i++) {
        if (sValidChars.indexOf(sVal.charAt(i)) == -1) {return false;}
    }
    return true;
}

/*=====================================================================
Description: Makes sure a date is in a valid format.
Parameters: Date to validate (sDate), Date field being validated (oElem)
Returns: True if valid, False if not, Corrects oElem to 4 digit year
======================================================================*/
function isDate(sDate, oElem) {
    var aVal = sDate.split("/");
    if (aVal.length != 3) {return false}
    else {
        var iMo = aVal[0] - 1 + 1;
        var iDay = aVal[1] - 1 + 1;
        var iYr = aVal[2] - 1 + 1;
        if (isNaN(iMo) || isNaN(iDay) || isNaN(iYr)) {return false;}		
        iYr = (iYr < 100) ? iYr + 2000 : iYr;			
        if (iYr > 9999) {return false;}
		if (iYr.toString().length != 4) {return false;}
        var iDays = 0;
        if (iMo >= 13) {return false;}
        else {
            switch (iMo) {
                case 2:
                    iDays = (((iYr % 4 == 0 && iYr % 100 != 0) || iYr % 400 == 0) ? 29 : 28 );
                    break;
                default:
                    iDays = 30 + ((iMo < 8) ? iMo % 2 : (iMo % 7) % 2);
                    break;
            }
            if (iDays < iDay) {return false;}
            else {
                oElem.value = iMo + "/" + iDay + "/" + iYr;				
                return true;
            }
        }		
    }
}

/*=====================================================================
Description: Validates format of US and Canadian postal codes
Parameters: The string that contains the zip to be validated
Returns: True if valid / False and error message (sPostal) if not.
======================================================================*/
function isValidZip(sZip) {
    var bCanada = (sZip.length == 7 || sZip.length == 6) ? true : false;
    var bUS = (sZip.length == 5 || sZip.length == 10) ? true : false;
    var sDash = "-"; var sSpace = " ";
    var sUsPat =  /^(\d{5}((-)\d{4})?)$/;
    var sCanPat = /^([A-Za-z]\d[A-Za-z]( |-)?\d[A-Za-z]\d)$/;

    if (!bCanada && !bUS) {sPostal = "Please enter a valid US Zip or Canadian Postal Code."; return false;}
    if (bCanada) {
        if (sZip.length == 7) {
            if (sZip.indexOf(sDash) == -1 && sZip.indexOf(sSpace) == -1) {
                sPostal = "Canadian postal codes must be formatted as [XXX XXX] or [XXX-XXX].";
                return false;
            } else if (sZip.search(sCanPat) == -1) {
                sPostal = "The postal code entered is invalid.";
                return false;
            }
        }
        if (sZip.length == 6) {
            if (sZip.search(sCanPat) == -1) {sPostal = "The postal code entered is invalid."; return false;}
        }
    }
    if (bUS) {
        if (sZip.length == 10) {
            if (sZip.indexOf(sDash) == -1 || sZip.indexOf(sDash) != 5) {
                sPostal = "5 plus 4 zip codes must be formatted as [XXXXX-XXXX].";
                return false;
            } else if (sZip.search(sUsPat) == -1) {
                sPostal = "The zip code entered is invalid.";
                return false;
            }
        }
        if (sZip.length == 5) {
            if (sZip.search(sUsPat) == -1) {sPostal = "The zip code entered is invalid."; return false;}
        }
    }
    return true;
}

/*=====================================================================
Description: Validates an email address against most common rules.
Parameters: The email string to be validated
Returns: True if valid / False and error message (sEmail) if not.
======================================================================*/
function isEmail(emailStr) {
	//Allow blank this way if XXXX
    if ((emailStr == "XXX")||(emailStr == "xxx")) {
        sEmail = "allow XXX";
        return true;
    }
    var checkTLD = 1;
    var knownDomsPat = /^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/i;
    var emailPat = /^(.+)@(.+)$/;
    var specialChars = "\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
    var validChars = "\[^\\s" + specialChars + "\]";
    var quotedUser = "(\"[^\"]*\")";
    var ipDomainPat = /^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
    var atom = 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) {
        sEmail = "Email address is in an incorrect format (check @ and .'s).";
        return false;
    }
    var user = matchArray[1];
    var domain = matchArray[2];
    for (i=0; i<user.length; i++) {
        if (user.charCodeAt(i)>127) {
            sEmail = "Your email address contains invalid characters.";
            return false;
        }
    }
    for (i=0; i<domain.length; i++) {
        if (domain.charCodeAt(i)>127) {
            sEmail = "Your email address domain name contains invalid characters.";
            return false;
       }
    }
    if (user.match(userPat) == null) {
        sEmail = "Your email address does not seem to be valid.";
        return false;
    }
    var IPArray = domain.match(ipDomainPat);
    if (IPArray != null) {
        for (var i=1; i<=4; i++) {
            if (IPArray[i] > 255) {
                sEmail = "Destination IP address is invalid!";
                return false;
            }
        }
        return true;
    }
    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) {
            sEmail = "The domain in your email address does not seem to be valid.";
            return false;
       }
    }
    if (checkTLD && domArr[domArr.length-1].length != 2 && domArr[domArr.length-1].search(knownDomsPat) == -1) {
        sEmail = "Your email address must end in a known domain.";
        return false;
    }
    if (len<2) {
        sEmail = "Your email address is missing a hostname!";
        return false;
    }
    return true;
}

/*=====================================================================
Description: Displays error message in alert
Parameters: A string of errors (sErrMsg) to be displayed
======================================================================*/
function displayError(sErrMsg) {
    sErrMsg = "        The following errors were found on the form:\n______________________________________________\n" +
    sErrMsg + "\n______________________________________________\n\n        Please correct the errors and submit again!";
    alert(sErrMsg);

}

/*=====================================================================
Description: Checks if cart is empty  EA 1/14/08
======================================================================*/

 function CheckShoppingCart (sEmpty, sURL) {	 		
	if (sEmpty == 'True' ) {
		//alert('test');
		displayError('\n  -  Your shopping cart is empty.  Please add at least one item to your shopping cart.');
		//return false;							
	}
	else {
		//alert(sURL);
		window.location.href = '/protectionplus/pp/shop/pp_checkout.asp?sPrevPage='+sURL;
	}
 }
 /*=====================================================================
Description: Validates search criteria.  EA 1/28/08
======================================================================*/
function ppValidateContractSearch() {
    var oForm = document.frmReport;
	var sEmpty = "True";	
		for (i=0; i<oForm.length; ++i){			
			if (oForm.elements[i].name != "cmdContractSearch" && oForm.elements[i].name != "AllContracts" 
				&& oForm.elements[i].name !="cmdClear" && oForm.elements[i].name != "cmdReset") {							
				if (oForm.elements[i].value != ""){
					sEmpty = "False";					
					//alert(oForm.elements[i].name + " " + oForm.elements[i].value);
					if ((oForm.elements[i].name == "txtBegDate" && oForm.elements[i].value != "") 
					|| (oForm.elements[i].value != "" && oForm.elements[i].name == "txtEndDate") ){
						if (!isDate(oForm.elements[i].value, oForm.elements[i]) ) {							
							alert ("\n  -  Please enter date in a mm/dd/yyyy format.");
							return false;		
						}
					}
				}			
			}
			if (oForm.elements[i].name == "AllContracts" && oForm.AllContracts.checked == true){
				sEmpty = "False";	
			}	
		}
		
	if (sEmpty == "True"){
		alert ("\n  -  Please select a search type.");
		return false;		
	}	
	else {	
		//alert("submit");
		//return false;
		//--- reset search result page # back to default. GV 12/18/08
		oForm.hidPage.value = '1'
		oForm.submit();
	}	
}
 /*=====================================================================
Description: Clear search criteria.  EA 1/28/08
======================================================================*/
function ppClearFields() {
	var oForm = document.frmReport;
	for (i=0; i<oForm.length; ++i){
		if (oForm.elements[i].name != "cmdContractSearch" && oForm.elements[i].name !="cmdClear" && oForm.elements[i].name != "cmdReset" && oForm.elements[i].name != "NextResults" && oForm.elements[i].name != "PrevResults") {
			if (oForm.elements[i].value != ""){
				oForm.elements[i].value = ""	
			}
			if (oForm.elements[i].name == "AllContracts" ){
				oForm.AllContracts.checked = false;
			}
		}
	}
	
}
/*=====================================================================
Description: Show text dynamically.  EA 1/29/08
======================================================================*/
function ShowText(sText,itemName) {	
	var strResponseText = sText;	
	//var itemName = "displayall";
	//alert(itemName);
	if (browserType == "gecko" )
		myVar = document.getElementById(itemName);
	else if (browserType == "ie")
		myVar = document.all[itemName];
	else
		myVar = document.layers[itemName];
	
	if (document.getElementById("AllContracts").checked == true){			
	  try { myVar.innerHTML = strResponseText; }
	  catch (e) {a=1; }
	}
	else{
		try { myVar.innerHTML = "";}
		catch (e) {a=1; }
	}
}
/*=====================================================================
Description: Validates and submits UW batch filter form EA 2/1/08
======================================================================*/
function ppValidateBatchSearch() {
    var oForm = document.frmReport;
    if (oForm.selDealer.options.selectedIndex == 0 && !isDate(oForm.txtBegDate.value, oForm.txtBegDate) && !isDate(oForm.txtEndDate.value, oForm.txtEndDate)) {
        alert("You must select a distributor, enter a date, or enter a date range to filter the report.")
    } 
	else if ((!isDate(oForm.txtBegDate.value, oForm.txtBegDate) && oForm.txtBegDate.value != "") 
	|| (oForm.txtEndDate.value != "" && !isDate(oForm.txtEndDate.value, oForm.txtEndDate)) ){									
		alert ("\n  -  Please enter at least one date in a mm/dd/yyyy format.");
		return false;		
	}
	
	else {
        oForm.hidRepType.value = 4;
        oForm.submit();
    }
}