(function( $ ){

    var filterObj;
    var obj = { filterLabel : null,
                filterLabelText : null,
                filterLabelParent : null,
                filterList : null,
                filterListParent : null,
                filterShadow : null,
                filterClearButton : null,
                isActive : false }
                
      animate_size = function( el, apply ){
        
        label = _label = el.data('filterLabelText');        
        $(el.data('filterList')).each(function(){ if($(this).hasClass('cur')) label += " " + $(this).html(); });
        
        if(el.find('.compactFilter').length > 0)
            el.find('.compactFilter').removeClass('expand').hide();

        
        if(label != _label){
            var limit = $(el.data('filterLabelParent')).height();
            el.animate({"height":limit}, {
                    duration: 300,
                    specialEasing:{height: 'easeInOutExpo'},
                    complete: function(){
                        $(el.data('filterListParent')).hide();                    
                        filter_settings($(el), true);
                        if(apply == true){
                            //applyChange();
                        }
                    }
                });
        }
    }
    
    animateback_size = function( el, clear ){
        filter_settings( el, false );
        if($(el.data('filterListParent')).parents('.filterCompact').length > 0){
            // $(el.data('filterListParent')).show();
            
            el.find('.compactFilter').show();
        }
        else $(el.data('filterListParent')).show();
        
        el.animate({"height": '100%'}, {
                    duration: 300,
                    specialEasing: { height: 'easeInOutExpo' },
                    complete: function() {
                        if(clear!=false) el.data('isActive', true);
                    }
                });
    }
    
    clear_filter = function( el ){

        animateback_size( el, false );
        el.data('isActive', false);

        $(el.data('filterLabel')).html(el.data('filterLabelText'));
        $(el.data('filterList')).removeClass('cur');
        $(el.data('filterLabelParent')).css({'background':'none'});

        var _title = $(el.data('filterListParent')).attr('title');        
        eval("url." + _title + " = Array()");

        applyChange();
    }
    
    clear_filter_onchange = function( el ){
        animateback_size( el, false );
        el.data('isActive', false);

        $(el.data('filterLabel')).html(el.data('filterLabelText'));
        $(el.data('filterList')).removeClass('cur');
        $(el.data('filterLabelParent')).css({'background':'none'});
    }
    
    filter_settings = function( el, clear){
        if(clear){
            el.css({'border-bottom':'none'});
            $(el.data('filterLabelParent')).css({'background':'#fff'});
            $(el.data('filterClearButton')).show();
            $(el.data('filterShadow')).show();
        }
        else {
            el.css({'border-bottom':'1px solid #D0CFC2'});
            $(el.data('filterLabelParent')).css({'background':'none'});
            $(el.data('filterClearButton')).hide();
            $(el.data('filterShadow')).hide();
        }
    }
    
    add_select_event = function( $this, par ){
        
        var d_parent = $(par).find('.filterItemList');
        $($this).change(function(){
            var selectedID = $(this).val();
            if(selectedID != ''){
                $(par).data('isActive', true);
                
                add_label($(par));
                
                d_parent
                    .find('.filterLimitId' + selectedID)
                    .removeClass('filterItemLimit')
                    .addClass('cur');

                var value = new Array();
                d_parent.children('.cur').each(function(i){ value[i] = $(this).attr('title'); });                
                setUrl( d_parent.attr('title'), value);
                //url.page = 1;
                applyChange();
            }
        });
    }
    
    add_label = function( $this ){
        label = _label = $this.data('filterLabelText');
        var t = setTimeout(function(){    
            $($this.data('filterList')).each(function(){ if($(this).hasClass('cur')) label += " " + $(this).html(); });
            if(label == _label) $this.data('isActive', false);                    
            $($this.data('filterLabel')).html(label);
            clearTimeout(t);
        },
        300);
    }
    
    $.fn.filterOption = function( _options ) {
        
        var initialize_option = false,
            with_select = false;
            
        if(typeof(_options) == 'object') {
            var $this = this;
            
            if(_options.run == true) {
                var t = setTimeout(function(){
                    label = _label = $this.data('filterLabelText');
                    $($this.data('filterList')).each(function(){ if($(this).hasClass('cur')) label += " " + $(this).html(); });
                    $($this.data('filterLabel')).html(label);
                    if(_label != label) animate_size($($this), false);
                    clearTimeout(t);
                },
                1000);
            }
            else if(_options.clear == true) {                
                var t = setTimeout(function(){ clear_filter_onchange( $($this) ); clearTimeout(t); }, 1300);
            }
            else if(_options.addselection == true) {
                initialize_option = true;
                with_select = true;
            }
        }
        else initialize_option = true;
        
        if(initialize_option){
            
            _parent = $(this);            
            _parent.addClass('filterOption');
            
            obj.filterLabel = _parent.find('.filterLabel span');
            obj.filterLabelText = _parent.find('.filterLabel span').html();
            obj.filterLabelParent = _parent.find('.filterLabel');
            
            obj.filterList = _parent.find('.filterItemList li');
            obj.filterListParent = _parent.find('.filterItemList');
            
            obj.filterShadow = _parent.find('.filterShadow');
            obj.filterClearButton = _parent.find('.clearFilter');
            
            obj.isActive = false;
            obj.parentId = _parent.attr('id');

            if(with_select){                
                obj.filterSelect = _parent.find('.filterSelect select');                
                add_select_event( obj.filterSelect, _parent);
            }

            this.data(obj);
            
            var $this = this;        
            
            $(this.data('filterList')).bind('click', function(){
    
                $this.data('isActive', true);
                add_label( $this );
                
            });
            
            $(document).bind('click', function(e) {
                var $clicked = $(e.target);                
                var parentFound = $clicked.parents("div.filterWrap").length;
                $('.filterOption').each(function(){
                    if((parentFound == 0) && ($(this).data('isActive'))){
                        $(this).data('isActive', false);
                        animate_size( $(this), true );
                    }
                });
            });
                
            $(this.data('filterLabel')).bind('click', function(){
                if(!$this.data('isActive')) animateback_size( $($this), true);
            });
    
            $(this.data('filterClearButton')).click(function(){ clear_filter( $($this) ); });

            return this;
        }
        return this;
    };
})( jQuery );

