﻿(function ($) {
    jQuery.nptFilter = (function () {
        var _selectedSizes = {},
        _selectedColors = {},

        _sizeText = "Storlek",
        _colorText = "Färg",
        _genderText = "Damherr",
        _sortText = "OrderBy",

        _lastSaved = {},
        _activeTab = "",

        _filterOptions,

        _updateData = function (data) {
        },

        _updateUrl = function (data) {
            $.address.queryString(url.substr(url.indexOf("?") + 1).replace(/%2c/g, ","));
            $.address.update()
        },

        _initAttributes = function () {
            var cookieData = _loadCookieAttributes();
            if (typeof cookieData == "object") {
                arrSizes = cookieData.sizes.split(",");

                for (var i = 0; i < arrSizes.length; i++) {
                    if (arrSizes[i] != "")
                        $('.attribute-values a[href^="#' + _sizeText + '\,' + arrSizes[i] + '"]').addClass('active').removeClass('inactive');
                }

                arrColors = cookieData.colors.split(",");

                for (var i = 0; i < arrColors.length; i++) {
                    if (arrColors[i] != "")
                        $('.attribute-values a[href^="#' + _colorText + '\,' + arrColors[i] + '"]').addClass('active').removeClass('inactive');
                }

                arrGender = cookieData.gender.split(",");

                for (var i = 0; i < arrGender.length; i++) {
                    if (arrGender[i] != "")
                        $('.attribute-values a[href^="#' + _genderText + '\,' + arrGender[i] + '"]').addClass('active').removeClass('inactive');
                }

                if (typeof cookieData.sort == "undefined") {
                    $(".sorting-active").removeClass("sorting-active");
                    $('a.sort-link[href^="#' + 0 + '"]').parent().addClass('sorting-active');
                }
                else {
                    $(".sorting-active").removeClass("sorting-active");
                    $('a.sort-link[href^="#' + cookieData.sort + '"]').parent().addClass('sorting-active');
                }

                return (true);  // return that cookie was loaded
            }

            return (false); // no cookie!
        },

        _loadAttributesFromHtml = function () {
            var data = new Object();
            var filters = new Array();
            var sortOrder = 0;

            $(".attribute-values a.active[href=^#]").each(function () {
                var $this = $(this);

                var splitStr = $this.attr('href').replace(/^#/, '');
                var variant = splitStr.split(",")[0];
                var attributeValue = splitStr.split(",")[1];

                if (typeof (filters[variant]) == 'undefined')
                    filters[variant] = new Array();

                var idx = filters[variant].indexOf(attributeValue); // Find the index
                if (idx == -1) {
                    filters[variant].push(attributeValue);
                }
            });

            $(".sorting-active a.sort-link[href=^#]").each(function () {
                var $this = $(this);
                sortOrder = $this.attr('href').replace(/^#/, '');
            });

            if (typeof filters[_sizeText] == "undefined") {
                data.sizes = new Array();
            }
            else {
                data.sizes = filters[_sizeText];
            }
            if (typeof filters[_colorText] == "undefined") {
                data.colors = new Array();
            }
            else {
                data.colors = filters[_colorText];
            }
            if (typeof filters[_genderText] == "undefined") {
                data.gender = new Array();
            }
            else {
                data.gender = filters[_genderText];
            }
            data.sort = sortOrder;

            return data;
        },

        _initFromHistory = function () {
        },

        _attributeClicked = function (a) {
            $(a).toggleClass("active").toggleClass("inactive");

            var data = _loadAttributesFromHtml();

            _saveCookieAttributes(data);
            _updateGrid(data);
        },

        _sortingClicked = function (a) {
            if ($(a).parent().hasClass("sorting-active"))   // don't do nothing if already selected
                return;

            $(".sorting-active").removeClass("sorting-active");
            $(a).parent().toggleClass("sorting-active");

            var data = _loadAttributesFromHtml();

            _saveCookieAttributes(data);
            _updateGrid(data);
        },

        _addEvents = function () {
            $('.attribute-values a[href^=#]').live('click', function (e) {
                e.preventDefault();
                _attributeClicked(this);
                window.location = replaceLink(window.location.href);
            });

            $(".sorting a[href^=#]").live('click', function (e) {
                e.preventDefault();
                _sortingClicked(this);
            });
        },

        _getActiveTab = function () {
            if (_activeTab == "") {
                _activeTab = $.cookie("activeTab");
            }
            return _activeTab;
        },

        _setActiveTab = function (tab) {
            _activeTab = tab;
            $.cookie("activeTab", tab, { expires: 7, path: "/" });
        },

        _activateTab = function () {
            $(_getActiveTab()).toggle();
        },

        _updateGrid = function (pData, noAddressUpdate) {

            var data, action, attributes;

            if (pData === "undefined") {
                data = {};
            }
            else {
                data = pData;
            }

            action = "/ajax/getproducts";

            if (typeof data.sort === "undefined") {
                data.sort = "0";

                // search and select sortorder from page
            }

            // this holds all attributes
            //attributes = _loadCookieAttributes();

            if (typeof data.sizes === "undefined" || typeof data.colors === "undefined" || typeof data.gender === "undefined") {
                // sizes and/or colors empty, load from html (cookie?)
                var tempData = _loadAttributesFromHtml();
                data.sizes = tempData.sizes;
                data.colors = tempData.colors;
                data.gender = tempData.gender;
            }

            if (!noAddressUpdate)
                _updateAddressBar(data);

            if (typeof _filterOptions.onUpdate == "function") {
                _filterOptions.onUpdate.call(this, _renderParamString(data));
            }


        },

        _renderParamString = function (data) {
            var returnStr = "";

            if (typeof data.sizes !== "undefined") {
                returnStr = returnStr + _sizeText + "=" + data.sizes;
            }

            if (typeof data.colors !== "undefined") {
                if (returnStr != "")
                    returnStr = returnStr + "&";
                returnStr = returnStr + _colorText + "=" + data.colors;
            }


            if (typeof data.gender !== "undefined") {
                if (returnStr != "")
                    returnStr = returnStr + "&";
                returnStr = returnStr + _genderText + "=" + data.gender;
            }
            if (typeof data.sort !== "undefined") {
                if (returnStr != "")
                    returnStr = returnStr + "&";
                returnStr = returnStr + _sortText + "=" + data.sort;
            }

            return returnStr;
        },

        _saveCookieAttributes = function (cookiedata) {
            var category = $(".category .active");
            if (category.length === 1) {
                $.cookie(category.text() + "-sizes", cookiedata.sizes, { expires: 7, path: "/" });
                $.cookie(category.text() + "-colors", cookiedata.colors, { expires: 7, path: "/" });
                $.cookie(category.text() + "-gender", cookiedata.gender, { expires: 7, path: "/" });
                _lastSaved = cookiedata;
            }
            $.cookie("sort", cookiedata.sort, { expires: 7, path: "/" });
        },

        _loadCookieAttributes = function () {
            //retrieve active catagory
            var category = $(".category .active");
            var data = new Object();

            data.sort = $.cookie("sort");
            if ((typeof data.sort == "undefined") || (data.sort == null)) {
                data.sort = 0;
            }

            if (category.length === 1) {
                data.sizes = $.cookie(category.text() + "-sizes");
                data.colors = $.cookie(category.text() + "-colors");
                data.gender = $.cookie(category.text() + "-gender");

                if ((typeof data.sizes == "undefined") || (data.sizes == null)) {
                    data.sizes = "";
                }
                if ((typeof data.colors == "undefined") || (data.colors == null)) {
                    data.colors = "";
                }
                if ((typeof data.gender == "undefined") || (data.gender == null)) {
                    data.gender = "";
                }

                return data;
            }
        },

        _loadFromUrl = function (parameterNames, parameters) {
            var bFoundSizes, bFoundColors, bFoundGender, data = new Object;
            // Loads data from url when changed externaly
            for (i = 0; i < parameterNames.length; i = i + 1) {
                if (parameters[parameterNames[i]].indexOf("%2C") !== -1) {
                    parameters[parameterNames[i]] = parameters[parameterNames[i]].replace(/%2C/g, ",")
                }
            }
            bFoundSizes = parameterNames.indexOf("sizes") != -1;
            if (bFoundSizes) {
                data.sizes = parameters["sizes"];
            }
            else
                data.sizes = "";

            bFoundColors = parameterNames.indexOf("colors") != -1;
            if (bFoundColors) {
                data.colors = parameters["colors"];
            }
            else
                data.colors = "";

            bFoundGender = parameterNames.indexOf("gender") != -1;
            if (bFoundGender) {
                data.gender = parameters["gender"];
            }
            else
                data.gender = "";

            bFoundSort = parameterNames.indexOf("sort") != -1;
            if (bFoundSort) {
                data.sort = parameters["sort"];
            }
            else
                data.sort = 0;

            // handle active tab?
            return data;
        },

        _updateAddressBar = function (data) {
            $.address.queryString("");
            for (key in data) {
                if (data.hasOwnProperty(key)) {
                    $.address.parameter(key, data[key])
                }
            }
            // HANDLE ACTIVE TAB?
            /*
            if (activeTab.length == 1) {
            $.address.parameter("activeTab", activeTab.attr("id"))
            }
            */
            $.address.update()
        }
        ;

        return {
            init: function (options) {
                var hasCookie, data;

                var defaults = {
                    checkFilterEnabled: true,
                    checkFilterEnabledDiv: "#filter-enabled"
                };
                _filterOptions = $.extend(defaults, options);

                if (_filterOptions.checkFilterEnabled) {
                    $(_filterOptions.checkFilterEnabledDiv)
                }

                hasCookie = _initAttributes();

                if (hasCookie) {
                    data = _loadCookieAttributes();
                }
                else {
                    data = _loadAttributesFromHtml();
                }

                _addEvents();

                _activateTab();

                //_updateGrid(data, true);
                if (typeof $.address != 'undefined') {
                    $.address.init(function (event) { }).externalChange(function (event) {
                        if ($.address.queryString.length > 0) {
                            var urlData = _loadFromUrl(event.parameterNames, event.parameters);
                            _saveCookieAttributes(urlData);
                            _initAttributes();
                            _updateGrid(urlData);
                        }
                        else {
                            // don't need to load from url, lead from cookie?
                        }
                    }).autoUpdate(false);
                }
            },   //end init
            setActiveTab: function (tab) {
                _setActiveTab(tab);
            }
        }   // end return
    })()    // en function $fn.nptFilter
})(jQuery);

$(function () {
    $("body").delegate(".product-pager", "hover", function () {
        var newlink;
        
        $(".product-pager a").each(function () {
            if ($(this).attr("baseref") === undefined) {
                $(this).attr("baseref", $(this).attr("href"));
            }
            
            $(this).attr("href", buildLink($(this).attr("baseref")));
        });
    });
});

function buildLink(link) {
    return link + "#/?" + $.address.queryString()
}

function replaceLink(link) {
    return link.replace(/pageindex=[\d]+/, "pageindex=1");
}

//var filters = new Array();
//var activeTab = '';

//// Adds a filter to an attribute
//function AddFilter(variant, value) {
//    if (typeof (filters[variant]) == 'undefined')
//        filters[variant] = new Array();

//    var idx = filters[variant].indexOf(value); // Find the index
//    if (idx == -1)
//    {
//        filters[variant].push(value);
//        //alert("Add " + value + " to " + variant);
//    }
//    /*
//    else
//        alert("Exist: " + value + " to " + variant);
//    */
//}

//function RemoveFilter(variant, value) {
//    if (typeof (filters[variant]) == 'undefined')
//        filters[variant] = new Array();

//    var idx = filters[variant].indexOf(value); // Find the index
//    if (idx != -1) filters[variant].splice(idx, 1); // Remove it if really found!
//}

//// Marks all the objects in the active filter
//function SetHash() {
//    var state = {};
//    for (key in filters) {
//        state[key] = filters[key].join(",");
//    }

//    state['activeTab'] = activeTab;

//    $.bbq.pushState(state);
//}

//function LoadHashToFilter(variant) {
//    var s = $.bbq.getState(variant) || '';
//    var arrayStr = s.split(',');
//    for (value in arrayStr) {
//        AddFilter(variant, arrayStr[value]);
//    }
//}

//function SetActiveTab(tabId) {
//    activeTab = tabId;
//}

//// Loads the page based on filter
//function LoadListPage() {

//}

//function GetFilterString() {
//    var str = "";
//    for (variant in filters) {
//        if (filters[variant].length > 0) {
//            if (str != "")
//                str = str + "&";
//            str = str + variant + "=";
//            for (value in filters[variant]) {
//                str = str + filters[variant][value] + ",";
//            }
//        }
//    }
//    return str;
//}

//function debug($obj) {
//    if (window.console && window.console.log)
//        window.console.log('filter is:' + filters);
//};

//////
////// create closure
//////
////(function ($) {

////    // plugin def
////    $.fn.sysfilter = function (options) {
////        debug(this);

////        var opts = $.extend({}, $.fn.sysfilter.defaults, options);

////        return this.each(function () {
////            var $this = $(this);

////            $this.click(function () {
////                // check if active
////                if ($this.hasClass(opts.ActiveCssClass)) {
////                    //Remove filter
////                    RemoveFilter(

////                    $this.removeClass(opts.ActiveCssClass);
////                    $this.addClass(opts.DeActiveCssClass);
////                }
////                else if ($this.hasClass(opts.DeActiveCssClass)) {
////                    // add filter

////                    $this.removeClass(opts.DeActiveCssClass);
////                    $this.addClass(opts.ActiveCssClass);
////                }

////                LoadListPage();
////            });
////        });
////    };

////    function debud($obj) {
////        if (window.console && window.console.log)
////            window.console.log('sysfilter selection count: ' + $obj.size());
////    };

////    $.fn.sysfilter.defaults = { ActiveCssClass: 'active', DeActiveCssClass: 'deactive', targetDiv: 'productList' }

////    var filters = {
////        '': ''
////    }

////    // Adds a filter to an attribute
////    function AddFilter(variant, value) {

////    }

////    function RemoveFilter(variant, value) {
////    }

////    // Marks all the objects in the active filter
////    function MarkActiveFilter() {
////    }

////    // Loads the page based on filter
////    function LoadListPage() {
////    }
////})(jQuery);
