/*
 * Autocompletion scripts for eSellerPro models based on jquery ui
 * author: Micha? Skrzypek
 * version: 0.2.2
 * last modification: 2011-04-06
 */
 
$.fn.populate = function (keyword,source,limit)
{
    url = source + '?searchquery=' + keyword + '&searchmaxreturn=' + limit;
    $list = $(this);
    limit = 5;
    
    $.ajax({
        url: url,
        dataType: "html",
        success: function( response ) {
            $list.html(response);
            
            if ($list.find('.Item').length > 0 ){
                /*** limiter ***/
                $list.find('.Item').each(function(index){
                    if (index>limit-1) $(this).css('display','none');
                });
                /*** limiter ***/
                
                $list.show();
            }
        }
    });
}
 
$.fn.productSuggestions = function( options ){
    
    minLength = (options['minLength']?options['minLength']:2);
    delayTime = (options['delay']?options['delay']+20:220);
    source = '/' + (options['source']?options['source']:'productsuggestions2.html');
    limit = (options['limit']?options['limit']:5);
    
    $list = $("<div></div>").attr('id','Product-Suggestions').css('display','none').css('position','absolute').css('z-index','99999').appendTo($('body'));
            
    var timeout = undefined;
    var left = 0;
    var top = 0;
    $(this).keyup(function(){
        
        var $input = $(this);
        
        if ($input.val().length < minLength){
            $list.hide();
            return;
        }
        
        if(timeout != undefined) clearTimeout(timeout);
        
        timeout = setTimeout(function(){
            offset = $input.offset();
            
            left = offset.left;
            top = $input.outerHeight() + offset.top;
            
            if ($('.ui-autocomplete').css('display') == 'block')
                top += $('.ui-autocomplete').outerHeight();
                
            $list.populate($input.val(),source,limit);
            $list.css('left',left + 'px');
            $list.css('top',top + 'px');
            
        },delayTime);
        
    });
    $(this).blur(function(){
        if(timeout != undefined) clearTimeout(timeout);
        
        timeout = setTimeout(function(){
            $list.hide();
        },100);
    })
}

$(function() {

	function highlight( keyword )
	{
		$(".ui-autocomplete li a").each(function()
		{
			$(this).html(
				$(this).html().replace(
					new RegExp(keyword.toLowerCase(),'gi'),
					'<span class="highlight">' + keyword.toLowerCase() + '</span>'
					)
			);
		});
	}

	$.ajax({
		url: "/!autocomplete.xml",
		dataType: "xml",
		success: function( xmlResponse ) {
			var data = $( "item", xmlResponse ).map(function() {
				return $( "title", this ).text() ;
			}).get();
			
			var minLength = 2;
			var delay = 300;

			$.each( autocompleteSearchIds , function(index,value){
				$("#"+value).autocomplete({
					source: data,
					minLength: minLength,
					delay: delay,
					position: { my : "left top", at: "left bottom" },
					open: function(event, ui) {
						highlight(this.value);
					},
					focus: function(event,ui) {
						this.value = ui.item.value;
					},
					select: function(event, ui) {
						$(this).parents('form:first').submit();
					}
				});
				$("#"+value).productSuggestions({
				    minLength: minLength,
				    delay: delay
				});
			});
		}
	});
});
