var markerArray = new Array();
var htmlArray = new Array();
var toArray = new Array();
var from_htmls = new Array();

var theMap = null;
var baseIcon = null;
var currentItem = null;
var count = 1;

function initMapLrg() { initMap(true); }
function initMapSmall() { initMap(false); }

function initMap(isLg) {
	if (GBrowserIsCompatible()) {
		var map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(43.6400, -79.3660), 7);
		theMap = map;

		if(isLg) {
			map.addControl(new GLargeMapControl());
			map.addControl(new GMapTypeControl());

			//Monitor the window resize event and let the map know when it occurs
			if (window.attachEvent) { window.attachEvent("onresize", setMapSize); }
			else { window.addEventListener("resize", setMapSize, false); }
		}
		else {
			map.addControl(new GSmallMapControl());
		}

		// define base icon
		baseIcon = new GIcon();
		baseIcon.image = "http://www.google.com/mapfiles/marker.png";
		baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
		baseIcon.iconSize = new GSize(20, 34);
		baseIcon.shadowSize = new GSize(37, 34);
		baseIcon.iconAnchor = new GPoint(9, 34);
		baseIcon.infoWindowAnchor = new GPoint(9, 2);
		baseIcon.infoShadowAnchor = new GPoint(18, 25);

		//loadMarkers(map, document.forms[0].elements[0].value, document.forms[0].elements[1].value);
	}
}

function loadListing(categoryValue) {
	window.location = "listing.php?id=" + categoryValue;
}

function loadDetail() {
	var bounds = new GLatLngBounds();
	var latValue = document.getElementById("map").getAttribute("lat");
	var longValue = document.getElementById("map").getAttribute("long");
	var point = new GLatLng(latValue, longValue);

	bounds.extend(point);
	theMap.addOverlay(createSimpleMarker(point));
	theMap.setCenter(bounds.getCenter(), 9);
}

function loadAllMarkers() { loadMarkers(theMap, "all", "SC01"); }

function loadMarkers(map, categoryValue, regionValue) {

	var bounds = new GLatLngBounds();
	count = 1;

	if(regionValue == "na") { alert("Please select a region from the drop down."); }
	else {
		currentItem = null;
		//document.getElementById("status").className = "show";

		map.clearOverlays();

		document.getElementById("resultList").innerHTML = "";

		GDownloadUrl("xml/markers.php?category="+ categoryValue +"&region="+ regionValue, function(data, responseCode) {
			var xml = GXml.parse(data);
			var markers = xml.documentElement.getElementsByTagName("marker");

			for (var i = 0; i < markers.length; i++) {
				var id = markers[i].getAttribute("id");
				var business = markers[i].getAttribute("business");
				var owner = markers[i].getAttribute("owner");
				var photo = markers[i].getAttribute("photo");
				var link = markers[i].getAttribute("link");
				var address = markers[i].getAttribute("address");
				var city = markers[i].getAttribute("city");
				var phone = markers[i].getAttribute("phone");
				var categories = markers[i].getAttribute("categories");
				var directions = markers[i].getAttribute("directions");
				var hours = markers[i].getAttribute("hours");
				var notes = markers[i].getAttribute("notes");
				var lat = parseFloat(markers[i].getAttribute("lat"));
				var lng = parseFloat(markers[i].getAttribute("long"));
				var point = new GLatLng(lat, lng);

				if(parseInt(lat) != 0 && parseInt(lng) != 0) {
					map.addOverlay(createMarker(point, id, business, owner, photo, link, address, city, phone, categories, directions, hours, notes));
					bounds.extend(point);
				}
			}

			Behaviour.apply();
			document.getElementById("instructions").className = "hide";
			document.getElementById("results").className = "show";
			//document.getElementById("status").className = "hide";

			// recenter and zoom map
			var regionLat = xml.documentElement.getAttribute("lat");
			var regionLong = xml.documentElement.getAttribute("long");
			var regionZoom = xml.documentElement.getAttribute("zoom");

			map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
		});
	}
}

