var braapf_grab_single_search_field,
braapf_apply_search_field,
braapf_show_search_filter_suggestion;
(function ($){
    $(document).on('submit', '.bapf_srch .bapf_body .bapf_form', function(event) {
        event.preventDefault();
        if ( $(this).is('.bapf_rm_filter') ) {
            $('.bapf_sfilter:not(.bapf_srch)').trigger('braapf_unselect');
        }
        $(this).trigger('bapf_search_update');
        berocket_do_action('update_products', 'update', $(this));
    });
    $(document).on('bapf_search_update', '.bapf_srch .bapf_body .bapf_form', function() {
        var input = $(this).find('.bapf_input:not(:disabled)');
        if( input.length ) {
            var data_name = input.data('name');
            if( typeof(data_name) != 'undefined' && data_name.length ) {
                if( data_name != input.val() ) {
                    input.data('value', '');
                    input.data('name', '');
                }
            }
        }
        event.preventDefault();
        var filter_changed_element = {
            element:'#'+$(this).closest('.bapf_sfilter').attr('id'),
            parent: 0,
            find: '.bapf_body'
        };
        berocket_apply_filters('filter_changed_element', filter_changed_element, $(this));
    });
    $.expr[":"].brContains = $.expr.createPseudo(function(arg) {
        return function( elem ) {
            return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
        };
    });
	braapf_show_search_suggestions_list = function($list, $element) {
        var height = $($element).closest('.bapf_srch').find('.bapf_input_suggestion').data('height');
        if( typeof(height) == 'undefined' || height <= 0 ) {
            height = 0;
        }
        var html = '<div class="bapf_current_suggest"';
        if( height != 0 ) {
            html += ' style="max-height:'+height+'px;"';
        }
        html += '></div>';
		var $html = $(html);
		$list.each(function(i, val) {
			var new_element = $(this).clone();
			$html.append(new_element);
		});
        $($element).closest('.bapf_srch').find('.bapf_current_suggest').remove();
		$($element).closest('.bapf_suggest').append($html);
	}
	braapf_last_search_field = false;
    $(document).on('keyup click', '.bapf_srch .bapf_suggest .bapf_input', function() {
        var $current_suggest = $(this).closest('.bapf_srch').find('.bapf_current_suggest');
		braapf_last_search_field = $(this);
        var value = $(this).val();
        $(this).data('value', value).data('name', value);
        if( value.length >= 3 && $(this).closest('.bapf_srch').find('.bapf_input_suggestion').length ) {
            if( ! $(this).closest('.bapf_srch').find('.bapf_input_suggestion.bapf_ajax_sug').length ) {
                $current_suggest.remove();
                var $suggestions = $(this).closest('.bapf_srch').find('.bapf_input_suggestion');
                var $suggested = $suggestions.find('.bapf_suggest_element:brContains("'+value+'")');
				braapf_show_search_suggestions_list($suggested, $(this));
            } else {
                var current_srch = '';
                if( $current_suggest.length ) {
                    current_srch = $(this).closest('.bapf_srch').data('ajax_search');
                    if( typeof(current_srch) == 'undefined' ) {
                        current_srch = '';
                    }
                }
				var last_value = $(this).closest('.bapf_srch').find('.bapf_input_suggestion.bapf_ajax_sug').data('lastval');
                if( current_srch == value ) {
                    
				} else if( last_value == value ) {
                    $current_suggest.remove();
					var $suggested = $(this).closest('.bapf_srch').find('.bapf_input_suggestion.bapf_ajax_sug').first().find('.bapf_suggest_element');
					braapf_show_search_suggestions_list($suggested, $(this));
				} else {
                    $current_suggest.remove();
                    var old_value = $(this).data('value');
                    var old_name = $(this).data('name');
                    $(this).data('value', '');
                    $(this).data('name', '');
					var $html = $(the_ajax_script.load_image);
					$html = $('<div class="bapf_loader_search">'+$html.html()+'</div>');
					braapf_show_search_suggestions_list($html, $(this));
                    $(this).closest('.bapf_srch').data('ajax_search', value);
					var url_filtered = braapf_get_url_with_filters_selected();
                    $(this).data('value', old_value);
                    $(this).data('name', old_name);
					braapf_ajax_load_from_url(berocket_apply_filters('before_update_products_context_url_filtered_partial', url_filtered, 'search_field', $(this)), {}, berocket_apply_filters('ajax_load_from_search_field', {done:[braapf_show_search_filter_suggestion, braapf_init_load]}, url_filtered, 'partial'), 'search_field');
				}
            }
        } else {
            $current_suggest.remove();
        }
    });
	braapf_show_search_filter_suggestion = function(html) {
		var $new = $(html).find('.bapf_ajax_sug').last().clone();
		$('.bapf_ajax_sug').replaceWith($new);
		var $suggested = $('.bapf_ajax_sug').first().find('.bapf_suggest_element');
		braapf_show_search_suggestions_list($suggested, braapf_last_search_field);
	}
    $(document).on('click', function(event) {
        var $target = $(event.target);
        if( ! $target.is('.bapf_suggest') && ! $target.closest('.bapf_suggest').length && ! $target.is('.bapf_input') ) {
            $('.bapf_current_suggest').remove();
        }
    });
    $(document).on('click', '.bapf_srch .bapf_current_suggest .bapf_suggest_open', function(event) {
        var input = $(this).closest('.bapf_srch').find('.bapf_form .bapf_input:not(:disabled)');
        if( input.length ) {
            input.data('value', $(this).data('search'));
            input.data('name', $(this).data('name'));
            input.val($(this).data('name'));
            $(this).closest('.bapf_srch').find('.bapf_form').trigger('submit');
        }
    });
    braapf_grab_single_search_field = function(single_data, element) {
        if( element.is('.bapf_srch') && single_data != false ) {
            var input = element.find('.bapf_body .bapf_input:not(:disabled)');
            var data_value = input.data('value');
            if( typeof(data_value) != 'undefined' && data_value.length ) {
                var value = encodeURIComponent(data_value);
                var data_name = input.data('name');
                if( typeof(data_name) != 'undefined' && data_name.length ) {
                    var html = data_name;
                    input.val(data_name);
                } else {
                    var html = value;
                }
            } else {
                var value = encodeURIComponent(input.val());
                var html = value;
            }
            if( value ) {
                single_data.values.push({value: value, html: html});
            }
            single_data.customValuesLine = '';
            single_data.search = true;
        }
        return single_data;
    }
    braapf_apply_search_field = function(url_data, single_data) {
        if(typeof(single_data.search) != 'undefined' && single_data.search) {
            var exist = false;
            if( Array.isArray(url_data.queryargs) ) {
                var newqueryargs = [];
                $.each(url_data.queryargs, function(i, val) {
                    if( val.name == single_data.taxonomy ) {
                        if( single_data.values.length ) {
                            val.value = single_data.values[0].value;
                            newqueryargs.push(val);
                        }
                        exist = true;
                    } else {
                        newqueryargs.push(val);
                    }
                });
                url_data.queryargs = newqueryargs;
            } else if( single_data.values.length ) {
                url_data.queryargs = [];
            }
            if( ! exist && single_data.values.length ) {
                url_data.queryargs.push({name:single_data.taxonomy, value:single_data.values[0].value});
            }
        }
        return url_data;
    }
    $(document).on('braapf_unselect braapf_unselect_all', '.bapf_srch', function(event, data) {
        $(this).find('.bapf_input:not(:disabled)').val('').data('value', '');
    });
    $(document).on('click', '.bapf_srch span.bapf_search[type="submit"]', function() {
        $(this).closest('.bapf_form').trigger('submit');
    });
    braapf_update_products_search_field = function(context, element) {
        if( context === 'update' ) {
            jQuery('.bapf_srch .bapf_body .bapf_form').trigger('bapf_search_update');
        }
    }
    berocket_add_filter('grab_single_filter_default', braapf_grab_single_search_field);
    berocket_add_filter('apply_additional_filter_data', braapf_apply_search_field);
    berocket_add_filter('update_products', braapf_update_products_search_field, 2);
})(jQuery);
