var js_blankErrorFrontText = 'These fields cannot be blank: ';
var js_invalidErrorFrontText = 'These fields have invalid values: ';
var js_ViewsAndSubmissionsErrorFrontText = 'Limit number of submissions can not be greater then limit number of views.';

//Declared the variables and assinged the hard coded strings from [evalSubmission function]- by swaroop on 04/13/2009
var js_sectionscontainerrors = 'The following section(s) contain errors: ';
var js_specificerrormsg = 'Specific error descriptions appear below each section title.';

var js_OnlyNumericEntryAllowed = 'Only numeric entries are allowed in this field';

function validateSection(frm, sectionID) {
    var errArr;
    var sectionErrArr;

    if ((sectionErrArr = sectionErrors(frm, sectionID)) != null) {
        if (sectionErrArr.length > 0) { //if returning a blank error, just return a false value out of here instead of display any error 
            var errHTML = "<ul>";
            for (var index = 0; index < sectionErrArr.length; index++)
                errHTML += "<li>" + sectionErrArr[index] + "</li>";
            errHTML += "</ul>";

            displayError(sectionID, errHTML)
        }
        return false;
    } else {
        clearSectionError(sectionID)
        return true;
    }
   }

//This method displays an error to the user
function displayError(sectionID, errHTML) {
    //separate from validateSection() so errors can be forced
    var containerRow = document.getElementById('errorRow_' + sectionID);
    var containerText = document.getElementById('errors_' + sectionID);

    if (typeof containerText == 'undefined' || containerText == null) {
        //generate an error message to this effect to notify of a bug on the calling page
        //NOTE: this does not work in FFOX <2.0 but is better than nothing (which caused the census ticket!)
        alert("Unable to locate error container on page, please notify technical support");

        return;
    }

    containerText.innerHTML = errHTML;
    containerRow.style.display = '';

    var titleContainer = document.getElementById('titleLeft_' + sectionID);
    if (titleContainer) { //comcenter doesn't have title sections
        //determine if this is a number section
        var isNumberSection = document.getElementById('titleLeft_' + sectionID).src.indexOf('titleLeft_number') > 0;
        var isCollapsibleSection = ( (document.getElementById('titleLeft_' + sectionID).src.indexOf('titleLeft_hide') > 0) || (document.getElementById('titleLeft_' + sectionID).src.indexOf('titleLeft_show') > 0));
        
        //if this is a number sections
        if (isNumberSection) {
            //set graphic as a number error
            //Change - 10/15/2009 - used getAttribute and setAttribute for HTML custom attribute(census # 20402& 19670)
            var strGif = (titleContainer.getAttribute("srcbk") == "") ? document.getElementById('titleLeft_' + sectionID).src : titleContainer.getAttribute("srcbk");
                
            titleContainer.setAttribute("srcbk", strGif);
            //titleContainer.srcbk = (titleContainer.srcbk == "" ? document.getElementById('titleLeft_' + sectionID).src : titleContainer.srcbk);
            titleContainer.src = '/controlPanel/images/titleBar/titleLeft.png';
        } else if (isCollapsibleSection) {
            //do nothing.
        } else {//otherwise
            //set graphic as a regular error
            titleContainer.src = '/controlPanel/images/titleBar/titleLeft.png';
        }
    }

    // Scroll to the top of the current window
    var targetScroll = window;
    if (self != top) targetScroll = top;
        
    if (typeof targetScroll.scrollTo != 'undefined')
        targetScroll.scrollTo(0, 0);
}

function clearSectionError(sectionID) {
    //separate from validateSection() so there is a way to allow manual clearing of an error since it's possible for users to dynamically remove a section of the form that previously had an error, or if displayError() was manually called
    var containerRow = document.getElementById('errorRow_' + sectionID);
    var containerText = document.getElementById('errors_' + sectionID);

    if (containerRow != null) {
        containerRow.style.display = 'none';
    }
    if (containerText != null) {
        containerText.innerHTML = "";
    }

    if (document.getElementById('titleLeft_' + sectionID)) { //comcenter doesn't have title sections
        var isNumberSection = document.getElementById('titleLeft_' + sectionID).src.indexOf('titleLeft_number') > 0;
        //Change 09/14/2009 - Used getAttribute for custom attribute  for Gooogle chrome and firefox (census #19670) 
		if (isNumberSection) 
		{   
		    //Added: Census issue 20251 : Need to add if condition for IE browser as 'getAttribute' was giving error on IE
		    if (/MSIE/i.test(navigator.userAgent))
		    {
		        if (document.getElementById('titleLeft_' + sectionID).srcbk!= "") 
                { //only needs to be switched back if it had an error
                    document.getElementById('titleLeft_' + sectionID).src = document.getElementById('titleLeft_' + sectionID).srcbk
                    document.getElementById('titleLeft_' + sectionID).srcbk = ""
                }
		    }
		    else
		    {
		        if (document.getElementById('titleLeft_' + sectionID).getAttribute("srcbk")!= "") 
                { //only needs to be switched back if it had an error
                	document.getElementById('titleLeft_' + sectionID).src = document.getElementById('titleLeft_' + sectionID).getAttribute("srcbk")
                	//Change 10/15/2009 - Used setAttribute (census #20402)
                	document.getElementById('titleLeft_' + sectionID).setAttribute("srcbk","");
				}
            }
        } else {
            document.getElementById('titleLeft_' + sectionID).src = '/controlPanel/images/titleBar/titleLeft.png'
        }
    }
}