function createMarker(point, id, business, owner, photo, link, address, city, phone, categories, directions, hours, notes) {
  var icon = new GIcon(baseIcon);
  icon.image = "template/markers/marker" + count + ".png";

	var marker = new GMarker(point, icon);
	var resultHtml = document.getElementById("resultList");
	var linkUrl = (link.substr(0,4) == 'http') ? link : 'http://' + link;

	var windowHtml = '<b><a href="' + linkUrl + '" target="_blank">' + business + '</a></b>';
	windowHtml += '<p>' + address + '<br/>';
	windowHtml += city + ', ON<br/>';
	windowHtml += phone + '</p>';


  // The info window version with the "to here" form open
  toArray[id] = '<div id="infoText">' + windowHtml +
		'<p>Directions: <b>To here</b> - <a href="javascript:fromhere(' + id + ')">From here</a></p>' +
		'<form action="http://maps.google.com/maps" method="get" target="_blank">' +
		'<p>Start address:' +
		'<input type="text" size="35" maxlength="40" name="saddr" id="saddr" value="" /></p>' +
		'<p><input value="Get Directions" type="submit"></p>' +
		'<input type="hidden" name="daddr" value="' + point.lat() + ',' + point.lng() +
            // "(" + name + ")" +
		'"/>' +
		'</form>' +
		'</div>';

  // The info window version with the "to here" form open
  from_htmls[id] = '<div id="infoText">' + windowHtml +
		'<p>Directions: <a href="javascript:tohere(' + id + ')">To here</a> - <b>From here</b></p>' +
		'<form action="http://maps.google.com/maps" method="get"" target="_blank">' +
		'<p>End address:' +
		'<input type="text" size="35" maxlength="40" name="daddr" id="daddr" value="" /></p>' +
		'<p><input value="Get Directions" type="submit"></p>' +
		'<input type="hidden" name="saddr" value="' + point.lat() + ',' + point.lng() +
            // "(" + name + ")" +
		'"/>' +
		'</form>' +
		'</div>';

  // The inactive version of the direction info
  windowHtml = '<div id="infoText">' + windowHtml +
		'<p>Directions: <a href="javascript:tohere('+id+')">To here</a> - <a href="javascript:fromhere('+i+')">From here</a></p>' +
		'</div>';


	GEvent.addListener(marker, "click", function() {
		toggleInfo(document.getElementById(id));
	});

	markerArray[id] = marker;
	htmlArray[id] = windowHtml;

	var detailHtml = '';
	detailHtml += '<div class="resultc">';
	detailHtml += '<div class="rName">'+ count +'. <a id="' + id + '" href="javascript:onResultClick(' + id + ')">' + business + '</a></div>';
	detailHtml += '<div class="rInfo">';
	if(link != "") detailHtml += '<p><a href="' + linkUrl + '" target="_blank">' + link + '</a></p>';
	if(photo != "") detailHtml += '<img src="../images/farms/resized/' + photo + '" />';
	if(categories != "") detailHtml += '<p><b>What\'s available:</b><br/>' + categories + '</p>';
	if(directions != "") detailHtml += '<p><b>Directions:</b><br/>' + directions + '</p>';
	if(hours != "") detailHtml += '<p><b>Hours:</b><br/>' + hours + '</p>';
	if(notes != "") detailHtml += '<p><b>Notes:</b><br/>' + notes + '</p>';
	detailHtml += '</div>';
	detailHtml += '</div>';

	resultHtml.innerHTML += detailHtml;
	count++;

	return marker;
}

function createSimpleMarker(point) {
	var marker = new GMarker(point, baseIcon);
	return marker;
}

function setMapSize() {
	document.getElementById("map").style.width = "400px";
	document.getElementById("map").style.height = "350px";
}

function setMapSmall() {
	document.getElementById("map").style.width = "280px";
	document.getElementById("map").style.height = "240px";
}

function toggleInfo(element) {
	if(currentItem != null) {
		currentItem.parentNode.parentNode.className = (currentItem.parentNode.parentNode.className == "resultc") ? "resulte" : "resultc";
	}
	element.parentNode.parentNode.className = (element.parentNode.parentNode.className == "resultc") ? "resulte" : "resultc";

	markerArray[element.id].openInfoWindowHtml(htmlArray[element.id]);

	currentItem = element;
}

// functions that open the directions forms
function tohere(id) {
  markerArray[id].openInfoWindowHtml(toArray[id]);
}

function fromhere(id) {
  markerArray[id].openInfoWindowHtml(from_htmls[id]);
}

function deleteMarker(element) {
	var url = "index.php?action=deleteMarker&id=" + element.title;
	if(confirm("Are you sure you want to delete this marker?")) {
		document.location.href = url;
	}
}


var rules = {
	'a.deleteMarker' : function(element){
		element.onclick = function(){ deleteMarker(this); return false; }
	},
	'div.rName a' : function(element){
		element.onclick = function(){ toggleInfo(this); return false; }
	},
	'input.trailCheckbox' : function(element){
		element.onclick = function(){ toggleTrailCheck(this); }
	}
};
