(function ($) {
    $.fn.vipAutoComplete = function (customOptions) {
        var options = $.extend({}, $.fn.vipAutoComplete.defaultOptions, customOptions);
        var timeout;
        var timeout_2;
        var currentIndex = -1;
        return this.each(function() {
            function initElements(){
                $('#search').parents('.searchBox').append('<div class="autocomplete_body" style="display:none"><ul class="autocomplete_list"> </ul></div>');
            }
            function attachEvents(){
                $('#search').keydown(function(e){
                    var key = e.which;
                    if (key == 13 && $('.autocomplete_body > ul > li.active').length) {    //enter
                        e.preventDefault();
                        var theLink = $('.autocomplete_body > ul > li.active > a').attr('href');
                        document.location = theLink;
                    } else if (key == 13 && $('#search').val()){
                        $('#formQuery')[0].submit();
                    }
                });
                $('#search').keyup(function(e){
                    var target = e.target;
                    var key = e.which;
                    clearTimeout(timeout);
                    if ($(target).val().replace(/^\s/, '').length >= options.minChars && key != 38 && key != 40){
                        $(target).data('lastQuery', $(target).val());
                        var func = function(){
                            filter($(target));
                        }
                        timeout = setTimeout(func, options.keyUpTimeout);
                    } else if (!$(target).val()){
                        $('.autocomplete_body').hide();
                    }
                    var selIndex = $('.autocomplete_body > ul > li.active').index();
                    var maxIndex = 0;
                    if (key == 38) {    //up
                        if ($('.autocomplete_body > ul > li.active').length != 0) {
                            $('.autocomplete_body > ul > li.active').removeClass('active');
                        }
                        if ($('.autocomplete_body').find('.searchAll').length){
                            maxIndex = $('.autocomplete_body > ul > li').length - 1
                        } else {
                            maxIndex = $('.autocomplete_body > ul > li').length
                        }
                        if (selIndex-1 >= 0){
                            $('.autocomplete_body > ul > li').eq(selIndex-1).addClass('active');
                        } else {
                            $('.autocomplete_body > ul > li').eq(maxIndex-1).addClass('active');
                        }
                        $(this).val($('.autocomplete_body > ul > li.active').text());
                        return;
                    }
                    if (key == 40) {    //down
                        if ($('.autocomplete_body > ul > li.active').length != 0) {
                            $('.autocomplete_body > ul > li.active').removeClass('active');
                        }
                        if ($('.autocomplete_body').find('.searchAll').length){
                            maxIndex = $('.autocomplete_body > ul > li').length - 1
                        } else {
                            maxIndex = $('.autocomplete_body > ul > li').length
                        }
                        if (selIndex+1 < maxIndex){
                            $('.autocomplete_body > ul > li').eq(selIndex+1).addClass('active');
                        } else {
                            $('.autocomplete_body > ul > li').eq(0).addClass('active');
                        }
                        $(this).val($('.autocomplete_body > ul > li.active').text());
                        return;
                    }
                });
                
                $('#formQuery').submit(function(e){
                    if ($('.autocomplete_body').is(':visible')) {
                        e.preventDefault();
                        return false;
                    }
                    return false;
                });
                $('#formQuery .go').click(function(e){
                    if (!$('#search').val()){
                        e.preventDefault();
                    } else {
                        var url = $('#formQuery').attr("action") + "?" + $('#formQuery').serialize();
                        document.location = url;
                    }
                });

                $('.autocomplete_body > ul > li').live('mouseover', function(){
                    $(this).parent().find('li').removeClass('active');
                    $(this).addClass('active');
                }).live('mouseout', function(){
                    $(this).removeClass('active');
                });
                
                $('.searchAll').live('click', function(e){
                    e.preventDefault();
                    var target = e.target;
                    $('#formQuery')[0].submit();
                    
                    return false;
                });
                
                $('.autocomplete_body').live('mouseout', function(e){
                    var func = function(){
                        $('#search').val($('#search').data('lastQuery'));
                        $('.autocomplete_body').hide();
                    }
                    timeout_2 = setTimeout(func, options.keepDivTimeout);
                }).live('mouseover', function(e){
                    clearTimeout(timeout_2);
                });
                
            }
            function filter(elem){
                var query = $(elem).val();
                $.getJSON('/php/search/data.php?query=' + query + '&vid=' + options.versionId, function(data){
                    var html = '';
                    $(data).each(function(i, item){
                        if (i<10){
                            html += getItemHtml(item);
                        }
                    });
                    if ($(data).length){
                        $('.autocomplete_body').show();
                        if ($(data).length >= 10){
                            html += '<li class="allResults"><a href="#" class="searchAll">' + options.lang.Show_all_results + '</a></li>'
                        }
                        $('.autocomplete_list').html(html);
                    } else {
                        $('#search').val($('#search').data('lastQuery'));
                        $('.autocomplete_body').hide();
                    }
                    
                });
            }
            function getItemHtml(item){
                var className = '';
                    var style ='';
                    if (item.item_type == 1 ){
                        className = "type_page";
                        
                    } else {
                        className = "type_phone";
                        if (item.item_image){
                            style=' style="background-image:url(..' + item.item_image + ');" ';
                        }
                    }

                return '<li class="' + className + '"><a ' + style + ' href="' + item.item_href + '">' + item.item_title + '</a></li>';
            }
            initElements()
            attachEvents();
        });
    };
    $.fn.vipAutoComplete.defaultOptions = {
        minChars: 1,
        keyUpTimeout: 10,
        keepDivTimeout: 10,
        versionId: 1,
        lang: {
            Show_all_results : 'Show all results'
        }

    };
})(jQuery);
