var objMap;
var objGeoCoder;
var objDirections;
var objBaseIcon, objIcon;
var aListings_IDs = [];
var aListings_Markers = [];
var aListingTypes = [];
var aListingCategories = [];
var aListings;
var objMarkerSP;

var iDefaultZoom = 15;
var bUpdateMap = false;
var bDirectionsView = false;

var aListingIcons = [];
aListingIcons[1] = "listing-restaurant";
aListingIcons[2] = "listing-bar";
aListingIcons[3] = "listing-cafe";
aListingIcons[4] = "listing-design";
aListingIcons[5] = "listing-fashion";
aListingIcons[6] = "listing-grocery";
aListingIcons[7] = "listing-artgallery";
aListingIcons[8] = "listing-books";
aListingIcons[9] = "listing-bakedgoods";

function ToggleListingTypes(bValue){
	var Form = document.forms.frmTorontoMap;
	var aListingTypes = Form.ListingType;
	for(i=0; i<aListingTypes.length; i++){
		aListingTypes[i].checked = bValue;
	}
}

function InArray(aArray, vItem){
	for(iCursor = 0; iCursor < aArray.length; iCursor ++){
		if(aArray[iCursor] == vItem) return true;
	}
	return false;
}

function UpdateMap(){
	if(bDirectionsView) return;
	if(!bUpdateMap){
		bUpdateMap = true;
		return;
	}
	var Form = document.forms.frmTorontoMap;
	
	objBounds = objMap.getBounds();
	objPointSW = objBounds.getSouthWest();
	objPointNE = objBounds.getNorthEast();
	aBounds = [objPointSW.lat(), objPointSW.lng(), objPointNE.lat(), objPointNE.lng()];
	sBounds = aBounds.join(",");
	
	aData = [];
	aData.push("cmd=get-markers");
	aData.push("current=" + encodeURIComponent(aListings_IDs.join(",")));
	aData.push("bounds=" + encodeURIComponent(sBounds));
	aData.push("listing_types=" + encodeURIComponent(aListingTypes.join(",")));
	sData = aData.join("&");
	ShowLoading();
	
	AJAXRequest("/torontomap/index.php", "POST", sData, function(sResponse, aError){
		if(!aError){
			if(sResponse == "noresults") return;
			aResults = sResponse.split(";");
			aListings = [];
			
			for(i=0; i<aResults.length; i++){
				aRecord = aResults[i].split(",");
				aResult = [];
				for(j=0; j<aRecord.length; j++){
					aField = aRecord[j].split("=");
					sValue = unescape(aField[1]);
					aResult[aField[0]] = sValue;
				}
				aListings.push(aResult);
				if(!InArray(aListings_IDs, parseInt(aResult["ID"])) && !isNaN(parseInt(aResult["ID"]))){
					aListings_IDs.push(parseInt(aResult["ID"]));
				}
			}
			
			for(i=0; i<aListings.length; i++){
				if(aListings[i]["command"]){
					switch(aListings[i]["command"]){
						case "center-map":
							objMap.setCenter(new GLatLng(aListings[i]["latitude"], aListings[i]["longitude"]), 14);
							break;
					}
				}
				
				if(!aListings[i]) continue;
				if(!aListings[i]["Type"]) continue;
				iListingType = parseInt(aListings[i]["Type"]);
				if(isNaN(iListingType)) continue;
				if(!aListingIcons[iListingType]) continue;
				
				var objBaseIcon = new GIcon();
				objBaseIcon.shadow = "http://www.blogto.com/site/images/torontomap/listing-shadow.png";
				objBaseIcon.iconSize = new GSize(15, 20);
				objBaseIcon.shadowSize = new GSize(30, 30);
				objBaseIcon.iconAnchor = new GPoint(7, 20);
				objBaseIcon.infoWindowAnchor = new GPoint(15, 2);
				objBaseIcon.infoShadowAnchor = new GPoint(30, 30);
		
				objIcon = new GIcon(objBaseIcon);
				objIcon.image = "http://www.blogto.com/site/images/torontomap/" + aListingIcons[iListingType] + ".png";
				objMarkerOptions = {icon:objIcon, title:aListings[i]["Name"]};
				objPoint = new GLatLng(parseFloat(aListings[i]["Latitude"]), parseFloat(aListings[i]["Longitude"]));
				objMarker = new GMarker(objPoint, objMarkerOptions);
				aListings_Markers.push({
					ID : parseInt(aListings[i]["ID"]),
					Name : aListings[i]["Name"],
					Type : parseInt(iListingType),
					Custom : aListings[i]["Custom"],
					TypeShorthand : aListings[i]["TypeShorthand"],
					Shorthand : aListings[i]["Shorthand"],
					EntryID : parseInt(aListings[i]["EntryID"]),
					Address : aListings[i]["Address"],
					Phone : aListings[i]["Phone"],
					Marker : objMarker
				});
				if(!InArray(aListingTypes, iListingType)) objMarker.hide();
				iMarkerID = (aListings_Markers.length - 1);
				sCode = 
				'GEvent.addListener(aListings_Markers[' + iMarkerID + '].Marker, "click", function(){' +
				'	SelectListing(' + iMarkerID + ');' +
				'});';
				eval(sCode);
				objMap.addOverlay(objMarker);
			}
			
			UpdateListingResults();
		}
	});
}

