var request = null;
$(window).resize(function() {
    if($('#suggestions').is(':visible')) showResults('bfulltext', 'suggestions', true);
    if($('#enableAjax').is(':visible')) showResults('bfulltext', 'enableAjax', false);
});

$(function() {
     goAjax();
     $('div#suggestions').css({'-moz-box-shadow':'2px 2px 5px #555555','-webkit-box-shadow':'2px 2px 5px #555555','box-shadow':'2px 2px 5px #555555','zoom':'1','_border-width':'0 2px 2px 1px','*border-width':'0 2px 2px 1px'});
});

function goAjax() {
    $('#bfulltext').attr("autocomplete", "off");
    if ($('#suggestions').length < 1) $('body').append('<div id="suggestions"></div>');
    $('#suggestions').hide();
    $('#bfulltext').bind('keyup', showAjax);
    $('#bfulltext').click(function() {
    		if ($(this).val() == 'hledat...') {
    			$(this).val('');
    		}
    });
    $('#bfulltext').blur(function(){ fill(); });
}

function showAjax () {
	if ($(this).val() == 'hledat...') $(this).val('');
    lookup($(this).val());
}

function lookup(inputString) {
    if (inputString.length < 3) {
        $('#suggestions').hide();
        if (request && request.abort) request.abort();
        $('#bfulltext').removeClass('working');
    } else {
        if (request && request.abort) request.abort();
        $('#bfulltext').addClass('working');
        var inputString = encodeURIComponent(inputString);
        request = $.ajax({
            type: "POST",
	        url: "/suggestion.php",
	        data: "word=" + inputString,
	        dataType: "html",
	        success: function(data){
	            if (data.length >0) {
		            $('#suggestions').html(data);
		            showResults('bfulltext', 'suggestions', true);
		            $('#bfulltext').removeClass('working');
		            request = null;
	            }
	        }
	    });
    }
}

function showResults(input, container, ajax) {
    input = '#' + input;
    container = '#' + container;

    $('div#suggestion-box').css({'zoom':'1'});
    $('div#suggestion-box .suggestsection a').css({'_border-bottom':'1px solid #eee', '_zoom':'1'});
    
    var pos = $(input).offset();
    var width = $(input).outerWidth();
    var height = $(input).outerHeight();

    if (ajax) {
	    $(container).css({
	        top: (pos.top + height) + "px",
	        left: (pos.left - width - 9) + "px"
	    }).show();
    } else {
	    $(container).css({
	      top: (pos.top - $(container).outerHeight() + 1) + 'px',
	      left: (pos.left + 1) + "px"
	    }).show();
    }
}

function fill(thisValue) {
	if ($('#bfulltext').val() == '') $('#bfulltext').val('hledat...');
    setTimeout("$('#suggestions').hide();", 200);
}