// JavaScript Document
var url = {};
var priceMin = 0, priceMax = 500;
var isApplyUrl = false;
var iblockID = '';
var compareCount = 0;
var ajax_request_favorites,
    ajax_start_favorites = false,
    ajax_requesttime,
    ajax_request_favorites_count = 0;

function startGallery(){
    $('.ad-gallery')
        .adGallery({
            effect:'fade',
            enable_keyboard_move: false
        });
}

function reloadGallery( id ){
    $('#adg' + id)
        .adGallery({
            effect:'fade',
            enable_keyboard_move: false
        });
}

function changeThumb( el, id ){
    var list = '';
    var b = $(el).children('b').html();    
    
    eval('var ' + b);
    
    $.each(colorItem, function( i, url){
        list += '<li><a href="' + url + '"><img width="0" height="0"></a></li>';
    });
    
    $('#adg' + id + ' .ad-thumb-list').html( list );

    reloadGallery( id );
    
    return false;
}

function openOverlay(){
    $('.productOverlay').show();
    $('.productApplyFilterWrap').show();
}

function setUrl( key, val){
    if(val != '') eval('url.' + key + ' = "' + val + '"');
    else eval('delete url.' + key );
}

function runUrl(){
    var href = '#';
    $.each(url, function( key, val){
        if(val != '') href += '|' + key + ':' + val;
    });
    document.location = href;
}

function getUrl(){
    var raw, anchorAr;
    
    var i = document.location.href.indexOf('#');
    
    if( i === -1 ) raw = '|';
    else raw = document.location.href.split('#')[1];
    
    $.each( raw.split('|'), function( key, val){                                         
        if(val != ''){
            data = val.split(':');
            setUrl( data[0], data[1].split(','));
        }
    });        
}

function resetFilter(){
    
    $('.cur').removeClass('cur');
    
    //$( "#slider-range" ).slider({values: [priceMin, priceMax] });
    //$( ".priceContainer .min" ).text(priceMin);
    //$( ".priceContainer .max" ).text(priceMax);
    
    var brand_found = false,
        type_found = false,
        size_found = false,
        season_found = false,
        collection_found = false,
        color_found = false;
        
    $.each( url, function( key, val){            
        switch(key){
            case 'price':
                price = val.split(',');
                //$( "#slider-range" ).slider({values: price });
                //$( ".priceContainer .min" ).text(price[0]);
                //$( ".priceContainer .max" ).text(price[1]);
                
                //$('#filterPrice .filterLabel span').html('<strong>Prijs ' + price[0] + ' - ' + price[1] + '</strong>');
                //price_settings(true);
                
            break;
            case 'sort':
                
            break;
            default:
                $('ul[title=' + key + '] li').each(function(){
                    var t = $(this).attr('title');                        
                    if(in_array( t, val.split(','))) $(this).addClass('cur');
                });
            break;                
        }
        
        switch(key){
            case 'type':
                $('#filterType').filterOption({'run':true});
                 type_found = true;
            break;                
            case 'brand':
                $('#filterBrand').filterOption({'run':true});
                 brand_found = true;
            break;                
            case 'size':
                $('#filterSize').filterOption({'run':true});
                 size_found = true;
            break;                
            case 'season':
                $('#filterSeason').filterOption({'run':true});
                 season_found = true;
            break;                
            case 'collection':
                $('#filterCollection').filterOption({'run':true});
                 collection_found = true;
            break;            
            case 'color':
                $('#filterColor').filterOption({'run':true});
                 color_found = true;
            break;
        }
    });
    
    if(!size_found)$('#filterSize').filterOption({'clear':true});
    if(!type_found)$('#filterType').filterOption({'clear':true});
    if(!brand_found)$('#filterBrand').filterOption({'clear':true});
    if(!season_found)$('#filterSeason').filterOption({'clear':true});
    if(!collection_found)$('#filterCollection').filterOption({'clear':true});
    if(!color_found)$('#filterColor').filterOption({'clear':true});
}