function evalSubmission(frm, invalidSections, submitForm) {
    //works along with validateSection in the individual pages form submission functions
    if (invalidSections.length != 0) {
        invalidSections = invalidSections.replace(/, $/, "");
        //replaced the strings with the variables for localizing them in sublearncenter page - added by swaroop on 04/13/2009
        var errHTML = js_sectionscontainerrors + ' ' + invalidSections + ".<br>" + js_specificerrormsg
        document.getElementById("errorContainer").innerHTML = errHTML;
        document.getElementById("errorContainer").style.display = "";

        //close out the alert container if it's open so any previous success message doesn't confuse the users
        if (document.getElementById("alertContainer")) document.getElementById("alertContainer").style.display = "none";

        window.scrollTo(0, 0); //go to top so user can always see the error message.
        return false;
    } else {
        document.getElementById("errorContainer").style.display = "none";
        if ((submitForm == undefined) || submitForm) frm.submit();
        return true;
    }
}
function evalErrors(blankErr, invalidErr) {
    if ((blankErr == "") && (invalidErr == "")) {
        return null;
    } else {
        var errArr = new Array();
        if (blankErr != "") errArr[errArr.length] = js_blankErrorFrontText + blankErr.replace(/, $/, "");
        if (invalidErr != "") errArr[errArr.length] = js_invalidErrorFrontText + ' ' + invalidErr.replace(/, $/, "");
        return errArr;
    }

}

function trim(str) {
    return (str.replace(/^ */, "").replace(/ *$/, ""));
}

/*--------------------------------------------------------------------------------
As you Type Validation
--------------------------------------------------------------------------------*/
function allowSpecific(e, strChars) {
    var key;
    var keychar;

    if (window.event) {
        key = window.event.keyCode;
        e = window.event;
    }
    else if (e) key = e.which;
    else return true;

    keychar = String.fromCharCode(key);
    keychar = keychar.toLowerCase();

    // control keys
    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;
    else if (strChars.indexOf(keychar) <= -1) {
        try {
            e.preventDefault(); //13.12.1 
        } catch (Error) {
        e.returnValue = false; 
        }
    } else return true;
}
function allowRegExp(e, strRegExp) {
    var key, keychar;
    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else return true;

    if ((key == 13) || (key == 8) || (key == 0)) return true; //Return true for enter, backspace, delete key.

    var reg = new RegExp("[^" + strRegExp + "]")
    keychar = String.fromCharCode(key);
    var matchedArr = keychar.match(reg)
    return (matchedArr == null);

}

function allowAlphaNumeric(e) {
    var strChars = 'abcdefghijklmnopqrstuvwxyz0123456789- '
    if (allowAlphaNumeric.arguments.length == 2) strChars += allowAlphaNumeric.arguments[1];
    return allowSpecific(e, strChars)
}
function allowAlphaNumericNoSpaces(e) {
    var strChars = 'abcdefghijklmnopqrstuvwxyz0123456789'
    if (allowAlphaNumericNoSpaces.arguments.length == 2) strChars += allowAlphaNumericNoSpaces.arguments[1];
    return allowSpecific(e, strChars)
}
function allowNumeric(e) {
    var strChars = '0123456789';
    if (allowNumeric.arguments.length == 2) strChars += allowNumeric.arguments[1];
    return allowSpecific(e, strChars)
}
function allowDecimalNumeric(e) {
    var strChars = '0123456789.';
    if (allowDecimalNumeric.arguments.length == 2) strChars += allowDecimalNumeric.arguments[1];
    return allowSpecific(e, strChars)
}
//added This Function :: 1st November 2007:: DateValidations In Custom Field
function allowDate(e) {
    var strChars = '0123456789/-';

    if (allowDate.arguments.length == 2) strChars += allowDate.arguments[1];
    return allowSpecific(e, strChars)
}
//12.6.1 :: Added This Function :: 04/13/2009 :: Alpha type Validation
function allowalpha(e) {
    var strChars = 'abcdefghijklmnopqrstuvwxyz.?!:;-_()[],/""' + "' "; //Added empty space to the charset at the end. dont ignore while merging C# - 18341

    if (allowalpha.arguments.length == 2) strChars += allowalpha.arguments[1];
    return allowSpecific(e, strChars)
}

