var BrowserDetect = {
    init: function () {
        this.browser = this.searchString(this.dataBrowser) || "NotSafari";
        this.version = this.searchVersion(navigator.userAgent)
            || this.searchVersion(navigator.appVersion)
            || "an unknown version";
    },
    searchString: function (data) {
        for (var i=0;i<data.length;i++) {
            var dataString = data[i].string;
            var dataProp = data[i].prop;
            this.versionSearchString = data[i].versionSearch || data[i].identity;
            if (dataString) {
                if (dataString.indexOf(data[i].subString) != -1)
                    return data[i].identity;
            }
            else if (dataProp)
                return data[i].identity;
        }
    },
    searchVersion: function (dataString) {
        var index = dataString.indexOf(this.versionSearchString);
        if (index == -1) return;
        return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
    },
    dataBrowser: [
        {
            string: navigator.vendor,
            subString: "Apple",
            identity: "Safari",
            versionSearch: "Version"
        }]
};
BrowserDetect.init();

function log(logtext) { console.log(logtext); }

//INPUT FIELDS VALIDATION
//SETTING UP POPUP
//0 means disabled; 1 means enabled;
var popupStatus = 0;
var answerStatus = 0;
var lenderShown = 0;
var currentFocus = '';
var currentQuestionId = '';

//number of checked boxes
var numberChecked = 0;

//When un/checking checkboxes validate numerical values
function validateInputValue(el, checkboxWrappingDivId) {
    //check for checked input box
    var hasCheckedBox = $("#" + checkboxWrappingDivId + "  .rows .row input:checked").length > 0;
    if (hasCheckedBox) {
        //grab the entered amount of the respective input box
        currentAmountInputFieldId = checkboxWrappingDivId.split('_')[0] + "_amount";
        validateAmount(currentAmountInputFieldId, el.id, true);
    }
}

function isValidCurrency (val, loanId) {
    var min = 1, max = 55000;
    if (loanId == 'fssl' || loanId == 'fsul') { max = 7500; }

    var trimmedVal = val.replace(/\s/g, "");

    if (trimmedVal.indexOf(',') > -1) {
        var value = trimmedVal.split(',').join('');
        return (RegExp(/^(\d{1,5}((\,\d{3}?))((\.\d{1,2})?))$/).test(String(trimmedVal).replace(/^\s+|\s+$/g, "")) && parseFloat(value) >= min && parseFloat(value) <= max);
    } else {
        return (RegExp(/^\$?[0-9\,\d{3}]+(\.\d{1}|\.\d{2})?$/).test(String(trimmedVal).replace(/^\s+|\s+$/g, "")) && parseFloat(trimmedVal) >= min && parseFloat(trimmedVal) <= max);
    }
}

