﻿//Hide (Collapse) the toggle containers on load
$(".ItemsContainer").hide();

$(document).ready(function() {
    ExecuteJS();

    // Open the sections if it's marked as active (selection being made)
    $(".SelectionActive").each
        (
            function() {
                // Select the category
                CategorySelected($(this).parent(), true);
                // Update Button CSS
                SelectionMade($(this), true);
            }
        );


    $(".SubHeader")
           .click(
            function(event) {
                event.preventDefault();
                if ($(this).find('a').attr('disabled')) {
                    event.preventDefault();
                }
                else {
                    var originalStateIsOpen = $(this).next(".ItemsContainer").is(":visible");

                    if (!originalStateIsOpen) {
                        PostBack();
                    }
                    $(this).next(".SubItemContainer").slideToggle("fast");
                }
            });

    // Open  / Close the content of the category
    $(".Header")
           .click(
            function(event) {
                event.preventDefault();

                if ($(this).find('a').attr('disabled')) {
                    event.preventDefault();
                }
                else {
                    var originalStateIsOpen = $(this).next(".ItemsContainer").is(":visible");
                    CategorySelected($(this), !originalStateIsOpen);
                }
            });

});


function ZipCodeHandler(obj) {
    var value = $(obj).val();

    if (isNaN(value) || value == "" || value.length != 5) {
        // Disable all search buttons
        $("INPUT[type='submit']").attr('disabled', 'true');
        $("#spZipCodeRequired").addClass("PaymentRequired")
        $("#spZipCodeRequired").removeClass("PaymentNotRequired")
        $("#dvZipCodeError").css("display", "block");
        return false;
    }
    else {
        if (value != "") {
            // Remove any disabled attribute on the button, if any
            $("INPUT[type='submit']").removeAttr('disabled');
            $("#spZipCodeRequired").addClass("PaymentNotRequired")
            $("#spZipCodeRequired").removeClass("PaymentRequired")
            $("#dvZipCodeError").css("display", "none");
        }
        return true;
    }
}

function PaymentTextboxesHandler(obj) {

    var paymentTextBoxHasText = 0;
    var paymentTextBoxHasNumeric = 0;
    var readyToCalc = false;
    var paymentTextBoxItems = 0;

    $(".PaymentTextbox").each(
            function() {
                // Keep track of how many payment checkboxes are there
                paymentTextBoxItems++;

                var val = $(this).val();

                if (isNaN(val) || val == "" || val == null) {
                    $(this).parent().next().find("span").removeClass("PaymentNotRequired");
                    $(this).parent().next().find("span").addClass("PaymentRequired");
                }
                else {
                    paymentTextBoxHasNumeric++;
                }

                if (!(val == "" || val == null)) {
                    paymentTextBoxHasText++;
                }
            });

    if (paymentTextBoxHasText > 0) {
        //Check for the other numeric values in this section
        $(obj).parents(".ItemsContainer").find(".NumericTextbox").each(
                function() {
                    // Keep track of how many payment checkboxes are there
                    paymentTextBoxItems++;

                    var val = $(this).val();

                    if (isNaN(val) || val == "" || val == null) {
                        $(this).parent().next().find("span").removeClass("PaymentNotRequired");
                        $(this).parent().next().find("span").addClass("PaymentRequired");
                    }
                    else {
                        paymentTextBoxHasNumeric++;
                    }

                    if (!(val == "" || val == null)) {
                        paymentTextBoxHasText++;
                    }
                });
    }

    // If all textboxes have numeric values, go ahead and show the caluclate icon
    if (paymentTextBoxItems == paymentTextBoxHasNumeric) {

        // Show the row
        $("#ShowCalIconRow").css("display", "");
        // Set the amount to empty
        $("#TotalAffordableAmount").text("");
        // Update events after selection made
        SelectionMade($(obj), true);
        // Disable price
        PricePaymentSelected($(obj), true, false);
        // Remove any previous disabled attribute on the submit button
        $("INPUT[type='submit']").removeAttr('disabled');
        // Hide the error row
        $("#ErrorRow").css("display", "none");
    }
    else if (paymentTextBoxHasText == 0) {
        // All textboxes are empty

        // No selection is being made
        SelectionMade($(obj), false);
        // Hide the error row
        $("#ErrorRow").css("display", "none");

        // Remove any previous disabled attribute on the submit button
        try {
            $("INPUT[type='submit']").removeAttr('disabled');
        }
        catch (E) { }

        // Apply correct CSS Class
        try {
            $(".PaymentTextbox, .NumericTextbox").parent().next().find("span").removeClass("PaymentRequired");
            $(".PaymentTextbox, .NumericTextbox").parent().next().find("span").addClass("PaymentNotRequired");
        }
        catch (E) { }

        // Do not disable price
        PricePaymentSelected($(obj), false, false);
    }
    else {
        // User did not enter all texboxes with numeric values
        // Show the error row
        $("#ErrorRow").css("display", "");
        // Do not show the calculate row
        $("#ShowCalIconRow").css("display", "none");
        // Disable the submit buttons
        $("INPUT[type='submit']").attr('disabled', 'true');
        // No selection has been made
        SelectionMade($(obj), false);
        // Disable price
        PricePaymentSelected($(obj), true, false);
    }
}

