function flip(el){
	//console.log($(el));
	$(el).children('li.inactive').fadeOut(750);
	$(el).children('li.active').fadeIn(750);
}

function unflip(el){
	//console.log($(el));
	$(el).parents('li.active').fadeOut(500);
	$(el).parents('li').siblings('li.inactive').fadeIn(500);
}



function do_ajax(form_id){
	//alert("form: " + form_id);
	//console.log($('form#'+form_id).serialize());
	//alert('s' + $('form#' + form_id + ' input[name=search_type]').val());
	$.post('/property/' + form_id + '/search/ajax',
	
		{ 
			search_type: $('form#' + form_id + ' input[name=search_type]').val(),
			location: $('form#' + form_id + ' select[name=location]').val(),
			bedrooms: $('form#' + form_id + ' select[name=bedrooms]').val(),
			min_price: $('form#' + form_id + ' select[name=min_price]').val(),
			max_price: $('form#' + form_id + ' select[name=max_price]').val(),
			min_price_lettings: $('form#' + form_id + ' select[name=min_price_lettings]').val(),
			max_price_lettings: $('form#' + form_id + ' select[name=max_price_lettings]').val(),
			keywords: $('form#' + form_id + ' input[name=keywords]').val()
		},
		
		function(data){
			$('span.' + form_id + '_results').text('(' + data + ')');
			$('span.' + form_id + '_results').hide();
			$('span.' + form_id + '_results').fadeIn('normal');
			//console.log(data);
			//alert(data);
		}
		
	);
}

function initiate_ajax(){
	
	// Bind an event handler on the appropriate form elements
	$('select').change(function(){
		do_ajax($(this).parents('form').attr('id'));							
	});
	
	$('input[name="keywords"]').keyup(function() {
		if ($(this).val() != $(this).lastValue && $(this).val().length>2) {
		  if ($(this).timer) clearTimeout($(this).timer);
		  $(this).timer = setTimeout('do_ajax("' + $(this).parents('form').attr('id') + '")', 350);
		  $(this).lastValue = $(this).val();
		}
	});
	
}

$(document).ready(function(){
						   
	auto_fill($('#keywords_lettings'), 'Keyword / Postcode');
	
	$('ul.home-buttons li.inactive').click(function(){
		flip($(this).parent());						  
	});
	
	$('a.close-panel').click(function(){
		unflip($(this));						  
	});
	
	$('li.active').hide(); // Hide the 'flip' panels
	
	initiate_ajax();
	do_ajax('for-sale');
	do_ajax('to-let');
	
});
