var map;
var mapUtils;
var load_map = false;
var last_autocomplete_search = '';

$(document).ready(function(){
	//Assign listeners for fuel_types
	$('.ft-select').each(function(){
		$(this).click(function(){
			var val = $(this).attr('id').split('_')[1];
			setFuelType(val, $(this));
			$('#query').focus();
			return false;
		});
	});
	//Assign listeners for search_days
	$('.day-select').each(function(){
		$(this).click(function(){
			var val = $(this).text().toLowerCase();
			setSearchDay(val, $(this));
			$('#query').focus();
			return false;
		});
	});
	
	//Init autocompleter
	$('#query').autocomplete({
		delay: 500,
		source: '/search/autocomplete',
		autoFocus: true,
		minLength: 1,
		position: {
			my: 'left top',
			at: 'left bottom',
			of: $('#query-wrap')
		},
		focus: function( event, ui ) {
			//$( "#query" ).val(ui.item.value);
			return false;
		},
		select: function( event, ui ) {
			// if typed string doesn't match what's currently searching, ignore the suggestion last focused on
			// the only tradeoff is for fast mouse clickers, their selection will be ignored, 
			// but for keyboard ninjas this will save from frustrating behavior
			if (last_autocomplete_search == $(this).val()) {
				$( "#query" ).val(ui.item.value);
			}
			return false;
		},
		search: function(event, ui) {
			last_autocomplete_search = $(this).val();
		},
		close: function(event, ui) {
			last_autocomplete_search = '';
		}
	}).data( "autocomplete" )._renderItem = function( ul, item ) {
		var li = $('<li></li>').data( "item.autocomplete", item );
		if (item.postcode) {
			li.append('<a><span class="auto_s">' + item.value + '</span><span class="auto_p">' + item.postcode + '</span></a>');
		} else {
			li.append('<a>' + item.value + '</a>');
		}
		return li.appendTo(ul);
	};
	
	
	$('#discard_location').click(function(){
		deleteSavedLocation();
		return false;
	});
	
	if (load_map == true) {
		loadMap();
	}
	
	//Attach handlers for clickable results
	if (mapUtils) {
		
		//if < IE8 may need to trim long search-queried location in sidebar
		if ($.browser.msie && ($.browser.version.substr(0,1) < 8)) {
			//trim to 23 chars
			var max_length = 23;
			var printed_query = $('#results-tab-title h1 b').text();
			if (printed_query.length > max_length) {
				$('#results-tab-title h1 b').text(printed_query.substr(0,max_length) + '...');
			}
		}
		mapUtils.setupStationsClickAndHover();
		
		// If we have a map listen for maptype selector
		mapUtils.initFTMTListeners();
		
		// Initialize toggler for lock/unlock list of map scanner
		mapUtils.initLockUnlockToggle();
		
		// The map options toggles (mapsize)
		mapUtils.initMapOptionsToggles();
		
		// The save map location behavior
		mapUtils.initMapLocationSaver();
	}
	
	//Is there any saved location link?
	$('#discard-link').click(function(){
		discardLocationLinkClicked();
	});
	
	//Focus on the search input
	$('#query').focus();
});

//Saved location links admin, put here because it may be present in non mapUtils'ed page
function toggleMapStringLink (show){
	var links_wrapper = $('#header-links').html('');
	
	if (show) {
		var jump_link_wrap = $('<div id="jump-link-wrapper"></div>');
		var discard_link = $('<a id="discard-link" title="discard saved location">(x)</a>').click(function(){
			discardLocationLinkClicked();
		});
		jump_link_wrap.append(discard_link);
		jump_link_wrap.append($('<a id="jump-link" href="/my_area">go to your saved location</a>'));
		
		links_wrapper.append(jump_link_wrap);
	}
}
function discardLocationLinkClicked(){
	var confirmed = confirm('Are you sure you want to discard your saved location?')
	if (confirmed) {
		eraseCookie('map_string');
		toggleMapStringLink(false);
	} 
}

function setFuelType(val, el) {
	$('#fuel_type').val(val);
	$('.ft-select').each(function(){
		$(this).removeClass('selected');
	});
	//Mark recently clicked item
	el.addClass('selected');
}

function setSearchDay(val, el) {
	$('#search_day').val(val);
	$('.day-select').each(function(){
		$(this).removeClass('selected');
	});
	//Mark recently clicked item
	el.addClass('selected');
}

// Cookie admin
function deleteSavedLocation()
{
	remove = confirm("Are you sure you want to discard your saved location");
	if (remove)
	{
		eraseCookie('map_string');
		$('#jump').remove();
	}
}

function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+escape(value)+expires+"; path=/";
}

function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name)
{
	createCookie(name,"",-1);
}
