	window.suggestionIndex = -1;
	window.lastsuggestions = '';
	window.lastdata = '';
	window.lastreq = '';

    var delay = (function(){
      var timer = 0;
      return function(callback, ms){
        clearTimeout (timer);
        timer = setTimeout(callback, ms);
      };
    })();

	function parseJSON(data) {
		if ( typeof data !== "string" || !data ) {
			return null;
		}

		// Make sure leading/trailing whitespace is removed (IE can't handle it)
		data = jQuery.trim( data );

		// Attempt to parse using the native JSON parser first
		if ( window.JSON && window.JSON.parse ) {
			return window.JSON.parse( data );
		}

		// Make sure the incoming data is actual JSON
		// Logic borrowed from http://json.org/json2.js
		if ( rvalidchars.test( data.replace( rvalidescape, "@" )
			.replace( rvalidtokens, "]" )
			.replace( rvalidbraces, "")) ) {

			return (new Function( "return " + data ))();

		}
		jQuery.error( "Invalid JSON: " + data );
	}

	function search(){
        delay(function(){
            sb = $("#searchbox");
            if(!sb.val()){
                $('#suggestions').fadeOut();
                lastsuggestions = 'false';
                return;
            }

            if(sb.val().length < start_chars) {
                return;
            }

            su = $("#suggestions");
            su.css("left",sb.position().left);
            su.css("top",sb.offset().top + sb.outerHeight() + 5);

            if(lastreq)
                lastreq.abort();

            lastreq = $.ajax({
                url: 'suggestions.php',
                type: 'post',
                data: 'query=' + sb.val(),
                success: function(res){
                    if(sb.val())
                    if((res != 'false')){
                        if(lastsuggestions != res){
                            su.html('');

                            lastsuggestions = res;
                            var data = parseJSON(res);
                            lastdata = data;
                            $.each(data, function(i, object) {
                                if(i == 0){
                                    su.append('<div class="suggestion_row" style="border-top:none;" onmouseover="javascript:suggestionIndex=-1;suggestionNavigate(' + (i+1) + ');" onclick="javascript:location.href=\'' + object.url + '\'"><table border="0" cellpadding="3" cellspacing="5"><tr><td class="suggestiontd"><img width="100" height="70" src="suggestion_thumb.php?id=' + object.productid + '" /></td><td>' + object.product + "</td></tr/</table></div>");
                                }else{
                                    su.append('<div class="suggestion_row" onmouseover="javascript:suggestionIndex=-1;suggestionNavigate(' + (i+1) + ');" onclick="javascript:location.href=\'' + object.url + '\'"><table border="0" cellpadding="3" cellspacing="5"><tr><td class="suggestiontd"><img width="100" height="70" src="suggestion_thumb.php?id=' + object.productid + '" /></td><td>' + object.product + "</td></tr/</table></div>");
                                }
                            });
                            su.fadeIn();
                        }
                    }else{
                        lastsuggestions = 'false';
                        su.fadeOut();
                    }
                }
            });
        }, delay_in_search );
	}

    function showsuggestions(){
        if(lastsuggestions == "" || lastsuggestions == "false") {
            search();
        } else {
            $('#suggestions').fadeIn();
        }
        console.log(lastsuggestions);
    }

	function hidesuggestions(){
		$('#suggestions').fadeOut();
	}

    function suggestionNavigate (diff) {
        suggestionIndex += diff;

        var suggestionCollection = $(".suggestion_row");

        if (suggestionIndex >= suggestionCollection.length)
            suggestionIndex = suggestionCollection.length -1; // 0;

        if (suggestionIndex < 0)
            suggestionIndex = -1; //suggestionCollection.length -1;

        if(suggestionIndex == -1){
            suggestionCollection.removeClass("suggestion_row_hover");
        }else{
            suggestionCollection.removeClass("suggestion_row_hover").eq(suggestionIndex).addClass("suggestion_row_hover");
        }

        return false;
    }
