//Autocomplete searcher by behinddesign.co.uk

var search = {
	
	search_data : false,
	limit : 20,
	timeout_id : false,
	typing_timeout : 500,
	min_chars : 2,
	cache_data : new Array(),
	slow_close : false,
	slow_close_timeout : 3000,
	in_box : false,
	box_open : false,
	
	init : function(){
		//Bind to search box
		$("#search").bind("keyup", this.keyPressed);
	},
	
	keyPressed : function(event){
		//Check keycode
		var RETURN = 13;
		var ESC = 27;

		switch(event.keyCode)
		{
			case RETURN:
				return true;
				break;

			case ESC:
				search.closeBox();
				return true;
				break;
		}
		
		if($('#search').val().length > search.min_chars){
			//check cache here
			if(!search.cache_data[$('#search').val()]){
				clearTimeout(search.timeout_id);
				search.timeout_id = setTimeout("search.ajax()",search.typing_timeout);
			}else{
				//Cache is set, display that instead.
				search.updateBox(search.cache_data[$('#search').val()]);
			}
		}else{
			if($('#search').val().length == 0){
				search.closeBox();
			}
		}
		return true;
	},
	
	updateBox : function(cachedata){
		if(cachedata){
			//Display cached HTML instead of generating HTML
			$('#live_search').html(cachedata);
			$('#live_search').show();
		}else{
			if(search.search_data.length > 0){
				var html = '<ul class="listing ui-tabs ui-widget ui-widget-content ui-corner-all">';
				var limit_count = 0;
				var show_count = 0;
				//Set loop count based on maximum limit or current in array
				if(search.search_data.length < search.limit){
					show_count = search.search_data.length;
				}else{
					show_count = search.limit;
				}
				for(x=0;x<show_count;x++){
					var nameHighlighted = search.search_data[x]['name'];
					var re = new RegExp("("+$('#search').val()+")","i");
					nameHighlighted = nameHighlighted.replace(re,"<strong>$1</strong>");
					html += '<li class="item"><div class="pic"><a href="'+search.search_data[x]['url']+'">';
					html += '<img border="0" width="80" height="80" alt="'+search.search_data[x]['name']+'" src="'+search.search_data[x]['image']+'"></a></div>';
					html += '<h3><a href="'+search.search_data[x]['url']+'">'+nameHighlighted+'</a></h3><div class="price">';
					html += '<span>£'+search.search_data[x]['price'];
					html += '</span></div>';//<div title="Rating : 4/5" class="stars stars_4"><span class="hide">****</span></div>
					//<div class="stock">50+ items in stock</div>
					html += '<div class="action"><a href="'+search.search_data[x]['url']+'"><span>MORE</span></a>';
					html += '</div></li>';
					limit_count++;
				}
				html += '</ul><div class="more_results"><a href="#" onclick="$(\'#main_search\').submit(); return false">See more results</a></div>';
				$('#live_search').html(html);
				search.showBox();

				//Insert HTML into cache
				search.cache_data[$('#search').val()] = html;
			}else{
				//No data, close search box.
				search.closeBox();
			}
		}
	},
	
	showBox : function(){
		if(search.box_open == true){
			return false;
		}
		search.box_open = true;
		//Remove closeBox binds
		$('#search').unbind("mouseenter");
		
		//Do search box opening
		//$('#live_search').show();
		$('#live_search').fadeIn('medium');


		//Lets close the box after x second if mouse leaves
		$('#live_search').mouseleave(function(){
			if(search.in_box == true){
				//search.slow_close = setTimeout("search.closeBoxTimeout()",search.slow_close_timeout);
				search.in_box = false;
			}
		});
		$('#live_search').mouseenter(function(){
			if(search.in_box == false){
				//clearTimeout(search.slow_close);
				search.in_box = true;
			}
		});
		
		//If mouse is out of the box, and only if it's out of the box, and the mouse is clicked. Close box. Unless eventtarget is search box
		$('body').click(function(event){
			if(event.target.id != 'search'){
				if(search.in_box == false){
					search.closeBox();
				}
			}
		});
	
		return true;
	},
	
	closeBoxTimeout : function(){
		
		$("#live_search").mouseleave(search.closeBox());
	},
	
	closeBox : function(){
		if(search.box_open == false){
			return false;
		}
		//clearTimeout(search.slow_close);
		search.box_open = false;
		//Remove showBox binds
		$('body').unbind("click");
		$('#live_search').unbind("mouseenter");
		$('#live_search').unbind("mouseleave");
		
		//Do search box closing
		$('#live_search').fadeOut('medium');
		
		//If there's data saved, box has just closed, so allow it to open on search hover
		if(search.search_data.length > 0){
			$('#search').mouseenter(function(){
				if($('#search').val().length > 0){
					search.showBox();
				}
			});
		}
		return true;
	},
	
	ajax : function(){
		$.ajax({
			//url: "/json.php?q=" + escape($('#search').val()),
			url: "/cgi-bin/qs.cgi?" + escape($('#search').val()),
			type: 'get',
			dataType: 'json',
			success : function(t) {
				if(t.length > 0){
					search.search_data = t;
					search.updateBox();
					return true;
				}else{
					search.closeBox();
					return false;
				}
			},
			error : function () {
				search.closeBox();
			},
			timeout : function () {
				
			},
			async : true
		});
	}
}
