$(document).ready(function()
{
	site.init();
});

var site =
{
	init: function()
	{
		this.clear_and_recall('email');
		this.clear_and_recall('password');
		this.set_up_header_search_form();
		this.set_up_search_form();
		this.set_up_autocompleter();
	},
	
	set_up_header_search_form: function()
	{	
		var labels = $('#search_types label');
		var inputs = labels.find('input[name=flatshare_type]');

		// Highlight the label that contains this radio input
		inputs.click(function()
		{
			labels.removeClass('on');
			$(this).parent().addClass('on');
		});

		// Highlight the initial label
		// If there is no input already checked, just check the first one
		var highlight = inputs.filter(':checked');
		var checked = highlight.length;		
		if (!checked) highlight = inputs.filter(':first');
		highlight.trigger('click');
		
		// Focus the text box if the page doesn't contain a more important field
		var has_field = $('#main_content input[type=text]').length;
		if (!has_field) $('#where').focus();
	},
	
	set_up_search_form: function()
	{
		// Insert a link to toggle the edit search form
		$('body.adlist div.title.has_menu h1').after('<p id="edit_search_link">(<a href="#searchbox">Edit search</a>)</p>');
	
		var edit_search = $('body.adlist #searchbox');
		edit_search.hide();
		
		// Toggle the edit search form on click
		var edit_search_link = $('#edit_search_link');
		edit_search_link.click(function()
		{
			edit_search.slideToggle('fast');
			return false;
		});
	},
	
	clear_and_recall: function(text_field_id)
	{
		var field = $('#'+text_field_id);
		var initial_value = field.val();
	
		// Clear text box value on click
		field.click(function()
		{
			if ($(this).val() == initial_value) $(this).val('');
		});
		// Restore original value on blur
		field.blur(function()
		{
			if (!$(this).val()) $(this).val(initial_value);
		});
	},
	
	set_up_autocompleter: function()
	{
		// Add autocompletion to the big search box in the header
		this.autocompleter = new autocompleter('where');
		this.autocompleter.initialise();
	}
}