var reset_filter = false;
var iMarginTop = 0;
var increment = 165;
var scrolling = false;
var iBlockHeight = 165;
var bAsync = true;

var hash = window.location.hash;
var aAnchors = new Array();
aAnchors = hash.split("@");

var CategoriesURL = new Array();
var PriceRange = '';

function setBlockHeight(block_locator, block_element_locator, visible_block_element_number, maximum_block_height) {
    var block_elements = $(block_element_locator);
    var visible_block_elements_height = 0;
    
    if(block_elements.length < visible_block_element_number) {
        visible_block_element_number = block_elements.length;
    }
    
    for(var i = 0; i<visible_block_element_number; i++) {
        visible_block_elements_height += $(block_elements[i]).height();
    }
    
    //visible_block_elements_height + 1;
    
    if(maximum_block_height < visible_block_elements_height) {
        visible_block_elements_height = maximum_block_height;
    }
    
    $(block_locator).height(visible_block_elements_height);
}

$(document).ready(function() {

    // IF we have any anchors in URL we need to turn off async for ajax actions.
    if (aAnchors.length > 1) {
        bAsync = false;
    }
    
    var tag_height = 20 * ($('#tag_content div').length - 1);
    if(tag_height > iBlockHeight) {
        tag_height = iBlockHeight;
    }
    $('#tag_wrapper').height(tag_height);


    $('.filter_color_type_box').show();
    $('.filter_brand_box').show();
    $('.filter_production_time_box').show();
    $('.filter_price_box').show();
    $('.filter_color_box').show();
    $('.filter_tag_box').show();
    $('.filterNavigation').show();
    $('#reset_button').show();
    
    setBlockHeight('#category_wrapper', '#category_content .category', 10, 200);
    setBlockHeight('#color_wrapper', '.filterColorElement', 10, 200);
    setBlockHeight('#brand_wrapper', '#brand_content .category', 10, 200);
    setBlockHeight('#production_time_wrapper', '#production_time_content .category', 10, 200);
    setBlockHeight('#color_type_wrapper', '#color_type_content .category', 10, 200);
    setBlockHeight('#tag_wrapper', '#tag_content .category', 10, 200);

    $('#category_wrapper').mousewheel(function(event, delta) {
        increment = 50;
        if (delta > 0) { //Scroll up
            $("#up").click();
        } else if (delta < 0) { //Scroll Down
            $("#down").click();
        }

        increment = $('#category_wrapper').parent().height();

        return false;
    });

    $('#brand_wrapper').mousewheel(function(event, delta) {
        increment = 50;
        if (delta > 0) { //Scroll up
            $("#brand_up").click();
        } else if (delta < 0) { //Scroll Down
            $("#brand_down").click();
        }

        increment = $('#brand_wrapper').parent().height();

        return false;
    });
    
    $('#production_time_wrapper').mousewheel(function(event, delta) {
        increment = 50;
        if (delta > 0) { //Scroll up
            $("#production_time_up").click();
        } else if (delta < 0) { //Scroll Down
            $("#production_time_down").click();
        }

        increment = $('#production_time_wrapper').parent().height();

        return false;
    });

    $('#color_type_wrapper').mousewheel(function(event, delta) {
        increment = 50;
        if (delta > 0) { //Scroll up
            $("#color_type_up").click();
        } else if (delta < 0) { //Scroll Down
            $("#color_type_down").click();
        }

        increment = $('#color_type_wrapper').parent().height();

        return false;
    });


    $('#color_wrapper').mousewheel(function(event, delta) {
        increment = 50;
        if (delta > 0) { //Scroll up
            $("#color_up").click();
        } else if (delta < 0) { //Scroll Down
            $("#color_down").click();
        }

        increment = $('#color_wrapper').parent().height();

        return false;
    });

    $('#tag_wrapper').mousewheel(function(event, delta) {
        increment = 50;
        if (delta > 0) { //Scroll up
            $("#tag_up").click();
        } else if (delta < 0) { //Scroll Down
            $("#tag_down").click();
        }

        increment = $('#tag_wrapper').parent().height();

        return false;
    });


    $(".filterCheckBox").live('change', function() {
        param = getPagingParams();
        filterProducts(param,this);

        if (this.checked == false ) {
            rewriteURL(this,'delete');
        } else {
            rewriteURL(this,'add');
        }
        
    });
    
    $("#filter_search").live('keyup', function() {
        param = getPagingParams();
        filterProducts(param,this);
    });

    $("#up").click(function() {
        scrollUpClick($(this),$("#down"),$("#category_content"));
    });
    $("#down").click(function() {
        scrollDownClick($("#up"),$(this),$("#category_content"));
    });

    $("#brand_up").click(function() {
        scrollUpClick($(this),$("#brand_down"),$("#brand_content"));
     });
    $("#brand_down").click(function() {
        scrollDownClick($("#brand_up"),$(this),$("#brand_content"));
    });
    
    $("#production_time_up").click(function() {
        scrollUpClick($(this),$("#production_time_down"),$("#production_time_content"));
     });
    $("#production_time_down").click(function() {
        scrollDownClick($("#production_time_up"),$(this),$("#production_time_content"));
    });

    $("#color_type_up").click(function() {
        scrollUpClick($(this),$("#color_type_down"),$("#color_type_content"));
     });
    $("#color_type_down").click(function() {
        scrollDownClick($("#color_type_up"),$(this),$("#color_type_content"));
    });

    $("#color_up").click(function() {
        scrollUpClick($(this),$("#color_down"),$("#color_content"));
     });

    $("#color_down").click(function() {
        scrollDownClick($("#color_up"),$(this),$("#color_content"));
    });

    $("#tag_up").click(function() {
        scrollUpClick($(this),$("#tag_down"),$("#tag_content"));
     });
    $("#tag_down").click(function() {
        scrollDownClick($("#tag_up"),$(this),$("#tag_content"));
    });

    $(".filter_head span").click( function() {
        background = $(this).parent().css('background-image');
        var patt1=new RegExp('images/arrow_down.png');

        $(this).parent().next(".filter_body").slideToggle(600);

        if (patt1.test(background)) {
            $(this).parent().css('background-image', 'url(images/arrow_up.png)');
        } else {
            $(this).parent().css('background-image', 'url(images/arrow_down.png)');
        }
    });
    
    $("#reset_button") .click(function() {

        $("input:checked[class='filterCheckBox']").attr('checked', '');
        $(".subcategory").remove();

        iPreviousMinVal = $("#filter_begin_price_min").val();
        iPreviousMaxVal = $("#filter_begin_price_max").val();

        resetFilterBlock('campaign');

        $("#filter_price_min").val(iPreviousMinVal);
        $("#filter_price_max").val(iPreviousMaxVal);
        $("#amount").html('$' + (iPreviousMinVal) + ' - $' + (iPreviousMaxVal))
        window.location.hash = '';
        reset_filter = true;
        $("#slider-range" ).slider({values: [iPreviousMinVal,iPreviousMaxVal]});
        reset_filter = false;
    });

    $(".filter_block_rest") .click(function() {
         resetFilterBlock(this);
    });

    $("#filterColor").easySlider({
        prevText:'',
        nextText:'',
        nextId: 'nextColorBtn',
        prevId: 'prevColorBtn',
        vertical:true
    });

    $("#filterBrand").easySlider({
        prevText:'',
        nextText:'',
        nextId: 'nextBrandBtn',
        prevId: 'prevBrandBtn',
        vertical:true
    });
    
    $("#filterProductionTime").easySlider({
        prevText:'',
        nextText:'',
        nextId: 'nextProductionTimeBtn',
        prevId: 'prevProductionTimeBtn',
        vertical:true
    });

    $("#filterColorType").easySlider({
        prevText:'',
        nextText:'',
        nextId: 'nextColorTypeBtn',
        prevId: 'prevColorTypeBtn',
        vertical:true
    });

    $("#filterTag").easySlider({
        prevText:'',
        nextText:'',
        nextId: 'nextTagBtn',
        prevId: 'prevTagBtn',
        vertical:true
    });


    $('.category a').each(function() {
        $($(this).parent()).html($(this).html());
    });


    if (aAnchors.length > 1) {
        setAnchorsVariables();
        checkCategBYURL();

        for(i = 0; i < aAnchors.length; i++) {

            element = aAnchors[i];
            id = 'filter_'+element;

            if (element.search('color') == 0 ) {
                $('#'+id).attr('checked', 'checked');
            }

            if (element.search('brand') == 0 ) {
                $('#'+id).attr('checked', 'checked');
            }
            
            if (element.search('production') == 0 ) {
                $('#'+id).attr('checked', 'checked');
            }

            if (element.search('color_type') == 0 ) {
                $('#'+id).attr('checked', 'checked');
            }

            if (element.search('tag') == 0 ) {
                $('#'+id).attr('checked', 'checked');
            }
            
            if (element.search('pricerange') == 0) {
                var range = element.split('_');
                var min_price = parseFloat(range[1]);
                var max_price = parseFloat(range[2]);
                $('#filter_price_min').val(min_price);
                $('#filter_price_max').val(max_price);
                $("#slider-range" ).slider({values: [min_price,max_price]});
            }
            

        }
        object =  document.getElementById(id);
        param = getPagingParams();
        filterProducts(param,object);
    }

    $(".filterCampaign").live('change', function() {
        if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
            filterTypeDisplay('.filter_category_box', false);
        } else {
            filterTypeDisplay('.filter_category_box', true);
        }
    });
    
    // tracking filter clicks
    $('.filter_category_box .filter_body').live('click', function() {
        trackJSEvent('filter-category-click');
    });
    $('.filter_color_box .filter_body').live('click', function() {
        trackJSEvent('filter-color-click');
    });
    $('.filter_brand_box .filter_body').live('click', function() {
        trackJSEvent('filter-brand-click');
    });
    $('.filter_production_time_box .filter_body').live('click', function() {
        trackJSEvent('filter-production-time-click');
    });
    $('.filter_color_type_box .filter_body').live('click', function() {
        trackJSEvent('filter-color-type-click');
    });
    $('.filter_campaign_box .filter_body').live('click', function() {
        trackJSEvent('filter-campaign-click');
    });
    $('.filter_tag_box .filter_body').live('click', function() {
        trackJSEvent('filter-tag-click');
    });


    bAsync = true;
});