//12.6.1 :: Added This Function :: 04/13/2009 :: Negative Decimal Numeric type validation
// This function allows only -999999999.999 to 999999999.999 range values with maximum of three decimal values if allownegativesign is false.

function allowNegativeDecimalNumeric(obj, allownegativesign, e) {
    var key, keychar;
    var entervalue, allownegativesign;
    var val = obj.value;
    if (window.event) key = window.event.keyCode;
    else if (e) key = e.which;
    else return true;

    if ((key == null) || (key == 0) || (key == 8) || (key == 9) || (key == 13) || (key == 27))
        return true;
    if ((key < 45) || (key > 57) || (key == 47))
        return false;
    if (allownegativesign == false) {
        // if (key == 45) return false;
        keychar = String.fromCharCode(key);
        keychar = keychar.toLowerCase();
        var cursorPosition = getCursor(obj);
        entervalue = val.substring(0, cursorPosition) + keychar + val.substring(cursorPosition, val.length)
        if ((entervalue > 999999999.999))
            return false;
        if ((entervalue.indexOf(".") != entervalue.lastIndexOf(".")) || (entervalue.indexOf("-") != entervalue.lastIndexOf("-"))) {
            return false;
        }
        // Check for the max precision of 3 for the value
        if (val != '') {
            var textSplit = entervalue.split(".");
            if (textSplit.length > 1) {
                if (textSplit[1].length > 3) return false;
            }
        }
    }
    else if (allownegativesign == true) {
        keychar = String.fromCharCode(key);
        keychar = keychar.toLowerCase();
        var cursorPosition = getCursor(obj);
        entervalue = val.substring(0, cursorPosition) + keychar + val.substring(cursorPosition, val.length)
        if (entervalue.indexOf("-") > 0) return false;
        if (((entervalue.indexOf(".") != entervalue.lastIndexOf("."))) || (entervalue.indexOf("-") != entervalue.lastIndexOf("-"))) {
            return false;
        }
    }
}

//12.6.1 :: Added This Function :: 05/11/2009 :: Function to get the cursor position

function getCursor(obj) {
    var cursorPos = 0;
    if (document.selection) {
        obj.focus();
        var tmpRange = document.selection.createRange();
        tmpRange.moveStart('character', -obj.value.length);
        cursorPos = tmpRange.text.length;
    }
    else {
        if (obj.selectionStart || obj.selectionStart == '0') {
            cursorPos = obj.selectionStart;
        }
    }

    return cursorPos;
}


/*--------------------------------------------------------------------------------
OnBlur Validation
--------------------------------------------------------------------------------*/
//function to check if the "val" is numeric or not.
function isNumeric(val) {
    var strChars = '0123456789';
    if (isValid(val, strChars)) {
     return true;
 } else { return false; }
}

//function to check if the "val" is alpha or not.
function isAlpha(val) {
    var strChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    return isValid(val, strChars);
}

//function to check if the "val" is alphanumeric or not.
function isAlphaNumeric(val, allowSpace, allowHyphen) {
    var strChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
    var strSpace = ' '
    var strHyphen = '-'
    if (isAlphaNumeric.arguments.length == 4) strChars += isAlphaNumeric.arguments[3];
    if (allowSpace == true) {
        strChars = strChars + strSpace
    }
    if (allowHyphen == true) {
        strChars = strChars + strHyphen
    }
    if (isValid(val, strChars)) {
	  return true;
    } else
    { 
      return false; }
}



//function to check if the "val" is decimal or not.//isDecimalNumeric
function isDecimalNumeric(val, allowOnlyOneDecimalPoint) {
    var strChars = '0123456789.';
    var retVal = isValid(val, strChars);
    if (retVal == false) {
        return false;
    }

    if (allowOnlyOneDecimalPoint == true) {
        if (val.indexOf('.') != val.lastIndexOf('.')) {
            return false;
        }
        //check for at least one digit after decimal point.
        if ((val != '') && (val.indexOf('.') >= val.length - 1)) {
            return false;
        }
        // Check for the max precision of 3 for the value
        if (val != '') {
            var textSplit = val.split(".");
            if (textSplit.length > 1) {
                if (textSplit[1].length > 3) {
                    return false;
                }
            }            
        }
    }    
    return true;
}

