﻿SSI.Search = {
    searchCompareSkusCurrent: null,
    init: function () {
        this.searchCompareSkusCurrent = this.collectSearchCompareSelections(true, false);
        this.setupSearchCheckboxes();
        this.initSearchResultsCompare();
        this.showMore();
        this.showMoreCategories();

        // handlers
        $("#refine-current a").click(this.onRefinementRemoveClick);
        $('div.paging > a').click(this.onPagingClick);

    },
    setupSearchCheckboxes: function () {

        var currentCompareSkus = SSI.Search.searchCompareSkusCurrent;
        var compareCount;
        (currentCompareSkus == '') ? compareCount = 0 : compareCount = currentCompareSkus.split(',').length;

        //enable/disable all if needed        
        if (compareCount > 3) {
            $("td.compare-col input:not(:checked)").attr("disabled", true);
        } else {
            $("td.compare-col input").attr("disabled", false);
        }

        //check for existing SKUs on the page - if there enable/select them
        var $pageCheckboxes = $("td.compare-col input");
        if ($pageCheckboxes.length > 0) {
            $pageCheckboxes.each(function () {
                //check if it is in the existing SKUs already - add it if not
                if (SSI.Search.isSkuFound($(this).val(), SSI.Search.searchCompareSkusCurrent) == true) {
                    $(this).attr("disabled", false);  //enable it so it can be removed
                    $(this).attr("checked", true); //check it
                }
            });
        }

        return true;

    },
    initSearchResultsCompare: function () {

        if ($("#search-results").length) {

            // handle compare checkbox clicks
            $("td.compare-col input").click(function () {
                SSI.Search.setSelectedSkus();
                SSI.Search.setupSearchCheckboxes();
            });

            // handle sorting dropdown changes
            $(".searchSortOptions").change(function (e) {
                e.preventDefault();
                var sortedUrl = window.location.pathname + '?sort=' + $(".searchSortOptions").val(),
                    params = SSI.Utilities.getQuerystringParams(),
                    pageParam = params["page"],
                    compareParam = params["compare"] || SSI.Search.searchCompareSkusCurrent;

                if (pageParam) {
                    sortedUrl += '&page=' + pageParam;
                }
                if (compareParam) {
                    sortedUrl += '&compare=' + compareParam;
                }

                window.location = sortedUrl;
            });


            // handle compare
            $(".compare").click(function (e) {
                e.preventDefault();
                var currentCompareSkus = SSI.Search.searchCompareSkusCurrent;
                var compareCount;
                (currentCompareSkus == '') ? compareCount = 0 : compareCount = currentCompareSkus.split(',').length;

                if (compareCount < 2) {
                    alert("Please check at least two products to compare.");
                }
                else {
                    if (compareCount > 4) {
                        alert("A maximum of 4 products only can be compared.");
                    }
                    else {
                        window.location = "/compare.aspx?skus=" + currentCompareSkus;
                    }
                }
            });

        }

    },
    isSkuFound: function (findSku, existingSkus) {
        var isFound = false;
        if (existingSkus != '') {
            var skuList = existingSkus.split(',');
            for (var i = 0; i < skuList.length; i++) {
                if (skuList[i] == findSku) {
                    isFound = true;
                    break;
                }
            }
        }
        return isFound;
    },
    collectSearchCompareSelections: function (urlValues, checkboxValues) {

        var finalSKUs = '',
            allChecked = '',
            compareSkusURL = '';

        if (urlValues) {
            // Getting URL compare SKUs
            compareSkusURL = SSI.Utilities.getQuerystringParams()["compare"];
            if (compareSkusURL == null) {
                compareSkusURL = '';
            }
        }

        if (checkboxValues) {
            //collect checkbox Skus
            var $comparedCheckboxes = $("td.compare-col input:checked");
            if ($comparedCheckboxes.length > 0) {
                $comparedCheckboxes.each(function () {
                    //check if it is in the existing SKUs already - add it if not
                    if (SSI.Search.isSkuFound($(this).val(), SSI.Search.searchCompareSkusCurrent) == false) {
                        allChecked += ',' + $(this).val();
                    }
                });
                allChecked = allChecked.substring(1);
            }
        }

        //append skus as needed
        if ((compareSkusURL != '') && (allChecked != '')) {
            finalSKUs = compareSkusURL + ',' + allChecked;
        }
        if ((compareSkusURL == '') && (allChecked != '')) {
            finalSKUs = allChecked;
        }
        if ((compareSkusURL != '') && (allChecked == '')) {
            finalSKUs = compareSkusURL;
        }

        return finalSKUs;

    },
    setSelectedSkus: function () {

        //add the selected SKUs
        var $comparedSelected = $("td.compare-col input:checked");
        if ($comparedSelected.length > 0) {
            $comparedSelected.each(function () {
                //check if it is in the existing SKUs already - add it if not
                if (SSI.Search.isSkuFound($(this).val(), SSI.Search.searchCompareSkusCurrent) == false) {
                    (SSI.Search.searchCompareSkusCurrent.length == 0) ? SSI.Search.searchCompareSkusCurrent += $(this).val() : SSI.Search.searchCompareSkusCurrent += ',' + $(this).val();
                }
            });
        }

        //remove unchecked Skus 
        var $comparedRemoved = $("td.compare-col input:not(:checked)");
        if ($comparedRemoved.length > 0) {
            $comparedRemoved.each(function () {
                if (SSI.Search.isSkuFound($(this).val(), SSI.Search.searchCompareSkusCurrent) == true) {
                    var replaceVal = $(this).val();
                    var tempSkus = SSI.Search.searchCompareSkusCurrent;
                    SSI.Search.searchCompareSkusCurrent = tempSkus.replace(replaceVal, "");
                }
            });
        }

        //fix the final variable for bad commas before final setting
        var tempSkusFinal = SSI.Search.searchCompareSkusCurrent;
        if (tempSkusFinal.length > 0) {
            var arrFinal = tempSkusFinal.split(",")
            tempSkusFinal = "";
            for (var i = 0; i < arrFinal.length; i++) {
                if (arrFinal[i] != "") {
                    tempSkusFinal += "," + arrFinal[i];
                }
            }
            (tempSkusFinal.length > 0) ? SSI.Search.searchCompareSkusCurrent = tempSkusFinal.substring(1) : SSI.Search.searchCompareSkusCurrent = tempSkusFinal; //fixing prepended comma if needed
        }

        return true;

    },
    showMore: function () {
        $("li.hide").hide();
        $("li.more").show().click(function (e) {
            e.preventDefault();
            $(this).hide().closest("ul").find(".hide").show();
            return false;
        });
    },
    showMoreCategories: function () {
        if ($("#more-attributes").length) {
            $("div.hide,ul.hide").hide();
            $("#more-attributes").show().click(function () {
                $(this).hide();
                $("div.hide,ul.hide").show();
                return false;
            });
        }
    },
    onRefinementRemoveClick: function () {
        if ($(this).parent().siblings().length === 0) {
            alert("You cannot remove the last search refinement.");
            return false;
        }
    },
    onPagingClick: function (e) {
        e.preventDefault();
        var newURL = this.href;
        if (SSI.Search.searchCompareSkusCurrent != '') {
            newURL = this.href + '&compare=' + SSI.Search.searchCompareSkusCurrent;
        }
        window.location = newURL;
    }
};

$(function () {
    SSI.Search.init();
});

