var booIW = false;
var markers = [];
var map;
var marker;
var htmlInfo	= [];
var geo;
var xmlLocations;
var day = 1;
var dir;
var dirRoute = Array();
var dirTotal = Array();
var dirMarkers = Array();

if(document.getElementById("map")) {
	map = new GMap2(document.getElementById("map"));
	geo = new GClientGeocoder(); 

	var reasons=[];
	      reasons[G_GEO_SUCCESS]            = "Success";
	      reasons[G_GEO_MISSING_ADDRESS]    = "Missing Address: The address was either missing or had no value.";
	      reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Address:  No corresponding geographic location could be found for the specified address.";
	      reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	      reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	      reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	      reasons[G_GEO_SERVER_ERROR]       = "Server error: The geocoding request could not be successfully processed.";

	// Setup the tooltip
	var tooltip = document.createElement("div");
	document.getElementById("map").appendChild(tooltip);
	tooltip.style.visibility="hidden";

	// Setup the zoom buttons
	var zoomOut = document.createElement("div");
	document.getElementById("map").appendChild(zoomOut);
	zoomOut.innerHTML = '<img src="/images/Gzoomout.png" border="0" style="cursor: pointer;" onClick="map.setZoom(map.getZoom()-1)"><img src="/images/Gzoomin.png" border="0" style="cursor: pointer; margin-left: 3px;" onClick="map.setZoom(map.getZoom()+1)">';
	zoomOut.style.position="absolute";
	zoomOut.style.zindex="0";

	// Load the basics for google maps
	if (GBrowserIsCompatible()) {
		map.setCenter(new GLatLng(-40.78054143186031,173.25439453125));
		map.setZoom(6);

		var icon = new GIcon();
		icon.image = "images/Gapartment.png";
		icon.iconSize = new GSize(40, 44);
		icon.iconAnchor = new GPoint(20, 27);
		icon.infoWindowAnchor = new GPoint(20, 27);

		var iconKiwi = new GIcon(icon);
		iconKiwi.image = "/images/map_kiwi.png";

		var iconCity = new GIcon(icon);
		iconCity.image = "";
		iconCity.iconAnchor = new GPoint(20, 15);
		iconCity.iconSize = new GSize(100, 12);
		
		var iconWaterfront = new GIcon(icon);
		iconWaterfront.image = "images/Gwaterfront.png";
		
		var iconRural = new GIcon(icon);
		iconRural.image = "images/Grural.png";

		var iconSection = new GIcon(icon);
		iconSection.image = "images/Gsection.png";
		// If we have a property then we don't want to move the zoom around anywhere
		if(!document.getElementById('propertyid') || document.getElementById('propertyid') != '') createRoute();
		loadMarkers();
		
		GEvent.addListener(map, "infowindowopen", function() {
			booIW = true;
		});

		GEvent.addListener(map, "infowindowclose", function() {
			booIW = false;
		});

		GEvent.addListener(map, "zoom", function mapMoved() {
			showMarkers();
		});

		GEvent.addListener(map, "moveend", function() {
			showMarkers();
		});
	}
}

function markerSearch(i) {
	setupMarker(xmlLocations[i], icon, i);
	i++;
	// Load the next marker straight away if we already knew the coordinates
	if(xmlLocations[i]) {
		if(xmlLocations[i].getAttribute("google_coordinate")) {
			markerSearch(i);
		} else if(i < xmlLocations.length) {
			setTimeout('markerSearch(' + i + ')', 250);
		} else {
			// Do one last loop through in case some were missed - can't query google to many times to quickly as it times some out
			for(i = 0; i < xmlLocations.length; i++) if(!markers[i]) setupMarker(xmlLocations[i], icon, i);
			// alert me of the real failed ones
			//for(i = 0; i < xmlLocations.length; i++) if(!markers[i]) alert(xmlLocations[i].getAttribute('address') + ' failed!');
		}
	}
}

function setupMarker(location, selIcon, i) {
	var googleAddress = '';
	selIcon = iconKiwi;
	// Use exisiting coordinates if we can
	if(location.getAttribute("google_coordinate")) {
		p = location.getAttribute("google_coordinate").split(',');
		createMarker(location, selIcon, i, parseFloat(p[1]), parseFloat(p[0]));
	} else {
		if(location.getAttribute("google_address")) {
			googleAddress = location.getAttribute("google_address");
		} else if(location.getAttribute("city_name")) {
			googleAddress = location.getAttribute("city_name") + ', New Zealand';
		} else {
			googleAddress = location.getAttribute("address");
		}
		geo.getLocations(googleAddress, function (result) { 
			if (result.Status.code == G_GEO_SUCCESS) {
				var p = result.Placemark[0].Point.coordinates;
				createMarker(location, selIcon, i, p[1], p[0]);
				// Save the coordinates and address in the database so we don't have to do this every time
				if(location.getAttribute("city_name")) {
					loadAjaxFunctionKHP('saveCoordinate', 'city_name=' + location.getAttribute('city_name') + '&address=' + googleAddress + '&clat=' + p[0] + '&clng=' + p[1]);
				} else {
					loadAjaxFunctionKHP('saveCoordinate', 'propertyid=' + location.getAttribute('propertyid') + '&address=' + googleAddress + '&clat=' + p[0] + '&clng=' + p[1]);
				}
			}
		});
	}
}

