/*
 * Name: Simple jQuery AutoComplete
 * Author: Michael Stowe
 * Version 1.0
 * ---------------------
 * Sends user input via "GET" to a dynamic page with a "q" query, and then takes the
 * pipe-delimited text and returns it as a clickable dropdown list.
 * ---------------------
 * Example: 
 * <input type="text" name="example" id="example" rel="use_this_page_for_results.php" />
 * <script language="javascript">$('#example').autosuggest();< /script>
 * ---------------------
 * Changelog: 
 * ---------------------
 * (c) 2010, http://www.mikestowe.com
 */ 

autosuggest_min_length = 2; // Minimum characters before running ajax check
autosuggest_left_offset = -10; // Left Offset Adjustment
autosuggest_top_offset = -2; // Top Offset Adjustment

jQuery.fn.autosuggest = function() {
  return this.each(function(){
  	var id = $(this).attr('id');
   	var offset = $(this).offset();
	var left = offset.left + autosuggest_left_offset;
	if($(this).height() == 0) { var height = 30; } else { var height = $(this).height() + 5; }
	if($(this).width() == 0) { var width = 200; } else { var width = $(this).width() + 5; }
	var top = offset.top + height + autosuggest_top_offset;
	document.write('<div class="autosuggest" id="autosuggest_'+id+'" style="position: absolute; left: '+left+'px; top: '+top+'px; width: 200px; display: none;"></div>');
    $(this).keyup(
        function() {
				if($('#'+id).val().length > autosuggest_min_length) {
				$.ajax({
				  url: $('#'+id).attr('rel'),
				  data: {q: $('#'+id).val()},
				  success: function(data) {
				    if(data.length > 0) {
						var ret = '<div class="autosuggest_inner">';
						var pairs = data.split('|');
						for(var i in pairs){
							var info = pairs[i].split(',');
							ret += '<a href="javascript: void(0);" onclick="$(\'#'+id+'\').val(\''+info[0]+'\'); $(\'#autosuggest_'+id+'\').hide();">'+info[0]+'</a>';
							ret += '<a href="'+info[1]+'" onclick="$(\'#autosuggest_'+id+'\').hide();" target="_blank" class="productlink"><nobr>view &raquo;</nobr></a>';
						}
						ret += '</div>';
						$('#autosuggest_'+id).html(ret).show();
					} else {
						$('#autosuggest_'+id).hide();
					}
				  }
				});
			} else {
				$('#autosuggest_'+id).hide();
			}
        }); 
    	
    $(this).blur(
  		  function() {
  			  $('#autosuggest_'+id).hide('slow');
  		  }
    );
    
  });
};