/*  validationController() - handles all user actions on input fields/boxes
 *  params:     'elId' - the field user is acting upon
 *              'calculatorId' - the calculator the field 'lives in'
 *              'ownLoanId' - when modifying 'Name Your Own Loan X' the div wrapper id is provided
 *              'ficoId'    - when fico score is 'present/available'
 *                          to user to enter, then fico score field id is provided
 *              'checkingOwnLoan' - 'true' when validating own loans
*/
function validationController(elId, calculatorId, ownLoanId, ficoId, checkingOwnLoan) {
    if(popupStatus == 0) { //Do not validate if already an error
        var inputFieldType = $("#" + elId).attr("type");

        var validAmount = isValidCurrency($("#" + calculatorId + "_amount").attr("value"), calculatorId);
        currentFocus = calculatorId + "_amount";
        var checkBoxes = $("#" + calculatorId + " input:checked");
        var checkedOnPage = $("#wrapAll input:checked");
        var ownLoanValidEntry = [true, true];

        if(checkingOwnLoan) {
            if (ficoId == undefined) {
                ownLoanValidEntry = verifyFPLOwnLoans(ownLoanId, calculatorId); //retuns [true, true] | [false, elId]
            } else {
                ownLoanValidEntry = verifyOwnLoans(ownLoanId, calculatorId); //retuns [true, true] | [false, elId]
            }
        }

        if (inputFieldType == "text") { //entering dollar amount
            //if checked and invalid $ amount display error
            if (checkBoxes.length > 0 && !validAmount) { editLoanPopup(elId, calculatorId); }

            //verify whether 'name your own loan' checked
            if (ownLoanId != undefined) {
                /*
                var amount_value = $("#" + calculatorId + "_amount").attr("value");
                if ((!validAmount && amount_value != '') || (amount_value == '' && checkBoxes.length > 0)) {
                    editLoanPopup(elId, calculatorId);
                }
                */

                var fico_value = $("#" + ficoId).attr("value");
                if (!isValidFico && checkBoxes.length > 0) {
                    currentFocus = ficoId;
                    hideLenders();
                    editLoanPopup("valid_" + elId, calculatorId);
                }
            }
        } else if (checkedOnPage.length < 4 || (checkedOnPage.length == 4 && !(validAmount)) || (!ownLoanValidEntry[0] && checkedOnPage.length < 5)) {
            // checking checkBox - verify entered $ amount is valid
            if ((checkBoxes.length == 1 && !validAmount) || !ownLoanValidEntry[0]) {
                if (ownLoanId != undefined) {
                    if (!validAmount) {
                        document.getElementById(elId).checked = false;
                        editLoanPopup(elId, calculatorId);
                    /*} else if (!isValidFico && validAmount) {
                        document.getElementById(elId).checked = false;
                        hideLenders();
                        currentFocus = ficoId;
                        editLoanPopup(elId, calculatorId);*/
                    } else {
                        if (checkingOwnLoan && !ownLoanValidEntry[0]) { //if own load selected
                            document.getElementById(elId).checked = false;
                            currentFocus = ownLoanValidEntry[1];
                            editLoanPopup(elId, calculatorId);
                        }
                    }
                } else {
                    //ERROR - uncheck the box, focus on $ field, display error
                    document.getElementById(elId).checked = false;
                    editLoanPopup(elId, calculatorId);
                }
            }
        } else { //check if 4th checked Box
            if (checkedOnPage.length == 4) { displayEditLoansForm(0); }
            //Selected too many; submit the selected; or edit
            if (checkedOnPage.length == 5) {
                document.getElementById(elId).checked = false;
                displayEditLoansForm(1);
            }
        }

    }//popupStatusCheck
}

//load popup background layover
function loadPopupBackground() {
    //needed for IE6
    var xy = getScrollXY();
    var XY = getViewingSize();
    if (jQuery.support.boxModel) {
        $("#backgroundPopup").append('<iframe id="hiddenFrame" width="' + XY[0] + '" height="' + XY[1] + '"></iframe>');
        $("#hiddenFrame").css({"opacity": "0.2"});
        $("#hiddenFrame").fadeIn("slow");
    }
    $("#backgroundPopup").css({"height": XY[1]});
    $("#backgroundPopup").css({"width": XY[0]});
    $("#backgroundPopup").css({"opacity": "0.2"});
    $("#backgroundPopup").fadeIn("slow");
}

// unload popup background layover
function unloadPopupBackground() { $("#backgroundPopup").fadeOut("slow"); }


// Invalid Entry popup
function editLoanPopup(elId, calculatorId) {
    //perhaps handle this in another function
    //if (elId == 'alt_loans_amount' && lenderShown == 1) { hideLenders(); }

    var errorMsg = $("#" + currentFocus).siblings(".ieError").html();
    loadELPopup(errorMsg, elId, calculatorId);
}