function NumericTextBoxHandler(obj) {
    var value = $(obj).val();
    if (isNaN(value)) {
        // Disable all search buttons
        $(obj).parent().next().find("span").removeClass("PaymentNotRequired");
        $(obj).parent().next().find("span").addClass("PaymentRequired");
        $("INPUT[type='submit']").attr('Title', 'Please fill out all required fields.');
        $("INPUT[type='submit']").attr('disabled', 'true');
        return false;
    }
    else {
        if (value != "") {
            // Remove any disabled attribute on the button, if any
            $(obj).parent().next().find("span").removeClass("PaymentRequired");
            $(obj).parent().next().find("span").addClass("PaymentNotRequired");
            $(this.form).find("INPUT[type='submit']").removeAttr('disabled');
            $(this.form).find("INPUT[type='submit']").removeAttr('Title');
        }
        return true;
    }
}

function ShowHideStatus(obj, show) {

    obj.parents(".ItemsContainer").prev('.Header').find('span').removeClass('SelectionInactive');
    obj.parents(".ItemsContainer").prev('.Header').find('span').removeClass('SelectionActive');

    if (show) {
        obj.parents(".ItemsContainer").prev('.Header').find('span').addClass('SelectionActive');
    }
    else {
        obj.parents(".ItemsContainer").prev('.Header').find('span').addClass('SelectionInactive');
    }
}

function UpdateButtonCSS(object, isActive) {

    if (isActive) {
        $(object).addClass('ActiveButton');
        $(object).removeClass('InactiveButton');
    }
    else {
        $(object).addClass('InactiveButton');
        $(object).removeClass('ActiveButton');
    }
}

function DisablePriceCategory(ToDisable) {
    if (ToDisable) {

        SelectionMade($("#PriceCategory"), false);
        CategorySelected($("#PriceCategory").parents(".Header"), false);

        toggleDisabled(document.getElementById("PriceCategory"), ToDisable);

        $("#PriceCategory").attr('title', 'Search by Price is not available while Payment search is selected');
    }
    else {
        toggleDisabled(document.getElementById("PriceCategory"), ToDisable);
        $("#PriceCategory").removeAttr('title');
    }
}

function toggleDisabled(el, disable) {
    try {
        if (disable) {
            el.disabled = true;
            $(el).attr("headerdisabled", "1");
            $(el).css("color", "#9D9DA1");
        }
        else {
            el.disabled = false;
            $(el).removeAttr("headerdisabled");
            $(el).css("color", "#5A626D");
        }
    }
    catch (E) {
    }
}

function DisablePaymentCategory(ToDisable) {
    if (ToDisable) {
        SelectionMade($("#PaymentCategory"), false);
        CategorySelected($("#PaymentCategory").parents(".Header"), false);
        toggleDisabled(document.getElementById("PaymentCategory"), ToDisable);
        $("#PaymentCategory").attr('title', 'Search by Payment is not available while Price search is selected');
    }
    else {
        toggleDisabled(document.getElementById("PaymentCategory"), ToDisable);
        $("#PaymentCategory").removeAttr('title');
    }
}

