var map;
var point;
var geocoder;
var marker;
var gmarker = [];
var gsuburb = [];
var plotsuccess = 0;
var directions;

function setupMap(latitude, longitude, zoomlevel) {
	if (GBrowserIsCompatible()) {
		map = new GMap2(document.getElementById("map"));
		directions	= new GDirections(map, document.getElementById("directionsPanel"));

		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.addControl(new GOverviewMapControl(new GSize(100,100)));
		
		GEvent.addListener(directions, "error", dirErrors);

		point = new GLatLng(latitude, longitude);
		map.setCenter(point, zoomlevel);
	}
}


function dirErrors(){
	/*
	if (directions.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 (directions.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 (directions.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 (directions.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 (directions.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.");
	else alert("An unknown error occurred.");
	*/
	alert("Unfortunately, we cannot locate at least one of the addresses specified.\nTherefore, directions request cannot be processed.");
}


function showLocation(address, html, suburb, id, catid, strlat, strlng, catcolor) {
	if ((strlat == "") || (strlng == "")) {
		geocoder = new GClientGeocoder();
		geocoder.getLocations(address, function(response) {
			if (!response || response.Status.code != 200) {
				assignDummyMarker(id, catid, address, html, suburb);
			} else {
				place = response.Placemark[0];
	
				point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
				map.addOverlay(createMarker(point, address, html, suburb, id, catid, catcolor));
			}
		});
	} else {
		point = new GLatLng(parseFloat(strlat), parseFloat(strlng));
		map.addOverlay(createMarker(point, address, html, suburb, id, catid, catcolor));
	}
}

function createMarker(point, address, html, suburb, id, catid, catcolor) {
	// define marker icon
	var picon = new GIcon();
	picon.image = "marker.php?color=" + catcolor;
	picon.shadow = "images/markers_shadow.png";
	picon.iconSize = new GSize(20, 34);
	picon.shadowSize = new GSize(37, 34);
	picon.iconAnchor = new GPoint(9, 33);
	picon.infoWindowAnchor = new GPoint(9, 1);
	picon.infoShadowAnchor = new GPoint(18, 25);
	
	var marker = new GMarker(point, picon);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
		document.getElementById("directionStart").value	= 	document.getElementById("directionEnd").value;
		document.getElementById("directionEnd").value	=	address;
		document.getElementById("mapInfo").innerHTML	=	html;
	});

	if (gmarker[catid] == undefined) {
		gmarker[catid]	= new Array();
	}
	
	gmarker[catid][id]		= new Array();
	gmarker[catid][id][0]	= marker;
	gmarker[catid][id][1]	= address;
	gmarker[catid][id][2]	= html;
	gmarker[catid][id][3]	= suburb;

	plotsuccess += 1;
	return marker;
}

function assignDummyMarker(id, catid, address, html, suburb) {
	if (gmarker[catid] == undefined) {
		gmarker[catid]	= new Array();
	}
	
	gmarker[catid][id]		= new Array();
	gmarker[catid][id][0]	= null;
	gmarker[catid][id][1]	= address;
	gmarker[catid][id][2]	= html;
	gmarker[catid][id][3]	= suburb;
}

function showMarker(id, catid, msg) {
	if (id != "") {
		for (c in gmarker) {
			if (c != catid) {
				document.getElementById("select" + c).selectedIndex = 0;
			}
		}
		document.getElementById("filterSuburb").selectedIndex = 0;
		document.getElementById("filter" + catid).checked = true;
		toggleMarker();
	
		if (gmarker[catid][id][0] == null) {
			document.getElementById("directionStart").value	= 	document.getElementById("directionEnd").value;
			document.getElementById("directionEnd").value	=	gmarker[catid][id][1];
			document.getElementById("mapInfo").innerHTML	=	gmarker[catid][id][2];
			alert(msg);
		} else {
			GEvent.trigger(gmarker[catid][id][0], "click");
		}
	}
}

function toggleMarker() {
	currentSuburb	= document.getElementById("filterSuburb").value;

	for (catid in gmarker) {
		clickcat	= document.getElementById("filter" + catid).checked;
		if (clickcat) {
			for (id in gmarker[catid]) {
				if (gmarker[catid][id][0] != null) {
					if ((gmarker[catid][id][3] == currentSuburb) || (currentSuburb == "")) {
						gmarker[catid][id][0].show();
					} else {
						gmarker[catid][id][0].hide();
					}
				}
			}
		} else {
			for (id in gmarker[catid]) {
				if (gmarker[catid][id][0] != null) {
					gmarker[catid][id][0].hide();
				}
			}
		}
	}
}

function assignSuburb(id, catid, suburb) {
	if (gsuburb[suburb] == undefined) {
		gsuburb[suburb]	= new Array();
	}
	gsuburb[suburb].push(catid + "," + id);
}