//Added below function for Census # 16822 fix by ValueLabs on 11/25/2010
function isDecimalNumericWithPrecision(val, allowOnlyOneDecimalPoint, allowedNumericDigits, allowPrecision) {
    if (allowPrecision == 0) {
        allowPrecision = 3;
    }
    if (!isDecimalNumeric(val, allowOnlyOneDecimalPoint, allowPrecision)) {
        return false;
    }
    if (val.indexOf('.') == -1 && val.length > allowedNumericDigits) {
        return false;
    }
    // Check for the Numeric and max precision of for the value
    if (val != '' && val.indexOf('.') > -1) {
        var textSplit = val.split(".");
        if (textSplit.length > 1) {            
            if (textSplit[1].length > allowPrecision) return false;
        }
        if (textSplit[0].length > allowedNumericDigits) {
            return false;
        }
    }
    return true;
}
/*
//Ravisankar 30th october 2007 ::Chanded the code :: for numeric decimal validations
function isDecimalNumeric(val, allowOnlyOneDecimalPoint) {//ravisankar
	
var strDescrip = ""
var datePat = /^([0-9]*)([\.])(\d{2})$/ ; ///^(\d{1,2})([\/-])(\d{1,2})([\/-])(\d{2,4})$/
var matchArray = val.match(datePat);
if (matchArray == null){	
return false;
} 
else{
return true	;	
}
}
*/

function isValid(val, validChars) {
    if (val == '') return true;

    for (i = 0; i < val.length; i++) {
        if (validChars.indexOf(val.charAt(i), 0) == -1) {
            return false;
        }
    }
    return true;
}

function isDate(sDate) {
    var sDate = ConvertForDB(sDate);
    
    if (sDate && sDate.length > 0) {
        var scratch = new Date(sDate);

        if (scratch.toString() == "NaN" || scratch.toString() == "Invalid Date") {
            return false;
        } 
        else 
           return true;
    }
    
    return false;
}


