(function($){
    var DJCatalog2FiltersWizard = function(settings, is_listing_page) {
        var self = this;

        this.url = settings.catalog_base_url;
        this.base_url = settings.base_url;
        this.autosubmit = is_listing_page;

        this.modules = $('div.mod_djc2fw');
        if (this.modules.length > 0) {
            this.setupModuleFilters();
        }

        this.temp = $('<div />').css('display', 'none');
        $(document.body).append(this.temp);
    };

    DJCatalog2FiltersWizard.prototype = {
        constructor: DJCatalog2FiltersWizard,
        request: false,
        modules: null,
        temp: null,
        url: '',
        base_url: '',

        setupModuleFilters: function() {
            var self = this;

            var inputs = this.modules.find('input[type="radio"],input[type="checkbox"],input[type="text"],select');
            inputs.removeAttr('onchange');
            inputs.unbind('change');
            inputs.change(function(event){
                event.stopPropagation();
                self.updateModules($(this).parents('form'));
                //return $(this).parents('form').trigger('submit');
            });

            var links = this.modules.find('a.field_reset_button, a.reset_button, ul > li > a');
            links.unbind('click submit');
            links.click(function(event){
                event.preventDefault();
                event.stopPropagation();

                //var href = $(event.target).attr('href');
                var href = $(event.currentTarget).attr('href');
                var data = {
                    url: href,
                    params: ''
                };

                if (self.autosubmit) {
                    document.location.href = href;
                    return;
                }
                self.updateModules($(this).parents('form'), data);
            });

            this.modules.find('button.reset_button').click(function(event){
                event.preventDefault();
                event.stopPropagation();
                var form = $(this).parents('form');
                $(form).find('input[type="radio"],input[type="checkbox"]').removeAttr('checked');
                $(form).find('select option').removeAttr('selected');
                setTimeout(function(){self.updateModules(form);}, 200);
            });

            inputs.filter('input[type=radio]').each(function(){
                $(this).mousedown(function() {
                    if (this.checked) {
                        $(this).mouseup(function(e) {
                            var radio = this;
                            setTimeout(function() {
                                radio.checked = false;
                                $(radio).trigger('change');
                            }, 5);
                            $(this).unbind('mouseup');
                        });
                    }
                });

                var lblRadio = this;
                $(lblRadio).parent('label').mousedown(function() {
                    if (lblRadio.checked) {
                        $(this).mouseup(function(e) {
                            setTimeout(function() {
                                lblRadio.checked = false;
                                $(lblRadio).trigger('change');
                            }, 5);
                            $(this).unbind('mouseup');
                        });
                    }
                });
            });

            setTimeout(function(){
                $('#djcatalog').trigger('ajaxFilter:setupModules');
            }, 10);
        },

        updateModules: function(form, requestData) {
            var self = this;

            if (self.modules.length < 1) {
                return;
            }

            if (self.autosubmit) {
                return form.submit();
            }

            self.fadeOut([self.modules]);

            var data;

            if (typeof requestData == 'undefined') {
                var formData = [];
                $.each($(form).serializeArray(), function(i, item){
                    if (item.name != 'task') {
                        formData.push(item.name+'='+item.value);
                    }
                });
                data = {
                    url: $(form).attr('action'),
                    params: formData.join('&')
                };
            } else {
                data = requestData;
            }

            var params = data.params;
            self.modules.each(function(){
                params += '&module_id[]=' + $(this).attr('data-moduleid');
            });

            params += '&task=getFilterModules';

            $.ajax({
                url: data.url,
                method: 'get',
                data: params,
                dataType: 'html',
            }).done(function(data, status, xhr){
                $(data).find('div[data-filtersmodule]').each(function(){
                    $('#mod_djc2fw-' + $(this).attr('data-filtersmodule')).replaceWith($(this).find('#mod_djc2fw-' + $(this).attr('data-filtersmodule')));
                });
                self.modules = $('div.mod_djc2fw');
                self.setupModuleFilters();
                self.fadeIn([self.modules]);
                if ($('#djcatalog').length > 0) {
                    $('#djcatalog').trigger('ajaxFilter:loadItems');
                } else {
                    $(document).trigger('ajaxFilter:loadItems');
                }
            });
        },

        fadeIn: function(elements) {
            //console.log('fade in call');
            //console.log(elements);
            $.each(elements, function(){
                $(this).css({
                    'opacity': '1'
                });
            });
        },

        fadeOut: function(elements) {
            //console.log('fade out call');
            //console.log(elements);
            $.each(elements, function(){
                $(this).css({
                    'opacity': '0.3'
                });
            });
        }
    };

    window.DJCatalog2FiltersWizard = DJCatalog2FiltersWizard;
})(jQuery);