﻿$(document).ready(function() {
    // Show red borders on inputs without values when the page is first loaded
    $("#RefineYourQuoteWidgetForm input").each(function() {
        if ($(this).val() == "" || $(this).val() == "0.00" || $(this).val() == "0") {
            $(this).css("border", "2px solid red");
        }
    });
    
    // Show red borders on selects without values when the page is first loaded
    $("#RefineYourQuoteWidgetForm select").each(function() {
        if ($(this).val() == "") {
            $(this).closest(".SelectContainer").css("padding", "2px");
        }
    });

    // Format the text inputs as currency when the page is first loaded
    $(".CurrencyInput").each(function() {
        if (!isNaN($(this).val())) {
            var id = $(this).attr("id");
            formatCurrency(id);
        }
    });

    // Handle LTV calculation on load if the values it relies on are blank
    if ($("#LTVInput").val() == "NaN") {
        $("#LTVInput").val("0.00");
    }

    // Handle county visibility on load
    UpdateCountyVisibility();

    // Handle lock period visibility on load
    UpdatLockPeriodVisibility();

    // Show the appropriate inputs depending on the loan purpose when the page is first loaded
    if ($("select[name=LoanPurpose]").val() == "1") {
        $("#LoanAmountListItem").hide();
        $("#PropertyValueListItem").hide();
        $("#PurchasePriceListItem").show();
        $("#DownPaymentListItem").show()
    }

    // Update county dropdown based on state selection when page loads
    $("select[name=PropertyStateLocation]").each(function() {
        UpdateCountyDropdown();
    });

    // Update county dropdown based on state selection
    $("select[name=PropertyStateLocation]").change(function() {
        UpdateCountyDropdown();
    });


    // Show the appropriate inputs when the loan purpose changes
    $("select[name=LoanPurpose]").change(function() {
        if ($(this).val() == "1") {
            $("#LoanAmountListItem").hide();
            $("#LoanAmountInput").val("0.00");
            $("#LoanAmountInput").change();
            $("#PropertyValueListItem").hide();
            $("#PropertyValueInput").val("0.00");
            $("#PropertyValueInput").change();
            $("#LTVInput").val("0.00");
            $("#PurchasePriceListItem").show();
            $("#DownPaymentListItem").show()
        } else {
            $("#PurchasePriceListItem").hide();
            $("#PurchasePriceInput").val("0.00");
            $("#PurchasePriceInput").change();
            $("#DownPaymentListItem").hide()
            $("#DownPaymentInput").val("0.00");
            $("#DownPaymentInput").change();
            $("#LTVInput").val("0.00");
            $("#LoanAmountListItem").show();
            $("#PropertyValueListItem").show();
            UpdateLTV();
        }

        UpdatLockPeriodVisibility();
    });

    $(".TipImage").hover(
        function(event) {
            event.stopPropagation()
            var tipBubble = $(this).next(".TipBubble");
            tipBubble.css("top", $(this).position().top - 61);
            tipBubble.css("left", $(this).position().left - 305);
            tipBubble.show();
        },
        function(event) {
            event.stopPropagation()
            var tipBubble = $(this).next(".TipBubble");
            tipBubble.hide();
        }
    );

    $(".TipImageRight").live("mouseover", function(event) {
        event.stopPropagation()
        var tipBubble = $(this).next(".TipBubbleRight");
        tipBubble.css("top", $(this).position().top - 61);
        tipBubble.css("left", $(this).position().left + 22);
        tipBubble.show();
    });

    $(".TipImageRight").live("mouseout", function(event) {
        event.stopPropagation()
        var tipBubble = $(this).next(".TipBubbleRight");
        tipBubble.hide();
    });


    // If value is defaulted to 0.00, remove text when user focuses on input
    $(".CurrencyInput").focus(function() {
        if ($(this).val() == "0.00") {
            $(this).val("");
        }
    });

    // If input is blank when user leaves text box, default to 0.00
    $(".CurrencyInput").blur(function() {
        if ($(this).val() == "") {
            $(this).val("0.00");
        }
    });

    // Ensure that the text inputs are still formatted as currency after they are changed
    $(".CurrencyInput").change(function() {
        var id = $(this).attr("id");
        formatCurrency(id);
    });

    // If value is defaulted to 0.00, remove text when user focuses on input
    $("#CreditScoreInput").focus(function() {
        if ($(this).val() == "0") {
            $(this).val("");
        }
    });

    // If input is blank when user leaves text box, default to 0.00
    $("#CreditScoreInput").blur(function() {
        if ($(this).val() == "") {
            $(this).val("0");
        }
    });

    // Remove red borders from inputs with values when the value changes
    $("#RefineYourQuoteWidgetForm input").change(function() {
        if ($(this).val() != "" && $(this).val() != "0.00") {
            $(this).css("border", "1px solid #ccc");
        } else {
            $(this).css("border", "2px solid red");
        }
    });
    
    // Remove red borders from selects with values when the value changes
    $("#RefineYourQuoteWidgetForm select").change(function() {
        if ($(this).val() != "") {
            $(this).closest(".SelectContainer").css("padding", "0px");
        } else {
            $(this).closest(".SelectContainer").css("padding", "2px");
        }
    });

    // Update the loan amount or down payment when the LTV is manually updated
    $("input[name=LTV]").change(function() {
        var ltvVal = $("input[name=LTV]").val().replace(/\$|\,/g, '');

        if (ltvVal != "0.00") {
            if ($("select[name=LoanPurpose]").val() == "1") {
                var purchasePriceVal = $("input[name=PurchasePrice]").val().replace(/\$|\,/g, '');
                var downPaymentVal = $("input[name=DownPayment]").val().replace(/\$|\,/g, '');

                if (!(purchasePriceVal == "0.00" && downPaymentVal == "0.00")) {
                    if (purchasePriceVal != "0.00") {
                        var updatedDownPayment = purchasePriceVal - (purchasePriceVal * (ltvVal / 100));

                        $("input[name=DownPayment]").val(updatedDownPayment);
                        formatCurrency($("input[name=DownPayment]").attr("id"));
                        $("input[name=DownPayment]").change();
                    } else {
                        var updatedPurchasePrice = downPaymentVal / (ltvVal / 100)

                        $("input[name=PurchasePrice]").val(updatedPurchasePrice);
                        formatCurrency($("input[name=PurchasePrice]").attr("id"));
                        $("input[name=PurchasePrice]").change();
                    }
                }
            } else {
                var loanAmountVal = $("input[name=LoanAmount]").val().replace(/\$|\,/g, '');
                var propertyValueVal = $("input[name=PropertyValue]").val().replace(/\$|\,/g, '');

                if (!(loanAmountVal == "0.00" && propertyValueVal == "0.00")) {
                    if (propertyValueVal != "0.00") {
                        var updatedLoanAmount = propertyValueVal * (ltvVal / 100);

                        $("input[name=LoanAmount]").val(updatedLoanAmount);
                        formatCurrency($("input[name=LoanAmount]").attr("id"));
                        $("input[name=LoanAmount]").change();
                    } else {
                        var updatedPropertyValue = loanAmountVal / (ltvVal / 100);

                        $("input[name=PropertyValue]").val(updatedPropertyValue);
                        formatCurrency($("input[name=PropertyValue]").attr("id"));
                        $("input[name=PropertyValue]").change();
                    }
                }
            }
        }
    });

    // Update the loan to value when the loan amount is manually updated
    $("input[name=LoanAmount]").change(function() {
        UpdateLTV();
        UpdateCountyVisibility();
    });

    // Update the loan to value when the property value is manually updated
    $("input[name=PropertyValue]").change(function() {
        UpdateLTV();
    });

    // Update the loan to value when the purchase price is manually updated
    $("input[name=PurchasePrice]").change(function() {
        UpdateLTV();
        UpdateCountyVisibility();
    });

    // Update the loan to value when the down payment is manually updated
    $("input[name=DownPayment]").change(function() {
        UpdateLTV();
        UpdateCountyVisibility();
    });

    function UpdateLTV() {
        if ($("select[name=LoanPurpose]").val() == "1") {
            var purchasePriceVal = $("input[name=PurchasePrice]").val().replace(/\$|\,/g, '');
            var downPaymentVal = $("input[name=DownPayment]").val().replace(/\$|\,/g, '');

            if (purchasePriceVal != "0.00" && downPaymentVal != "0.00") {
                var loanAmount = purchasePriceVal - downPaymentVal;
                var updatedLTV = (loanAmount / purchasePriceVal) * 100;

                if (isFinite(updatedLTV) ) {
                    $("input[name=LTV]").val(updatedLTV);
                    formatCurrency($("input[name=LTV]").attr("id"));
                    $("input[name=LTV]").css("border", "1px solid #ccc");
                } else {
                    $("input[name=LTV]").val(0);
                    formatCurrency($("input[name=LTV]").attr("id"));
                }
            }

        } else {
            var loanAmountVal = $("input[name=LoanAmount]").val().replace(/\$|\,/g, '');
            var propertyValueVal = $("input[name=PropertyValue]").val().replace(/\$|\,/g, '');

            if (loanAmountVal != "0.00" && propertyValueVal != "0.00") {
                var updatedLTV = (loanAmountVal / propertyValueVal) * 100;

                if (isFinite(updatedLTV)) {
                    $("input[name=LTV]").val(updatedLTV);
                    formatCurrency($("input[name=LTV]").attr("id"));
                    $("input[name=LTV]").css("border", "1px solid #ccc");
                } else {
                    $("input[name=LTV]").val(0);
                    formatCurrency($("input[name=LTV]").attr("id"));
                }
            }
        }
    }

    function UpdateCountyVisibility() {
        var loanAmount = $("#LoanAmountInput").val().replace(/\$|\,/g, '');
        var purchasePrice = $("#PurchasePriceInput").val().replace(/\$|\,/g, '');
        var downPayment = $("#DownPaymentInput").val().replace(/\$|\,/g, '');

        if ((loanAmount > 417000) || ((purchasePrice - downPayment) > 417000)) {
            $("#PropertyCountyLocationListItem").show();
        } else {
            $("#PropertyCountyLocationListItem").hide();
        }
    }

    function UpdatLockPeriodVisibility() {
        if ($("select[name=LoanPurpose]").val() == "1") {
            $("#LockPeriodListItem").show();
        } else {
            $("#LockPeriodListItem").hide();
        }
    }

    function UpdateCountyDropdown() {
        var countyDropdown = $("select[name=PropertyCountyLocation]");
        var countyDropdownHtml = ""
        var stateId = $("select[name=PropertyStateLocation]").val();
        var selectedItem = "";

        for (obj in countiesList) {
            if (countiesList[obj].StateId == stateId || countiesList[obj].StateId == "0") {
                if (countiesList[obj].IsDefault == "True") {
                    selectedItem = countiesList[obj].CountyId;
                }

                countyDropdownHtml += "<option value='" + countiesList[obj].CountyId + "'>" + countiesList[obj].CountyName + "</option>";
            }
        }

        countyDropdown.html("");
        countyDropdown.html(countyDropdownHtml);
        countyDropdown.val(selectedItem);
    }


    /* Horizontal Question Widget Modifications */


});