/*--------------------------------------------------------------------------------
Check Blank
--------------------------------------------------------------------------------*/
function checkBlank(field, value) {
    var isBlank;
    var forValue = (checkBlank.arguments.length == 2);
    var checkValue;
    if (forValue) { //submitting an actual value instead of a form field
        isBlank = trim(value) == "";
    } else {
        if (field) {

            if (!field.type) {
                //Aded by Vishal Nerkar - 09/16/2009 - To fix the ticket #19877, to avoid the null object javascript error 
                if (field[0]){
                //Addition completd by Vishal Nerkar
                    switch (field[0].type) {
                        case "radio":
                        case "checkbox":
                            isBlank = true;
                            for (var i = 0; i < field.length && isBlank; i++) {
                                if (field[i].checked) {
                                    isBlank = false;
                                    break;
                                }
                            }
                            break;
                        case "select-one": //will occur if two select boxes with same name on page
                            isBlank = true;
                            for (var i = 0; i < field.length && isBlank; i++) {
                                isBlank = (field[i].value == "");
                            }
                            break;
                    }
                    for (var i = 0; i < field.length; i++) field[i].className = (isBlank ? "inputError" : "")
                }
                //  Aded by Vishal Nerkar - 09/16/2009 - To fix the ticket #19877, to avoid the null object javascript error 
                else{
                    isBlank = true;
                }
                //Addition completd by Vishal Nerkar
            } else {
                switch (field.type) {
                    case "checkbox": //will get here instead of above if there is only one checkbox with this name on the page
                        isBlank = !field.checked;
                        break;
                    case "select-one":
                        if (field.options.length == 0) {
                            isBlank = true;
                        }
                        else if (field.selectedIndex == 0 && field.options[0].value == '-1') { // handle editEnrollments.asp validation
                            isBlank = true;
                        }
                        else {
                            if (field.options[0].value != '')
                                isBlank = field.selectedIndex < 0;
                            else
                                isBlank = field.selectedIndex <= 0;
                        }
                        break;
                    case "text":
                    case "textarea":
                    case "hidden":
                    case "password":
                    case "file":
                        isBlank = trim(field.value).length == 0;
                        break;
                    case "select-multiple": //return false if select list is empty...unless special attribute set since this mainly applies to the multiple selects in Reports					    						
                        isBlank = (field.options.length == 0);
                        if ((!isBlank) && (field.attributes["validateIndex"])) isBlank = field.selectedIndex < 0;
                        break;
                    default:
                        alert("Encountered a " + field.type + " data type that is not handled.  Name:" + field.name);
                }
                field.className = (isBlank ? "inputError" : "")
            }
        }
    }

    return (isBlank);
}
function checkBlankField(displayName, field) {
    return (checkBlank(field) ? displayName + ", " : "");
}
function checkBlankValue(displayName, value) {
    return (checkBlank(null, value) ? displayName + ", " : "");
}
/*--------------------------------------------------------------------------------
Check Valid
--------------------------------------------------------------------------------*/
function checkValid(field, value, valueType) {
    var isValid;
    var forValue = (checkValid.arguments.length == 3);
    var checkValue;
    if ((field) || (forValue)) {
        if (!forValue && field.type != "text") {
            isValid = true; //can't handle anything other than text form fields right now
        } else {
            checkValue = trim((forValue ? value : field.value));
            if (checkValue != "") {
                var checkType = (forValue ? valueType : field.name);
                if (checkType.search(/areacode/i) >= 0) {
                    isValid = ValidateAreaCode(checkValue);
                } else if (checkType.search(/phonenumber|faxnumber|cellularnumber|faximportnumber/i) >= 0) {
                    isValid = ValidatePhoneNumber(checkValue);
                    if ((isValid) && (!forValue)) field.value = formatPhoneNumber(field.value);
                } else if (checkType.search(/email/i) >= 0) {
                    isValid = ValidateEmailAddress(checkValue);
                } else if (checkType.search(/zip/i) >= 0) {
                    isValid = ValidateZipCode(checkValue);
                } else if (checkType.search(/date/i) >= 0) {
                    isValid = ValidateDate(checkValue);
                } else {
                    isValid = true;
                }
                if (!forValue) field.className = (isValid ? "" : "inputError")
            } else {
                isValid = true;
            }

        }

    }

    return (isValid);
}
function checkValidField(displayName, field) {
    return (checkValid(field) ? "" : displayName + ", ");
}
function checkValidValue(displayName, value, valueType) {
    return (checkValid(null, value, valueType) ? "" : displayName + ", ");
}
function checkValidRegExp(displayName, field, strRegExp) {
    var isValid = true;
    if (trim(field.value) != "") {
        var reg = new RegExp(strRegExp);
        isValid = (field.value.match(reg) == null)
        field.className = (isValid ? "" : "inputError")
    }
    return (isValid ? "" : displayName + ", ");
}
function checkValidFieldSize(displayName, field, min, max) {
    var isValid = true;
    if (trim(field.value) != "") {
        isValid = ((field.value.length >= min) && (field.value.length <= max))
        field.className = (isValid ? "" : "inputError")
    }
    return (isValid ? "" : displayName + ", ");
}
function checkValidPassword(displayName, field1, field2) {
    var isValid = true;
    if (trim(field1.value + field2.value) != "") {
        isValid = (field1.value == field2.value)
        field1.className = (isValid ? "" : "inputError")
        field2.className = (isValid ? "" : "inputError")
    }
    return (isValid ? "" : displayName + ", ");
}
function checkValidFieldContains(displayName, field, value) {
    var isValid = true;
    if (trim(field.value) != "") {
        isValid = (field.value.toLowerCase().indexOf(value.toLowerCase()) != -1)
        field.className = (isValid ? "" : "inputError")
    }
    return (isValid ? "" : displayName + ", ");
}
/*--------------------------------------------------------------------------------
Utilities
--------------------------------------------------------------------------------*/
function getCheckedRadioID(field) {
    var checkedID = -1;
    if (field[0].type == "radio") {
        for (var i = 0; i < field.length && checkedID == -1; i++) {
            checkedID = (field[i].checked ? i : -1);
        }
    }
    return checkedID;
}

/*--------------------------------------------------------------------------------
Type Specific Validations
--------------------------------------------------------------------------------*/
function ValidateZipCode(Value) {
    if (Value.indexOf(".") != -1)
        return false;
    if (Value.indexOf(",") != -1)
        return false;

    var l = Value.length;
    if (l == 5) {
        return !isNaN(Value);
    } else {
        if (l == 10) {
            return (!isNaN(Value.substr(0, 5))) && (!isNaN(Value.substr(6, 4))) && (Value.substr(5, 1) == "-");
        } else {
            return false;
        }
    }
    return false;
}

function ValidateAreaCode(Value) {
    if (Value.indexOf(".") != -1)
        return false;
    if (Value.indexOf(",") != -1)
        return false;
    if (Value.length == 3)
        return !isNaN(Value);
    return false;
}

function formatPhoneNumber(value) {
    //this function is called after validating that the phone number has a valid format
    //strip any existing non-numeric characters
    value = value.replace(/[A-z]\.-,/g, "");
    //put a dash in the appropriate place
    value = value.replace(/(\d{3})(\d{4})/, "$1-$2");
    return value;
}

