var $browse = {
    currency: false,
    increment: false,
    context: false,
    filter: {},
    categories: { context: false, items: false },
    slider: { context: false, min: false, max: false, increment: false },

    init: function() {
        if(!window.outlets) return;

        this.context = $('#mainContent2');
        this.slider.context = $('#optionSlider');
        this.slider.min = parseFloat(window.outlets.MinAmount);
        this.slider.max = parseFloat(window.outlets.MaxAmount);

        this.categories.context = $('#categorylist');
        this.categories.items = window.outlets.CategoryList;

        this.increment = (window.outlets.Increment/100) || 1;
        this.currency = (window.outlets.CurrencyRef && window.outlets.CurrencyRef === 'GBP') ? '&pound;' : '$';

        this.preparePriceRangeSlider();

        // only render category list if there is more than one
        if(this.categories.items.length > 1) {
            this.prepareCategories();
        }

        // details for rendered products
        this.loadProducts();
    },


    /* ------------------------------------------------ */
    /* loadProducts
    /* Adds fade animation to simulate loading
    /* ------------------------------------------------ */
    loadProducts: function() {
        var self = this;

        self.context.stop(true, true).animate({'opacity': 0.5}, 300, function() {
            self.renderProducts();
            self.context.animate({'opacity': 1}, 300);
        });
    },


    /* ------------------------------------------------ */
    /* preparePriceRangeSlider
    /* builds, initialises and binds events 
    /* to the price range slider
    /* ------------------------------------------------ */
    preparePriceRangeSlider: function() {
        var self = this, onSlide, onChange;

        if((self.slider.min == 0 && self.slider.max == 0) || (self.slider.min > self.slider.max)) {
            self.slider.context.empty();
            return;
        }

        if(self.slider.min === self.slider.max) {
            self.slider.context.children().not('h3, #categorylist').remove();
            self.slider.context.find('h3').after('<p>All products are <strong>' + self.currency + self.slider.min.toFixed(2) + '</strong></p>');
            return;
        }

        onSlide = function(e, ui) {
            self.slider.context.find('.currency-ref:eq(0)').html(self.currency + ui.values[0].toFixed(2));
            self.slider.context.find('.currency-ref:eq(1)').html(self.currency + ui.values[1].toFixed(2));        
        };

        onChange = function(e, ui) {
            self.slider.min = ui.values[0];
            self.slider.max = ui.values[1];

            self.loadProducts();
        };

        $('#slider').slider({
            min: self.slider.min,
            max: self.slider.max,
            values: [self.slider.min, self.slider.max],
            range: true,
            step: self.increment,
            slide: onSlide,
            change: onChange
        });
    },


    /* ------------------------------------------------ */
    /* prepareCategories
    /* builds checkbox list of categories and 
    /* adds them to DOM
    /* ------------------------------------------------ */
    prepareCategories: function() {
        var self = this, html = [], checkbox;

        $.each(self.categories.items, function(i, category) {
            checkbox = [
                '<li>',
                    '<input type="checkbox" value="' + i + '" id="category' + i + '" />',
                    '<label for="category' + i + '">' + category.name + '</label>',
                '</li>'
            ];
            
            html.push(checkbox.join(''));
        });

        self.categories.context.html('<ul>' + html.join('') + '</ul>');
        self.renderUncheckAllButton();

        // bind category click event
        self.categories.context.find('input[type=checkbox]').click(function() {
            if($(this).is(':checked')) {
                self.filter[this.value] = this.value;
            } else {
                delete self.filter[this.value];
            }

            self.loadProducts();
        });
    },


    /* ------------------------------------------------ */
    /* renderUncheckAllButton
    /* builds 'uncheck all' button and appends it to DOM
    /* ------------------------------------------------ */
    renderUncheckAllButton: function() {
        var self = this, 
            uncheck = $('<a href="#" class="clearAll_slider">Clear All</a>');

        // Uncheck All button
        uncheck.click(function(e) {
            e.preventDefault();

            var checked = self.categories.context.find('input:checked');;
            if(!checked.length) return;

            // clear filter
            self.filter = {};

            checked.attr('checked', false);
            self.loadProducts();
        }).appendTo(self.categories.context);
    },


    /* ------------------------------------------------ */
    /* renderProducts
    /* builds and appends html for products to DOM
    /* ------------------------------------------------ */
    renderProducts: function() {
        var self = this, html = [];

        $.each(self.categories.items, function(c, category) {
            var productHtml = [];

            // if the filter has values and this category 
            // isn't in it then don't go any further
            if(!$.isEmptyObject(self.filter) && !self.filter[c]) return;

            $.each(category.ProductList, function(p, product) {
                var price = $(product.price), template;

                price = price[price.length - 1].firstChild.nodeValue;
                price = price.replace(/.([0-9+\.0-9]+)/, '$1');

                // don't go any further if the price isn't within the slider range
                if (price < self.slider.min || price > self.slider.max) return;

                template = [
                    '<li class="thebox">',
                        '<a href="ProductDetails.aspx?ProductRef=' + product.styleRef + '&amp;Option=' + product.optionCode + '">',
                            '<img src="/Assets/ProductImages/110/' + product.image + '" width="110" height="110" alt="' + product.name + '" />',
                            '<span class="title">' + product.name + '</span>',
                            product.price,
                        '</a>',
                    '</li>'
                ];

                productHtml.push(template.join(''));
            });

            if(productHtml.length) {
                html.push('<h3 class="catHead">' + category.name + '</h3>');
                html.push('<ul class="catBlock">');
                html.push(productHtml.join(''));
                html.push('</ul>');
            }
        });

        if(html.length) {
            self.context.html(html.join(''));
        } else {
            self.context.html('<p>Unfortunately we do not have any products that match your search criteria.</p>');
        }
    }
};

$(function() {
    $browse.init();
});