//var address;
var mapAddress;
var addresses = new Array();
var map;
var startZoom = 10;
var articleText;
var geoCoder;
var markers = new Array();
var addressLinks = new Array();
var directions = 0;
var st = 'NC';
var gdir;
$(document).ready(function(){
	articleText = $(".article_text");
	var str = articleText.text();
//	var designation = "STREET|ST|AVENUE|AVE|LANE|LN|PARKWAY|PKWY|WAY|ROAD|RD|DRIVE|DR|PLACE|PL|CIRCLE|CIR|COURT|CT|PIKE|TERRACE|TER|TRAIL|TRL|TL|BOULEVARD|BLVD";
//	var towns = "Wilmington|Wrightsville Beach|Kure Beach|Carolina Beach|Castle Hayne|New Hanover County";
//	var myRe = new RegExp("(\\d+\\s[A-Za-z0-9\.]+\\s*[A-Za-z0\.]*\\s(?:STREET|ST|AVENUE|AVE|LANE|LN|PARKWAY|PKWY|WAY|ROAD|RD|DRIVE|DR|PLACE|PL|CIRCLE|CIR|COURT|CT|PIKE|TERRACE|TER|TRAIL|TRL|TL|BOULEVARD|BLVD)\\.?, *(?:Wilmington|Wrightsville Beach|Kure Beach|Carolina Beach|Castle Hayne|New Hanover County))","gim");
	var myRe = new RegExp("(\\d+\\s[A-Za-z0-9\.]+\\s*[A-Za-z0-9]*\\s(?:STREET|ST|AVENUE|AVE|LANE|LN|PARKWAY|PKWY|WAY|ROAD|RD|DRIVE|DR|PLACE|PL|CIRCLE|CIR|COURT|CT|PIKE|TERRACE|TER|TRAIL|TRL|TL|BOULEVARD|BLVD)\\.?, *(?:Wilmington|Wrightsville Beach|Kure Beach|Carolina Beach|Castle Hayne|New Hanover County))","gim");
	addresses = str.match(myRe);
	if (addresses.length) {
		geoCoder = new GClientGeocoder();
		mapAddress = addresses.shift();
		geoCoder.getLocations(mapAddress,makeMap);
	}

});
function makeMap(response) {
	if (response) {
		var width = $(".article_text:last").width();
		var height = Math.floor(width/2);
		var mapDiv = '<div id="articleMap" style="width:' + 
			width + 
			'px;height:' + 
			height + 
			'px;"></div>';
//		articleText.slice(articleText.length-1,articleText.length).after(mapDiv);
		$(".article_text:last").after(mapDiv);
		map = new GMap2(document.getElementById("articleMap"));
		map.addControl(new GSmallMapControl());
		var place = response.Placemark[0];
		var point = new GLatLng( place.Point.coordinates[1],place.Point.coordinates[0]);
		map.setCenter(point, startZoom);
		var marker = new GMarker(point);
		GEvent.addListener(marker, "click", function() {
			marker.openInfoWindowHtml(mapAddress);
		});
		var linkAddress = place.address;
		map.addOverlay(marker);
		markers.push(marker);
		addressLinks.push(linkAddress);
		if(addresses.length) {
			addMarkers(addresses);
		}
		else {
			showLinks();
		}
	}
}


function addMarkers(addresses) {
var count = 0;
	for(var i = 0; i < addresses.length; i++) {
		address = addresses[i];
		geoCoder.getLatLng(address,function(point) {
			var thisAddress = addresses[count];
			count++;
			var marker = new GMarker(point);
			GEvent.addListener(marker,"click",function() {
				marker.openInfoWindowHtml(thisAddress);
			});			
			map.addOverlay(marker);
			markers.push(marker);
			addressLinks.push(thisAddress);
		if (count == addresses.length) {
			showLinks();
		}
		});
	}

}

function showLinks() {
	var addressLabels = "<p><strong>This address appears on this map</strong></p>";
	if(addressLinks.length > 1) {
		addressLabels = "<p><strong>These addresses appear on this map</strong></p>";
	}
	for(var i = 0; i < addressLinks.length; i++) {
		addressLabels += '<a href="javascript:myClick(' + i + ')">' + addressLinks[i] + '</a> ';
		addressLabels += "<a href=\"javascript:getDirections('" + addressLinks[i] + "')\">Get directions</a><br />";
	}
	$("#articleMap").after(addressLabels);
}

function myClick(marker){
	GEvent.trigger(markers[marker],"click");
}

function getDirections(address) {
	var formDiv = '<div id="directionsForm"><p>Directions to ' + address + '</p>' +
		'<form name="addressForm" id = "addressForm"><label for="fromAddress">Starting address: ' + 
		'<input type="text" name="fromAddress" id="fromAddress" /><button style="background:black;font-size:8pt;color:white;text-transform:uppercase" onclick="showDirections();return false;">Show</button>' + 
		'<input type="hidden" name="toAddress" id="toAddress" value="' + address + '" /></form>' + 
		'<div id="directions"></div>' +
		'</div>';

	if(directions) {
//		var smallerWidth = $("#directionsForm").width();
		$("#directions").empty();
		document.getElementById("toAddress").value = address;
//		$("#directionsForm > input:hidden").attr({'value': address});
//		$("#directionsForm").remove();
//		$("#directionsForm").replaceWith(formDiv);
//		$("#articleMap").after(formDiv);
//		$("#directionsForm").css({'width': smallerWidth,'float':'left'});
		$("#directionsForm > p").replaceWith('<p>Directions to ' + address + '</p>');
		map.setZoom(startZoom);
		map.panTo(markers[0].getLatLng());
	}

	else {
	
		var fullWidth = $("#articleMap").width();
		var smallerWidth = Math.floor(fullWidth/2) - 3;
		smallerWidth += "px";
		$("#articleMap").css({'width': smallerWidth,'float':'left','margin-right': '4px'});
		var mapCenter = markers[0].getLatLng();
		map.checkResize();
		map.panTo(mapCenter);
		$("#articleMap").after(formDiv);
		$("#directionsForm").css({'width': smallerWidth,'float':'left'});
		directions++;
	}
}
function showDirections() {
//	var fromAddress = document.addressForm.fromAddress.value;
//	var toAddress = document.addressForm.toAddress.value;
	var fromAddress = document.getElementById("fromAddress").value;
	var toAddress = document.getElementById("toAddress").value;
	var width = $("#directionsForm").width();
	var height = $("#articleMap").height() - $("#directionsForm").height();
//	$("#directionsForm").append('<div id="directions"></div>');
	$("#directions").css({'width': width,'height': height,'float': 'left','overflow':'auto'});
	gdir = new GDirections(map, document.getElementById("directions"));
	GEvent.addListener(gdir, "load", onGDirectionsLoad);
	GEvent.addListener(gdir, "error", handleErrors);
	gdir.load("from: " + fromAddress + " to: " + toAddress, { "locale": "en_US" });
}

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_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 onGDirectionsLoad(){ 
	map.addOverlay(gdir.getPolyline());
//	$("#formControls").html('<a href="#" onclick="printMap()">Format for printing</a>');
//	$("#formPanel").html('<a href="#" onclick="printMap()">Format for printing</a>');
      // Use this function to access information about the latest load()
      // results.

      // e.g.
      // document.getElementById("getStatus").innerHTML = gdir.getStatus().code;
	  // and yada yada yada...
}