function SelectListing(iMarkerID){
	bUpdateMap = false;
	sListingURL = "/" + aListings_Markers[iMarkerID].TypeShorthand + "/" + aListings_Markers[iMarkerID].Shorthand;
	sHTML = "<p style=\"font-size: 15px; font-weight: bold;\"><strong><a href=\"" + sListingURL + "\" target=\"_blank\">" + aListings_Markers[iMarkerID].Name + "</a></strong></p>" +
				aListings_Markers[iMarkerID].Address + "<br>" + aListings_Markers[iMarkerID].Phone +
				"<p><a href=\"" + sListingURL + "\" target=\"_blank\">View Review</a> | <a href=\"/listings/facebook-faves.php?entryid=" + aListings_Markers[iMarkerID].EntryID + "\" target=\"_blank\">Add to Faves</a></p>" +
				"<p style=\"font-size: 11px;\">Get Directions <a href=\"#\" onclick=\"GetDirections(" + iMarkerID + ", 'to', '" + escape(aListings_Markers[iMarkerID].Address) + "'); return false;\">to here</a>&nbsp;<a href=\"#\" onclick=\"GetDirections(" + iMarkerID + ", 'from', '" + escape(aListings_Markers[iMarkerID].Address) + "'); return false;\">from here</a></p>";
	aListings_Markers[iMarkerID].Marker.openInfoWindowHtml(sHTML);
}

function UpdateListingTypes(){
	var Form = document.forms.frmTorontoMap;
	aListingTypes = [];
	for(i=0; i<Form.ListingType.length; i++){
		if(Form.ListingType[i].checked) aListingTypes.push(Form.ListingType[i].value);
	}
	
	for(i=0; i<aListings_Markers.length; i++){
		if(aListingCategories.length != 0 && aListings_Markers[i].Custom != ""){
			bInCategories = InArray(aListingCategories, aListings_Markers[i].Type + ":" + aListings_Markers[i].Custom);
		}
		else{
			bInCategories = true;
		}
		if(InArray(aListingTypes, aListings_Markers[i].Type) && bInCategories){
			aListings_Markers[i].Marker.show();
		}
		else{
			aListings_Markers[i].Marker.hide();
		}
	}
	
	if(aListings_Markers.length != 0){
		UpdateListingResults(false);
	}
}

function UpdateListingCategories(bUpdateResults){
	if(bUpdateResults == null) bUpdateResults = true;
	var Form = document.forms.frmMapFilters;
	aListingCategories = [];
	for(i=0; i<Form.Categories.length; i++){
		aCategoryID = Form.Categories[i].id.split("_");
		iListingType = parseInt(aCategoryID[1]);
		if(Form.Categories[i].checked) aListingCategories.push(iListingType + ":" + Form.Categories[i].value);
	}
	if(bUpdateResults){
		UpdateListingTypes();
	}
}

function UpdateListingResults(bUpdateCategories){
	if(bDirectionsView) return;
	if(bUpdateCategories == null) bUpdateCategories = true;
	var sHTML = "";
	for(i=0; i<aListings_Markers.length; i++){
		if(aListingCategories.length != 0 && aListings_Markers[i].Custom != ""){
			bInCategories = InArray(aListingCategories, aListings_Markers[i].Type + ":" + aListings_Markers[i].Custom);
		}
		else{
			bInCategories = true;
		}
		if(InArray(aListingTypes, aListings_Markers[i].Type) && bInCategories){
			sIcon = "/site/images/torontomap/" + aListingIcons[aListings_Markers[i].Type] + ".png";
			sHTML += "<img src=\"" + sIcon + "\" align=\"absmiddle\" />&nbsp;<a href=\"#\" onclick=\"SelectListing(" + i + "); return false;\">" + aListings_Markers[i].Name + "</a><div style=\"margin-left: 18px; padding: 5px 0px 0px 0px; border-top: 1px #CCCCCC solid;\"></div>";
		}
	}
	if(sHTML == "") sHTML = "<strong><em>No results were found.</em></strong>";
	document.getElementById("MapSidebar_Results").innerHTML = sHTML;
	if(bUpdateCategories) UpdateListingCategories(false);
}