function loadELPopup(errorMsg, elId, calculatorId) {
    //loads popup only if it is disabled
    if(popupStatus==0) {
        $("#editLoanBody").html(errorMsg);
        document.getElementById("editLoanBtn").onclick = function() { editLoanSelections(elId) };
        document.getElementById("cancelBtn").onclick = function() { clearLoanSelections(elId, calculatorId); }

        //loadPopupBackground();
        var xy = getScrollXY(); //returns array - [x, y]
        var elTop = $("#" + currentFocus).position().top;
        var elLeft = $("#" + currentFocus).position().left;
        var xy = getScrollXY(); //returns array - [x, y]
        var browserHeight = document.documentElement.clientHeight ? document.documentElement.clientHeight : document.body.clientHeight;
        var visibleTop = screen.availHeight - xy[1];
        var visibleBottom = (xy[1] == 0) ? screen.availHeight - xy[1] - browserHeight : screen.availHeight - xy[1] - browserHeight;
        var top = elTop + 40 - xy[1];
        var left = elLeft - 20 - xy[0];
        loadPopupBackground();
        $("#editLoan").css("top", top);
        $("#editLoan").css("left", left);

        /* CENTER POPUP */
        document.getElementById(currentFocus).focus();
        centerPopup('editLoan');
        /* CENTER POPUP */

        $("#editLoan").fadeIn("slow");
        popupStatus = 1;
    }
}

function clearLoanSelections(elId, calculatorId) {
    //var textFields = $("#" + calculatorId + " input:text");
    //for (i in textFields) { textFields[i].value = ""; }
    var checkBoxes = $("#" + calculatorId + " input:checked");

    //uncheck only 'current' checkbox
    if(elId.indexOf('checkbox') > -1 || elId.indexOf('Checkbox') > -1) {
        $("#" + elId).checked = false;
    } else {//uncheck all checkbox
        for (i in checkBoxes) { checkBoxes[i].checked = false; }
    }
    closeELPopup();
}

function editLoanSelections(elId) { closeELPopup(elId); }

function closeELPopup(elId) {
    //disables popup only if it is enabled
    if(popupStatus==1) {
        unloadPopupBackground();
        $("#editLoan").fadeOut("slow");
        popupStatus = 0;
        setTimeout("document.getElementById('" + currentFocus + "').focus()", 450);
    }
}

//handles displaying and hiding help text
function answerController(elId, popupType, questionId) {
    if (answerStatus == 0) {
        currentQuestionId = elId;
        answerQuestion(elId, popupType, questionId);
    } else {
        //User clicks on a new '?' while a '?-popup' is open. Then close previous popup prior to opening a new one
        if (currentQuestionId != elId) {
            hideAnswer();
            setTimeout('answerQuestion("' + elId + '","' + popupType + '","' + questionId + '")', 350);
            currentQuestionId = elId;
        } else { hideAnswer(popupType); }
    }
}

//display help text for hovered 'question mark' image
function answerQuestion(elId, popupType, questionId) {
    var header = $("#" + questionId + ' .title').html();
    var answer = $("#" + questionId + ' .text').html();

    var xy = getScrollXY(); //returns array - [x, y] (coordinates)
    var nudgeTop = -58, nudgeLeft = 11;
    if (popupType == 'viewmore') { nudgeTop = 11; nudgeLeft = -145; }

    var el = $("#" + elId);
    var padding_top = parseInt(el.css('padding-top').replace('px', ''));
    var padding_left = parseInt(el.css('padding-left').replace('px', ''));
    var margin_left = parseInt(el.css('margin-left').replace('px', ''));
    var image_left = ($("#" + elId + " img").length == 0) ? 0 : parseInt($("#" + elId + " img").css('padding-left').replace('px', ''));

    var top = el.position().top + nudgeTop - xy[1] + padding_top;
    var left = el.position().left + nudgeLeft - xy[0] + margin_left + padding_left + image_left;
    if (checkVersionIE6()) { top += xy[1]; }

    $("#" + popupType).css("top",top);
    $("#" + popupType).css("left", left);
    $("#" + popupType + "Text").html(answer);
    $("#" + popupType + " #headerText p").html(header);
    $("#" + popupType).fadeIn("fast");
    answerStatus = 1;
}

