var defaultEmptyOK = false

//***********************************************************
// This function is used to validate
// a year that was entered by a user.
// The year must be four numeric digits
// and may not contain numeric operators
// such as (+ - .)
//***********************************************************
function ValidateYYYY(pstrField) {
    var strTemp = pstrField;
    var today = new Date();
    var year = today.getYear();


    // Only perform check if the field has data in it
    if (CheckLength(strTemp.value, 0, "!=")) {
        // Check Length
        if (CheckLength(strTemp.value, 4, "!=")) {
            alert('The Calendar Year field must contain a valid four digit year.');
            return (false);
        }
        else {
            if ((strTemp.value.indexOf("-", 0) != -1) ||
					(strTemp.value.indexOf("+", 0) != -1) ||
					(strTemp.value.indexOf(".", 0) != -1)) {
                alert('The Calendar Year field must contain a valid four digit year.');
                return (false);
            }
            else {
                // Check for numbers only (NaN = Not a Number)
                if (isNaN(strTemp.value)) {
                    alert('The Calendar Year field may only contain numeric values');
                    return (false);
                }
                else {
                    if ((parseInt(strTemp.value) < 1700) || (parseInt(strTemp.value) > year)) {
                        var sMsg = "The Calendar Year field must be between 1700 and " + year;
                        alert(sMsg);
                        return (false);
                    }
                }
            }
        }
    }
    return (true);
}


//***********************************************************
// This function validates a MM/DD/YYYY type date.  It accepts
// a form field as a parameter.  This function includes 
// support for leap years.  
//***********************************************************
function ValidateMMDDYYYY(theField) {
    var checkOK;
    var checkStr;
    var allValid;
    var ch;
    var ch2;
    var prsVal;
    var monthVal;
    var dayVal;
    var yearVal;
    var leap;
    var iRet;
    var iRet2;

    leap = false;

    checkOK = "0123456789/index.html";
    checkStr = theField.value;

    if (checkStr.length == 0) { return (true); }

    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;
            break;
        }
    }
    if (!allValid) {
        alert("Please enter only digit and \"/\" characters in this field.  Format mm/dd/yyyy");
        theField.focus();
        return (false);
    }

    iRet = Instr(0, checkStr, "index.html");
    if (iRet > 0) {
        iRet2 = Instr(iRet + 1, checkStr, "index.html");
        if (iRet2 < 0) {
            alert("Please enter a date in the mm/dd/yyyy format.");
            theField.focus();
            return (false);
        }
    }
    else {
        alert("Please enter a date in the mm/dd/yyyy format.");
        theField.focus();
        return (false);
    }

    ch = checkStr.substring(0, iRet);
    if (ch.substring(0, 1) == "0") {
        ch = ch.substring(1, 2);
    }
    if ((ch != "" && isNaN(parseInt(ch))) || ch.length == 0) {
        alert("Please enter a numeric value in the range 01-12 in the month portion.");
        theField.focus();
        return (false);
    }
    else {
        prsVal = parseInt(ch);
        monthVal = parseInt(prsVal);
        if (!(prsVal >= "01" && prsVal <= "12") && ch != "") {
            alert("Please enter a value in the range 01-12 in the month portion.");
            theField.focus();
            return (false);
        }
    }

    ch = checkStr.substring(iRet + 1, iRet2);
    if (ch.substring(0, 1) == "0") {
        ch = ch.substring(1, 2);
    }
    if ((ch != "" && isNaN(parseInt(ch))) || ch.length == 0) {
        alert("Please enter a numeric value in the range 01-31 in the day portion.");
        theField.focus();
        return (false);
    }
    else {
        prsVal = parseInt(ch);
        dayVal = parseInt(prsVal);
        if (!(prsVal >= "01" && prsVal <= "31") && (ch != "") && (monthVal != "2")) {
            alert("Please enter a value in the range 01-31 in the day portion.");
            theField.focus();
            return (false);
        }
    }

    if (monthVal == "4" || monthVal == "6" || monthVal == "9" || monthVal == "11") {
        if (dayVal == "31") {
            alert("Please enter a value in the range 01-30 in the day portion.");
            theField.focus();
            return (false);
        }
    }

    ch = checkStr.substring(iRet2 + 1);
    prsVal = parseInt(ch);
    yearVal = parseInt(prsVal);
    if (ch != "" && !(prsVal >= "1800" && prsVal <= "2399")) {
        alert("Please enter a valid year.");
        theField.focus();
        return (false);
    }

    if (monthVal == "2") {
        if ((yearVal % 4) == 0) {
            if (((yearVal % 100) != 0) || ((yearVal % 400) == 0)) {
                leap = true;
            }
        }
        if (leap == true) {
            if (dayVal > "29" || dayVal < "01") {
                alert("Please enter a value in the range 01-29 in the day portion.");
                theField.focus();
                return (false);
            }
        }
        else {
            if (dayVal > "28" || dayVal < "01") {
                alert("Please enter a value in the range 01-28 in the day portion.");
                theField.focus();
                return (false);
            }
        }
    }
    return (true);
}