function ShowLoading(){
	MapSidebar_Tab("results");
	document.getElementById("MapSidebar_Results").innerHTML = "<img src=\"/site/images/torontomap/loading.gif\" align=\"absmiddle\" /><span style=\"margin-left: 10px; font-size: 19px;\">Loading...</span>";
}

function ClearListings(){
	for(i=0; i<aListings_Markers.length; i++){
		objMap.removeOverlay(aListings_Markers[i].Marker);
	}
	if(objMarkerSP) objMap.removeOverlay(objMarkerSP);
	bDirectionsView = false;
	aListings = [];
	aListings_IDs = [];
	aListings_Markers = [];
}

function ChangeNeighborhood(){
	var Form = document.forms.frmTorontoMap;
	sAddress = unescape(Form.Neighborhood.value);
	ChangeStartingPoint(sAddress);
}

function ChangeStartingPoint(sAddress){
	if(!sAddress) sAddress = document.forms.frmTorontoMap.Address.value;
	if(sAddress == "") return;
	sAddress += ", Toronto";
	ClearListings();
	ShowLoading();
	bUpdateMap = true;
	objGeoCoder.getLatLng(sAddress, function(objPoint){
		if(objPoint){
			objMap.setCenter(objPoint, iDefaultZoom + 1);
		}
		else{
			alert("Sorry, we couldn't find the address you provided.");
		}
	});
}

function GetDirections(iMarkerID, sType, sAddress){
	var sAddress = unescape(sAddress);
	var sHTML = "<form name=\"frmDrivingDirections\" onSubmit=\"LoadDirections(); return false;\">" +
				"<input type=\"hidden\" name=\"Type\" value=\"" + sType + "\" />" +
				"<input type=\"hidden\" name=\"ListingID\" value=\"" + iMarkerID + "\" />" +
				"<input type=\"hidden\" name=\"ListingAddress\" value=\"" + escape(aListings_Markers[iMarkerID].Address) + "\" />" +
				"<p style=\"font-size: 15px; font-weight: bold\">Get Driving Directions</p>";
	if(sType == "to"){
		sHTML += "<p><strong>Destination:</strong><br />" + aListings_Markers[iMarkerID].Name + "<br />" + aListings_Markers[iMarkerID].Address + "</p><p><strong>Enter the start address:</strong><br /><input type=\"text\" name=\"Address\" size=\"20\" /></p>";
	}
	else if(sType == "from"){
		sHTML += "<p><strong>Start:</strong><br />" + aListings_Markers[iMarkerID].Name + "<br />" + aListings_Markers[iMarkerID].Address + "</p><p><strong>Enter the destination address:</strong><br /><input type=\"text\" name=\"Address\" size=\"20\" /></p>";
	}
	sHTML += "<p><input type=\"submit\" name=\"btnSubmit\" value=\"Get Directions\" /></p>";
	aListings_Markers[iMarkerID].Marker.openInfoWindowHtml(sHTML);
}

function LoadDirections(){
	var Form = document.forms.frmDrivingDirections;
	var sType = Form.Type.value;
	var sAddress = unescape(Form.ListingAddress.value);
	SelectListing(parseInt(Form.ListingID.value));
	if(objDirections) objDirections.clear();
	if(sType == "to"){
		var sStart = Form.Address.value;
		if(sStart != ""){
			objDirections = new GDirections(objMap, document.getElementById("MapSidebar_Results"));
			GEvent.addListener(objDirections, "load", GDirections_Load);
			GEvent.addListener(objDirections, "error", GDirections_HandleError);
			ShowLoading();
			objDirections.load(sStart + ", Toronto to " + sAddress + ", Toronto");
		}
	}
	else if(sType == "from"){
		var sDestination = Form.Address.value;
		if(sDestination != ""){
			objDirections = new GDirections(objMap, document.getElementById("MapSidebar_Results"));
			GEvent.addListener(objDirections, "load", GDirections_Load);
			ShowLoading();
			objDirections.load(sAddress + ", Toronto to " + sDestination + ", Toronto");
		}
	}
}

function HideDirections(){
	bDirectionsView = false;
	objDirections.clear();
	UpdateListingResults();
}