function hideAnswer(popupType) {
    if (popupType !== undefined) {
        $("#" + popupType).fadeOut("fast");
        $("#" + popupType + "Text").html("");
    } else {
        $("#questionHover").fadeOut("fast");
        $("#viewmore").fadeOut("fast");
    }
    answerStatus = 0;
}

//Determine Scrolling Offset if Any
function getScrollXY() {
    var scrOfX = 0, scrOfY = 0;
    if( typeof( window.pageYOffset ) == 'number' ) {
        //Netscape compliant
        scrOfY = window.pageYOffset;
        scrOfX = window.pageXOffset;
    } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
        //DOM compliant
        scrOfY = document.body.scrollTop;
        scrOfX = document.body.scrollLeft;
    } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
        //IE6 standards compliant mode
        scrOfY = document.documentElement.scrollTop;
        scrOfX = document.documentElement.scrollLeft;
    }
    return [scrOfX, scrOfY];
}

//Determine Browser Width/Height
function getViewingSize() {
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {//Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }
    return [myWidth, myHeight];
}

//Hide '?-popups' when scrolling
$(window).scroll(function () {
    if(BrowserDetect.browser != 'Safari' || (BrowserDetect.browser == 'Safari' && BrowserDetect.version >= 4)) {
        if (answerStatus == 1) { hideAnswer(); }
    }
});

//Hide '?-popups' when scrolling on results page
$(document).ready(function(){
    if(BrowserDetect.browser != 'Safari' || (BrowserDetect.browser == 'Safari' && BrowserDetect.version >= 4)) {
        $("#lcr_results").scroll(function () {
            if (answerStatus == 1) { hideAnswer(); }
        });
    }
    darkenNamedLoans()
});

function darkenNamedLoans() {
    var name = "Name Your Own Loan ";
    for (var i=1; i<9; i++) {
        if($('#n' + i).attr("value") != name + i) {
            $('#n' + i).css("color","#000");
        }
    }
}

function nameYourLoan(el, action , order) {
    var name = "Name Your Own Loan ";
    if (action == 'click' && (el.value == name + "1" || el.value == name + "2" || el.value == name + "3" || el.value == name + "4" || el.value == name + "5" || el.value == name + "6" || el.value == name + "7" || el.value == name + "8")) {
        el.value = "" ;
        $("#" + el.id).css("color", "#000");
    }
    if (action == 'blur' && el.value == '') {
        el.value = name + order;
        $("#" + el.id).css("color", "#999");
    }
}

function displayEditLoansForm(errorMsgCode) {
    var messageCode = ["You have selected the maximum of four loans to compare. To compare these loans, click Compare. To edit your loan selections, click Edit", "You have already selected the maximum of four loans to compare. To compare these loans, click Compare. To edit your loan selections, click Edit"];

    centerPopup('compareLoans');
    loadPopupBackground();
    $("#clFormBody").html(messageCode[errorMsgCode]);
    $("#compareLoans").fadeIn("slow");
}

function editLoans() {
    $("#compareLoans").fadeOut("slow");
    unloadPopupBackground();
}

function tryToCompare() {
    var checkBoxes = $("#wrapAll input:checked");
    if (checkBoxes.length > 0 && popupStatus == 0) { document.form.submit(); }
}

function compareLoans() {
    $("#compareLoans").fadeOut("slow");
    unloadPopupBackground();
    document.form.submit();
}

//Display Clear From Popup
function displayClearForm() {
    centerPopup('clearForm');
    loadPopupBackground();
    $("#clearForm").fadeIn("slow");
}

function closeClearForm() {
    $("#clearForm").fadeOut("slow");
    unloadPopupBackground();
}

function clearForm() {
    var checkBoxes = $("#wrapAll input:checked");
    for (check in checkBoxes) { checkBoxes[check].checked = false; }

    var inputFields = $("#wrapAll input:text");
    for (input in inputFields) {
        var name = "Name Your Own Loan ";
        if (inputFields[input].name == name+"1" || inputFields[input].name == name+"2" || inputFields[input].name == name+"3"
        || inputFields[input].name == name+"4" || inputFields[input].name == name+"5" || inputFields[input].name == name+"6"
        ||inputFields[input].name == name+"9" || inputFields[input].name == name+"8") {
            inputFields[input].value = inputFields[input].name;
            $("#" + inputFields[input].id).css("color", "#999");
        } else { inputFields[input].value = ""; }
    }

    var selectFields = $("#wrapAll .content select");
    for (sel in selectFields) { selectFields[sel].selectedIndex = 0; }
    closeClearForm();
}

function centerPopup(formId){
    //data for centering
    if (popupStatus == 0) {
        var xy = getScrollXY(); //returns array - [x, y]
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $("#" + formId).height();
        var popupWidth = $("#" + formId).width();
        var top = windowHeight/2-popupHeight/2+xy[1];
        var left = windowWidth/2-popupWidth/2+xy[0];

        //apply xy coordinates
        $("#" + formId).css( {"position": "absolute", "top": top, "left": left});

        //needed for IE6
        $("#backgroundPopup").css( {"height": windowHeight + xy[1]} );
    }
}



function verifyFPLOwnLoans(ownLoanId, calculatorId) {
    loanNumber = ownLoanId.substring(ownLoanId.length - 1);
    var ids = ['ownrate', 'ownfees', 'ownterm'], fieldIds;

    if (calculatorId == 'alt_loans') {
        fieldIds = [intRateValidation('ownrate' + loanNumber, calculatorId), feesValidation('ownfees' + loanNumber, calculatorId), termValidation('ownterm' + loanNumber)];
    } else {
        fieldIds = [intRateValidation('ownrate' + loanNumber, calculatorId), feesValidation('ownfees' + loanNumber, calculatorId)];
    }


    if ($("#ownfees" + loanNumber).attr("value") == '') {
        invalid_count = 0;
        //Check if all valid and Fees == ''. If so, set Fees to 0
        for (var i in fieldIds) {
            if (fieldIds[i] == false) { invalid_count++; }
        }

        //if (invalid_count == 1 && fieldIds[1] == false) {
        if (fieldIds[0] == true && fieldIds[1] == false) {
            fieldIds[1] = true;
            $("#ownfees" + loanNumber).attr("value", "0");
        }
    }

    for (var i in fieldIds) {
        //If invalid entry stop checking; return element id
        if (fieldIds[i] == false) { return [false, ids[i] + loanNumber]; }
    }
    return [true, true];
}

function hasCheckedBox(loanId) {
    return $("#" + loanId + " input:checked").length > 0;
}

/* Interest Rate Field Validation (onblur) */
function verifyIntRate(elId, rowId, calculatorId) {
    if (hasCheckedBox(rowId)) {
        if(!intRateValidation(elId, calculatorId)) {
            currentFocus = elId;
            editLoanPopup(elId, rowId);
        }
    }
}

/* Interest Rate Field Validation */
//var intRates = {fssl:{min:0, max:subRate}, fsul:{min:0, max:unSubRate}, fpl:{min:0, max:plusRate}, alt_loans:{min:1, max:25}};
function intRateValidation(elId, calculatorId) {
    var min = intRates[calculatorId].min;
    var max = intRates[calculatorId].max;

    var value = $("#" + elId).attr("value");
    var valid = (RegExp(/\$?(\d|\?\.\d)+(\.\d{1}|\.\d{2}|\.\d{3})?$/).test(String(value)) && parseFloat(value) >= min && parseFloat(value) <= max && value.indexOf('.') == value.lastIndexOf('.'));
    return valid;
}

/* Fees Field Validation (onblur) */
function verifyFees(elId, rowId, calculatorId) {
    if (hasCheckedBox(rowId)) {
        if (!feesValidation(elId, calculatorId)) {
            currentFocus = elId;
            editLoanPopup(elId, rowId);
        }
    }
}


/* Fees Field Validation */
//var feeRates = {fssl:{min:0, max:subFee}, fsul:{min:0, max:unSubFee}, fpl:{min:0, max:plusFee}, alt_loans:{min:1, max:25}};
function feesValidation(elId, calculatorId) {
    var min = feeRates[calculatorId].min;
    var max = feeRates[calculatorId].max;

    var value = $("#" + elId).attr("value");
    var valid = (RegExp(/\$?(\d|\?\.\d)+(\.\d{1}|\.\d{2}|\.\d{3})?$/).test(String(value)) && parseFloat(value) >= min && parseFloat(value) <= max && value.indexOf('.') == value.lastIndexOf('.'));
    return valid;
}

/* Term Field Validation (onblur) */
function verifyTerm(elId, calculatorId) {
    if (hasCheckedBox(calculatorId)) {
        if (!termValidation(elId)) {
            currentFocus = elId;
            editLoanPopup(elId, calculatorId);
        }
    }
}

/* Term Field Validation */
function termValidation(elId) {
    var value = $("#" + elId).attr("value");
    var valid = (RegExp(/^\d{1}$|\d{2}$/).test(String(value)) && parseFloat(value) >= 5 && parseFloat(value) <= 30);
    return valid;
}


function validateOwnTerms(el) {
    var maxDigits = $("#" + el.id).attr("maxlength");
    var value = el.value;
    var valid = false;
    if (maxDigits == 5) {//percentage field
        valid = RegExp(/[0-9]+(\.\d{3})?$/).test(String(value).replace(/^\s+|\s+$/g, ""));
    } else { //year field
        valid = (RegExp(/^\d+$/).test(String(value).replace(/^\s+|\s+$/g, "")) && value.charAt(0) != 0);
    }

    if (!valid) {
        var errorMsg = $("#valid_" + el.id).html();
        loadIEPopup(errorMsg, el.id);
    }
}

function countChecked() {
    var checkBoxes = $("#wrapAll .content input:checked");
    if (checkBoxes.length > 3) { displayEditLoansForm("You have selected the maximum of four loans to compare. To compare these loans, click Compare. To edit your loan selections, click Edit");  }
}

function getInternetExplorerVersion() {
// Returns the version of Internet Explorer or a -1
  var rv = -1; // Return value assumes failure.
  if (navigator.appName == 'Microsoft Internet Explorer') {
    var ua = navigator.userAgent;
    var re  = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
    if (re.exec(ua) != null)
      rv = parseFloat( RegExp.$1 );
  }
  return rv;
}

function checkVersionIE6() {
    var ver = getInternetExplorerVersion();
    if ( ver == 6.0 ) { return true } else { return false }
}


/* Submit the form */
function submitForm(action){
    input = document.createElement("INPUT");
    input.name = action;
    input.type = "hidden";
    input.value = "Y";
    document.instLoanForm.appendChild(input);
    document.instLoanForm.submit();
}


function submitForm(action){
    input = document.createElement("INPUT");
    input.name = action;
    input.type = "hidden";
    input.value = "Y";
    document.studentForm.appendChild(input);
    document.studentForm.submit();
}



// display Invalid Entry popup
function loadIEPopup(errorMsg) {
    //loads popup only if it is disabled
    if(popupStatus==0) {
        $("#ieError").append(errorMsg);
        loadPopupBackground();
        centerPopup("invalidEntryPopup");
        $("#invalidEntryPopup").fadeIn("slow");
        popupStatus = 1;
    }
}

// hide Invalid Entry popup
function disableIEPopup(focusId){
    //disables popup only if it is enabled
    if(popupStatus==1) {
        unloadPopupBackground()
        $("#invalidEntryPopup").fadeOut("slow");
        $("#ieError").html("");
        popupStatus = 0;
        setTimeout("document.getElementById('"+currentFocus+"').focus()", "50");
    }
}
