﻿
$(document).ready(function () {

    var _searchCompareSkusCurrent = collectSearchCompareSelections(true, false);
    setupSearchCheckboxes();

    initShowMore();
    initShowMoreCategories();
    initPagingCompare();
    initSearchResultsCompare();

    function initShowMore() {
        $("li.hide").hide();
        $("li.more").show().click(function () {
            $(this).hide().closest("ul").find(".hide").show();
            return false;
        });
    }

    function initShowMoreCategories() {
        if ($("#more-attributes").length) {
            $("div.hide,ul.hide").hide();
            $("#more-attributes").show().click(function () {
                $(this).hide();
                $("div.hide,ul.hide").show();
                return false;
            });
        }
    }

    function initSearchResultsCompare() {

        if ($("#search-results").length) {

            // handle compare checkbox clicks
            $("td.compare-col input").click(function () {
                setSelectedSkus();
                setupSearchCheckboxes();
            });

            // handle sorting dropdown changes
            $(".searchSortOptions").change(function () {
                //rebuild URL with sort and compare params and go to it
                var selectedSortVal = $(".searchSortOptions").val();
                var sortLocationTemp = window.location.href;
                var sortLocationFinal = "";
                var querySortVal = "";
                (window.location.href.indexOf('sort=') >= 0) ? querySortVal = getSearchUrlVars()["sort"] : querySortVal = "";
                if (window.location.href.indexOf('sort=') == -1) {
                    sortLocationFinal = sortLocationTemp + "&sort=" + selectedSortVal;
                }
                else {
                    sortLocationFinal = sortLocationTemp.replace('sort=' + querySortVal, 'sort=' + selectedSortVal);
                }
                sortLocationTemp = sortLocationFinal;
                var queryCompareVal = "";
                (window.location.href.indexOf('compare=') >= 0) ? queryCompareVal = getSearchUrlVars()["compare"] : queryCompareVal = "";
                if (window.location.href.indexOf('compare=') == -1) {
                    sortLocationFinal = sortLocationTemp + "&compare=" + _searchCompareSkusCurrent;
                }
                else {
                    sortLocationFinal = sortLocationTemp.replace('compare=' + queryCompareVal, 'compare=' + _searchCompareSkusCurrent);
                }
                sortLocationTemp = sortLocationFinal;
                window.location = sortLocationFinal;
                return false;
            });


            // handle compare
            $(".compare").click(function () {
                var currentCompareSkus = _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;
                    }
                }
                return false;
            });

        }

    }

    function initPagingCompare() {

        //attach all paging related child links
        $('div.paging > a').click(function () {

            var newURL = this.href;
            if (_searchCompareSkusCurrent != '') {
                newURL = this.href + '&compare=' + _searchCompareSkusCurrent;
            }

            window.location = newURL;

            return false

        });

    }

    function collectSearchCompareSelections(urlValues, checkboxValues) {

        var finalSKUs = '';
        var allChecked = '';
        var compareSkusURL = '';

        if (urlValues) {
            // Getting URL compare SKUs
            compareSkusURL = getSearchUrlVars()["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 (isSkuFound($(this).val(), _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;

    }

    function getSearchUrlVars() {
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for (var i = 0; i < hashes.length; i++) {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }

    function isSkuFound(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;

    }

    function setupSearchCheckboxes() {

        var currentCompareSkus = _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 (isSkuFound($(this).val(), _searchCompareSkusCurrent) == true) {
                    $(this).attr("disabled", false);  //enable it so it can be removed
                    $(this).attr("checked", true); //check it
                }
            });
        }

        return true

    }

    function setSelectedSkus() {

        //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 (isSkuFound($(this).val(), _searchCompareSkusCurrent) == false) {
                    (_searchCompareSkusCurrent.length == 0) ? _searchCompareSkusCurrent += $(this).val() : _searchCompareSkusCurrent += ',' + $(this).val();
                }
            });
        }

        //remove unchecked Skus 
        var $comparedRemoved = $("td.compare-col input:not(:checked)");
        if ($comparedRemoved.length > 0) {
            $comparedRemoved.each(function () {
                if (isSkuFound($(this).val(), _searchCompareSkusCurrent) == true) {
                    var replaceVal = $(this).val();
                    var tempSkus = _searchCompareSkusCurrent;
                    _searchCompareSkusCurrent = tempSkus.replace(replaceVal, "");
                }
            });
        }

        //fix the final variable for bad commas before final setting
        var tempSkusFinal = _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) ? _searchCompareSkusCurrent = tempSkusFinal.substring(1) : _searchCompareSkusCurrent = tempSkusFinal; //fixing prepended comma if needed
        }

        return true;

    }

});

