var map;
var gmarkers = [];
var htmls = [];
var activeInfoWindow = 0;
var bounds;
var sdClass = 'station-row';
var followMapView = true;

//Only turn on onclick checker on a results page: attached to show controller onload event
function check(e){ 
	if ($('morefuel') && $('fuel_type_a'))
	{
		var target = (e && e.target) || (event && event.srcElement); 
		var obj = $('morefuel'); 
		var obj2 = $('fuel_type_a'); 
		checkParent(target) ? switchFuel(false) : null; 
		target == obj2 ? switchFuel(true) : null;
	}
} 

function checkParent(t){ 
	while(t.parentNode){ 
		if(t == $('morefuel')){ 
			return false;
		} 
		t = t.parentNode;
	} 
	return true;
}

function switchFuel(show){
	if($('morefuel') && $('fuel_type_a'))
	{
		if (show == true)
		{
			Element.show('morefuel');
			$('fuel_type_a').className = 'active';
		}
		else
		{
			Element.hide('morefuel');
			$('fuel_type_a').className = 'inactive';
		}
	}
}

function showPage(prefix,page) {
	if ($(prefix + 'p_03')) { 
		pages = 3;
	}
	else
	{
		pages = 2;
	}
	
	newPageLinks = '';
	for (i=1;i<=pages;i++) {
		if (i == page) {
			Element.show(prefix + 'p_0' + i);
			newPageLinks += '<b>' + i + '</b>';
		}
		else
		{
			Element.hide(prefix + 'p_0' + i)
			newPageLinks += '<a href="#" class="paging_link" id="pl_' + i + '" onClick="showPage(\'' + prefix + '\',' + i + '); return false;">' + i + '</a>';
		}
	}
	$(prefix + 'paging').innerHTML = newPageLinks;
}


function setFuelType(val,id) {
	$('fuel_type').value = val;
	
	arrFs = ['01', '02', '03', '04', '05', '06'];
	arrFs.each (function(x) {
		$('f_' + x).className = (x == id ? 'inactive' : 'active');
	});
	
	Field.focus('suburb_name');
}

function setSearchDay(val) {
	$('search_day').value = val;
	
	if (val == 'today') {
		$('w_today').className = 'inactive';
		$('w_tomorrow').className = 'active';
	}
	else
	{
		$('w_today').className = 'active';
		$('w_tomorrow').className = 'inactive';
	}
	
	Field.focus('suburb_name');
}

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

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);
}

function saveMap()
{
	var center = map.getCenter();
	var bounds = map.getBounds();
	var ne_bound = bounds.getNorthEast();
	var sw_bound = bounds.getSouthWest();
	var map_type = map.getCurrentMapType();

	var south_west = sw_bound.toString();
	var north_east = ne_bound.toString();

	south_west = south_west.slice(1,south_west.indexOf(')'));
	var sw_latlng = south_west.split(',');

	north_east = north_east.slice(1,north_east.indexOf(')'));
	var ne_latlng = north_east.split(',');

	var center_st = center.toString();
	center_st = center_st.slice(1,center_st.indexOf(')'));
	var center_latlng = center_st.split(',');

	map_string = sw_latlng[0] + ',' + sw_latlng[1] + ',' + ne_latlng[0] + ',' + ne_latlng[1] + ',' + center_latlng[0] + ',' + center_latlng[1] + ',' + map.getZoom() + ',' + map_type.getName() + ',' + fuelType;
	createCookie('map_string',map_string,365);
	
	
	if (!$('jump'))
	{
		jump_link = '<div id="jump"><a id="jump_link" href="/my_area">go to your saved location</a> <a id="discard_location" href="#" title="discard saved location" onclick="deleteSavedLocation(); return false;">(delete)</a></div>';
		$('links').innerHTML = jump_link;
	}
	
	new Effect.Highlight('jump_link');
	new Effect.Highlight('save_map');
}

function sbTooltipOn(id) {
	if (activeInfoWindow != id) {
		showTooltip(gmarkers[id]);
	}
	if ($('sb_' + id)) { 
		sdClass = $('sb_' + id).className;
		$('sb_' + id).className = "station-row-active"; 
	}
	if ($('mv_' + id)) { 
		sdClass = $('mv_' + id).className;
		$('mv_' + id).className = "station-row-active"; 
	}
}

function sbTooltipOff(id) {
	if ($('sb_' + id)) { $('sb_' + id).className = sdClass; }
	if ($('mv_' + id)) { $('mv_' + id).className = sdClass; }
	sdClass = 'station-row';
	if ($('tooltip')){ $('tooltip').style.visibility="hidden"; }
}