function createMarker(property, selIcon, i, clat, clng) {
	// Are we doing city names or another marker
	if(property.getAttribute('city_name')) {
		// Apply a different class if this city contains a kiwi
		var labelClass = 'markerLabel';
		if(property.getAttribute('khp_in_city') == '1') {
			labelClass = 'markerLabelKiwi';
		}
		opts = {
			"icon": iconCity,
			"labelClass": labelClass,
			"clickable": true,
			"labelText": property.getAttribute("city_name"),
			"labelOffset": new GSize(-16, -16)
		};
		var marker = new LabeledMarker(new GLatLng(clat, clng), opts);
	} else {
		var marker = new GMarker(new GLatLng(clat, clng), selIcon);
	}
	var showMarker = true;
	// Center the map on the park if the user is looking at a property
	if(document.getElementById('propertyid')) {
		if(document.getElementById('propertyid').value == property.getAttribute('propertyid')) {
			map.setCenter(new GLatLng(clat, clng));
			map.setZoom(15);
			showMarker = true;
		} else {
			showMarker = false;
		}
	}
	if(showMarker) {
		// Info box display
		htmlInfo[i] = property;

		// Tooltip display
		//marker.tooltip = '<div class="tooltip"><table cellspacing="0" cellpadding="0" border="0"><tr><td bgcolor="#f9f9f9" valign="middle" style="border: 1px solid #797979; padding: 2px;">' + property.getAttribute("property_name") + '</td></tr></table></div>';
		
		marker.propertyid = property.getAttribute('propertyid');
		marker.property = property;
		marker.zoomLevel = property.getAttribute('zoom');
		marker.display = false;
		// on mouse over
		GEvent.addListener(marker, 'mouseover', function() {
			marker_over(i);
		});
		// on mouse out
		GEvent.addListener(marker, 'mouseout', function() {
			marker_out(i);
		});		
		// on click
		GEvent.addListener(marker, 'click', function() {
			marker_click(i);
		});
		// Show the marker if it is at the right zoom level
		if(marker.zoomLevel <= 5) {
			map.addOverlay(marker);
			marker.display = true;
		}
		// Add to global array
		markers[i] = marker;
	}
}

function loadMarkers() {
	var htmlResults		= '';
	var cur_zoom		= map.getZoom();
	var bounds			= map.getBounds(); 
	var sw				= bounds.getSouthWest(); 
	var ne				= bounds.getNorthEast(); 
	var urlstr			= "/includes/read_markers.php";
	var request			= GXmlHttp.create();
	var intResults		= '0';

	// Clear all currently loaded markers
	for(var i = 0; i < markers.length; i++) {
		map.removeOverlay(markers[i]);
	}
	markers = Array();
	// Check to see if we are loading city names or kiwis
	if(document.getElementById('itinerary_form')) urlstr += '?cities=true';

	request.open('GET', urlstr , true);	// request XML from PHP with AJAX call
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			locations = xmlDoc.documentElement.getElementsByTagName("location");
			xmlLocations = locations;
			if(locations.length) {
				intResults = locations.length;
				a = 0;
				// Need to load one every 1/4 of a second as Google rejects to many requests a second
				markerSearch(0);
			}
		}
	}
	request.send(null);	
}

function showMarkers() {
	var cur_zoom		= map.getZoom();
	var bounds = map.getBounds(); 
	var sw = bounds.getSouthWest(); 
	var ne = bounds.getNorthEast(); 
	for(var a = 0; a < markers.length; a++) {
		// Check level at which the marker should start being displayed from
		if(markers[a].zoomLevel <= cur_zoom) {
			if(!markers[a].display) {
				map.addOverlay(markers[a]);
				markers[a].display = true;
			}
		} else {
			map.removeOverlay(markers[a]);
			markers[a].display = false;
		}
		/*var point = markers[a].getPoint();
		
		if((point.lng() <= ne.lng() && point.lng() >= sw.lng()) && (point.lat() <= ne.lat() && point.lat() >= sw.lat())) {
			if(markers[a].display == false) {
				map.addOverlay(markers[a]);
				markers[a].display = true;
			}
		} else {
			map.removeOverlay(markers[a]);
			markers[a].display = false;
		}
		*/
	}
}