function GDirections_HandleError(){
   if (objDirections.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.");
   else if (objDirections.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.");
   
   else if (objDirections.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.");

   else if (objDirections.getStatus().code == G_GEO_BAD_KEY)
	 alert("The given key is either invalid or does not match the domain for which it was given.");

   else if (objDirections.getStatus().code == G_GEO_BAD_REQUEST)
	 alert("A directions request could not be successfully parsed.");
	
   else alert("An unknown error occurred.");
   
   UpdateListingResults();
}

function GDirections_Load(){ 
	document.getElementById("MapSidebar_Results").innerHTML = "<p align=\"center\" style=\"font-size: 15px; font-weight: bold;\"><a href=\"#\" onclick=\"HideDirections(); return false;\">&lt;&lt; Back to results</a></p>";
	bDirectionsView = true;
}
	
function MapFilters_ToggleNode(iListingType){
	objImage = document.images["imgMapFiltersNode_" + iListingType];
	if(objImage.src.indexOf("node-open.gif") != -1){
		objImage.src = "/site/images/torontomap/node-close.gif";
		document.getElementById("MapSidebar_Filters_Type_" + iListingType).style.display = "block";
	}
	else{
		objImage.src = "/site/images/torontomap/node-open.gif";
		document.getElementById("MapSidebar_Filters_Type_" + iListingType).style.display = "none";
	}
}

function ToggleCategories(iListingType, bValue){
	var Form = document.forms.frmMapFilters;
	for(i=0; i<Form.Categories.length; i++){
		if(Form.Categories[i].id.indexOf("_" + iListingType + "_") != -1){
			Form.Categories[i].checked = bValue;
		}
	}
	UpdateListingCategories();
}

function MapSidebar_Tab(sTabName){
	if(sTabName == "results"){
		document.images.imgTabResults.src = "/site/images/torontomap/results-on.jpg";
		document.images.imgTabFilters.src = "/site/images/torontomap/filters-off.jpg";
		document.getElementById("MapSidebar_Results").style.display = "block";
		document.getElementById("MapSidebar_Filters").style.display = "none";
	}
	else if(sTabName == "filters"){
		document.images.imgTabResults.src = "/site/images/torontomap/results-off.jpg";
		document.images.imgTabFilters.src = "/site/images/torontomap/filters-on.jpg";
		document.getElementById("MapSidebar_Results").style.display = "none";
		document.getElementById("MapSidebar_Filters").style.display = "block";
	}
}

function ShowDefaultListings(){
	bUpdateMap = true;
	UpdateMap();
	objMarkerSP.closeInfoWindow();
	objMap.removeOverlay(objMarkerSP);
	objMarkerSP = null;
}

window.onload = function(){
	if(GBrowserIsCompatible()){
		PreloadImage("/site/images/torontomap/loading.gif");
		PreloadImage("/site/images/torontomap/results-off.gif");
		PreloadImage("/site/images/torontomap/filters-on.gif");
		for(i=0; i<aListingIcons.length; i++){
			PreloadImage("/site/images/torontomap/" + aListingIcons[i] + ".png");
		}
		objMap = new GMap2(document.getElementById("MapLayer"));
		objGeoCoder = new GClientGeocoder();
		objMap.addControl(new GMapTypeControl());
		objMap.addControl(new GLargeMapControl());
		var objPoint = new GLatLng(43.67016874852075, -79.38682079315186);
		objMap.setCenter(objPoint, iDefaultZoom);
		
        var objBaseIcon = new GIcon();
        objBaseIcon.shadow = "http://www.blogto.com/site/images/torontomap/listing-shadow.png";
        objBaseIcon.iconSize = new GSize(30, 32);
        objBaseIcon.shadowSize = new GSize(30, 32);
        objBaseIcon.iconAnchor = new GPoint(15, 32);
        objBaseIcon.infoWindowAnchor = new GPoint(15, 2);
        objBaseIcon.infoShadowAnchor = new GPoint(25, 25);
		
		var objIcon = new GIcon(objBaseIcon);
		objIcon.image = "http://www.blogto.com/site/images/torontomap/starting-point.png";
		
		objMarkerOptions = {icon:objIcon};
		objMarkerSP = new GMarker(objPoint, objMarkerOptions);
		objMap.addOverlay(objMarkerSP);
		objMarkerSP.openInfoWindow("<p style=\"font-size: 14px; font-weight: bold;\">Starting Point</p><p><a href=\"#\" onclick=\"ShowDefaultListings(); return false;\">Show Listings</a></p>");
		
		GEvent.addListener(objMap, "moveend", function(){
			UpdateMap();
		});
		
		UpdateListingTypes();
	}
}