function showSuburb(suburb) {
	if (suburb != "") {
		// HIDE ALL
		for (c in gmarker) {
			for (l in gmarker[c]) {
				if (gmarker[c][l][0] != null) gmarker[c][l][0].hide();
			}
		}
		
		var found = false;
		for (i=0; i < gsuburb[suburb].length; i++) {
			loc			= gsuburb[suburb][i].split(",");
			catid		= loc[0];
			id			= loc[1];
			clickcat	= document.getElementById("filter" + catid).checked;
			
			if (clickcat) {
				if (gmarker[catid][id][0] != null) {
					gmarker[catid][id][0].show();
					found = true;
				}
			}
		}
		
		if (found == false) {
			alert("We cannot find any places within this suburb.\nPlease select different criteria/filter.");
		}
	} else {
		toggleMarker();
	}
}

function formatAddress(address1, address2, address3, suburb, postcode, state) {
	var first = true;
	var	rstate = false;
	var separator = ", ";

	var output = "";
	if (address1 != "") {
		output += address1;
		first = false;
	}
	if (address2 != "") {
		if (first == false) output += separator;
		output += address2;
		first = false;
	}
	if (address3 != "") {
		if (first == false) output += separator;
		output += address3;
		first = false;
	}
	if (suburb != "") {
		if (first == false) output += separator;
		output += suburb;
		first = false;
	}
	if (state != "") {
		if (first == false) output += separator;
		output += state;
		first = false;
		rstate = true;
	}
	if (postcode != "") {
		if (rstate == true) {
			output += " ";
		} else if (first == false) {
			output += separator;
		}
		output += postcode;
	}

	return output;
}

function formatGoogleAddress(address1, address2, address3, suburb, postcode, state) {
	var first = true;
	var	rstate = false;
	var separator = ", ";

	var output = "";
	if ((address2 == "") && (address3 == "")) {
		if (address1 != "") {
			output += address1;
			first = false;
		}
	} else {
		if (address2 != "") {
			if (first == false) output += separator;
			output += address2;
			first = false;
		}
		if (address3 != "") {
			if (first == false) output += separator;
			output += address3;
			first = false;
		}
	}
	if (suburb != "") {
		if (first == false) output += separator;
		output += suburb;
		first = false;
	}
	if (state != "") {
		if (first == false) output += separator;
		output += state;
		first = false;
		rstate = true;
	}
	if (postcode != "") {
		if (rstate == true) {
			output += " ";
		} else if (first == false) {
			output += separator;
		}
		output += postcode;
	}

	return output;
}

