
function filterAjax(url) {
    'use strict';

    var requestUrl = '/browse/ajax.php';

    if (doAjax) {
        $.ajax({
            url: requestUrl,
            type: 'post',
            data: {url: url},
            dataType: 'json',
            beforeSend: function () {
                doAjax = false;
                $('#loadingOverlay').fadeIn(500);
            },
            complete: function () {
                doAjax = true;
                $('#loadingOverlay').fadeOut(500);

                $('select').chosen({
                    disable_search_threshold: 8
                });

            },
            success: function (response) {
                if (typeof response.redirect === 'undefined') {
                    filterUpdatecontent(response);
                    try {
                        window.history.pushState({'pageTitle': document.title, 'response': response}, '', url);
                    }
                    catch (ex) {
                        window.location.href = url;
                    }
                    initFilter();
                } else {
                    doAjax = true;
                    filterAjax(response.redirect);
                }

            }
        });
    }

}

function filterUpdatecontent(response) {
    'use strict';

    $('#productFilterSelections').html(response.selections_html);

    if(!$.trim(response.selections_html).length) {
        $('#productFilterSelections').parent().hide();
    }else{
        $('#productFilterSelections').parent().show();
    }
    $('#productFilterCategories').html(response.category_html);
    $('#productFilterBrands').html(response.brands_html);
    $('#productFilterSizes').html(response.sizes_html);
    $('#productFilterItems').html(response.items_html);
    $('#productFilterPageNumbersBottom').html(response.pagenumber_html);
    $('#productFilterPageNumbers').html(response.pagenumber_html);
    $('#productFilterSort').html(response.sort_html);
    $('#productFilterBreadcrumbs').html(response.breadcrumbs_html);
    $('#productFilterGenders').html(response.genders_html);
    $('#productFilterPrice').html(response.price_html);
    $('#productFilterTitle').html(response.title_html);
    $('#productCount .number').html(response.product_count);

    if (typeof response.properties_html !== 'undefined') {
        $.each(response.properties_html, function (key, value) {
            var $thePropertyContainer = $('#productFilter_properties_' + key);

            if ($thePropertyContainer.length) {
                $thePropertyContainer.html(value);
            }
        });
    }

    try {
        document.title = response.seo_title;
    } catch (e) {
    }

    initFilter();

    //quickAddToBasketInit();
}


/*
* jQuery UI - Range Slider
*/
function rangeSlider() {

    'use strict';

    var $rangeSliders = $('.rangeSlider');

    if($rangeSliders.length) {

        $rangeSliders.each(function(){


            var $slider = $(this),
                minValue = parseFloat($slider.find('.minPrice').attr('min')),
                maxValue = parseFloat($slider.find('.maxPrice').attr('max')),
                currentMin = parseFloat($slider.find('.minPrice').val()),
                currentMax = parseFloat($slider.find('.maxPrice').val());

            //Reset sliders
            if($slider.find('.rangeSliderField').hasClass('.ui-slider')) {
                $slider.find('.minPrice,.maxPrice').off('change').off('paste keyup');
                $slider.find('.rangeSliderField').slider('destroy');
            }

            //Set min/max prices
            if(isNaN(minValue)) {
                minValue = 0;
            }

            if(isNaN(maxValue)) {
                maxValue = 999;
            }

            if(isNaN(currentMin)) {
                currentMin = minValue;
            }

            if(isNaN(currentMax)) {
                currentMax = maxValue;
            }


            $slider.find('.minPrice,.maxPrice').on('change', function () {

                var minPriceRange = parseInt($slider.find('.minPrice').val()),
                    maxPriceRange = parseInt($slider.find('.maxPrice').val());

                if (minPriceRange > maxPriceRange) {
                    $slider.find('.maxPrice').val(minPriceRange);
                }

                if($slider.find('.rangeSliderField').hasClass('ui-slider')) {

                    $slider.find('.rangeSliderField').slider({
                        values: [minPriceRange, maxPriceRange]
                    });

                }

                if($('#filter_price_min').length) {
                    $('#filter_price_min').val($slider.find('.minPrice').val());
                }
                if($('#filter_price_max').length) {
                    $('#filter_price_max').val($slider.find('.maxPrice').val());
                }

            }).on('paste keyup', function () {

                if(!$slider.find('.rangeSliderField').hasClass('ui-slider')) {
                    return false;
                }

                var minPriceRange = parseInt($slider.find('.minPrice').val()),
                    maxPriceRange = parseInt($slider.find('.maxPrice').val());

                if (minPriceRange === maxPriceRange) {

                    maxPriceRange = minPriceRange + 1;
                    $slider.find('.minPrice').val(minPriceRange);
                    $slider.find('.maxPrice').val(maxPriceRange);

                }else if (minPriceRange > maxPriceRange) {
                    $slider.find('.maxPrice').val(minPriceRange + 1);
                }

                if($slider.find('.rangeSliderField').hasClass('ui-slider')) {

                    $slider.find('.rangeSliderField').slider({
                        values: [minPriceRange, maxPriceRange]
                    });
                }

                if($('#filter_price_min').length) {
                    $('#filter_price_min').val($slider.find('.minPrice').val());
                }
                if($('#filter_price_max').length) {
                    $('#filter_price_max').val($slider.find('.maxPrice').val());
                }

            });

            var handleMin = $slider.find('.minHandle'),
                handleMax = $slider.find('.maxHandle');

            $slider.find('.rangeSliderField').slider({
                range: true,
                orientation: "horizontal",
                min: minValue,
                max: maxValue,
                values: [currentMin, currentMax],
                step: 1,

                slide: function (event, ui) {

                    if (ui.values[0] == ui.values[1]) {
                        return false;
                    }

                    handleMin.find('.valWrap').text(ui.values[0]);
                    handleMax.find('.valWrap').text(ui.values[1]);

                    $slider.find('.minPrice').val(ui.values[0]);
                    $slider.find('.maxPrice').val(ui.values[1]);

                    if($('#filter_price_min').length) {
                        $('#filter_price_min').val(ui.values[0]);
                    }
                    if($('#filter_price_max').length) {
                        $('#filter_price_max').val(ui.values[1]);
                    }
                },
                create: function () {
                    handleMin.find('.valWrap').text($(this).slider('value'));
                    handleMax.find('.valWrap').text(currentMax);
                }

            });

            $slider.find('.minPrice').val($slider.find('.rangeSliderField').slider('values', 0));
            $slider.find('.MaxPrice').val($slider.find('.rangeSliderField').slider('values', 1));


        });

    }

}