function setPriceRangeByURL() {
    aRange = PriceRange.split("_");
}

function checkCategBYURL() {

    if (CategoriesURL.length > 0) {
        for(i = 0; i < CategoriesURL.length; i++) {
            element = CategoriesURL[i];
            if (element.search('category') == 0 ) {
                id = 'filter_'+element;
                object = document.getElementById(id);
                if (object != null) {
                    $('#'+id).attr('checked', 'checked');
                    selectCategory(object,0);
                    filterColors();
                    filterBrands();
                    filterProductionTimes();
                    filterColorTypes();
                    filterPrice();
                    filterTags();
                }
            }
        }
    }
}

function setAnchorsVariables() {

    if (aAnchors.length > 0) {
        for(i = 0; i < aAnchors.length; i++) {

            element = aAnchors[i];

            if (element.search('category') == 0 ) {
                CategoriesURL.push(aAnchors[i]);
            }

            if (element.search('pricerange') == 0) {
                PriceRange = aAnchors[i];
            }
        }
    }
}

function scrollUpClick(upBtnElement,downBtnElement,contentElement) {
    if(scrolling) {
        return true;
    }

    topWrap = contentElement.parent().offset().top;

    if(increment != 50) {
        increment = contentElement.parent().height();
    }
    scrolling = true;
    iMarginTop = parseInt(contentElement.css('marginTop'));
    if (iMarginTop <= 0) {
        if (-iMarginTop <= contentElement.parent().height() ) {
            if(-iMarginTop > increment) {
                contentElement.animate({"marginTop": "+="+increment+"px"}, "slow", function(){scrolling = false;});
            } else {
                contentElement.animate({"marginTop": "+="+(-iMarginTop)+"px"}, "slow", function(){scrolling = false;});
                upBtnElement.attr('src','images/arrow_navig_up_disable.png');
            }
        } else {
            contentElement.animate({"marginTop": "+="+increment+"px"}, "slow", function(){scrolling = false;});
        }
        downBtnElement.attr('src','images/arrow_navig_down.png');
    } else {
        scrolling = false;
    }
}