function CategorySelected(obj, selected) {
    // For any active category (the user has clicked on the header to open)
    // Header is the object
    if (selected) {
        // 1.  Change the arrow to down
        var originalText = $(obj).find('a').html();
        var newText = $(obj).find('a').html().replace('►', '▼')
        $(obj).find('a').html(newText)
        // 2.  Slide the content to make visible
        if (originalText != newText)
            $(obj).next(".ItemsContainer").slideToggle("fast");
    }
    else {

        var newText = $(obj).find('a').html().replace('▼', '►')
        $(obj).find('a').html(newText)
        // 2.  Slide the content to make visible
        $(obj).next(".ItemsContainer").hide();
    }

}

function SelectionMade(obj, isSeleted) {
    // Show the EDIT on the header
    ShowHideStatus($(obj), isSeleted);

    // Update Button CSS
    UpdateButtonCSS($(obj).parents(".ItemsContainer").find("INPUT[type='submit']"), isSeleted);
}

function PricePaymentSelected(obj, isSelected, toDiablePayment) {

    // Price / Payment (If there is selection in price, disable payment, verse versa)
    var isPriceModel = $(obj).parents(".ItemsContainer").prev().find('#PriceCategory').length;
    if (isPriceModel > 0) {
        DisablePaymentCategory(isSelected);
    }
    else {
        var isPaymentModel = $(obj).parents(".ItemsContainer").prev().find('#PaymentCategory').length;
        if (isPaymentModel > 0) {
            DisablePriceCategory(isSelected);
        }
    }
}

function EventHandlersForMakeYear() {

    $(".MakeCheckBoxes").click(
            function() {

                // Find how many are checked
                var n = $(this).parents(".ItemsContainer").find(".MakeCheckBoxes INPUT[type='checkbox']:checked").length;
                // Update events after selection made
                SelectionMade($(this), n > 0);

                // Open it's associated sub items
                var obj = $(this).find('input');
                MakeSelected($(this), $(obj).is(":checked"), true);
            });

    // Anytime a make checkbox is checked, this is for the post back to style the make / year
    $(".MakeCheckBoxes :checked").each(
            function() {
                MakeSelected($(this).parent(), true, false);
            });

    // Anytime the close button is clicked  on the context pop up 
    $(".SubItemContainerCloseButton").click(
            function() {
                ShowPopUp($(this).parents("SubItemContainer"), false);
            });


    // Anytime a actual item checkbox within a context pop up is clicked
    $(".SubItemContainerItem").click(
                function() {
                    // If All is clicked, uncheck the all checkbox
                    var n = $(this).parents(".SubItemContainer").find(".SubItemContainerItem INPUT[type='checkbox']:checked").length;
                    if (n > 0)
                        $(this).parents(".SubItemContainer").find(".SubItemContainerAll INPUT[type='checkbox']").removeAttr('checked');
                }
            );

    // Anytime a All checkbox is clicked on the context pop up
    $(".SubItemContainerAll").click(
                function() {
                    // Un-check all the item checkboxes
                    $(this).parents(".SubItemContainer").find(".SubItemContainerItem INPUT[type='checkbox']").removeAttr('checked');
                }
            );
}


function ShowPopUp(obj, show) {

    var info = $('.SubItemContainer', $(obj));

    // Hide al the pop ups
    $('.SubItemContainer').css('display', 'none');

    if (show) {
        // Show the context pop up 
        info.css({ display: 'block' })

        // Check to see if any model's selected, if not select the all model checkbox
        var n = $(obj).find('.SubItemContainer').find("INPUT[type='checkbox']:checked").length;
        if (n == 0) {
            // find the All model checkbox and select it
            $(obj).find('.SubItemContainerAll').find("INPUT[type='checkbox']").attr('checked', 'checked');
        }
    }
    else {
        // Hide the current context pop up
        info.css({ display: 'none' })

        // Remove all selection
        $(obj).find('.SubItemContainer').find("INPUT[type='checkbox']:checked").removeAttr('checked');
    }
}

function ItemSelectedTextClick(event) {
    ShowPopUp(event.data.element, true);
}