function initFilter() {
    'use strict';

    $('.jshideme').hide();

    //Drop Downs
    $('.fdropdown').change(function () {
        var url = $(this).children('option:selected').val();

        filterAjax(url);
    });


    //Price text box change
    /*
    $('.fprice').change(function () {
        var url = $('#filter_current_url').val(),
            min = parseFloat($('#filter_price_min').val()),
            minRange = parseFloat($('#filter_price_min_range').val()),
            max = parseFloat($('#filter_price_max').val()),
            maxRange = parseFloat($('#filter_price_max_range').val()),
            filter_currency_ratio = $('#filter_currency_ratio').val(),
            priceUrlFirstChar = '',
            tempNum = 0;

        //remove current price range form the url
        url = url.replace(/&?price_(min|max)=[^&]+/g, '');
        url = url.replace(/\?&?$/, '');

        //swap min and max if min is more than max
        if (min > max) {
            tempNum = min;
            min = max;
            max = tempNum;
        }

        //if the price range filter is required, add it to the url
        if (min >= minRange || max <= maxRange) {
            if (url.indexOf('?') > -1) {
                priceUrlFirstChar = '&';
            } else {
                priceUrlFirstChar = '?';
            }

            url += priceUrlFirstChar + 'price_min=' + min + '&price_max=' + max;
        }
        console.log(url, min, minRange, max, maxRange);

        //ajax time
        filterAjax(url);
    });
    */

    //Update filter price on button click
    $('#updateFilter').on('click', function() {

        var url = $('#filter_current_url').val(),
            min = parseFloat($('#filter_price_min').val()),
            minRange = parseFloat($('#filter_price_min_range').val()),
            max = parseFloat($('#filter_price_max').val()),
            maxRange = parseFloat($('#filter_price_max_range').val()),
            filter_currency_ratio = $('#filter_currency_ratio').val(),
            priceUrlFirstChar = '',
            tempNum = 0;

        //remove current price range form the url
        url = url.replace(/&?price_(min|max)=[^&]+/g, '');
        url = url.replace(/\?&?$/, '');

        //swap min and max if min is more than max
        if (min > max) {
            tempNum = min;
            min = max;
            max = tempNum;
        }

        //if the price range filter is required, add it to the url
        if (min >= minRange || max <= maxRange) {
            if (url.indexOf('?') > -1) {
                priceUrlFirstChar = '&';
            } else {
                priceUrlFirstChar = '?';
            }

            url += priceUrlFirstChar + 'price_min=' + min + '&price_max=' + max;
        }

        //ajax time
        filterAjax(url);

    });

    //Update range slider
    rangeSlider();

    // If a link is clicked
    $('.js_filterLink').on('click', function (e) {

        e.stopImmediatePropagation();
        e.preventDefault();

        var id = $(this).attr('id'),
            currency_ratio = $('#filter_currency_ratio').val(),
            url = $(this).attr('href') + (typeof currency_ratio === 'undefined' ? '' : '&currency_ratio=' + currency_ratio);

        // Set the checbox to clicked
        $('#' + id + '_chk').attr('checked', true);

        if ($(this).parents('#productFilterPageNumbers').length) {
            $('html, body').animate({scrollTop: 0}, 'slow');
        }

        filterAjax(url);


    });

    $('.ftick').on('click', function (e) {
        e.stopImmediatePropagation();

        var id = $(this).attr('id'),
            link_id = id.replace('_chk', ''),
            currency_ratio = $('#filter_currency_ratio').val(),
            url = $('#' + link_id).attr('href') + (typeof currency_ratio === 'undefined' ? '' : '&currency_ratio=' + currency_ratio);

        filterAjax(url);
    });
}

var doAjax = true;

window.onpopstate = function (e) {
    'use strict';

    if (e.state) {
        filterUpdatecontent(e.state.response);
    }

};

$(document).ready(function () {
    'use strict';

    if ($('#productFilter').length) {
        initFilter();

        $('.collapseMe').each(function () {

            var filterSortContainer = $(this).next(),
                cachedThis = $(this);

            if ($(this).parent().hasClass('currentSelectionWrap')) {
                filterSortContainer.show();
            } else {

                if (filterSortContainer.is(':visible')) {
                    cachedThis.addClass('open');
                }

            }

        });

        $('body').on('click', '.collapseMe', function () {
            var filterSortContainer = $(this).next(),
                cachedThis = $(this);

            if (!$(this).parent().hasClass('currentSelectionWrap')) {

                if (filterSortContainer.is(':hidden')) {
                    filterSortContainer.slideDown();
                    cachedThis.addClass('open');
                } else {
                    filterSortContainer.slideUp();
                    cachedThis.removeClass('open');
                }
            }

        });

    }

});