function scrollDownClick(upBtnElement,downBtnElement,contentElement) {
    
    if(scrolling) {
        return true;
    }

    topWrap = contentElement.parent().offset().top;

    if(increment != 50) {
        increment = contentElement.parent().height();
    }
    scrolling = true;
    Itemtop = contentElement.find('.last_item').offset().top;
    difLastBox =  parseInt(topWrap +contentElement.parent().height() - Itemtop);
    sd = -difLastBox;

    if (difLastBox < 0) {
        if (sd > increment ) {
            sd = increment;
            downBtnElement.attr('src','images/arrow_navig_down.png');
        } else {
            downBtnElement.attr('src','images/arrow_navig_down_disable.png');
        }
        contentElement.animate({"marginTop": "-="+sd+"px"}, "slow", function(){scrolling = false;});
        upBtnElement.attr('src','images/arrow_navig_up.png');
    } else {
        scrolling = false;
    }
    
}

function resetFilterBlock (object) {
    if (object == 'campaign') {
        block = 'campaign';
    } else {
        block = $(object).parent().attr('block');
    }
//    block = $(object).parent().attr('block');
    if (block != 'price') {
        if (block == 'campaign') {
            oLement = $("#"+block+"_content").find("input:checked[class='filterCheckBox filterCampaign']");
            filterTypeDisplay('.filter_campaign_box', true);
            filterTypeDisplay('.filter_category_box', true);
        } else {
            oLement = $("#"+block+"_content").find("input:checked[class='filterCheckBox']");
        }

        if (oLement.length) {

            oLement.each( function(index, domEle) {
                $(domEle).attr("checked",'');
            });

            if (block == 'category') {
                $(".subcategory").remove();
//                var category_height = ($('#category_content input').height() + 1) * ($('#category_content div').length - 1);
//                if(category_height > iBlockHeight) {
//                    category_height = iBlockHeight;
//                }
//                $('#category_wrapper').height(category_height);
                setBlockHeight('#category_wrapper', '#category_content .category', 10, 200);
            }

            param = getPagingParams();
            filterProducts(param,object);

        }
    } else {
        min = $( "#slider-range" ).slider( "option", "min" );
        max = $( "#slider-range" ).slider( "option", "max" );
        $("#amount").html('$' + min + ' - $' + max);
        
        $("#filter_price_min").val(min);
        $("#filter_price_max").val(max);
        initSlider(min,max,min,max);

        filterColors();
        filterBrands();
        filterProductionTimes();
        filterColorTypes();
        filterTags();

        param = getPagingParams();
        filterProducts(param,object);
    }
}

