var map;
var markerList = new Markers();
var allMarkers = [];
var mapmode = "";
var show_featured_venues_onstart = true;
var base_marker;
var geocoder = null;
var destinationMarker = null;
var starttab = "venue";

var categoryIcons = [];

//venue categories
categoryIcons["artcentre"] =	 "/mmlib/images/visit-birmingham/map-pins/artscentre.png";
categoryIcons["attraction"] =	 "/mmlib/images/visit-birmingham/map-pins/attraction.png";
categoryIcons["bars"] =			 "/mmlib/images/visit-birmingham/map-pins/bars.png";
categoryIcons["classical"] =	 "/mmlib/images/visit-birmingham/map-pins/classical.png";
categoryIcons["clubs"] =		 "/mmlib/images/visit-birmingham/map-pins/clubs.png";
categoryIcons["comedy"] =		 "/mmlib/images/visit-birmingham/map-pins/comedy.png";
categoryIcons["dance"] =		 "/mmlib/images/visit-birmingham/map-pins/dance.png";
categoryIcons["film"] =			 "/mmlib/images/visit-birmingham/map-pins/film.png";
categoryIcons["galleries"] =	 "/mmlib/images/visit-birmingham/map-pins/galleries.png";
categoryIcons["museums"] =		 "/mmlib/images/visit-birmingham/map-pins/museums.png";
categoryIcons["music"] =		 "/mmlib/images/visit-birmingham/map-pins/music.png";
categoryIcons["opera"] =		 "/mmlib/images/visit-birmingham/map-pins/opera.png";
categoryIcons["specialevents"] = "/mmlib/images/visit-birmingham/map-pins/specialevents.png";
categoryIcons["sport"] =		 "/mmlib/images/visit-birmingham/map-pins/sport.png";
categoryIcons["theatre"] =		 "/mmlib/images/visit-birmingham/map-pins/theatre.png";
categoryIcons["featured"] =		 "/mmlib/images/visit-birmingham/map-pins/featured.png";

//listing categories
categoryIcons["support"] =	 "/mmlib/images/visit-birmingham/map-pins/supportservice.png";
categoryIcons["conferencesupport"] =	 "/mmlib/images/visit-birmingham/map-pins/supportservice.png";
categoryIcons["attractions"] =	 "/mmlib/images/visit-birmingham/map-pins/attraction.png";
categoryIcons["venues"] =	 "/mmlib/images/visit-birmingham/map-pins/venues.png";
categoryIcons["eating"] =	 "/mmlib/images/visit-birmingham/map-pins/restaurants.png";
categoryIcons["restaurants"] =	 "/mmlib/images/visit-birmingham/map-pins/restaurants.png";
categoryIcons["accommodation"] =	 "/mmlib/images/visit-birmingham/map-pins/accommodation.png";


function getIcon(category)
{
	var icon = new GIcon(G_DEFAULT_ICON);
	icon.iconSize = new GSize(31, 46);
	icon.shadow = "";
	icon.shadowSize = new GSize(0,0);
    icon.iconAnchor = new GPoint(15, 46);
    icon.infoWindowAnchor = new GPoint(9, 2);
	icon.imageMap = [0, 10, 15, 0, 31, 10, 31, 23, 15, 46, 0, 23];

	if (typeof(categoryIcons[category]) != "undefined")
	{
		icon.image = categoryIcons[category];
	}
	else
	{
		icon.image = "/mmlib/images/visit-birmingham/map-pins/default.png";
	}
	
	return icon;
}