function ValidatePhoneNumber(Value) {
    if (Value.indexOf(".") != -1)
        return false;
    if (Value.indexOf(",") != -1)
        return false;
    var l = Value.length;
    if (l == 7) {
        return !isNaN(Value);
    } else {
        if (l == 8)
            return (!isNaN(Value.substr(0, 2))) && (!isNaN(Value.substr(4, 4))) && (Value.substr(3, 1) == "-");
        else
            return false;
    }
    return false;
}

function ValidateDate(date) {

    //JT:11.6.1 Correct the format prior to validating
    date = ConvertForDB(date);

    //requires date to be in mm/dd/yyyy format
    var strDescrip = ""
    var datePat = /^(\d{1,2})([\/-])(\d{1,2})([\/-])(\d{2,4})$/;
    var matchArray = date.match(datePat);
    if (matchArray == null) {
        return false;
    } else {
        //now validate the values
        var month = matchArray[1];
        var day = matchArray[3];
        var year = parseInt(matchArray[5]);
        //account for 2 digit years. 
        if ((year > 50) && (year <= 99)) year += 1900;
        if ((year >= 0) && (year <= 49)) year += 2000;
        if ((month < 1) || (month > 12)) return false;
        if ((day < 1) || (day > 31)) return false;
        if ((year < 1950) || (year > 3000)) return false;
        if ((month == 4 || month == 6 || month == 9 || month == 11) && (day == 31)) return false;
        if (month == 2) {
            var isLeap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
            if (day > 29 || (day == 29 && !isLeap)) return false
        }
        return true;
    }

}

function ValidateEmailAddress(emailStr) {
    try {
        // Attempt to create the email address validator
        var emailValidator = new EmailAddress(emailStr);
        emailValidator.validate();
    }
    catch (e) {
        // Filter out the exception that i caused by an invalid email address or if the
        // parent page didn't include the email address validator class
        if (e.description != null && e.description.indexOf("undefined") < 0) {
            // Class must not exist
            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)
            var strErr = "";
            if (matchArray == null) {
                strErr = "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
                strErr = "The user name doesn't seem to be valid.";
                return false
            }
            var IPArray = domain.match(ipDomainPat)
            if (IPArray != null) {
                // this is an IP address
                for (var i = 1; i <= 4; i++) {
                    if (IPArray[i] > 255) {
                        strErr = "Destination IP address is invalid!";
                        return false
                    }
                }
                return true
            }

            var domainArray = domain.match(domainPat)
            if (domainArray == null) {
                strErr = "The domain name 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 > 3) {
                // the address must end in a two letter or three letter word.
                strErr = "The address must end in a three-letter domain, or two letter country.";
                return false
            }
            if (len < 2) {
                strErr = "This address is missing a hostname!"
                return false
            }
        }
        else
            return false;
    }

    return true;
}
/*--------------------------------------------------------------------------------
Limit text area maxCharacter
use text area on onkeyup="textAreaMaxChar(this,200)" and onbeforepaste="textAreaMaxChar(this,200)" 
--------------------------------------------------------------------------------*/
function textAreaMaxChar(textField, maxChars) {
    if (textField.value.length > maxChars) {
        textField.value = textField.value.slice(0, maxChars);
    }
}

/*
* 20071004.1325 - Reuben Soto - Start Changes 
* 
* For census ticket #8083:
* 1) convert data from unicode on demand
*/

function EnsureUnicodeConversion(stringToConvert) {
    //create a text area
    var ta = document.createElement("textarea");

    //convert the string to HTML
    ta.innerHTML = stringToConvert.replace(/</ig, "&lt;").replace(/>/ig, "&gt;");

    //return the converted value
    return ta.value;
} //end ()

/*
* 20071004.1325 - Reuben Soto - End Changes
*/

/***************************************************
* Purpose: Formats a date based on current LC/User format 
* Parameters: The currrent date formmat retrieved from DateFormat object, the month, the day, the year
* Returns: The appropriately formatted date string 
****************************************************/
function formatDate(currentformat, sMonth, sDay, iYear) {
    sMonth = sMonth + '';
    sDay = sDay + '';
    if (currentformat != "M/d/yyyy") {
        if (sMonth.length == 1) {
            sMonth = "0" + sMonth;
        }
        if (sDay.length == 1) {
            sDay = "0" + sDay;
        }
    }
    var sReturn = currentformat;
    sReturn = sReturn.replace(/mm/gi, sMonth);
    sReturn = sReturn.replace(/m/gi, sMonth);    
    sReturn = sReturn.replace(/dd/gi, sDay);    
    sReturn = sReturn.replace(/d/gi, sDay);    
    sReturn = sReturn.replace(/yyyy/gi, iYear);   
    return sReturn;
}