function initSlider (fMinPrice,fMaxPrice,fMinPriceDefault,fMaxPriceDefault) {
    $( "#slider-range" ).slider( "destroy" );
    $( "#slider-range" ).slider({
            range: true,
            step:0.01,
            min:fMinPrice,
            max:fMaxPrice,
            values: [fMinPriceDefault,fMaxPriceDefault],
            slide: function(event, ui) {
                $("#amount").html('$' + (ui.values[0]).toFixed(2) + ' - $' + (ui.values[1]).toFixed(2));
                $("#filter_price_min").val(ui.values[0]);
                $("#filter_price_max").val(ui.values[1]);
            },
            change: function(event, ui) {
                trackJSEvent('filter-price-click');
                
                // checking values for not sending several ajax request
                
                if ((iPreviousMinVal != ui.values[0]) || (iPreviousMaxVal != ui.values[1]) || reset_filter == true) {
                    param = getPagingParams();
                    filterProducts(param,this);
                }

                iPreviousMinVal = $("#filter_prev_price_min").val();
                iPreviousMaxVal = $("#filter_prev_price_max").val();

                $("#filter_prev_price_min").val(ui.values[0]);
                $("#filter_prev_price_max").val(ui.values[1]);
                
                rewriteURL(this,'add');
            }
    });
}

function filterPrice() {
    sData  = $("#filter_search").serialize();
    sData += "&page=filter_price";
    $.ajax({
        url:  'ajax_handler.php',
        type: "POST",
        dataType: 'json',
        data: sData,
        async: bAsync,
        success:function (Data) {

            $("#amount").html('$' + Data.result.minDefault + ' - $' + Data.result.maxDefault);
            initSlider(Data.result.min,Data.result.max,Data.result.minDefault,Data.result.maxDefault);

            if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
                filterTypeDisplay('.filter_price_box', false);
            } else {
                if (Data.result.min != Data.result.max) {
                    filterTypeDisplay('.filter_price_box', true);
                } else {
                    filterTypeDisplay('.filter_price_box', false);
                }
            }
        }
    });
}

function filterTypeDisplay (object, display) {

    filterHead = $(object).children('.filter_head');
    filterBody = filterHead.siblings('.filter_body');

    if (display == false) {
        filterBody.hide('slow');
        filterHead.css('background-image', 'url(images/arrow_up.png)');
    } else {
        filterBody.show();
        filterHead.css('background-image', 'url(images/arrow_down.png)');
    }
}


function filterBrands() {
    if ($("#brand_content").length <= 0 ) {
        return false;
    }
    
    sData  = $("#filter_search").serialize();
    sData += "&page=filter_brands";
    $.ajax({
        url:  'ajax_handler.php',
        type: "POST",
        dataType: 'json',
        data: sData,
        async: bAsync,
        success:function (Data) {
            var textElemt = "";
            
            $.each(Data.result, function(i,item){
                textElemt += '<div title="'+item.name+'" class="category">';
                textElemt += '<input type="checkbox" class="filterCheckBox"';

                if(item.checked) {
                    textElemt += "checked='checked'";
                }

                textElemt += 'value="'+item.name+'" id="filter_brand_'+item.id+'"  name="filter_brand[]" />';
                textElemt += '<label for="filter_brand_'+item.id+'">';
                textElemt += item.name;
                textElemt += '</label>';
                textElemt += '</div>';
            });
            
            $("#brand_content").html(textElemt+"<div class='last_item'>&nbsp;</div>");
            
            if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
                filterTypeDisplay('.filter_brand_box', false);
           } else {
                if (textElemt == '' ) {
                    filterTypeDisplay('.filter_brand_box', false);
                } else {
                    filterTypeDisplay('.filter_brand_box', true);
                    if (Data.result.length < 10 ) {
                        $('#brand_down').attr('src','images/arrow_navig_down_disable.png');
                    } else {
                        $('#brand_down').attr('src','images/arrow_navig_down.png');
                    }
                    
                    setBlockHeight('#brand_wrapper', '#brand_content .category', 10, 200);
                }
            }
        }
    });
}