function onLoadedMarkers(response, category, clearMarkers)
{
	//only show markers if they're still selected when ajax has finished loading
	if (!$("li." + category).hasClass("selected"))
	{
		$("li." + category).removeClass("loading");
		return;
	}
	
	if (clearMarkers)
	{
		map.clearOverlays();
	}
	
	var parts = category.split("_");
	
	for (var i = 0; i < response.length ; i++)
	{
		var title = response[i].title;
		var mIcon = getIcon(response[i].category);
		
		var point = new GLatLng(response[i].lat, response[i].long);
		var marker = new GMarker(point, { title:title, id:response[i].id, icon:mIcon})
		
		var tooltip = new Tooltip(marker,response[i].title,4);
		marker.tooltip = tooltip;
		map.addOverlay(tooltip);
		
		marker._markerCategory = response[i].category;
		if (response[i].address)
		{
			marker._address = response[i].address;
		}
		/*
		if (response[i].categories !== undefined)
		{
			for (var j = 0; j < response[i].categories.length; j++)
			{
				//marker.addClass(response[i].categories[j]);
				//markerList.addMarker(marker, parts[0] + "_" +  response[i].categories[j]);
			}
		}
		*/
		GEvent.addListener(marker,'mouseover',function(){ this.tooltip.show(); });
		GEvent.addListener(marker,'mouseout',function(){ this.tooltip.hide(); });
		
		allMarkers[response[i].id] = marker;
		//allMarkers.push(marker);
		GEvent.addListener(marker, "click", function() {
			var m = this;
			var loadingHTML = '<div id="loading"><img src="/mmlib/images/visit-birmingham/ajax-loader.gif" alt="loading" /></div>';
			
			if (parts[0] == "venue")
			{
				var catstring = "";
				$("ul.category-list li.selected").each(function(){
					var id = $(this).attr("id").split("_")[1];
					catstring += "&selected_cat[]=" + id;
				});
				
				var venue_url = "/mmlib/includes/visit-birmingham/maps/ajax.venue.php?venue_id=" + this.id + catstring;
			}
			else if (parts[0] == "listing")
			{
				var venue_url = "/mmlib/includes/visit-birmingham/maps/ajax.listing.php?id=" + this.id;
			}

			//this.openInfoWindowHtml(loadingHTML, windowoptions);
			m.openExtInfoWindow(
				map,
				"window-info",
				loadingHTML,
				{beakOffset: 64, ajaxUrl: venue_url}
			);
			GEvent.addListener(map, 'extinfowindowupdate', applyInfoWindowEventHandlers);
			
		});

		map.addOverlay(marker); 
	
		markerList.addMarker(marker, category);
	}
	
	$("li." + category).removeClass("loading");
	
}

function applyInfoWindowEventHandlers(e)
{
	$("li#get-directions").click(function(){
		$("h2.maps-tab").parent().hide();
		$("#map-directions").show();
		
		var point = map.getExtInfoWindow().marker_.getLatLng().toString();
		destinationMarker = map.getExtInfoWindow().marker_;
		$("#location-destination").val(point);
		return false;
	});
}

function clearMarkers()
{
	allMarkers = [];
	
	if (base_marker != null)
	{
		allMarkers[base_marker.id] = base_marker;
	}
	if (gdir)
	{
		gdir.clear();
	}
	clearDirectionsPanel();
	removeInfoWindow();
}

function placeMarkers(filter, clearCurrent)
{
	if (typeof(clearCurrent) == "undefined")
	{
		clearCurrent = false;
		clearMarkers();
	}
	
	if (mapmode != filter.displayType)
	{
		clearCurrent = true;
		mapmode = filter.displayType;
		clearMarkers();

		if (mapmode == 'venue')
		{
			$("ul.directory-list li.listing-category.selected").removeClass("selected");
		}
		else
		{
			$("li.category-filter.selected").removeClass("selected");
		}
	}
	$("li." + filter.groupName).addClass("loading");
	
	if (filter.displayType == "venue")
	{
		var marker_url = "/mmlib/includes/visit-birmingham/maps/ajax.venue_markers.php";
	
		if (filter.categories.length > 0)
		{
		
			$.get(marker_url,
				{'categories[]':filter.categories},
				function(response){
					//onLoadedVenueMarkers(response, filter.categories[0], clearCurrent)
					onLoadedMarkers(response, filter.groupName, clearCurrent)
				},
				'json');
		}
		else
		{
			$.get(marker_url,
				{},
				function(response){
					onLoadedMarkers(response, filter.groupName, clearCurrent)
				},
				'json');
		}
	}
	else if (filter.displayType == "listing")
	{
		
		var marker_url = "/mmlib/includes/visit-birmingham/maps/ajax.listing_markers.php";
		var properties = {'categories[]':filter.categories};
		if (filter.listingTypeId != "")
		{
			properties = {	'categories[]':filter.categories,
							'type_id': filter.listingTypeId};
		}
		
		$.get(marker_url,
			properties,
			function(response){
				onLoadedMarkers(response, filter.groupName, clearCurrent)
			},
			'json');
	}
}

function removeMarkers(markers_array)
{
	for(var i = 0;i<markers_array.length;i++)
	{
		var m = markers_array[i];
		map.removeOverlay(m);
		delete allMarkers[m.id];
	}
}

function removeCategory(groupName, clearStyles)
{
	if (typeof(clearStyles) == "undefined")
	{
		clearStyles = true;
	}
	
	if ($("li." + groupName).hasClass("loading"))
	{
		return;
	}
	
	if (clearStyles)
	{
		$("li." + groupName).removeClass("selected");
	}
	
	var toDelete = markerList.getMarkers(groupName);
	var parts = groupName.split("_");
	var category = parts[1];
	var type = parts[0];
	
	for(var i = 0;i<toDelete.length;i++)
	{
		var m = toDelete[i];
		
		var categories = m.getClasses();
		var canDelete = true;
		
		if (m.hasClass("base-marker"))
		{
			canDelete = false;
		}
		
		for (var j = 0;j<categories.length;j++)
		{
			var cat = categories[j];
			if ($("li." + type + "_" + cat).hasClass("selected"))
			{
				canDelete = false;
			}
		}
		
		if (canDelete)
		{
			map.removeOverlay(m);
			delete allMarkers[m.id];
			
			if (allMarkers.length == 0)
			{
				map.clearOverlays();
			}
		}
	}
	removeInfoWindow();
	markerList.removeCategory(groupName);
}