//***********************************************************
// This function will search for pstrTextToFind in pstrSource
// and replace each instance of it with pstrReplacementText.
// The function will return the newly formed string.
//
// If pbooCaseSensitive is true, a case sensitive search
// will be performed.
//
// If pbooWholeWordOnly is true, a 'whole word only' search
// will be performed.
//***********************************************************
function Replace(pstrSource, pstrTextToFind, pstrReplacementText, pbooCaseSensitive, pbooWholeWordOnly) {
    var work = pstrSource;
    var ind = 0;
    var next = 0;

    if (!pbooCaseSensitive) {
        pstrTextToFind = pstrTextToFind.toLowerCase();
        work = pstrSource.toLowerCase();
    }

    while ((ind = work.indexOf(pstrTextToFind, next)) >= 0) {
        if (pbooWholeWordOnly) {
            var before = ind - 1;
            var after = ind + pstrTextToFind.length;

            if (!(space(work.charAt(before)) && space(work.charAt(after)))) {
                next = ind + pstrTextToFind.length;
                continue;
            }
        }

        pstrSource = pstrSource.substring(0, ind) + pstrReplacementText +
			 pstrSource.substring(ind + pstrTextToFind.length, pstrSource.length);

        work = work.substring(0, ind) + pstrReplacementText +
		 work.substring(ind + pstrTextToFind.length, work.length);

        next = ind + pstrReplacementText.length;

        if (next >= work.length) {
            break;
        }
    }
    return (pstrSource);
}

//***********************************************************
// This function checks to see if a passed string contains
// one or more "spacer" characters, or is empty or NULL.  If 
// so, the function will return TRUE, otherwise it will return
// FALSE.
//***********************************************************
function space(check) {
    var space = " .,/<>?!'`;:@#$%^&*()|[]{}" + '"' + "\\\n\t";

    for (var i = 0; i < space.length; i++) {
        if (check == space.charAt(i)) { return true; }
    }
    if (check == "") { return true; }
    if (check == null) { return true; }

    return false;
}

//***********************************************************
// This function checks the text, specified in pstrSource and checks
// to see if the specified operater (in pstrOperator) and length 
// (in pintLength) form a TRUE statement:
//
// Some Examples:
// CheckLength("HELLO",5,"==") would return TRUE
// CheckLength("HELLO",5,"!=") would return FALSE
//***********************************************************
function CheckLength(pstrSource, pintLength, pstrOperator) {
    if (pstrOperator == "==") { return (pstrSource.length == pintLength); }
    if (pstrOperator == "!=") { return (pstrSource.length != pintLength); }
    if (pstrOperator == ">") { return (pstrSource.length > pintLength); }
    if (pstrOperator == ">=") { return (pstrSource.length >= pintLength); }
    if (pstrOperator == "<") { return (pstrSource.length < pintLength); }
    if (pstrOperator == "<=") { return (pstrSource.length <= pintLength); }

    // *** If you get here, we are not working with a valid operator ***
    alert('You have not specified a valid operator [==, !=, >, >=, <, <=].');
    return (false);
}


//***********************************************************
// This function checks to see if a passed string is either
// NULL or empty.  If it is, the function will return TRUE, 
// otherwise it will return FALSE.
//***********************************************************
function isEmpty(s) {
    return ((s == null) || (s.length == 0))
}

//***********************************************************
// This function checks to see if a single character contains
// a numeric value.  If it does, this function returns TRUE,
// otherwise it will return FALSE.
//***********************************************************
function isDigit(c) {
    return ((c >= "0") && (c <= "9") || (c == '.') || (c == '-') || (c == ','))
}

//***********************************************************
// This function checks to see if the passed string contains
// only number.  The function will return TRUE if the string
// contains only numbers, otherwise the function will return
// false.
//***********************************************************
function isInteger(s) {
    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;
}

