var queryCache = '';
var obj;
var totalItems = 0;
var keyboardAttached = false;
var pageLoaded = false;
var cHighlight = 0;

$(document).ready(function() {

    	obj = $('#form_search_query');
			
	obj.after( '<div id="results" style="display:none;"></div>' );
		
	$(document).keydown( function(e){ if(e.keyCode==13){ arrowPress( e.keyCode ); } });
			
	queryDefault = obj.val(); //capture our default
			
	obj.focus( function(){ 
			
		if( obj.val() == queryDefault ){ obj.val(''); obj.removeClass('default-value'); }
	
	});   			
		
	obj.blur( function(){ 
		
		if( obj.val() == '' ){ obj.val( queryDefault ); obj.addClass('default-value'); }
			
	});	
		
	watchSearch();
	
	
});		
		
function watchSearch() {
	
	if( obj.val().length >= 3 && obj.val() != queryCache && !obj.hasClass('default-value') ){
		
		queryCache = obj.val();
		executeSearch( queryCache );
	
	}else if( obj.val().length < 3 ){
	
		hideResults();
		queryCache = "";
	
	}
	
	window.setTimeout( watchSearch, 500 );

} // end watch search

function executeSearch( query ) {
	
	$.getJSON('/json_predict.php', {search:query}, function(data) {
		
		if( data!=null && (data.length > 0) ){
			
			handleResults( data );
			
			//attach keyboard events
			if( !keyboardAttached ){	
				keyboardAttached = true;
				$(document).keydown( function(e){ if(e.keyCode==38 || e.keyCode==40){ arrowPress( e.keyCode ); } });
			}
		
		}else{ //returned nothing
		
			hideResults();
		
		}
		
	});	
	
	
} //end execute search


function handleResults( data ){
	
	totalItems = 0;
	cHighlight = -1;
	
	$('#results').html(''); //clear results 
			
	$.each( data, function(index,val){ //each result	
		
		totalItems++;
		
		var lineHTML = "<a class='ritem' id='ritem_" + totalItems + "' href= '' ref='" + val + "'><span>" + val + "</span></div></a>";
		
		$('#results').append( lineHTML );
		
		$('#ritem_'+totalItems).hover( function(){
			highlight( $(".ritem").index(this), '' );
		});
		
		$('#ritem_'+totalItems).click( function(){
			// fillLaunchQuery( val );
			launchSearch( val, true, true );
			return false;
		});
							
	}); //end each
	
	$('#results').css('display','');
	
	$(document).bind('mouseup', hideResults );

}

function fillQuery( val ){
	
	queryCache = val;
	
	obj.val(val);
	
	hideResults();
	
}

function arrowPress( code ){

	if( code==38 ){ //up
	
		highlight( cHighlight-1, 'up' );
	
	}else if( code==40 ){ //down
	
		highlight( cHighlight+1, 'down' );
	
	}else if( code==13 ){ //enter
		
		if( cHighlight >= 0 ){
			fillQuery( $('.ritem.:eq(' + cHighlight + ')').attr('ref') );
		}else{
			launchSearch( obj.val(), true, true );
		}
	
	}

}

function highlight( id, dir ){
	
	cHighlight = id;
					
	//fix?
	if( cHighlight < 0 ){ cHighlight = totalItems; }
	if( cHighlight > totalItems ){ cHighlight = 0; } 
	
	$('.ritem').removeClass( 'active ');
	$('.ritem.:eq(' + cHighlight + ')').addClass( 'active' );


}

function hideResults(){
	$('#results').css('display','none');
	cHighlight = -1;
	$(document).unbind('mouseup', hideResults );
}

function launchSearch( search, slide, updateAddress){
	
	/*$('#results_block').load( '/businesses.php?inner=true&search=' + escape(search), function(){
		if( slide ){ $('#results_stage').slideDown(); }else{ $('#results_stage').show(); }
	});*/
	
	window.location = '/businesses.php?search=' + escape(search);
	
	//$('#choose img').css('display','none');
	
	hideResults();
	
}