function setOption( el ){
    var cur_sort;
    cur_sort = $(el).find('option:selected').text();
    $(el).siblings('span').html(cur_sort);
    
    setUrl( 'sort', $(el).val() );
}

function applyChange(){    
    isApplyUrl = true;
    runUrl();
    $('.productApplyFilterWrap').hide();
    url.page = 1;
    fetchProductItem();
    return false;
}

function resetChange(){
    url = {};
    getUrl();
    //resetFilter();
    $('.productOverlay').hide();
    $('.productApplyFilterWrap').hide();
    return false;
}

function resetAllChange(){
    url = {};
    runUrl();
    //resetFilter();
    $('.productOverlay').hide();
    $('.productApplyFilterWrap').hide();
    return false;
}

function startFilter(){
    url = {};
    getUrl();
    //resetFilter();
    fetchProductItem();
}

function fetchProductItemFavorites(){
    $('.shb_productOverlay').toggle();
    $('.shb_productFetchLoading').toggle();
    
    ajax_request_favorites_count++;
    if(ajax_start_favorites) ajax_request_favorites.abort('abort');
    //url.page = 1;
    ajax_request_favorites = $.ajax({
                    type: 'POST',
                    url: '/.action/getproduct.favorites.php?uid=' + iblockID,
                    data: url,
                    success: function( result )
                    {
                        $('div.shb_container #shb_shoes_wrapper').html( result );
                        
                        $('.shb_productOverlay').toggle();
                        $('.shb_productFetchLoading').toggle();
                    }
                });

    ajax_start_favorites = true;
}

function closeOverlay(){
    $('.productOverlay').hide();
    $('.productFetchLoading').hide();
}

function addToCompare( id ){
    $('#productItemWrap' + id).addClass('piwcompare');
    setCompare( 'add', id );
}

function removeToCompare( id ){
    $('#productItemWrap' + id).removeClass('piwcompare');
    setCompare( 'remove', id );
}

function clearCompare(){
    setCompare( 'clear', 'all');
    $('.piwcompare').removeClass('piwcompare');
}

function setCompare( action, id ){
    $.post('/.action/actioncompare.php', {'action': action, 'id': id}, function( count ){ compareCount = count; $('a.compare_wrapper span').html(count);});
}

function reset_price(){
    _parent = $('#filterPrice');
    _pricereset = new Array(priceMin, priceMax);
    
    //$( "#slider-range" ).slider({values: _pricereset });
    //$( ".priceContainer .min" ).text(_pricereset[0]);
    //$( ".priceContainer .max" ).text(_pricereset[1]);
    
    //_parent.find('.filterLabel span').html('<strong>Prijs</strong>');
    
    //price_settings(false);
}

function price_settings(clear){
    _parent = $('#filterPrice');
    
    if(clear){
        _parent.css({'border-bottom':'none'});
        _parent.find('.filterLabel').css({'background':'#fff'});
        _parent.find('.clearFilter').show();
        _parent.find('.filterShadow').show();
        _parent.find('.compactFilter').hide();
        _parent.find('.priceContainerWrapper').hide();
    }
    else {
        _parent.css({'border-bottom':'1px solid #D0CFC2'});
        _parent.find('.filterLabel').css({'background':'none'});
        _parent.find('.clearFilter').hide();
        _parent.find('.filterShadow').hide();
        
        _parent.find('.compactFilter').addClass('expand').show();
        _parent.find('.priceContainerWrapper').show();
    }
}

function setupCompactFilter( _parent, expanded ){
    if(expanded){
        $(_parent).find('.filterItemList').show();
        $(_parent).find('.priceContainerWrapper').show();
    }
    else {
        $(_parent).find('.filterItemList').hide();
        $(_parent).find('.priceContainerWrapper').hide();
    }
    //alert(_parent.data('isActive'));
}