function filterProductionTimes() {
    if ($("#production_time_content").length <= 0 ) {
        return false;
    }
    
    sData  = $("#filter_search").serialize();
    sData += "&page=filter_production_times";
    $.ajax({
        url:  'ajax_handler.php',
        type: "POST",
        dataType: 'json',
        data: sData,
        async: bAsync,
        success:function (Data) {
            var textElemt = "";
            
            $.each(Data.result, function(i,item){
                textElemt += '<div title="'+item.name+'" class="category">';
                textElemt += '<input type="checkbox" class="filterCheckBox"';

                if(item.checked) {
                    textElemt += "checked='checked'";
                }

                textElemt += 'value="'+item.name+'" id="filter_production_'+item.id+'"  name="filter_production[]" />';
                textElemt += '<label for="filter_production_'+item.id+'">';
                textElemt += item.name;
                textElemt += '</label>';
                textElemt += '</div>';
            });
            
            $("#production_time_content").html(textElemt+"<div class='last_item'>&nbsp;</div>");
            
            if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
                filterTypeDisplay('.filter_production_time_box', false);
           } else {
                if (textElemt == '' ) {
                    filterTypeDisplay('.filter_production_time_box', false);
                } else {
                    filterTypeDisplay('.filter_production_time_box', true);
                    if (Data.result.length < 10 ) {
                        $('#production_time_down').attr('src','images/arrow_navig_down_disable.png');
                    } else {
                        $('#production_time_down').attr('src','images/arrow_navig_down.png');
                    }
                    
                    setBlockHeight('#production_time_wrapper', '#production_time_content .category', 10, 200);
                }
            }
        }
    });
}

function filterColorTypes() {
    if ($("#color_type_content").length <= 0 ) {
        return false;
    }

    sData  = $("#filter_search").serialize();
    sData += "&page=filter_color_types";
    $.ajax({
        url:  'ajax_handler.php',
        type: "POST",
        dataType: 'json',
        data: sData,
        async: bAsync,
        success:function (Data) {
            var textElemt = "";

            $.each(Data.result, function(i,item) {
                textElemt += '<div title="'+item.name+'" class="category">';
                textElemt += '<input type="checkbox" class="filterCheckBox"';

                if(item.checked) {
                    textElemt += "checked='checked'";
                }

                textElemt += 'value="'+item.name+'" id="filter_color_type_'+item.name+'"  name="filter_color_type[]" />';
                textElemt += '<label for="filter_color_type_'+item.name+'">';
                textElemt += item.name;
                textElemt += '</label>';
                textElemt += '</div>';
            });

            $("#color_type_content").html(textElemt+"<div class='last_item'>&nbsp;</div>");

            filterBody = $('.color_type_filter_body');
            filterHead = filterBody.prev('.filter_head');

            if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
                filterBody.hide('slow');
                filterHead.css('background-image', 'url(images/arrow_up.png)');
            } else {
                if (textElemt == '' ) {
                    filterBody.hide('slow');
                    filterHead.css('background-image', 'url(images/arrow_up.png)');
                } else {
                    filterBody.show('slow');
                    filterHead.css('background-image', 'url(images/arrow_down.png)');
                    if (Data.result.length < 10 ) {
                        $('#color_type_down').attr('src','images/arrow_navig_down_disable.png');
                    } else {
                        $('#color_type_down').attr('src','images/arrow_navig_down.png');
                    }
                    
                    setBlockHeight('#color_type_wrapper', '#color_type_content .category', 10, 200);
                }
            }
        }
    });
}

