// product and product_category names store
var search_autocomplete_product = null;
var search_autocomplete_product_category = null;

// ajax requet in progress
var search_autocomplete_product_xhr = false;
var search_autocomplete_product_category_xhr = false;

// how many items show in autocomplete window
var search_autocomplete_limit = 15;
    
$(function() {
    var search = $('#fulltext_query');
    
    // keyup event (for autocomplete)
    search.keyup(function() {
        autocomplete_serach_categories();
        autocomplete_serach_products();
    });
    
    // focus/blur change
    var value = $('#fulltext_query').val();
    var title = $('#fulltext_query').attr('title');
    if (value == '') {
        search.val(title);
        search.focus(function() {
            if ($(this).val() == title) {
                $(this).val('');
            }
            autocomplete_search();
        });
        search.blur(function() {
            if ($(this).val() == '') {
                $(this).val(title);
            }            
        });
    }
    search.focus(function() {
        autocomplete_search();
    });
    search.blur(function() {
        setTimeout(function() { $('#autocomplete').hide(); }, 200);
    });
});

/**
 * Process autocomplete
 */
function autocomplete_search() {
    // reset autocomplete
    $('#ajaxAutocompleteCategories').html('');
    $('#ajaxAutocompleteProducts').html('');
    $('#ajaxAutocompleteCategories').parent().hide();
    $('#ajaxAutocompleteProducts').parent().hide();
    
    var query = $('#fulltext_query').val().trim();
    var show = false;
    if (query) {
        var r;
        var regex;
        var t;
        var p;
        var n = 0;        
        // search in categories
        if (search_autocomplete_product_category != null) {            
            var categories = '';            
            for (var key in search_autocomplete_product_category) {
                r = search_autocomplete_product_category[key];
                regex = new RegExp(query, 'i');
                if (r.name.search(regex) != -1) {
                    categories += '<li><a href="' + r.url + '">' + r.path.replace(regex, '<strong>' + query + '</strong>') + '</a></li>';
                    n ++;
                    if (n >= search_autocomplete_limit) {
                        break; // limit reached
                    }                    
                }
            }            
            if (categories) {
                show = true;
                $('#ajaxAutocompleteCategories').html(categories);
                $('#ajaxAutocompleteCategories').parent().show();
            }
        }
        // search in products
        if (search_autocomplete_product != null && n < search_autocomplete_limit) {
            var products = '';            
            for (key in search_autocomplete_product) {
                r = search_autocomplete_product[key];
                regex = new RegExp(query, 'gi');
                if (r.name.search(regex) != -1) {           
                    products += '<li><a href="' + r.url + '">' + r.name.replace(regex, '<strong>' + query + '</strong>') + '<span>|</span>' + r.price + '</a></li>';
                    n ++;
                    if (n >= search_autocomplete_limit) {
                        break; // limit reached
                    }                    
                }
            }           
            if (products) {
                show = true;
                $('#ajaxAutocompleteProducts').html(products);
                $('#ajaxAutocompleteProducts').parent().show();
            }
        }
        //var width = Math.max($('#ajaxAutocompleteProducts').width(),$('#ajaxAutocompleteCategories').width());
    }    
    // show or hide
    if (show) {
        $('#autocomplete').show();
    }
    else {
        $('#autocomplete').hide();
    }
}

/**
 * Get product data from HTTP url address using XHR
 */
function autocomplete_serach_products() {
    if (search_autocomplete_product == null && !search_autocomplete_product_xhr) {
        search_autocomplete_product_xhr = true;
        // get asynchronously product list 
        $.ajax({
            url: '/product_list_names.json',
            type: 'GET',
            error: function() {
                search_autocomplete_product = {}; // on error create empty object
            },
            success: function(data) {
                search_autocomplete_product = data; // on success save data
                search_autocomplete_product_xhr = false;
                autocomplete_search();                
            }
        });
    }
    else {
        autocomplete_search();
    }
}

/**
 * Get product category data from HTTP url address using XHR
 */
function autocomplete_serach_categories() {
    if (search_autocomplete_product_category == null && !search_autocomplete_product_category_xhr) {
        search_autocomplete_product_category_xhr = true;
        // get asynchronously product category list 
        $.ajax({
            url: '/product_category_list_names.json',
            type: 'GET',
            error: function() {
                search_autocomplete_product_category = {}; // on error create empty object
            },
            success: function(data) {
                search_autocomplete_product_category = data; // on success save data
                search_autocomplete_product_category_xhr = false;
                autocomplete_search();
            }
        });
    }
    else {
        autocomplete_search();
    }
}