//***********************************************************
// This function ensures that only digits can be entered into
// a specific field.
//***********************************************************
function ValidateNumbersOnly(theField) {
    if (!(theField.value == null || theField.value == '')) {
        if (!isInteger(theField.value)) {
            alert('Please enter only digits in this field.');
            theField.value = '';
            theField.focus();
        }
    }
}

//***********************************************************
// This function checks to make sure a valid
// dollar amount has be specified.  If cents or non-numeric
// characters are included, the user is prompted to fix the 
// condition.
//***********************************************************
function ValidateCurrency(theField) {
    if (!isEmpty(theField.value)) {

        if (!isInteger(theField.value)) {
            alert('Please enter a valid dollar value using only digits\n '
             + 'and without including any cents (XXXXX).');
            theField.value = '';
            theField.focus();
        }
    }
}

function Instr(plStart, psSource, psTarget) {
    for (var i = plStart; i < psSource.length; i++) {
        if (psSource.charAt(i) == psTarget) {
            return (i);
        }
    }

    return (-1);
}



//
function SetChangeFlag(pbFlag) {
    if (pbFlag != false)
        document.forms[0].elements["FORM_CHANGED"].value = true;
    return (pbFlag);
}

//Handler to keep check box values in a hidden field
function ChangeCB(poCB, psName) {
    if (poCB.checked)
        document.forms[0].elements[psName].value = poCB.value;
    else
        document.forms[0].elements[psName].value = "";
    SetChangeFlag(true);
}

function ApplyFormatting(poObject, psFormat, piLength, piDecimal) {
    var sText = '';
    var sRet = '';
    var iCtr = 0;
    var bNegFound = false;

    switch (piDecimal) {
        case "1":
            piDecimal = 10;
            break;
        case "2":
            piDecimal = 100;
            break;
        case "3":
            piDecimal = 1000;
            break;
        case "4":
            piDecimal = 10000;
            break;
    }

    switch (psFormat) {
        case 'YEAR':
            if (ValidateYYYY(poObject) != false)
                break;
            else {
                poObject.value = '';
                poObject.focus();
                return (false);
            }
        case 'DOLLAR':
        case 'DOLLAR_POSITIVE':
        case 'POSITIVE':
        case 'PERCENT':
        case 'NUMBER':

            if (poObject.value == '') return (true);

            // Remove Existing Commas, dollar sign and percent sign
            sText = Replace(poObject.value, ',', '', false, false);
            sText = Replace(sText, '$', '', false, false);
            sText = Replace(sText, '%', '', false, false);
            sText = Replace(sText, ' ', '', false, false);
            sText = Replace(sText, '+', '', false, false);

            if (sText.length != 0) {

                // Remove leading zeros
                sText = StripLeadingZeros(sText);

                // Must be numeric, also chaeck positive/negative
                switch (psFormat) {
                    case 'DOLLAR_POSITIVE':
                    case 'POSITIVE':
                    case 'PERCENT':
                        if (!isInteger(sText) || isNaN(sText) || (sText < 0)) {
                            alert('Please enter a valid positive number.');
                            poObject.value = '';
                            poObject.focus();
                            return (false);
                        }
                        break;
                    case 'DOLLAR':
                    case 'NUMBER':
                        if (!isInteger(sText) || isNaN(sText)) {
                            alert('Please enter a valid number.');
                            poObject.value = '';
                            poObject.focus();
                            return (false);
                        }
                        break;
                }

                // Round value if decimal encountered and then
                // cast back into a string for parsing operations
                //If decimal places, deal with it:
                //if (piDecimal > 0) 
                //	sText = (parseFloat(Math.round(parseFloat(sText)*piDecimal).toString())/piDecimal).toString()
                //else
                //  sText = Math.round(sText).toString();

                switch (psFormat) {
                    case 'DOLLAR':
                    case 'DOLLAR_POSITIVE':
                    case 'NUMBER':
                    case 'POSITIVE':
                        if (sText.length > piLength) {
                            alert('The value of this field may not be more than ' + piLength + ' digits');
                            poObject.value = '';
                            poObject.focus();
                            return (false);
                        }
                        // Format for Commas
                        var iIntLength = Instr(0, sText, ".");

                        if (iIntLength < 0) iIntLength = sText.length;

                        for (var i = iIntLength - 1; i >= 0; i--) {
                            if (iCtr == 3 && sText.charAt(i) != '-') {
                                iCtr = 0;
                                sRet = ',' + sRet;
                            }

                            sRet = sText.charAt(i) + sRet;

                            if (sText.charAt(i) == '-') bNegFound = true;

                            iCtr++;
                        }

                        iIntLength = Instr(0, sText, ".");
                        if (iIntLength > 0) {
                            for (i = iIntLength; i <= (sText.length - 1); i++) {
                                sRet = sRet + sText.charAt(i);
                            }
                        }

                        if (bNegFound && sText.charAt(0) != '-') {
                            alert('A negative symbol may only occur at the front of a numeric value.');
                            poObject.value = '';
                            poObject.focus();
                            return (false);
                        }
                        else {
                            if ((psFormat == 'DOLLAR') || (psFormat == 'DOLLAR_POSITIVE')) {
                                //sRet = '$' + sRet
                            }
                        }
                        break;

                    case 'PERCENT':
                        if ((sText < 0) || (sText > 100)) {
                            alert('Please enter a valid percent.');
                            poObject.value = '';
                            poObject.focus();
                            return (false);
                        }
                        else {
                            //sRet = sText + '%';
                            sRet = sText;
                        }
                        break;
                }

            } // end block of if (sText.length != 0) on line 482     

            poObject.value = sRet;
            break;  //end block of case "NUMBER" on line 471

        default:
            break;
    } //end block of switch (psFormat) on line 456

    return (true);
}