function calculateZoomFromRadius(radius)
{
	//This linear function calculates the appropriate zoom level from 16 (furthest in) to 10 (warwickshire sized)	
	return parseInt(16-((6/35)*radius));
}

function centreMapOnCoords(lat, lng, range)
{
	if (lng && lat)
	{
		removeInfoWindow();
		var point = new GLatLng(lat,lng);
		
		if (range)
		{
			map.setZoom(calculateZoomFromRadius(range));
		}
		map.panTo(point);
		$("div#choose-area").removeClass("show");
		
	}
	return false;
}

function removeInfoWindow()
{
	if (map.getExtInfoWindow)
	{
		var infowindow = map.getExtInfoWindow();
		if (infowindow != undefined)
		{
			infowindow.remove();
		}
	}
}

function selectListingsGroup(sender)
{
	var filter = new Filter();
	filter.displayType = "listing";
	filter.listingTypeId = $(sender).parent().find("input").val();
	//sfilter.categories.push(id);
	filter.groupName = "listing_" + $(sender).parent().find("input").val();
	
	$(sender).parent().find("ul.radios li.listing-category").each(function(){
		filter.categories.push($(this).attr("id").split("_")[1]);
	});
	
	$(sender).parent().addClass("loading");
	
	placeMarkers(filter, false);
}

function clearListingGroup(sender, clearStyles)
{
	$("ul.directory-list li.listing-type").each(function(){
		removeCategory("listing_" + $(this).find("input").val(), clearStyles);
		if ($(this).find('li.listing-category.selected').length > 0)
		{
			removeCategory($(this).find('li.listing-category.selected input.groupName').val());
		}
	});
	
}

function getDirections(from, to)
{
	var point = geocodeString(from, function(frompoint){
		if (frompoint != null)
		{
			var query = "from: " + frompoint.toString() + " to: " + to;

			//alert(query);
			gdir.clear();
			clearDirectionsPanel();
			gdir.load(query, {locale:'en_GB',getSteps:true});
			removeInfoWindow();
		}
		else
		{
			alert("Could not find '"+ from +"'");
		}
	});
}

function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
	     alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	   
	   else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
	     alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

	//   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);
	     
	   else if (gdir.getStatus().code == G_GEO_BAD_KEY)
	     alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

	   else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
	     alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	    
	   else alert("An unknown error occurred.");
	   
}

function geocodeString(input, callback)
{
	$.getJSON("/mmlib/includes/visit-birmingham/geocode.php?location="+escape(input),
		function(data) {
			if( data.point ) {
				callback(new GLatLng(data.point[0],data.point[1]));
			}
		}
	);
}

function getSelectedVenueCategories()
{
	var arr = [];
	
	$("ul.category-list li.selected").each(function(){
		var id = $(this).attr("id").split("_")[1];
		arr.push(id);
	});
	
	return arr;
}

function geoCodeSearch(query)
{
	var point = geocodeString(query, function(point){
		if (point == null)
		{
			alert("Could not locate '" + query + "'");
		}
		else
		{
			//map.panTo(point);
			centreMapOnCoords(point.lat(), point.lng());
		}
	});
}

var gdir;
var directionsPanel;

