var page = 1;
var type = 'all';
var alreadyOpen = 0;

$(document).ready(function() {
	var minLength = 3; // minimum chars
	var searchDelay = 450; // delay in ms
	var timer = undefined;
	
	$('#liveTypeSearch-container').hide();
	//$('#search-text').focus(function() {
	$('#ask_text').focus(function() {
		var newValue = $(this).val();
		if($(this).val() == 'ask the gooroos') { 
			$(this).attr('value',''); 
		} else { 
			$(this).val(newValue);
		}
		//$("#search-text").keyup(function() {
		$("#ask_text").keyup(function() {
			if (timer != undefined)
				clearTimeout(timer);
			
			if ($(this).val().length >= minLength) {
				page = 1;
				timer = setTimeout('runSearch()', searchDelay); // with this the new key is already in the input value attribute
			}
		});
	});

	//$('#search-text').blur(function() {
	$('#ask_text').blur(function() {
		var newValue = $(this).val();
		if($(this).val() == ''){
			$(this).attr('value','ask the gooroos');
		} else {
			$(this).val(newValue);
		}
		//$('#search-text').unbind('keyup');
		$('#ask_text').unbind('keyup');
	});
});

function runSearch() {
	//var input = $('#search-text');
	var input = $('#ask_text');
	if (input.val() == '') {
		alreadyOpen = 0;
		$('#liveTypeSearch-container').hide();
	}
	else
		$.ajax({
			type : "POST",
			url : indexUrl + '/',
			data : "ajaxRequest=1&s=" + input.val() + "&page=" + page + "&type=" + type,
			success : function(msg) {
				if(alreadyOpen == 0) {
				// show the results box
					$('#liveTypeSearch-container').show('blind');
				}
				
				alreadyOpen = 1;

				// print results into the results box
				$('#liveTypeSearch-results').html(msg);

				/*
				* reset the type - since there is no button to remove type from
				* search, when clicked on one type of results, there is no way
				* to get back to searching all, so we remove the type filter
				* after changing the search field
				*/
				type = 'all';

				/*
				* if there is a next button - bind an onClick event
				*/
				$('#liveTypeSearch-next').click(function() {
					page++;
					runSearch();
				});

				/*
				* if there is previous button - bind an onClick event
				*/
				$('#liveTypeSearch-previous').click(function() {
					page--;
					runSearch();
				});

				/*
				* bind event to type of post - after clicking it, we filter the
				* results to display only posts of given type, we reset the
				* page
				*/
				$('.liveTypeSearch-resultsList-type').click(function() {
					page = 1;
					type = $(this).attr('rel');
					runSearch();
				});

            }
        });
}