function StripLeadingZeros(psText) {
    var sTemp = '';
    var bFirstNonZeroFound = false;

    //Remove leading zeros
    for (var x = 0; x <= psText.length - 1; x++) {
        if (psText.charAt(x) != '0' && psText.charAt(x) != '-') {
            bFirstNonZeroFound = true;
        }

        // If all fields are 0z, return one of them
        // If we encounter a - sign in front, leave it      
        if ((bFirstNonZeroFound) || (psText.charAt(x) == '-') || (x == psText.length - 1)) {
            sTemp = sTemp + psText.charAt(x);
        }
    }

    return (sTemp);
}

function ActivateField(psFieldName) {
    if (psFieldName != "") {
        eval("document.forms[0]." + psFieldName + ".focus();");
    }
}


function CalculateIt(oThis, intSize) {
    var strBrowserName
    var intTotalSize
    var objForm
    var i
    var strPrefix
    var strTargetFieldName
    var strTotalSize
    var strFormName
    var strFieldName
    var blnAllowPeriod
    var blnAllowCommas
    var tmpValue, blnSelect

    objForm = document.frmCalculator;
    strFieldName = oThis.name;
    blnAllowPeriod = false
    blnAllowCommas = false

    if (oThis.value.length != 0) {
        if (!isInteger(oThis.value)) {
            alert("The value for unit must be an integer");
            blnSelect = true;
        }
    }
    tmpValue = Math.round(oThis.value);
    if (isNaN(tmpValue)) {
        if (!blnSelect) {
            alert("The value for unit must be an integer");
            blnSelect = true;
        }
    }

    oThis.value = isNaN(tmpValue) ? "" : tmpValue;
    intTotalSize = oThis.value * intSize;

    strValue = isNaN(intTotalSize) ? "" : intTotalSize;

    intPos = strFieldName.indexOf("Unit");
    strFieldName = strFieldName.substr(0, intPos) + "TotalSpace";
    eval("document.frmCalculator." + strFieldName + ".value=" + strValue);

    var i
    var intSubTotal
    var intCirculationArea
    var intTotalUsableSF
    var intAddOnFactor
    var intGrandTotal

    intSubTotal = 0;
    for (i = 1; i < 30; i++) {
        if (objForm.elements[i].type == "text") {
            if (objForm.elements[i].name.indexOf("TotalSpace") != -1) {
                if (!isEmpty(objForm.elements[i].value) && !isNaN(objForm.elements[i].value)) {
                    intSubTotal += parseInt(objForm.elements[i].value);
                    objForm.SubTotalSpace.value = intSubTotal;
                    intCirculationArea = parseInt(intSubTotal * 0.20);
                    objForm.CirCulationArea.value = intCirculationArea;
                    intTotalUsableSF = intSubTotal + intCirculationArea;
                    objForm.TotalUsableSF.value = intTotalUsableSF;
                    intAddOnFactor = parseInt(intTotalUsableSF * 0.16);
                    objForm.AddOnFactor.value = intAddOnFactor;
                    intGrandTotal = intTotalUsableSF + intAddOnFactor;
                    objForm.GrandTotal.value = intGrandTotal;
                }
            }
        }
    }
    if (blnSelect) {
        oThis.select();
        oThis.focus();
    }

}

function checkForm() {

    if (this.frmCalculator.GrandTotal.value.length == 0) {
        alert("You must enter some number in the #Units column");
        return false;
    }
    else
        return true;
}	