// ====== This function displays the tooltip ======
// it can be called from an icon mousover or a sidebar mouseover
function showTooltip(marker) {
	// Make sure the property is within the viewing range of the map otherwise don't show it
	var bounds = map.getBounds(); 
	var sw = bounds.getSouthWest(); 
	var ne = bounds.getNorthEast(); 
	var point = marker.getPoint();
	if((point.lng() <= ne.lng() && point.lng() >= sw.lng()) && (point.lat() <= ne.lat() && point.lat() >= sw.lat())) {
		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 + 2;
		var pos = new GControlPosition(G_ANCHOR_BOTTOM_LEFT, new GSize(offset.x - point.x - anchor.x + width,- offset.y + point.y +anchor.y - 40));
		pos.apply(tooltip);
		tooltip.style.visibility="visible";
		tooltip.style.position="absolute";
		tooltip.style.zindex="0";
	}	
}
  
// Runs when the mouse moves on a marker or on the search results panel
function marker_over(i) {
	//showTooltip(markers[i]);
	if(document.getElementById('map_activities')) getActivities(markers[i].property.getAttribute('city_name'));
}

// Runs when the mouse moves off a marker or off the search results panel
function marker_out(i) {
	//tooltip.style.visibility="hidden";
}

// Runs when a marker is clicked on the map or the search results panel
function marker_click(i) {
	// If the marker is not displayed then center in on the marker and reload the visible markers
	/*if(markers[i].display == false) {
		var point = markers[i].getPoint();
		map.setCenter(new GLatLng(point.lat(), point.lng()));
		showMarkers();
	}*/
	var city_name = markers[i].property.getAttribute("city_name")
	if(document.getElementById('city_name')) document.getElementById('city_name').value = city_name;
	loadAjaxFunctionKHP('locationPopup', 'city_name=' + city_name, 'displayItineraryPopup');
}

// Runs when a zoom link is clicked to zoom in on a property
function marker_zoom(i, zoom) {
	var point = markers[i].getPoint();
	map.setCenter(new GLatLng(point.lat(), point.lng()));

	// Only change the zoom level if needed
	if(map.getZoom() != zoom) map.setZoom(zoom);
}

function resizeMap() {
	objMap = document.getElementById("map");
	objMap.style.width = (document.body.clientWidth - 235) + "px";
}

function addToMyItinerary(id, type) {
	loadAjaxFunctionKHP('addMyItineraryType', 'day=' + day + '&id=' + id + '&type=' + type, 'displayItineraryDay');
}

function removeFromMyItinerary(id, type) {
	loadAjaxFunctionKHP('removeFromMyItinerary', 'day=' + day + '&id=' + id + '&type=' + type, 'displayItineraryDay');
}

function displayItineraryDay() {
	document.getElementById('itinerary_day_' + day).innerHTML = ajax_response;
	setCurrentDay(day)
	fb.end();
	// Loop through all directional maps and clear them
	for(var i = 0; i < dirTotal.length; i++) dirTotal[i].clear();
	// Because we add our markers on seperatly we need to clear them off now as well
	for(var i = 0; i < dirMarkers.length; i++) map.removeOverlay(dirMarkers[i]);
	dirMarkers = Array();
	createRoute();
	getActivities();
}
function createRoute() {
	var urlstr			= "/includes/read_markers.php?route=true";
	var request			= GXmlHttp.create();
	
	// Check if we are loading a suggested itinerary
	if(document.getElementById('suggested_itinerary')) urlstr += '&suggested=' + document.getElementById('suggested_itinerary').value;

	request.open('GET', urlstr , true);	// request XML from PHP with AJAX call
	request.onreadystatechange = function () {
		if (request.readyState == 4) {
			var xmlDoc = request.responseXML;
			var locations = xmlDoc.documentElement.getElementsByTagName("location");
			if(locations.length) {
				var a = 0;
				for(var i = 0; i < locations.length; i++) dirRoute[i] = locations[i];
				displayRoute(0);
			}
		}
	}
	request.send(null);
}

