var currentLocation = $('.blerb strong').text();

// modify the dom
$('#content').wrapInner('<div class="bg"></div>');

$('form').submit(submitForm);
$('form button').click(submitForm)

$('<div />')
	.attr('id', 'loading')
	.text('Locating Stations')
	.hide()
	.appendTo('.search-form');

$('#loading').ajaxStart(function() {
		$(this).stop().fadeIn(250);
});
$('#loading').ajaxStop(function() {
	var that = $(this);
	setTimeout(function() {
		that.fadeOut(175);
	}, 200);
});

function submitForm(e)
{
	e.preventDefault();
	
	$.ajax({
		url: 'ajax.php',
		data: {action: 'postcodes', term: $('#search').val()},
		dataType: 'json',
		success: function(data) {
			
			if(data.length > 0) {
				currentLocation = $('#search').val();
				updateResultsForPostcode(data[0].postcode);
			} else {
				// postcode not found
				$('.blerb').html('There are no local stations');
				$('.no-results').show();
				$('#results').hide();
			}
		}
	});
	return false;
}

registerCookieCallback();

function registerCookieCallback()
{
	$('#results a').click(function() {
		$.cookie('station', $(this).attr('href'), {expires: 30, path: '/'});
	})
}

function updateResultsForPostcode(postcode)
{
	$.ajax({
		url: 'ajax.php',
		data: {action: 'stations', postcode: postcode},
		dataType: 'json',
		success: updateResults
	});
}

function updateResults(results)
{
	var html = '';
	if(results.length > 0) {
		for(var i = 0, len = Math.min(results.length, 10), station; i < len; i++) {
			station = results[i];
			html += '<li><a href="'+station.show_url+'"><img src="public/images/logos/'+station.image+'"><span>'+station.station+'</span></a></li>';
		}
		$('.blerb').html('Your <span class="local">local '+(results.length === 1 ? 'station is' : 'stations are')+':</span>');
		$('.no-results').hide();
		$('#results').show();
		$('#results').slideUp().html(html).slideDown();
		registerCookieCallback();
	} else {
		// no results available
		$('.blerb').html('There are no stations for the provided postcode');
		$('.no-results').show();
		$('#results').hide();
	}
}

/*$('#search').autocomplete({
	source: "ajax.php?action=postcodes",
	minLength: 2,
	focus: function( event, ui ) 
	{ 
		$( "#search" ).val( ui.item.label ); 
		return false;
	},
	select: function( event, ui ) 
	{
		if( ui.item.postcode == "****") {
			return false;
		} else {
			currentLocation = ui.item.label.toString().toLowerCase().replace(/^([a-z])|\s+([a-z])/g, function(s) {
				return s.toUpperCase();
			});
			updateResultsForPostcode(ui.item.postcode);
			//$("p.searchQuery").html("results for "+ui.item.label).show();
			return false;
		}
	}
});*/