function sbClick(id){
	if (gmarkers[id]) {
		gmarkers[id].openInfoWindowHtml(htmls[id]);
		$('tooltip').style.visibility="hidden";
		if ($('sb_' + id)) { $('sb_' + id).className = "station-on"; }
		if ($('mv_' + id)) { $('mv_' + id).className = "station-on"; }
		sdClass = 'station-on';
	}
}

function markerMouseOver(id) {
	if (activeInfoWindow != id) {
		showTooltip(gmarkers[id]);
	}
}

function showTooltip(marker) {
	if (marker) {
		$('tooltip').style.visibility = "hidden";
		$('tooltip').innerHTML = marker.tooltip;

		var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.getBounds().getSouthWest(),map.getZoom());
		var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
		var anchor=marker.getIcon().iconAnchor;
		var width=marker.getIcon().iconSize.width;
		var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize((offset.x + 2) - point.x - anchor.x + width,(- offset.y - 28) + point.y +anchor.y));

		pos.apply($('tooltip'));
		$('tooltip').style.visibility="visible";
	}
}

function createMarker(id,point,tooltip,html,type) {
    var marker = new GMarker(point,(type == 1?icon_1:icon_2));
    marker.tooltip = '<div class="tooltip">'+tooltip+'</div>';
    
    gmarkers[id] = marker;
	htmls[id] = html;
    map.addOverlay(marker);

    GEvent.addListener(marker,"mouseover", function() {
      	markerMouseOver(id);
    });        
    GEvent.addListener(marker,"mouseout", function() {
	$('tooltip').style.visibility="hidden";
    });        
	GEvent.addListener(marker,"click", function() {
		//For some reason marker clicks not regarded as document.click, manually close fuelswitcher
		switchFuel(false);
		$('tooltip').style.visibility="hidden";
		marker.openInfoWindowHtml(html);
		if ($('sb_' + id)) { $('sb_' + id).className = 'station-on'; sdClass = 'station-on'; }
		if ($('mv_' + id)) { $('mv_' + id).className = "station-on"; sdClass = 'station-on'; }	
	});
	GEvent.addListener(marker,"infowindowopen", function(){
		activeInfoWindow = id;
	});
	GEvent.addListener(marker,"infowindowclose", function(){
		activeInfoWindow = 0;
		if ($('sb_' + id)) { $('sb_' + id).className = 'station-row'; }
		if ($('mv_' + id)) { $('mv_' + id).className = "station-row"; }
	});
}

function revealStations() {
  	center = map.getCenter();
	bounds = map.getBounds();
	ne_bound = bounds.getNorthEast();
	sw_bound = bounds.getSouthWest();
	map_type = map.getCurrentMapType();

	south_west = sw_bound.toString();
	north_east = ne_bound.toString();

	south_west = south_west.slice(1,south_west.indexOf(')'));
	sw_latlng = south_west.split(',');

	north_east = north_east.slice(1,north_east.indexOf(')'));
	ne_latlng = north_east.split(',');

	center_st = center.toString();
	center_st = center_st.slice(1,center_st.indexOf(')'));
	center_latlng = center_st.split(',');

	urlpars = fuelType + '/' + sw_latlng[0] + '/' + sw_latlng[1] + '/' + ne_latlng[0] + '/' + ne_latlng[1] + '/' + dateString;
	var url = "/stations/" + urlpars;
	GDownloadUrl(url,function(data, responseCode){
		var xml = GXml.parse(data);
		var stations = xml.documentElement.getElementsByTagName("station");
		//zoneAvg = xml.documentElement.getElementsByTagName("zone")[0].getAttribute("average");
		mapStationPrices = [];
		
		updateMapResults = followMapView;
		
		for (var i = 0; i < stations.length; i++) {
			var id = parseInt(GXml.value(stations[i].getElementsByTagName("id")[0]));

			if (gmarkers[id]) {
				//Do nothing re: marker
				//Should still be added to mapStationPrices
				
				if (updateMapResults == true) {
					var prices = stations[i].getElementsByTagName("price");
					if (prices.length > 0) {
						for (var p = 0; p < prices.length; p++) {
							if (prices[p].getAttribute("type") == typeString)
							{
								//Queue to array
								stationPrice = [id,GXml.value(stations[i].getElementsByTagName("name")[0]),GXml.value(prices[p])];
								mapStationPrices.push(stationPrice);
							}
						}
					}
				}

			} else {
				var point = new GLatLng(parseFloat(GXml.value(stations[i].getElementsByTagName("latitude")[0])),parseFloat(GXml.value(stations[i].getElementsByTagName("longitude")[0])));
				var tooltip = GXml.value(stations[i].getElementsByTagName("name")[0]) + '<br/>' + GXml.value(stations[i].getElementsByTagName("tooltip")[0]);
				var prices = stations[i].getElementsByTagName("price");
				var html = "<div class=\"infohtml\"><h3>" + GXml.value(stations[i].getElementsByTagName("name")[0]) + "</h3><div class=\"bphtml\">";
				if (prices.length > 0) {
					for (var p = 0; p < prices.length; p++) {
						html += "<div class=\"fthtml\">" + prices[p].getAttribute("type") + "</div><div class=\"fphtml\">" + GXml.value(prices[p]) + "</div>";
						if ((prices[p].getAttribute("type") == typeString) && (updateMapResults == true))
						{
							//Queue to array
							stationPrice = [id,GXml.value(stations[i].getElementsByTagName("name")[0]),GXml.value(prices[p])];
							mapStationPrices.push(stationPrice);
						}
					}
				}
				else
				{
					html += 'N/A'
				}
				html += "<br clear=\"both\"/></div></div>";
				var marker = createMarker(id,point,tooltip,html,2);
			}

		}
		
		if (updateMapResults == true) {
			showMapPrices(mapStationPrices);
		}
	});
}