function filterColors() {
    if ($("#color_content").length <= 0 ) {
        return false;
    }

    sData = $("#filter_search").serialize();
    sData += "&page=filter_colors";
    $.ajax({
        url:  'ajax_handler.php',
        type: "POST",
        dataType: 'json',
        data: sData,
        async: bAsync,
        success:function (Data) {
            var textElemt = "";

            $.each(Data.result, function(i,item) {
                textElemt += "<div class='category filterColorElement'  title='"+item.colorName+"'>";
                    textElemt += "<input type='checkbox' class='filterCheckBox' style='float:left;' id='filter_color_"+item.clientColorId+"' value='"+item.colorName+"' name='filter_color[]' ";

                    if (item.checked == 1) {
                        textElemt += "checked='checked'";    
                    }
                    
                    textElemt += "/>";
                    textElemt += "<label for='filter_color_"+item.clientColorId+"'>";
                            textElemt += "<span class='first_color' style='background-color:"+item.hexValue+";'>&nbsp;</span>";
                        if (item.secondHexValue) {
                            textElemt += "<span class='second_color' style='background-color:"+item.secondHexValue+";'>&nbsp;</span>";
                        } else {
                            textElemt += "<span class='second_color' style='background-color:"+item.hexValue+";'>&nbsp;</span>";
                        }
                    textElemt += "<span class='colorSwatchMask'>&nbsp;</span></label>";
                    textElemt += "<div style='white-space: nowrap; width: 102px; overflow:hidden; float:left; padding-left:5px;text-align:left;'>";
                    textElemt += "<label for='filter_color_"+item.clientColorId+"'>";
                        textElemt += item.colorName;
                    textElemt += "</label>";
                    textElemt += "</div>";
                textElemt += "<br clear='all'/>";
                textElemt += "</div>";
            });
            
            $("#color_content").html(textElemt+"<div class='last_item'>&nbsp;</div>");

            if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
                filterTypeDisplay('.filter_color_box', false);
            } else {
                if (textElemt == '' ) {
                    filterTypeDisplay('.filter_color_box', false);
                } else {
                    filterTypeDisplay('.filter_color_box', true);
                    if (Data.result.length < 10 ) {
                        $('#color_down').attr('src','images/arrow_navig_down_disable.png');
                    } else {
                        $('#color_down').attr('src','images/arrow_navig_down.png');
                    }
                    
                    setBlockHeight('#color_wrapper', '.filterColorElement', 10, 200);
                }
            }            
        }
    });    
}

function filterTags() {
    if ($("#tag_content").length <= 0 ) {
        return false;
    }

    sData  = $("#filter_search").serialize();
    sData += "&page=filter_tags";
    $.ajax({
        url:  'ajax_handler.php',
        type: "POST",
        dataType: 'json',
        data: sData,
        async: bAsync,
        success:function (Data) {
            var textElemt = "";

            $.each(Data.result, function(i,item){
                textElemt += '<div title="'+item.name+'" class="category">';
                textElemt += '<input type="checkbox" class="filterCheckBox"';

                if(item.checked) {
                    textElemt += "checked='checked'";
                }

                textElemt += 'value="'+item.name+'" id="filter_tag_'+item.id+'"  name="filter_tag[]" />';
                textElemt += '<label for="filter_tag_'+item.id+'">';
                textElemt += item.name;
                textElemt += '</label>';
                textElemt += '</div>';
            });

            $("#tag_content").html(textElemt+"<div class='last_item'>&nbsp;</div>");

            if ($("input:checked[name='filter_campaign\[\]']").length > 0 ) {
                filterTypeDisplay('.filter_tag_box', false);
           } else {
                if (textElemt == '' ) {
                    filterTypeDisplay('.filter_tag_box', false);
                } else {
                    filterTypeDisplay('.filter_tag_box', true);
                    if (Data.result.length < 10 ) {
                        $('#tag_down').attr('src','images/arrow_navig_down_disable.png');
                    } else {
                        $('#tag_down').attr('src','images/arrow_navig_down.png');
                    }
                    
                    setBlockHeight('#tag_wrapper', '#tag_content .category', 10, 200);
                }
            }
        }
    });
}

function filterProducts(param,elemObj) {
    sData = $("#filter_search").serialize();
    var checked = elemObj;
    showOverlay();

    var href_parts = window.location.href.split('?');
    href_parts = href_parts[0].split('#');

    $.ajax({
        url:  href_parts[0] + "?body=0&" + param,
        type: "POST",
        dataType: 'html',
        data:sData,
        async: bAsync,
        success:function (Data) {
            elem = $(Data).find(".paging b");
            hideOverlay();
            if (elem.length > 0 ) {
                iCount = parseInt($(elem[0]).html());
                if ( iCount ) {
                    $("#filterProductsBox").html($($(Data)[0]).html());
                    filterPrice();
                    filterColors();
                    filterBrands();
                    filterProductionTimes();
                    filterColorTypes();
                    filterTags();
                } else {
                    rewriteURL(checked,'delete');
                    noProductDialog(checked);
                }
            } else {
                rewriteURL(checked,'delete');
                noProductDialog(checked);
            }
        }
    });
}