/***************************************************    
* Purpose: Converts a datetime in European or Japenese format to US format. 
* Parameters: the formatted date 
* Returns: the date US format
* Note: Parameter strDateTime may be a date, a time, or a datetime
****************************************************/
function ConvertForDB(strDateTime) {
    if (strDateTime != undefined && strDateTime.length == 0)
        return strDateTime;

    try {
        var dtpart;
        this.None = 0;
        this.DatePart = 1;
        this.TimePart = 2;
        this.DateTimePart = 3;

        var strNewDate = "";
        var strNewTime = "";
        var strDate = "";
        var strTime = "";

        //Seperate the string into date, time and designator 
        var arrDateTime = strDateTime.split(" ");

        if (arrDateTime.length >= 2) //it is a date and time 
        {
            dtpart = DateTimePart;

            strDate = arrDateTime[0];
            strTime = arrDateTime[1];

            if (arrDateTime.length == 3) //(Date Time Designator)
            {
                //Set the local time variable (time + designator)
                strTime = arrDateTime[1] + " " + arrDateTime[2];
            }
            if (arrDateTime.length == 2) //(Date Time)
            {
                //Check if there is a designator in the time without the expected space i.e. 7:00PM instead of 7:00PM 
                if (strTime.indexOf("PM") > 0 || strTime.indexOf("AM") > 0) {
                    if (strTime.indexOf("PM") > 0)
                        strTime = strTime.replace("PM", " PM");
                    else
                        strTime = strTime.replace("AM", " AM");
                }
            }
        }
        else if (arrDateTime.length >= 1 && strDateTime.indexOf(":") > 0) //it is a time
        {
            dtpart = TimePart;
            strTime = arrDateTime[0];

            //Check for the designator
            if (arrDateTime.length == 2) // (Time Designator)
                strTime = arrDateTime[0] + " " + arrDateTime[1];

            //Check if there is a designator in the time without the expected space i.e. 7:00PM instead of 7:00PM 
            if (arrDateTime.length == 1) // (Time)
            {
                if (strTime.indexOf("PM") > 0 || strTime.indexOf("AM") > 0) {
                    if (strTime.indexOf("PM") > 0)
                        strTime = strTime.replace("PM", " PM");
                    else
                        strTime = strTime.replace("AM", " AM");
                }
            }
        }
        else if (arrDateTime.length == 1 && (strDateTime.indexOf("/") > 0 || strDateTime.indexOf(".") > 0)) // it is a date
        {
            dtpart = DatePart;
            strDate = arrDateTime[0];
        }
        else {
            dtpart = None;
        }

        //Convert the date to US format
        if (dtpart != None && strDate != "") {
            var re = new RegExp("^\\d\\d\\d\\d\/");  // yyyy/MM/dd			
            if (strDate.match(re)) {
                var strSplit = strDate.split("/");
                strNewDate = strSplit[1] + "/" + strSplit[2] + "/" + strSplit[0];
            }
            else if (strDate.indexOf(".") > 0) {
                var strSplit = strDate.split(".");
                strNewDate = strSplit[1] + "/" + strSplit[0] + "/" + strSplit[2];
            }
            else
                strNewDate = strDate;
        }

        //Convert the time to US format
        if (!(dtpart == None && strTime == "")) {
            var strDesignator = "";
            if (strTime.indexOf("AM") > 0) {
                strDesignator = "AM";
                strTime = strTime.replace("AM", "");
            }
            if (strTime.indexOf("PM") > 0) {
                strDesignator = "PM";
                strTime = strTime.replace("PM", "");
            }

            var arrHourMin = strTime.split(":");
            if (arrHourMin.length == 2) {
                var intHour = arrHourMin[0];
                var strMin = arrHourMin[1];

                if (strDesignator == "" || intHour > 12 || intHour == 0) //24 Hour
                {
                    if (intHour == 0) {
                        strNewTime = "12:" + strMin + " AM";
                    }
                    else if (intHour > 12) {
                        intHour = intHour - 12;
                        strNewTime = intHour + ":" + strMin + " PM";
                    }
                    else if (intHour == 12) {
                        strNewTime = intHour + ":" + strMin + " PM";
                    }
                    else
                        strNewTime = intHour + ":" + strMin + " AM";
                }
                else if (strDesignator != "" && intHour <= 12 && intHour > 0) {
                    strNewTime = intHour + ":" + strMin + " " + strDesignator;
                }
                else
                    strNewTime = strTime;

            } //end if
        } //end if

        //Return the correctly formatted string
        switch (dtpart) {
            case None:
                return strDateTime;
            case DatePart:
                return strNewDate;
            case TimePart:
                return strNewTime;
            case DateTimePart:
                return strNewDate + " " + strNewTime;
            default:
                return strDateTime;
        }
    }
    catch (ex) {
        alert(ex.Description);
    }
}