function showMapPrices(prices) {
	if (prices.length > 0)
	{
		Element.hide('view_warning');
		
		var perPage = 7;
		var pages = 1;
		var priceRows = '<div class="pages" id="mp_01">';
		
		//Sort prices array based on price value
		prices.sort(function(a,b) {
			if (a[2] != b[2])
			{
				return a[2] - b[2];
			}
			else
			{
				//second order sort by name
				var x = a[1].toLowerCase();
				var y = b[1].toLowerCase();
				return ((x < y) ? -1 : ((x > y) ? 1 : 0));
			}
		});
		
		for(i=0;i<prices.length;i++) {
			if ((i > 0) && ((i % perPage) == 0)) {
				pages++;
				//close page
				priceRows += '</div><div class="pages" id="mp_0' + (Math.floor(i / perPage) + 1) + '" style="display: none;">';
			}
			
			if (activeInfoWindow == prices[i][0]) {
				priceClass = 'station-on';
			} 
			else
			{
				priceClass = 'station-row';
			}
			priceRow = '<div class="' + priceClass + '" id="mv_' + prices[i][0] + '" onclick="sbClick(' + prices[i][0] + ');" onmouseover="sbTooltipOn(' + prices[i][0] + ');" onmouseout="sbTooltipOff(' + prices[i][0] + ');">' + prices[i][1] + '<br/><b>' + typeString + ': ' + prices[i][2] + '</b></div>';
			priceRows += priceRow;
		}
		priceRows += '</div>';
		
		var currentPage = 1;
		var pricePageLinks = '';
		if (pages > 1) {
			pricePageLinks += '<div id="mpaging">';
			
			for (p=1;p<=pages;p++) {
				if (p == currentPage) {
					pricePageLinks += '<b>' + p + '</b>';
				}
				else
				{
					pricePageLinks += '<a href="#" class="paging_link" id="mpl_' + p + '" onclick="showPage(\'m\',' + p + '); return false;">' + p + '</a>';
				}
			}
			pricePageLinks += '</div>';
		}
		
		$('map_area_prices').innerHTML = priceRows + pricePageLinks;
		
	}
	else
	{
		Element.show('view_warning');
		$('map_area_prices').innerHTML = '';
	}
}


/* results tabs */
function setMapType(mt) {
	map.setMapType(mt);
	redrawMapTabs();
}

function redrawMapTabs() {
	var currentMt = map.getCurrentMapType();
	var mt_state = [];
	mt_state[0] = ['normal',''];
	mt_state[1] = ['satellite',''];
	mt_state[2] = ['hybrid',''];
	
	switch(currentMt)
	{
	case G_SATELLITE_MAP:
		mt_state[1][1] = 'active'
		break;
	case G_HYBRID_MAP:
		mt_state[2][1] = 'active'
		break;
	default:
		mt_state[0][1] = 'active';
	}
	
	for(var i=0;i<mt_state.length;i++)
	{
		$('map_type_' + mt_state[i][0]).className = mt_state[i][1];
	}
}

function setResultView(id) {
	if (id == 'map')
	{
		mapClass = 'active';
		resClass = '';
		
		Element.show('view_wrapper_map');
		Element.hide('view_wrapper_res');
	}
	else
	{
		resClass = 'active';
		mapClass = '';
		
		Element.show('view_wrapper_res');
		Element.hide('view_wrapper_map');
	}
	
	$('view_res').className = resClass;
	$('view_map').className = mapClass;
}

function setFreeze(freeze)
{
	if (freeze == 1) {
		followMapView = false;
		Element.show('unfreeze');
		Element.hide('freeze');
	}
	else
	{
		followMapView = true;
		Element.show('freeze');
		Element.hide('unfreeze');
		revealStations();
	}
}

function setHover(element,classname) {
	element.className = classname;
}