function noProductDialog(ElementObject) {
    var ElemObj = ElementObject;
    
    $( "#filterDialog" ).dialog({
        title:"We're sorry, we found no results.",
        modal: true,
        width: $("#filterDialog").css('width'),
        height: $("#filterDialog").css('height'),
        dialogClass: 'no_results_dialog',
        draggable:false,
        resizable:false,
//        buttons: {
//            Close: function() {
//                $( this ).dialog( "close" );
//            }
//        },
        open: function(event, ui) {
            if (ElemObj.type != 'checkbox') {
                $("#filter_prev_price_min").val(iPreviousMinVal);
                $("#filter_prev_price_max").val(iPreviousMaxVal);
                
                $("#slider-range" ).slider({values: [iPreviousMinVal,iPreviousMaxVal]});
                $("#filter_price_min").val(iPreviousMinVal);
                $("#filter_price_max").val(iPreviousMaxVal);
                $("#amount").html('$' + (iPreviousMinVal) + ' - $' + (iPreviousMaxVal));
                //alert('$' + (iPreviousMinVal) + ' - $' + (iPreviousMaxVal));

            }
        },
        show: 'fade',
        hide: 'fade',
        close: function (event, ui) {
            if ($(ElemObj).attr("checked")) {
                $(ElemObj).attr("checked",'');
            } else {
                $(ElemObj).attr("checked",'checked');
            }

            $("#filter_subcategory_"+ElemObj.value).html( " " );
            $("#filterDialog").dialog("destroy");
        }

    });

    $(".no_results_dialog .ui-dialog-titlebar").hide();
    $(".no_results_dialog").css({border: 'none', padding: '0'});
    $("#filterDialog").css({height: '227px', padding: '0'});
    $(".ui-widget-overlay").click(function() {
        $("#filterDialog").dialog("close");
    });
}

function changePagingParams (params) {
    var url_parts = params.split('?');
    filterProducts(url_parts[1]);
}

function getPagingParams () {
    var page_dropdown = $("select[name='pagedropdown']");
    if(page_dropdown.length > 0) {
        var url_parts = page_dropdown[0].options[0].value.split('?');
        if(url_parts.length > 1) {
            return url_parts[1];
        } else {
            return '';
        }
    } else {
        return '';
    }
}

function selectCategory(object,ProductFilter) {
    
    oElems = $("input:checked[name='filter_categories[]']");
    iLength = oElems.length;
    var iParentId = $(object).val();
        if (object.checked) {
            $.ajax({
                url:  'ajax_handler.php',
                type: "POST",
                dataType: 'json',
                data: ({
                    id : iParentId ,
                    page: 'filter_category'
                }),
                async: bAsync,
                success:function (Data) {
                    var textElemt = "";

                    $.each(Data.result, function(i,item) {
                         textElemt += "<div class='category subcategory'>";
                         textElemt += "<input onclick='selectCategory(this,1)' type='checkbox' value='"+item.id+"' id='filter_category_"+item.id+"' rel='"+item.rel+"' name='filter_categories[]' class='filterCheckBox'>";
                         textElemt += "<label for='filter_category_"+item.id+"'>"+item.name+"</label>";
                         textElemt += "<span id='filter_subcategory_"+item.id+"'></span>";
                         textElemt += "</div>";
                     });
                     
                    $("#filter_subcategory_"+iParentId).html(textElemt);
                    
                    setBlockHeight('#category_wrapper', '#category_content .category', 10, 200);
                    
//                    topWrap = $("#category_wrapper").offset().top;
//                    Itemtop = $("#category_wrapper .last_item").offset().top;
//                    difLastBox = parseInt(topWrap +iBlockHeight - Itemtop);
//                    iNewHeight = $("#category_content .category").length * ($('#category_content input').height() + 1);
//
//                    if ( iNewHeight < iBlockHeight) {
//                        $("#category_wrapper").height(iNewHeight);
//                    } else if (iNewHeight > iBlockHeight) {
//                        $("#category_wrapper").height(iBlockHeight);
//                    }
//                        
//                    if ( -difLastBox > iBlockHeight ) {
//                        $("#down").attr('src','images/arrow_navig_down_disable.png');
//                    } else if ( -difLastBox > 0) {
//                        $("#down").attr('src','images/arrow_navig_down.png');
//                    }

                    if (ProductFilter == 1) {
                        param = getPagingParams();
                        filterProducts(param,object);
                    }
                }
            });
        } else {
            //.
            subElements = $("#filter_subcategory_"+iParentId).find("input:checked[class='filterCheckBox']");
            iLength = subElements.length;
                if (iLength) {
                    subElements.each(function() {
                    rewriteURL(this,'delete');
                });
            }

            /*$("#filter_subcategory_"+iParentId).html( " " );
            topWrap = $("#category_wrapper").offset().top;
            Itemtop = $("#category_wrapper .last_item").offset().top;
            difLastBox = parseInt( topWrap + iBlockHeight - (Itemtop) );
            if ( -difLastBox > iBlockHeight ) {
                $("#down").attr('src','images/arrow_navig_down.png');
            } else if ( -difLastBox < 0 ) {
                $("#down").attr('src','images/arrow_navig_down_disable.png');
            }

            iNewHeight = $("#category_content .category").length * 20;
            if ( iNewHeight < iBlockHeight ) {
                $("#category_wrapper").height(iNewHeight);
            } else if (iNewHeight > iBlockHeight ) {
                $("#category_wrapper").height(iBlockHeight);
            }*/
        }

    if (!object.checked) {
       $("#filter_subcategory_"+iParentId).html( " " );
    }
}