function MakeSelected(obj, isSelected, showPopUp) {
    // If selcted, make background orange background
    if (isSelected) {
        $(obj).parent().addClass('ItemSelected');
        var textObj = $(obj).next(".ItemTextNotselected");
        $(textObj).addClass("ItemSelectedText");
        $(textObj).removeClass("ItemTextNotselected");

        $(textObj).bind('click', { element: $(textObj.parent()) }, ItemSelectedTextClick);

        if (showPopUp)
            ShowPopUp($(obj.parent()), true);

    }
    else {
        $(obj).parent().removeClass('ItemSelected');
        var textObj = $(obj).next(".ItemSelectedText");
        $(textObj).removeClass("ItemSelectedText");
        $(textObj).addClass("ItemTextNotselected");
        ShowPopUp($(obj.parent()), false);
        $(textObj).unbind('click');

    }
}

function ScrollToTopOfPage() {
    // Scroll to the top of the page
    setTimeout("window.scrollTo(0,0)", 0);
}


function EventHandlersForControlsInJS() {
    $(".PaymentTextbox, .NumericTextbox").keyup(
            function() {

                var value = $(this).val();
                if (isNaN(value)) {
                    //$(this).parent().next().find("span").removeClass("PaymentNotRequired");
                    //$(this).parent().next().find("span").addClass("PaymentRequired");
                }
                else {
                    $(this).parent().next().find("span").removeClass("PaymentRequired");
                    $(this).parent().next().find("span").addClass("PaymentNotRequired");
                }
                PaymentTextboxesHandler($(this));
            }
        );

    // Select All / UnSelect All
    $(".SelectAll").click(
            function(event) {

                event.preventDefault();

                // Check all checkboxes
                $(this).parents(".ItemsContainer").find(".CheckBoxes INPUT[type='checkbox']").attr('checked', 'True');

                // Check all checkboxes
                $(this).parents(".ItemsContainer").find(".MakeCheckBoxes INPUT[type='checkbox']").attr('checked', 'True');

                // Update events after selection made
                SelectionMade($(this), true);

                // Price / Payment (If there is selection in price, disable payment, verse versa)
                var isPriceCategory = $(this).parents(".ItemsContainer").prev().find("#PriceCategory").length;
                if (isPriceCategory > 0)
                    PricePaymentSelected($(this), true, true);

            });

    // Expand All
    $(".Expand").click(
            function(event) {
                // Prevent the default behavior of a hyperlink
                event.preventDefault();
                // Show all the categories
                $(".Header").each(
                function() {
                    var x = $(this).parent().find('a').attr('headerdisabled')
                    if (x == null || x == undefined) {

                        // do not expand category if it is disabled
                        CategorySelected($(this), true);
                    }
                })
                // Scroll to the top of the page
                ScrollToTopOfPage();
            }
        );

    // Collapse All
    $(".Collapse").click(
            function(event) {
                // Prevent the default behavior of a hyperlink
                event.preventDefault();
                // Close all the categories
                $(".Header").each(
                function() {
                    CategorySelected($(this), false);
                })
                // Scroll to the top of the page
                ScrollToTopOfPage();
            });

    // Clear form
    $(".Clear").click(
            function(event) {
                event.preventDefault();
                // Hide the item containers
                $(".UnselectAll").each(
                function() {
                    $(this).click();
                })

                // Collpose all sections
                $(".Collapse").click();
            }
        );

    // Anytime a control with Checkboxes class is clicked
    $(".CheckBoxes").click(
            function() {
                // Find how many is checked
                var n = $(this).parents(".ItemsContainer").find(".CheckBoxes INPUT[type='checkbox']:checked").length;
                // Update events after selection made
                SelectionMade($(this), n > 0);

                // If the current model is Price, handle price payment situation
                var isPriceCategory = $(this).parents(".ItemsContainer").prev().find("#PriceCategory").length;
                if (isPriceCategory > 0)
                    PricePaymentSelected($(this), n > 0, n > 0);
            });

    // Anytime a control with RadioButtons Class is clicked
    $(".RadioButtons").click(
            function() {
                // Get the current object
                var id = $(this).find('input');
                // Set everything else to not selected
                $(this).parents(".ItemsContainer").find(".RadioButtons INPUT[type='radio']").removeAttr('checked');
                // Select this current object
                $(id).attr('checked', 'True');
                // Update events after selection made
                SelectionMade($(this), true);
            }
        );
}