$(document).ready(function() {
	
	var mapOptions = {mapTypes: [G_NORMAL_MAP]};
	
	map = new GMap2($("#map-main")[0], mapOptions);
	map.setCenter(new GLatLng(52.478868, -1.910789), 15);
	//map.setUIToDefault();
	
	var customUI = map.getDefaultUI();
	customUI.controls.maptypecontrol = true;
	customUI.controls.menumaptypecontrol = false;
	//customUI.controls.
	map.setUI(customUI);
	
	geocoder = new GClientGeocoder();
	geocoder.setBaseCountryCode('uk');	
	
	//this function is defined in map.php since it needs to be altered by the server.
	initBaseMarker();
	defaultfilter = getDefaultFilter();
	directionsPanel = $("#directions-panel")[0];
	gdir = new GDirections(map);
	
	GEvent.addListener(gdir, "error", handleErrors);
	//set the handler to draw the custom directions
	GEvent.addListener(gdir, "load", function() {
		setTimeout('customPanel(map,"map",gdir,directionsPanel)', 1);
	});
	
	//alert(nw + "," + se);
	if (show_featured_venues_onstart)
	{
		$("#cat_featured").addClass("selected");
		placeMarkers(new Filter());
	}
	
	
	if (starttab == "listing")
	{
		$("div.tab-container").toggleClass("active");
	}


	$("li.category-filter").click(function() {
		
		var id = this.id.split("_")[1];
		var groupname = $(this).find("input.groupName").val();
		if ($(this).hasClass("selected"))
		{
			//$(this).removeClass("selected");
			removeCategory(groupname);
		}
		else
		{
			$(this).addClass("selected");

			var filter = new Filter();
			filter.categories.push(id);
			filter.groupName = groupname;
			if (id > 0)
			{
				placeMarkers(filter, false);
			}
			else
			{
				placeMarkers(new Filter());
			}
		}
			$("div.blurb").fadeOut();
		return false;
	});
		
	$("li.listing-category").click(function() {	
		var id = this.id.split("_")[1];
		var type_id = $(this).parents("li.top-level").find("input#listingtype_id").val();
		var groupname = $(this).find("input.groupName").val();
		
		
		if ($(this).hasClass("selected"))
		{
			//removeCategory(groupname);
		}
		else
		{
			//clear all the subcategories loaded by the 'all' selector
			var typeheader = $(this).parent().parent().find("h3")[0];
			clearListingGroup(typeheader, false);
			
			$(this).parent().find("li").removeClass("selected");
			$(this).addClass("selected");
			
			var filter = new Filter();
			filter.displayType = "listing";
			filter.listingTypeId = type_id;
			filter.categories.push(id);
			filter.groupName = groupname;
			placeMarkers(filter, false);
		}
		$("div.blurb").fadeOut();
		return false;
	});

	$("h2.maps-tab").click(function(){
		if (!$(this).parents("div").hasClass("active"))
		{
			$("div.tab-container").toggleClass("active");
			$("div.tab-container h2").toggleClass("active-tab");
		}
		return false;
	});

	$("li.listing-type h3").click(function(){

		var clickedSelected = $(this).parent().hasClass("selected");
		
		clearListingGroup(this);
		
		$("li.listing-type.selected ul li.listing-category").removeClass("selected");
		$("li.listing-type ul").slideUp();
		$("li.listing-type").removeClass("selected");
		
		if (!clickedSelected)
		{
			if (!$(this).parent().find("ul").hasClass("animating"))
			{
				selectListingsGroup(this);
				$(this).parent().find("ul").addClass("animating");
				$(this).parent().find("ul").slideDown("normal", function(){ $(this).removeClass("animating") });
				$(this).parent().addClass("selected");
				$(this).parent().find("li.toggle-all").addClass("selected");
			}
		}
		
		$("div.blurb").fadeOut();
		return false;
	});

	//toggle all button
	$(".radios li.toggle-all").click(function(){
		
		var typeheader = $(this).parent().parent().find("h3")[0];
		if ($(this).hasClass("selected"))
		{
			/*
			clearListingGroup(typeheader, false);
			
			//clear any individual 
			$("ul.directory-list li.listing-type").each(function(){
				removeCategory("listing_" + $(this).find("input").val(), clearStyles);
			});
			*/
		}
		else
		{
			clearListingGroup(this, false);
			selectListingsGroup(typeheader);
			$(this).addClass("selected");
		}
		
		return false;
	});

	//search box
	$("#keyword").focus(function(){
		if ($(this).hasClass("placeholder"))
		{
			$(this).val("");
			$(this).removeClass("placeholder");
		}
	});
	$("#keyword").blur(function(){
		if ($(this).val() == "")
		{
			$(this).val("Location or Postcode");
			$(this).addClass("placeholder");
		}
	});
	
	$("#location-search").keypress(function(e){
		if (e.which == 13)
		{
			getDirections($("#location-search").val(), $("#location-destination").val());
			return false;
		}
	});
	
	$("#keyword").keypress(function(e){
		if (e.which == 13)
		{
			geoCodeSearch($("#keyword").val());
			return false;
		}
	});
	$("div.search-button").click(function()
	{
		geoCodeSearch($("#keyword").val());
		return false;
	});
	
	$("#directions-button").click(function(){
		
		getDirections($("#location-search").val(), $("#location-destination").val());
		return false;
	});
	
	$("#hide-directions").click(function(){
		$("h2.maps-tab").parent().show();
		$("#map-directions").hide();
		return false;
	});
	
	$("div.current-location a em").click(function(){
		if (base_marker != null)
		{
			map.removeOverlay(base_marker);
			$("div.current-location").fadeOut();
		}
	});
	
	$("#choose-area-close").click(function(){
		$("#choose-area").removeClass("show");
	});
});