function showOverlay() {
    $( "#overlay" ).dialog({
        dialogClass:'alert',
        height: 180,
        draggable:false,
        resizable:false,
        close:function(event, ui) {
            $("#overlay").dialog("destroy");
            $.ui.dialog.maxZ -= 1;
        },
        open: function(event, ui) {
        },
        show: {effect: 'fade', duration: 250},
        hide: {effect: 'fade', duration: 250},
        modal: false
    });
    $(".alert .ui-dialog-titlebar").hide();
}

function hideOverlay() {
    $( "#overlay" ).dialog('close');
}

function rewriteURL(object,mode) {

    href = window.location.href;

    if ( href.search("#") == -1 ) {
        href += "#";
    }

    paramName =  '';
    elemValue = object.value;

    if (object.id.search("filter_color") != -1) {
        paramName = 'color';
        aIds = object.id.split("_");
        elemValue = aIds[2];
    }

    if (object.id.search("filter_category") != -1) {
        paramName = 'category';
    }

    if (object.id.search("filter_brand") != -1) {
        paramName = 'brand';
        aIds = object.id.split("_");

        //elemValue = aIds[2]+'_'+aIds[3]+'_'+aIds[4];
        elemValue = '';
        if (aIds.length > 2) {
            for(j=2;j<aIds.length;j++) {
                if (j == 2) {
                    elemValue += aIds[j];
                } else {
                    elemValue += '_'+aIds[j];
                }
            }
        }
    }
    
    if (object.id.search("filter_production") != -1) {
        paramName = 'production';
        aIds = object.id.split("_");

        //elemValue = aIds[2]+'_'+aIds[3]+'_'+aIds[4];
        elemValue = '';
        if (aIds.length > 2) {
            for(j=2;j<aIds.length;j++) {
                if (j == 2) {
                    elemValue += aIds[j];
                } else {
                    elemValue += '_'+aIds[j];
                }
            }
        }
    }

    if (object.id.search("filter_tag") != -1) {
        paramName = 'tag';
        aIds = object.id.split("_");

        //elemValue = aIds[2]+'_'+aIds[3]+'_'+aIds[4];
        elemValue = '';
        if (aIds.length > 2) {
            for(j=2;j<aIds.length;j++) {
                if (j == 2) {
                    elemValue += aIds[j];
                } else {
                    elemValue += '_'+aIds[j];
                }
            }
        }
    }

    if (object.id.search("slider-range") != -1) {
        paramName = 'pricerange';
        elemValue = $("#filter_price_min").val()+'_'+$("#filter_price_max").val();
    }

    if (object.id.search("filter_color_type") != -1) {
        paramName = 'color';
        aIds = object.id.split("_");

        //elemValue = aIds[2]+'_'+aIds[3]+'_'+aIds[4];
        elemValue = '';
        if (aIds.length > 2) {
            for(j=2;j<aIds.length;j++) {
                if (j == 2) {
                    elemValue += aIds[j];
                } else {
                    elemValue += '_'+aIds[j];
                }
            }
        }
    }

    if (object.id.search("filter_campaign") != -1) {
        paramName = 'campaign';
        aIds = object.id.split("_");

        //elemValue = aIds[2]+'_'+aIds[3]+'_'+aIds[4];
        elemValue = '';
        if (aIds.length > 2) {
            for(j=2;j<aIds.length;j++) {
                if (j == 2) {
                    elemValue += aIds[j];
                } else {
                    elemValue += '_'+aIds[j];
                }
            }
        }
    }

    var value = "@"+paramName+"_"+escape(elemValue);
    var patt = new RegExp(value+"\\b","g");
    if ( mode == 'add' ) {
        if (object.id == 'slider-range'){
            href = href.replace(/@pricerange_([\d\._])*/, '');
            if (href.search('pricerange') == -1) {
                href += value;
            }
        } else {
            if (href.search(patt) == -1) {
                href += value;
            }
        }
    } else {
            href = href.replace(patt, '');
            
            if ( href.search("@") == -1 ) {
                href = href.replace(/#.*/g,'');
            }
    }
    
    window.location.href = href;
}
