$(document).ready(function() {

    $('body').append('<div id="dialogContainer"></div>');

    $('#msf').autocomplete("/xhr/search/header_suggestions.php", {
        width : 304,
        selectFirst : false
    });

    $('#msf').keydown(function(event) {
        if (event.keyCode == "40" || event.keyCode == "38") {
            var suggestion = $('.ac_results .ac_over').html();
            suggestion = suggestion.replace('<strong>', '');
            suggestion = suggestion.replace('</strong>', '');
            $('#msf').val(suggestion);
        }

        if (event.keyCode == "13") {
            $('#searchform').submit();
        }
    });

    search.ini();
});


var search = {
    value  : false,
    of     : 0,
    number : 0,
    limit  : 1,

    ini : function() {

        if (typeof SearchConf!="undefined") {
            search.number = SearchConf.searchNumber;
            search.value  = SearchConf.searchValue;
            search.of     = SearchConf.of;

            $(window).scroll(function() {
                if  (($(document).height() - $(window).height()) - $(window).scrollTop() <=1){
                    search.getArticles();
                }

            });
        }
    },

    getArticles : function() {
        var lastLoadedIndex = loaded.length;
        var articlesToLoad = lazyLoad.slice(lastLoadedIndex, lastLoadedIndex + 5);

        if (articlesToLoad.length > 0) {

            $.merge(loaded, articlesToLoad);
            search.showPreloader();
            $.ajax({
                url : '/xhr/search/get_article_data.php',
                data : {ids : articlesToLoad.join('-'), offset : lastLoadedIndex},
                context : document.body,
                success: function(data) {
                    var scope = this;

                    if (data != "") {
                        $(".articleRow:last").after(data);
                        $(".articleRow:last").hide().fadeIn('slow');
                    }
                    //fastOrder.ini();
                    search.hidePreloader();
                }
            });
        }
    },
    showPreloader : function() {
        var container = 'searchLoader';

        if (!$('#' + container).length) {
            loaderDiv = '<div id="' + container + '" style="display:none;"><img src="/img/misc/loading.gif" alt="" title="" /></div>';
            $('#searchResultContainer').append(loaderDiv);
        }

        $('#' + container).show();
    },

    hidePreloader : function() {
        $('#searchLoader').hide();
    }
}