function validateDateRange(fromDate, endDate) {
    try {
        var dateFrom = new Date(ConvertForDB(fromDate));
        var dateTo = new Date(ConvertForDB(endDate));

        if (dateTo < dateFrom)
            return false;
        else
            return true;
    } catch (e) {
        return false;
    }
}


function isAlphaWithPunctuations(answerPrompt) {
    var checkOK = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz.?!:;-_()[],/""' + "' "; //space added - C# 18478
    var checkStr = answerPrompt;
    var allValid = true;
    for (i = 0; i < checkStr.length; i++) {
        ch = checkStr.charAt(i);
        for (j = 0; j < checkOK.length; j++)
            if (ch == checkOK.charAt(j))
            break;
        if (j == checkOK.length) {
            allValid = false;
        }
    }
    return allValid;
}

var dateInput, dateReturnFunc, dateE, setDateHide;
function popupLoadFunc() {
	setDateWithReturn(dateInput, dateReturnFunc, dateE);
}

function setDateWithReturn(input, returnFunc, e) {
	try {
		e = e ? e : event;
		e.cancelBubble = true;
	} catch (myE) { }
	var popFrame = document.getElementById("popFrame");
	if (popFrame.src.indexOf('/LCNet') < 0) {
		popFrame.src = '/LCNet/Controls/popCal.aspx?cu=' + js_cu + '&df=' + js_df;
			dateInput = input;
			dateReturnFunc = returnFunc;
			dateE = e;
		var setDateTimeout = window.setTimeout(popupLoadFunc, 10);
		return;
	}
	if (popFrame != undefined) {
		try {
		    popFrame.contentWindow.fPopCalendar(input, input, document.getElementById("popCal"), null, (arguments.length > 3 ? arguments[3] : null), (arguments.length > 4 ? arguments[4] : null), (arguments.length > 5 ? arguments[5] : null));
			if (returnFunc != undefined) popFrame.contentWindow.returnFunction = returnFunc;
		} catch (myE) {
			var setDateTimeout = window.setTimeout(popupLoadFunc, 10);
		}
	} else {
		alert("popFrame is undefined");
	}
	document.body.onclick = hideCalendar;
}

function setDate(input, e) {
    var dtMin = (arguments.length > 2 ? arguments[2] : null);
    var dtMax = (arguments.length > 3 ? arguments[3] : null);
    setDateWithReturn(input, null, e, dtMin, dtMax);
}
function setDateValignTop(input, e) {
    var dtMin = (arguments.length > 2 ? arguments[2] : null);
    var dtMax = (arguments.length > 3 ? arguments[3] : null);
    setDateWithReturn(input, null, e, dtMin, dtMax, "1");
    // change date orientation to above the text box
}
function hideCalendar() {
	document.getElementById("popCal").style.display = "none";
}

function validateEmailAddresses(emails) {
    var arrEmails = formatEmailString(emails).split(';');

    if (emails == '' || arrEmails.length == undefined) return false;

    for (var i = 0; i < arrEmails.length; i++) {
        var email = arrEmails[i];
        if (email == '' || !ValidateEmailAddress(email)) return false;
    }
    return true;
}

function formatEmailString(str) {
    str = str.replace(' ', '');

    //trim trailing semicolon
    if (str.substring(str.length - 1, str.length) == ';')
        str = str.substring(0, str.length - 1);

    return str;
}


function checkNumeric(obj) {
    
    return checkNumeric(obj,null);
}

function checkNumeric(obj, strSection) {
    if (!isNumeric(obj.value)) {
        obj.value = '';
        if(strSection == null){
            alert(js_OnlyNumericEntryAllowed);
        }else{
            displayError(strSection, js_OnlyNumericEntryAllowed)
        }
        if (obj.form.id != '') window.setTimeout("try {document." + obj.form.id + "." + obj.name + ".focus();} catch(e){}", 100); //setTimeout is used for ff compatibility
        return false;
    }
    return true;
}

function checkDecimalNumeric(obj) {
    if (!isDecimalNumeric(obj.value)) {
        obj.value = '';
        alert(js_OnlyNumericEntryAllowed);
        if (obj.form.id != '') window.setTimeout("try {document." + obj.form.id + "." + obj.name + ".focus();} catch(e){}", 100); //setTimeout is used for ff compatibility
        return false;
    }
    return true;
}

function validateNumericRange(lowerNum, upperNum) {
    try {
        if (!isNaN(lowerNum) && !isNaN(upperNum)) {
            var lowerNumeric = parseInt(lowerNum);
            var upperNumeric = parseInt(upperNum);

            return lowerNumeric < upperNumeric;
        }
    } catch (e) {
        return false;
    }
}
