$(function() {

    var PROD_LISTING_SEARCH_STRING = "search part #";
    var PROD_LISTING_NO_RESULTS_STRING = "No results were found for this search.";

    function hideFilters() {
        //        alert("hideFilters");
        $("#filter1").hide();
        $("#filter2").hide();
        $("#filter3").hide();
        $("#filter4").hide();
    }

    function getCurrentTableName() {
        if ($(".internal-nav .current").length) {
            return ($(".internal-nav .current").attr("id").split("-")[1]);
        }

        return ("");
    }
    $(".filter-loading").hide();

    function populateOptions(tableName, filter, allRows) {
        //        alert("populateOptions " + tableName + " " + filter + " " + allRows);
        if (tableName != "") {
            var optionStarter = "<option>";
            var optionEnder = "</option>";
            var optionsHTML = "";  //optionStarter + "" + optionEnder;

            if (allRows != "all") {
                $(tableName + " tbody tr:visible").each(function(i) {
                    var aVal = $(this).find(".data" + filter).text();

                    if (optionsHTML.indexOf(optionStarter + aVal + optionEnder) == -1) {
                        optionsHTML += (optionStarter + aVal + optionEnder);
                    }
                });
            } else {
                $(tableName + " tbody tr").each(function(i) {
                    var aVal = $(this).find(".data" + filter).text();

                    if (optionsHTML.indexOf(optionStarter + aVal + optionEnder) == -1) {
                        optionsHTML += (optionStarter + aVal + optionEnder);
                    }
                });
            }

            //sort the select boxes
            var options = jQuery.makeArray($(optionsHTML));
            options.sort(function(a, b) {
                return (parseFloat(a.innerHTML) > parseFloat(b.innerHTML)) ? 1 : -1;
            });

            //alert(typeof (options[options.length - 1].value));
            $("#filter" + filter + " select").empty();

            //options = options.join("");
            //options += optionStarter + "" + optionEnder;
            $("#filter" + filter + " select").append("<option></option>");

            $("#filter" + filter + " select").append(options);


        }
    }

    function prepFilters(tableName) {
        //        alert("prepFilters");
        var tableName = "#" + tableName;
        $(tableName).show();

        $("#filter1 select option").remove();
        $("#filter2 select option").remove();
        $("#filter3 select option").remove();
        $("#filter4 select option").remove();

        $("#filter1").hide();
        $("#filter2").hide();
        $("#filter3").hide();
        $("#filter4").hide();

        if ($(tableName + " .data1").length > 0) {
            $("#filter1 select").bind("change", runFilter);
            $("#filter1 label").text($(tableName + " .data1-title").text());
            $("#filter1").show();
            populateOptions(tableName, "1");
        }

        if ($(tableName + " .data2").length > 0) {
            $("#filter2 select").bind("change", runFilter);
            $("#filter2 label").text($(tableName + " .data2-title").text());
            $("#filter2").show();
            populateOptions(tableName, "2");
        }

        if ($(tableName + " .data3").length > 0) {
            $("#filter3 select").bind("change", runFilter);
            $("#filter3 label").text($(tableName + " .data3-title").text());
            $("#filter3").show();
            populateOptions(tableName, "3");
        }

        if ($(tableName + " .data4").length > 0) {
            $("#filter4 select").bind("change", runFilter);
            $("#filter4 label").text($(tableName + " .data4-title").text());
            $("#filter4").show();
            populateOptions(tableName, "4");
        }
    }


    function runFilter(e) {

        $(".filter-loading").show();
        setTimeout(runFilter1, 2);

    }

    function runFilter1(e) {

        $(".filter-loading").show();

        $(".pui-category:visible tbody tr").hide();

        var partSearchString = $("#product-searchForm").val().toUpperCase();
        var theSelection = $(".pui-category:visible tbody tr");



        var filtered = false;

        if ((partSearchString != "") && (partSearchString != PROD_LISTING_SEARCH_STRING.toUpperCase())) {
            theSelection = theSelection.find("td").filter("td[id*='" + partSearchString + "']");
            filtered = true;
        }
        filterVal1Orig = $("#filter1 select").val();
        filterVal2Orig = $("#filter2 select").val();
        filterVal3Orig = $("#filter3 select").val();

        if ((filterVal1Orig != null && filterVal1Orig != "") || (filterVal2Orig != null && filterVal2Orig != "") || (filterVal3Orig != null && filterVal3Orig != "")) {

            if (filterVal1Orig != null && filterVal1Orig != "") {
                theSelection = theSelection.closest("tr").find("td").filter(".data1[title|=" + filterVal1Orig + "]");
            }
            if (filterVal2Orig != null && filterVal2Orig != "") {
                theSelection = theSelection.closest("tr").find("td").filter(".data2[title|=" + filterVal2Orig + "]");
            }
            if (filterVal3Orig != null && filterVal3Orig != "") {
                theSelection = theSelection.closest("tr").find("td").filter(".data3[title|=" + filterVal3Orig + "]");
            }
            filtered = true;
        }

        if (filtered) {
            theSelection.parent().show();
        } else {
            $(".pui-category:visible tbody tr").show();
        }

        if (!IsThisBrowserIE()) {

            if ($(".internal-nav li.current").length) {
                var filterVal1 = "";
                var filterVal2 = "";
                var filterVal3 = "";
                var filterVal4 = "";

                var filterVal1Orig = "";
                var filterVal2Orig = "";
                var filterVal3Orig = "";
                var filterVal4Orig = "";

                if ($("table:visible .data1").length) {
                    filterVal1Orig = $("#filter1 select").val();
                    filterVal1 = filterVal1Orig.toUpperCase();

                } else {
                    filterVal1 = "";
                }

                if ($("table:visible .data2").length) {
                    filterVal2Orig = $("#filter2 select").val();
                    filterVal2 = filterVal2Orig.toUpperCase();
                } else {
                    filterVal2 = "";
                }

                if ($("table:visible .data3").length) {
                    filterVal3Orig = $("#filter3 select").val();
                    filterVal3 = filterVal3Orig.toUpperCase();
                } else {
                    filterVal3 = "";
                }

                if ($("table:visible .data4").length) {
                    filterVal4Orig = $("#filter4 select").val();
                    filterVal4 = filterVal4Orig.toUpperCase();
                } else {
                    filterVal4 = "";
                }

                var tableName = "#" + getCurrentTableName();

                if (($("select[value!='']").length == 0) || ($("select[value!='']").length > 1)) {
                    populateOptions(tableName, "1");
                    populateOptions(tableName, "2");
                    populateOptions(tableName, "3");
                    populateOptions(tableName, "4");

                    $("#filter1 select").val(filterVal1Orig);
                    $("#filter2 select").val(filterVal2Orig);
                    $("#filter3 select").val(filterVal3Orig);
                    $("#filter4 select").val(filterVal4Orig);
                } else {
                    if (filterVal1 == "") {
                        populateOptions(tableName, "1");
                    } else {
                        populateOptions(tableName, "1", "all");
                    }

                    if (filterVal2 == "") {
                        populateOptions(tableName, "2");
                    } else {
                        populateOptions(tableName, "2", "all");
                    }

                    if (filterVal3 == "") {
                        populateOptions(tableName, "3");
                    } else {
                        populateOptions(tableName, "3", "all");
                    }

                    if (filterVal4 == "") {
                        populateOptions(tableName, "4");
                    } else {
                        populateOptions(tableName, "4", "all");
                    }

                    $("#filter1 select").val(filterVal1Orig);
                    $("#filter2 select").val(filterVal2Orig);
                    $("#filter3 select").val(filterVal3Orig);

                    $("#filter4 select").val(filterVal4Orig);
                }
            }
        }

        checkForNoResults();
        showNumResults();
        zebraStripe();

        $(".filter-loading").hide();

        //Remove focus from the dropbox. This is a work around for IE browsers.
        $("#focusMe a").focus();


    }

    function IsThisBrowserIE() {
        return false;

    }


    function clearFilter1() {
        $("#filter1 select").val("");
        runFilter();
    }

    function clearFilter2() {
        $("#filter2 select").val("");
        runFilter();
    }

    function clearFilter3() {
        $("#filter3 select").val("");
        runFilter();
    }

    function clearFilter4() {
        $("#filter4 select").val("");
        runFilter();
    }

    function clearFilter(e) {

        clearProductSearch();
        $("#content-products div").show();
        $(".internal-nav li").removeClass("current");
        $("#filter-options").hide();
        $("#filter-message").show();
        $(".pui-category").hide();
        $(".filter-loading").hide();
        $("#content-products tbody tr").show();
        showNumResults();
        zebraStripe();
    }

    function chooseCategory(e) {

        var categoryName = $(this).attr("id").split("-")[1];

        applyTableSort(categoryName);

        $("#content-products table").show();

        $(".internal-nav li.current").removeClass("current");
        $(this).addClass("current");

        prepFilters(extractID($(this).attr("id")));
        $("#filter-message").hide();
        $("#filter-options").show();
        var category = extractID($(this).attr("id"));

        $("#content-products div").not("." + category).hide();
        $("#content-products ." + category).show();

        productClickSearchButton();
    }


    /* return only the NUM portion of an ID */
    function extractID(theID) {
        return (theID.split("-")[1]);
    }

    function zebraStripe() {

        $("#content-products tr").removeClass("even");
        $("#content-products tr").removeClass("odd");
        $("#content-products tr:visible:even").addClass("even");
    }

    function checkForNoResults() {

        $("#content-products table").show();
        $("#content-products div.no-results").remove();

        $("#content-products table").each(function() {
            if ($(this).find("tbody tr:visible").length == 0) {
                $(this).hide();

                var resultsNotFoundHtml = "<div class='no-results'><h3>" + PROD_LISTING_NO_RESULTS_STRING + "</h3></div>";
                $(this).before(resultsNotFoundHtml);
            }
        });

    }

    function showNumResults() {

         // loop through the visible tables
        // add the number of results to the inner nav
        var theTotal = 0;
        var totalSet = 0;

        $("#content-products table").each(function() {
            var theNum = $(this).find("tbody tr:visible").length;
            theTotal += theNum;

            // taking out the nav item numbers for now
            //var theText = $(".internal-nav-container li#cat-" + $(this).attr("id")).text();
            //theText = theText + " (" + theNum + ")";
            //$(".internal-nav-container li#cat-" + $(this).attr("id")).text(theText);
            if ($(".internal-nav-container li#cat-" + $(this).attr("id")).hasClass("current")) {
                $("#label span").text(theNum);
                totalSet = 1;
            }
        });

        // set the total number of records found
        if (!totalSet) {
            $("#label span").text(theTotal);
        }
    }

    /************************************************************************************
    productClickSearchField - handles the "click" event on the "search part #" input
    on the product-listing.aspx file
    *************************************************************************************/
    function productClickSearchField() {

        if ($(this).val() == PROD_LISTING_SEARCH_STRING) {         //if the value is "search part #"
            $(this).val("");                                //empty the input
            $(this).attr("style", "color: black;");         //make the text color black
        }
    }

    /************************************************************************************
    productBlurSearchField - handles the "blur" event on the "search part #" input
    on the product-listing.aspx file
    - "blur" is when an input loses focus
    *************************************************************************************/
    function productBlurSearchField() {

        if (($(this).val() == "") || ($(this).val() == PROD_LISTING_SEARCH_STRING)) {   //if the value is empty or "search part #"
            $(this).val(PROD_LISTING_SEARCH_STRING);                                       //set the value to "search part #"
            $(this).attr("style", "color: #777");                            //make the text color #777
        }
    }

    function clearProductSearch() {

        $("#product-searchForm").val(PROD_LISTING_SEARCH_STRING);
        $("#product-searchForm").attr("style", "color: #777");

        //        productClickSearchField();
    }


    /************************************************************************************
    productClickSearchButton - handles the "click" event on the product search button
    *************************************************************************************/
    function productClickSearchButton() {

        if (($("#product-searchForm").val() == PROD_LISTING_SEARCH_STRING) || ($("#product-searchForm").val() == "")) {
            $("#content-products .pui-products tbody tr").show();
        } else {
            var searchString = $("#product-searchForm").val();
            searchString = searchString.split("-").join("");
            searchString = searchString.split(" ").join("");
            searchString = searchString.split("+").join("");
            $("#product-searchForm").val(searchString);


            var myRegEx = new RegExp(searchString, "i");

            $("#content-products .pui-products tbody tr td.part-number a").each(function() {
                var findInString = $(this).text();
                findInString = findInString.split("-").join("");
                findInString = findInString.split(" ").join("");

                if (findInString.search(myRegEx) > -1) {
                    $(this).parents("tr").show();
                } else {
                    $(this).parents("tr").hide();
                }
            });
            $('.pui-category').show();
        }
       
       
        zebraStripe();
        checkForNoResults();
        showNumResults();
    }

    function applyTableSort(categoryName) {
        var theTableID = "#" + categoryName;

        if (!$(theTableID + " .header").length) {   // if this table hasn't been sorted
            $(theTableID).tablesorter({
                widgets: ['zebra']
                //sortList: [[0, 0]]
            });
        }
    }

    $(".pui-category").hide();   // hide the tables on page load

    $('ul.sf-menu').superfish();


    function productKeyPressSearchField(event) {

        if (event.keyCode == '13') {
            productClickSearchButton();
        }
    }

    $("#product-searchForm").bind("keypress", productKeyPressSearchField);

    $(".clear-search").bind("click", clearFilter);
    $(".internal-nav li").bind("click", chooseCategory);

    $("#product-searchForm").bind("click", productClickSearchField);      //bind click for "search part #" input (product-listing.aspx)
    $("#product-searchForm").bind("blur", productBlurSearchField);        //bind blur for "search part #" input (product-listing.aspx)
    $("#product-listingSearch").bind("click", productClickSearchButton);  //bind click for the actual product search

    hideFilters();

    $("#product-searchForm").val(PROD_LISTING_SEARCH_STRING);
    $("#products-filter").show();


    var theCat = location.href.toLowerCase().split("category=")[1];   //get the category paramater
    var theNum = location.href.toLowerCase().split("quicksearchpart=")[1];   //get the quick part search number

    if (typeof (theCat) != "undefined") {
        if ($("#cat-" + theCat).length) {
            $("#cat-" + theCat).click();
        }
    }

    if (typeof (theNum) != "undefined") {
        $("#product-searchForm").val(theNum);
        $("#product-searchForm").attr("style", "color: black;");
    }

    productClickSearchButton();
}
);