function buildInitialData() {
	GDownloadUrl("xmldata.php", function (data) {
		var xmlData		= GXml.parse(data);
		var contentData	= xmlData.documentElement.getElementsByTagName("item");

		var lolat	= null;
		var hilat	= null;
		var midlat	= null;
	
		var lolng	= null;
		var hilng	= null;
		var midlng	= null;

		for (var i = 0; i < contentData.length; i++) {
			itemData	= contentData[i].childNodes;

			orgID		= "";
			orgName		= "";
			orgAddress1	= "";
			orgAddress2	= "";
			orgAddress3	= "";
			orgSuburb	= "";
			orgPostcode	= "";
			orgState	= "";
			orgPhone	= "";
			orgFax		= "";
			orgEmail	= "";
			orgWebsite	= "";
			orgContacts	= "";
			orgDetails	= "";
			orgCatID	= "";
			orgLatitude	= "";
			orgLongitude= "";
			orgCatColor	= "";

			for (var j = 0; j < itemData.length; j++) {
				if (itemData[j].firstChild != null) {
					switch (itemData[j].nodeName) {
						case "id":
							orgID		= itemData[j].firstChild.nodeValue;
							break;
						case "name":
							orgName		= itemData[j].firstChild.nodeValue;
							break;
						case "address1":
							orgAddress1	= itemData[j].firstChild.nodeValue;
							break;
						case "address2":
							orgAddress2	= itemData[j].firstChild.nodeValue;
							break;
						case "address3":
							orgAddress3	= itemData[j].firstChild.nodeValue;
							break;
						case "suburb":
							orgSuburb	= itemData[j].firstChild.nodeValue;
							break;
						case "postcode":
							orgPostcode	= itemData[j].firstChild.nodeValue;
							break;
						case "state":
							orgState	= itemData[j].firstChild.nodeValue;
							break;
						case "phone":
							orgPhone	= itemData[j].firstChild.nodeValue;
							break;
						case "fax":
							orgFax		= itemData[j].firstChild.nodeValue;
							break;
						case "email":
							orgEmail	= itemData[j].firstChild.nodeValue;
							break;
						case "website":
							orgWebsite	= itemData[j].firstChild.nodeValue;
							break;
						case "contacts":
							orgContacts	= itemData[j].firstChild.nodeValue;
							break;
						case "details":
							orgDetails	= itemData[j].firstChild.nodeValue;
							break;
						case "catid":
							orgCatID	= itemData[j].firstChild.nodeValue;
							break;
						case "latitude":
							orgLatitude	= itemData[j].firstChild.nodeValue;
							break;
						case "longitude":
							orgLongitude= itemData[j].firstChild.nodeValue;
							break;
						case "color":
							orgCatColor	= itemData[j].firstChild.nodeValue;
							break;
					}
				}
			}
			
			// SET THE LOWEST AND HIGHEST LATITUDE POINT
			if (orgLatitude != "") {
				if (lolat == null) {
					lolat = parseFloat(orgLatitude);
				} else if (lolat > parseFloat(orgLatitude)) {
					lolat = parseFloat(orgLatitude);
				}

				if (hilat == null) {
					hilat = parseFloat(orgLatitude);
				} else if (hilat < parseFloat(orgLatitude)) {
					hilat = parseFloat(orgLatitude);
				}
			}

			// SET THE LOWEST AND HIGHEST LONGITUDE POINT
			if (orgLongitude != "") {
				if (lolng == null) {
					lolng = parseFloat(orgLongitude);
				} else if (lolng > parseFloat(orgLongitude)) {
					lolng = parseFloat(orgLongitude);
				}

				if (hilng == null) {
					hilng = parseFloat(orgLongitude);
				} else if (hilng < parseFloat(orgLongitude)) {
					hilng = parseFloat(orgLongitude);
				}
			}

			//FORMAT ADDRESS
			address = formatGoogleAddress(orgAddress1, orgAddress2, orgAddress3, orgSuburb, orgPostcode, orgState);
			
			//FORMAT TEXT HTML
			html = "";
			html += '<p class="mapText">';
			html += '<strong>' + orgName + '</strong><br />';
			if (orgAddress1 != "")	{ html += orgAddress1 + '<br />'; }
			if (orgAddress2 != "")	{ html += orgAddress2 + '<br />'; }
			if (orgAddress3 != "")	{ html += orgAddress3 + '<br />'; }
			if (orgSuburb != "")	{ html += orgSuburb + ', '; }
			if (orgState != "")		{ html += orgState + ' '; }
			if (orgPostcode != "")	{ html += orgPostcode + '<br />'; }
			if (orgPhone != "")		{ html += 'Phone: ' + orgPhone + '<br />'; }
			if (orgFax != "")		{ html += 'Fax: ' + orgFax + '<br />'; }
			if (orgEmail != "")		{ html += 'Email: ' + orgEmail + '<br />'; }
			if (orgWebsite != "")	{ html += 'Website: ' + orgWebsite + '<br />'; }
			
			if ((orgContacts != "") || (orgDetails != "")) {
				html += "<br />";
				if (orgContacts != "")	{ html += '<strong>Contacts:</strong> ' + orgContacts + '<br />'; }
				if (orgDetails != "")	{ html += '<strong>Details:</strong> ' + orgDetails + '<br />'; }
			}
			html += '</p>';
			
			assignSuburb(orgID, orgCatID, orgSuburb);
			showLocation(address, html, orgSuburb, orgID, orgCatID, orgLatitude, orgLongitude, orgCatColor);
		}

		// SET THE CENTERED LATITUDE POINT
		if ((lolat != null) && (hilat != null)) {
			//alert(lolat + " " + hilat);
			midlat	= (lolat + hilat) / 2;
			diflat	= hilat - lolat;
			
			if (diflat < 1) {
				if (diflat > 0) {
					zoomlat	= Math.round(Math.log(1 / diflat));
				} else {
					zoomlat	= 15;
				}
			} else {
				zoomlat	= Math.round(diflat / -2);
			}
		} else {
			midlat	= -37.84;
			zoomlat = 0;
		}
		
		// SET THE CENTERED LONGITUDE POINT
		if ((lolng != null) && (hilng != null)) {
			//alert(lolng + " " + hilng);
			midlng	= (lolng + hilng) / 2;
			diflng	= hilng - lolng;

			if (diflng < 1) {
				if (diflng > 0) {
					zoomlng	= Math.round(Math.log(1 / diflng));
				} else {
					zoomlng	= 15;
				}
			} else {
				zoomlng	= Math.round(diflng / -2);
			}
		} else {
			midlng	= 145.08;
			zoomlng	= 0;
		}
		
		// SET ZOOM LEVEL
		if (zoomlat < zoomlng) {
			zooml	= 9 + zoomlat;
		} else {
			zooml	= 9 + zoomlng;
		}
	
		centerpoint	= new GLatLng(midlat, midlng);
		map.setCenter(centerpoint, zooml);
	});
}

function displayDirections() {
	startPoint	= document.getElementById("directionStart").value;
	endPoint	= document.getElementById("directionEnd").value;
	directions.load(startPoint + " to " + endPoint);
}