/**
 * @repository-version 1.0.0
 */
$.extend(
  $.expr[ ':' ],
  {
      reallyvisible : function (a) {
          return !(jQuery(a).is(':hidden') || jQuery(a).parents(':hidden').length);
      }
  }
);

/**
 * Filter - ajax search engine front-end interface.
 * @author Grzegorz Zagrobelny
 * @version 2010-08-24
 */
var Filter = {
    resetDom: '<a href="#" class="reset" onclick="Filter.reset(this);return false;"><sup>X</sup></a>',
    trim: function(str, chars) {
	return this.ltrim(this.rtrim(str, chars), chars);
    },
    ltrim:function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
    },
    rtrim:function(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
    },
    strip_tags: function(str, allowed_tags) {
    var key = '', allowed = false;
    var matches = [];
    var allowed_array = [];
    var allowed_tag = '';
    var i = 0;
    var k = '';
    var html = '';
    var replacer = function(search, replace, str) {
        return str.split(search).join(replace);
    };
    if (allowed_tags) {
        allowed_array = allowed_tags.match(/([a-zA-Z]+)/gi);
    }
    str += '';
    matches = str.match(/(<\/?[\S][^>]*>)/gi);
    for (key in matches) {
        if (isNaN(key)) {
            // IE7 Hack
            continue;
        }
        html = matches[key].toString();
        allowed = false;
        for (k in allowed_array) {
            allowed_tag = allowed_array[k];
            i = -1;
            if (i != 0) {i = html.toLowerCase().indexOf('<'+allowed_tag+'>');}
            if (i != 0) {i = html.toLowerCase().indexOf('<'+allowed_tag+' ');}
            if (i != 0) {i = html.toLowerCase().indexOf('</'+allowed_tag)   ;}
            if (i == 0) {
                allowed = true;
                break;
            }
        }
        if (!allowed) {
            str = replacer(html, "", str); 
        }
    }
    return str;
    },
    show: function() {
//        $('#filter').animate({
//          height: 250
//        }, 500, function() {
//          $('#filter').css('height', 'auto');
//          $('#filter-breadcrumbs').css('visibility', 'visible');
//          $('#filter-results').show();
//          $('#filter-switcher').html('schowaj').removeClass('switch-show').addClass('switch-hide');
//        });

//        $('#filter-switcher').unbind('click').toggle(
//        function() {
//            $('#filter-breadcrumbs').css('visibility', 'hidden');
//            $('#filter-results').hide();
//            $('#filter').animate({
//              height: 6
//            }, 500, function() {
//              $('#filter-switcher').html('wyszukaj').removeClass('switch-hide').addClass('switch-show');;
//            });
//        },
//        function() {
//            $('#filter').animate({
//              height: 250
//            }, 500, function() {
//              $('#filter').css('height', 'auto');
//              $('#filter-breadcrumbs').css('visibility', 'visible');
//              $('#filter-results').show();
//              $('#filter-switcher').html('schowaj').removeClass('switch-show').addClass('switch-hide');
//            });
//        });
    },
    reset: function(oSender) {
        var oSpan = $(oSender).parent('span');
        var sId = String($(oSpan).attr('id')).split('-')[2];
        switch ($(oSpan).attr('type')) {
            case 'text':
                $('#'+sId).val('');
                $(oSpan).html('').hide();
                Filter.query();
                break;
            case 'range':
                if ($(oSpan).attr('comborange') == 'yes') {
                    $('#filter-by-'+sId+' select[sliderid="'+sId+'"]').val('');                    
                }
                $('#'+sId).slider('values', 0, $('#'+sId).slider('option', 'min'), true, true);
                $('#'+sId).slider('values', 1, $('#'+sId).slider('option', 'max'), true);
                $('#'+sId+'-from').val();
                $('#'+sId+'-to').val();
                $(oSpan).html('').hide();
                break;
            case 'radio':
                $('#filter-by-'+sId+' input[type="radio"]').attr('checked', '');
                $(oSpan).html('').hide();
                Filter.query();
                break;
            case 'checkbox':
                $('#filter-by-'+sId+' input[type="checkbox"]').attr('checked', '');
                $(oSpan).html('').hide();
                Filter.query();
                break;
            case 'select':
                $('#'+sId).val('');
                $(oSpan).html('').hide();
                Filter.query();
                break;
            default:
                alert('Nie zdefiniowany typ: '+$(oSpan).attr('type'));
                break;
        }
    },
    init: function() {
        $('#fields-list a').click(function() {
            $('#fields-list a').removeClass('selected');
            $(this).addClass('selected');
            $('div.filter-container').hide();
            $('#'+$(this).attr('filterby')).show();
            return false;
        });



        $('#filter-switcher').click(function() {
            $('#filter-breadcrumbs').css('visibility', 'hidden');
            //$('#filter-results').hide();
            $('#filter').hide('slow');
            //$('#filter-results').hide();
        });

        $('.advancedSearch a').click(function(){
            $('#filter').animate({
              height: 250
            }, 500, function() {
              $('#filter').css('height', 'auto');
              $('#filter-breadcrumbs').css('visibility', 'visible');
              $('#filter-results').show();
              //$('#filter-switcher').html('schowaj').removeClass('switch-show').addClass('switch-hide');
            });
            return false;
        })

       $('div.slider').each(function() {

           var min = parseFloat($(this).attr('min'));
           var max = parseFloat($(this).attr('max'));
           var step = parseFloat($(this).attr('step'));
           var id = $(this).attr('id');

           if (step == 0) step = 1;           

           $(this).slider({
                orientation: 'horizontal',
                range: true,
                min: min,
                max: max,
                step: step,
                values: [min, max],
                slide: function(event, ui) {
                    $('select[sliderid="'+id+'"]').val('');
                    $('#'+id+'-from').val(ui.values[0]);
                    $('#'+id+'-to').val(ui.values[1]);
                    $('#breadcrumb-by-'+id).html('od'+' '+ui.values[0]+' '+'do'+' '+ui.values[1] + Filter.resetDom).show();                    
                },
                change: function(event, ui) {
                    Filter.query();
                }
           });
           $(this).append('<span class="range-info">Od: '+min+'<br/>'+'Do: '+max+'</span>');
        });

        $('select.combo-range').change(function() {
            var sSliderId = $(this).attr('sliderId');
            var mFrom = $(this).children('option:selected').attr('from');
            var mTo   = $(this).children('option:selected').attr('to');
            if (mFrom !== undefined) {
                $('#'+sSliderId).slider('values', 0, mFrom, true, true);
                $('#'+sSliderId).slider('values', 1, mTo, true);
                $('#breadcrumb-by-'+sSliderId).html('od'+' '+mFrom+' '+'do'+' '+mTo + Filter.resetDom).show();
                $('#'+sSliderId+'-from').val(mFrom);
                $('#'+sSliderId+'-to').val(mTo);
            } else {
                $('#breadcrumb-by-'+sSliderId).html('').hide();
                $('#'+sSliderId).slider('values', 0, $('#'+sSliderId).slider('option', 'min'), true, true);
                $('#'+sSliderId).slider('values', 1, $('#'+sSliderId).slider('option', 'max'), true);
                $('#'+sSliderId+'-from').val('');
                $('#'+sSliderId+'-to').val('');
            }
        });


        /*
         * Ustawianie breadcrumbsów
         */

        // inputy tekstowe
        $('input.bc-text').blur(function() {
            var sValue = Filter.strip_tags(Filter.trim($(this).val()));
            $(this).val(sValue);
            if (sValue != '')
                $('#breadcrumb-by-'+$(this).attr('id')).html(sValue + Filter.resetDom).show();
            else
                $('#breadcrumb-by-'+$(this).attr('id')).html('').hide();
            Filter.query();
        });
        $('input.bc-text').keyup(function(e) {
            if (e.keyCode == 13) {
                var sValue = Filter.strip_tags(Filter.trim($(this).val()));
                $(this).val(sValue);
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('id')).html(sValue + Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('id')).html('').hide();
                Filter.query();
            }
        });

        // inputy radiowe ;)
        $('input.bc-radio').click(function() {
             var sValue = '';
             if ($(this).attr('name') == 'seria') {
                    switch ($(this).val()) {
                        case '128':
                            sValue = 'Y ';
                            break;
                        case '129':
                            sValue = 'M ';
                            break;
                        case '130':
                            sValue = 'X ';
                            break;
                    }
             } else if ($(this).attr('name') == 'ecoline_produkt_energooszczedny' || $(this).attr('name') == 'produkt_przyjazny_dziecku')
                sValue = 'x';
             else
                sValue = Filter.strip_tags(Filter.trim($(this).attr('bc-value')));
            
            if ($(this).attr('name') == 'ecoline_produkt_energooszczedny') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('Ecoline Produkt Energooszczędny'+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            } else if ($(this).attr('name') == 'seria') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('Seria '+sValue+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            } else if ($(this).attr('name') == 'produkt_przyjazny_dziecku') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('Produkt Przyjazny Dziecku'+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            } else if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html(sValue + Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            Filter.query();
        });
        // inputy checkboxowe ;)
        $('input.bc-checkbox').click(function() {
            var sValue = '';
            $(this).parent('div').children('input[type="checkbox"]:checked').each(function() {
                if ($(this).attr('name') == 'seria') {
                    switch ($(this).val()) {
                        case '128':
                            sValue += 'Y ';
                            break;
                        case '129':
                            sValue += 'M ';
                            break;
                        case '130':
                            sValue += 'X ';
                            break;
                    }
                } else
                    sValue += Filter.strip_tags(Filter.trim($(this).attr('bc-value'))) + ' ';
            });
            if ($(this).attr('name') == 'ecoline_produkt_energooszczedny') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('Ecoline Produkt Energooszczędny'+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            } else if ($(this).attr('name') == 'seria') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('Seria '+sValue+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            } else if ($(this).attr('name') == 'produkt_przyjazny_dziecku') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('Produkt Przyjazny Dziecku'+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            } else
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html(sValue + Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('bc-id')).html('').hide();
            Filter.query();
        });
        // selecty
        $('select.bc-select').change(function() {
            var sValue = '';
             if ($(this).attr('name') == 'seria') {
                    switch ($(this).children('option:selected').val()) {
                        case '128':
                            sValue = 'Y ';
                            break;
                        case '129':
                            sValue = 'M ';
                            break;
                        case '130':
                            sValue = 'X ';
                            break;
                    }
             } else if ($(this).attr('name') == 'ecoline_produkt_energooszczedny' || $(this).attr('name') == 'produkt_przyjazny_dziecku')
                sValue = $(this).children('option:selected').val();
             else
                sValue = Filter.strip_tags(Filter.trim($(this).children('option:selected').html()));

            if ($(this).attr('name') == 'ecoline_produkt_energooszczedny') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('id')).html('Ecoline Produkt Energooszczędny'+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('id')).html('').hide();
            } else if ($(this).attr('name') == 'seria') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('id')).html('Seria '+sValue+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('id')).html('').hide();
            } else if ($(this).attr('name') == 'produkt_przyjazny_dziecku') {
                if (sValue != '')
                    $('#breadcrumb-by-'+$(this).attr('id')).html('Produkt Przyjazny Dziecku'+ Filter.resetDom).show();
                else
                    $('#breadcrumb-by-'+$(this).attr('id')).html('').hide();
            } else if (sValue != '' && sValue != '[ Wybierz ]')
                $('#breadcrumb-by-'+$(this).attr('id')).html(sValue + Filter.resetDom).show();
            else
                $('#breadcrumb-by-'+$(this).attr('id')).html('').hide();
            Filter.query();
        });
    },
    collectParameters: function() {
        var aData = new Array();
        $('#filter-breadcrumbs span:reallyvisible').each(function() {
            var sId = String($(this).attr('id')).split('-')[2];
            var sType = $(this).attr('type');
            switch (sType) {
                case 'text':
                    aData.push({id:sId, type:sType, value: Filter.trim(Filter.strip_tags($('#'+sId).val()))});
                    break;
                case 'range':
                    var iChoosenRange = '';
                    if ($(this).attr('comborange') == 'yes') {
                        iChoosenRange = $('select[sliderid="'+sId+'"]').val();                        
                    }
                    if (iChoosenRange != '' && !isNaN(parseInt(iChoosenRange))) {
                        aData.push({id:sId, type:sType, range_id: parseInt(iChoosenRange)});
                    } else {
                        aData.push({id:sId, type:sType, range_id: null, from: $('#'+sId+'-from').val(), to: $('#'+sId+'-to').val()});
                    }
                    break;                    
                case 'radio':
                    aData.push({id:sId, type:sType, value: $('#filter-by-'+sId+' input[type="radio"]:checked').val()});
                    break;
                case 'checkbox':
                    var values = new Array();
                    $('#filter-by-'+sId+' input[type="checkbox"]:checked').each(function() {
                       values.push(this.value);
                    });
                    aData.push({id:sId, type:sType, values: values});
                    break;
                case 'select':
                    aData.push({id:sId, type:sType, value: $('#'+sId).val()});
                    break;
                default:
                    alert('Nie zdefiniowany typ: '+sType);
                    break;
            }
        });        
        return aData;
    },
    query: function(iPage, oSender) {
        var iCurrentPage = (iPage == undefined) ? 1 : parseInt(iPage);
        if (isNaN(iCurrentPage)) iCurrentPage = 1;
        var aData = this.collectParameters();
        var sJson = JSON.stringify(aData, function (key, value) {
            if (typeof value === 'number' && !isFinite(value)) {
                return String(value);
            } else if (typeof value == 'string') {
                return String(value).replace('+', '[#plus#]');
            } else {
                if (typeof value == 'object') {                    
                    for (var k in value) {
                        if (typeof value[k] == 'string')
                        value[k] = String(value[k]).replace('+', '[#plus#]');
                    }
                    return value;
                } else
                    return value;
            }
        });
        //var oLoader = document.getElementById('filter-loader');
        if (oSender !== undefined)
            $(oSender).addClass('loadingPage');
            //oLoader.style.display = 'block';
        $.post('/', {
            request: 'filter/query',
            query:  sJson,
            page: iCurrentPage,
            category_id: Filter.iCategoryId
        }, function(sResponse) {
            if (sResponse == '-1') {
                $('.contentDivSmall div#loaded-content').hide();
                document.getElementById('filter-results').innerHTML = '<p>&#160;</p><img src="/gfx/load_result.gif" id="filter-loader" alt="' + t('Wyszukiwanie...') + '"/><div class="no-product"><strong>' + t('Nie znaleziono żadnego produktu.') + '</strong><br/>' + t('Zmień kryteria wyszukiwania i spróbuj ponownie.') + '</div>';
            } else if (sResponse == '') {
                document.getElementById('filter-results').innerHTML = '';
                $('.contentDivSmall div#loaded-content').show();
            } else {
                $('.contentDivSmall div#loaded-content').hide();
                document.getElementById('filter-results').innerHTML = sResponse;                
            }
            if (oSender !== undefined)
                $(oSender).removeClass('loadingPage');
                //oLoader.style.display = 'none';
        });
    }
}

$(document).ready(function() {
    Filter.init();
});