function displayRoute(i) {
	var route = Array();
	var a = 0;
	var count = dirTotal.length;
	var boolViewpoint = true;
	// First time the map appears zoom around the waypoints
	if(!count) boolViewpoint = false;
	// Setup the directions class
	dir = new GDirections(map);
	dirTotal[count] = dir;
	
	for(i = i; i < dirRoute.length; i++) {
		// Only add in the address if it is different from the previous one
		if(a == 0 || (a > 0 && route[(a-1)] != dirRoute[i].getAttribute('google_address'))) {
			route[a] = dirRoute[i].getAttribute('google_address');
			a++;
		}
		// create the route if there is nothing after this day (e.g. a gap in the itinerary where they are staying somewhere else
		if(dirRoute[i].getAttribute('another') == 'false') {
			dir.loadFromWaypoints(route, {preserveViewport : boolViewpoint});
			GEvent.addListener(dir,"load", function(){
				// Need to set a time out of zero so that this loads after the load event is finished - its a weird thing but technically the markers don't exist yet until this event has finished so we can't do anything until its done.
				setTimeout(function() {
				for (var i=0; i < dir.getNumRoutes() + 1; i++) {
					// make a copy of the original marker and add it back in normally - this wipes out any events associated with it plus it lets us change it around completly with our own markers, titles, and events
					var originalMarker = dir.getMarker(i);
					latLngs = originalMarker.getLatLng();
					icons = originalMarker.getIcon();
					newMarker = new GMarker(latLngs,{title: originalMarker.getTitle(),icon:icons,draggable:false}); 
					originalMarker.hide();
					map.addOverlay(dir.getPolyline());
					map.addOverlay(newMarker); 
					dirMarkers[dirMarkers.length] = newMarker;
				}
				// Check to see if we need to run a window print command
				if(window.location.href.indexOf('printpage') > 0) setTimeout('window.print()', 1000);
				},0);
			  });
			if(i + 1 != dirRoute.length) setTimeout('displayRoute(' + (i + 1) + ')', 2500);
			break;
		}
	}
}

function setCurrentDay(newDay) {
	if(document.getElementById('itinerary_date_' + newDay)) {
		document.getElementById('itinerary_date_' + day).style.backgroundColor = '#dcdee0';
		document.getElementById('itinerary_date_' + newDay).style.backgroundColor = '#b6b6b6';
		document.getElementById('current_day_text').innerHTML = document.getElementById('itinerary_date_' + newDay).innerHTML;
		day = newDay;
	}
}
setCurrentDay(day);
getActivities();

function getActivities(city_name) {
	if(!city_name && document.getElementById('city_name_day_' + day)) city_name = document.getElementById('city_name_day_' + day).value;
	if(city_name) loadAjaxFunctionKHP('loadActivities', 'city_name=' + city_name, 'loadActivities');
}
function loadActivities() {
	document.getElementById('map_activities').innerHTML = ajax_response;
}
function loadActivity(activityid) {
	loadAjaxFunctionKHP('loadActivity', 'day=' + day + '&activityid=' + activityid, 'displayItineraryPopup');
}
function displayItineraryPopup() {
	document.getElementById('propertyBox').innerHTML = ajax_response;
	fb.start({ href: '#propertyBox', rev: 'width:448 height:300 scrolling:no roundCorners:none innerBorder:0 padding:0 controlPos:bl doAnimations:false outerBorder:0 enableKeyboardNav:false' });
}
function loadProperty(propertyid) {
	loadAjaxFunctionKHP('loadProperty', 'day=' + day + '&propertyid=' + propertyid, 'displayItineraryPopup');
}
function itineraryChange(form) {
	// Check to see if there is a starting point - as this is required if this is a brand new plan
	if(document.getElementById('startid')) {
		if(document.getElementById('startid').value != '') submitAjaxFormKHP(form, 'updateItinerary', 'refreshPage');
	} else {
		submitAjaxFormKHP(form, 'updateItinerary', 'refreshDays');
	}
}

function datePickerClosed() {
	itineraryChange(document.getElementById('itinerary_form'));
}

function saveLocationSelection() {
	var i = 0;
	var propertyid = '0';
	while(document.getElementById('id_location_' + i)) {
		if(document.getElementById('id_location_' + i).checked == true) {
			propertyid = document.getElementById('id_location_' + i).value;
			break;
		}
		i++;
	}
	if(document.getElementById('startid')) {
		document.getElementById('startid').value = propertyid;
		itineraryChange(document.getElementById('itinerary_form'));
	} else {
		var city_name = document.getElementById('city_name').value;
		var city_comments = document.getElementById('city_comments').value;
		loadAjaxFunctionKHP('addMyItinerary', 'day=' + day + '&city_name=' + city_name + '&propertyid=' + propertyid + '&comments=' + city_comments, 'displayItineraryDay');
	}
}

function refreshDays() {
	if(ajax_response) {
		document.getElementById('itinerary_days').innerHTML = ajax_response;
		setCurrentDay(1);
	}
}

function refreshPage() {
	window.location.href = window.location.href;
}

function changeDayCity(city_name, id, itinerarymapid) {
	document.getElementById('city_name').value = city_name;
	loadAjaxFunctionKHP('locationPopup', 'city_name=' + city_name + '&id=' + id + '&itinerarymapid=' + itinerarymapid, 'displayItineraryPopup');
}

function itineraryHelp(helpid) {
	loadAjaxFunctionKHP('itineraryHelp', 'helpid=' + helpid, 'displayItineraryPopup');
}