var map;
var markers = [];
var mgr;
var gdir;
var distance;
var curLocMarker;

function initialize() {
 	if (GBrowserIsCompatible()) {
   	map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(new GLatLng(40, -100.1419), 3);
    map.setUIToDefault();
    mgr = new MarkerManager(map,{trackMarkers:true});
    gdir = new GDirections(map, document.getElementById("dirContainer"));
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
    GEvent.addListener(gdir, "error", handleErrors);
    GEvent.addListener(gdir, "addoverlay", emptyFunction);
  }
}

function emptyFunction() {
	//alert("Adding overlay");
}

function animate() {
 	var coords;
 	var coordsSplit;
 	var latitude;
 	var longitude;
 	var bounds = new GLatLngBounds();
  	
 	coords = document.getElementById('coords').value;

 	coordsSplit = coords.split(",");
  	
 	longitude = coordsSplit[0];
	latitude = coordsSplit[1];
 	map.panTo(new GLatLng(longitude, latitude), 1);
 	marker = new GMarker(new GLatLng(longitude, latitude));
 	map.setCenter(new GLatLng(longitude, latitude),13)
 	map.addOverlay(marker);
}

function zoomToPoint(markerID) {
	
	map.setCenter(markers[markerID].point, 10);
	markers[markerID].openInfoWindow();

}

function onGDirectionsLoad(){ 

	//document.getElementById("dirContainer");

}

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_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
	//     alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\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 addGroup(typeId) {
		
 	var coords;
 	var coordsSplit;
 	var latitude;
 	var longitude;
 	var locDescription;
 	var locType;
 	var meters;
 	var bounds = new GLatLngBounds();
  var badge = new GIcon(G_DEFAULT_ICON);

	badge.image = "http://www.findsigmachi.com/images/badge_marker.png";
	var markerOptions = { icon:badge };

 	coords = document.getElementById('coords').value;

 	coordsSplit = coords.split("|");
 	var coordsComSplit = coords.split(",");
 	locDescription = coordsComSplit[3];

	if(document.getElementById(locDescription).checked == false) {
		
		var markersLength = markers.length;
		var tempArray = [];
		for (var i=0;i<markersLength;i++) {

 			if (markers[0].type==typeId) {
 				mgr.removeMarker(markers[0]);
 				markers.splice(0,1);
 			}
 			else {
 				tempArray.splice(0,0,markers[0]);
 				markers.splice(0,1);
 			}
 		}
 		markers = tempArray;
 		document.getElementById("infoContainer").innerHTML = "";

 		for(i=0;i<markers.length;i++) {
 			if(document.getElementById('curAddressSubmit').value == "true") {
				document.getElementById("infoContainer").innerHTML += "<a href=\"#\" onClick=\"getDirections(" + i + ");\">" + markers[i].title + "</a> " + addCommas(markers[i].distance) + " miles. <br/>";
			}
			else {
				document.getElementById("infoContainer").innerHTML += "<a href=\"#\" onClick=\"zoomToPoint(" + i + ");\">" + markers[i].title + "</a><br/>";
			}
		}
	}
	else {

 		for (i=0;i<coordsSplit.length;i++) {	
  	
  		var coordsReSplit = coordsSplit[i].split(",");
  		
	 		longitude = coordsReSplit[0];
			latitude = coordsReSplit[1];
			locName = coordsReSplit[2];
			locDescription = coordsReSplit[3];
			locType = coordsReSplit[4];
		
			var point = new GLatLng(longitude,latitude);
			var marker = new GMarker(point,markerOptions);
			document.getElementById("infoContainer").innerHTML = "";
			
			if(document.getElementById('curAddressSubmit').value == "true") {
				var dirArray = [];
				dirArray.push(curLocMarker);
				dirArray.push(point);
				gdir.loadFromWaypoints(dirArray);
				document.getElementById("statusContainer").innerHTML = gdir.getStatus().code;

				meters = curLocMarker.distanceFrom(point);
					
				marker.bindInfoWindowHtml(locName + " - " + locDescription);
				marker.point = point;
				marker.type = locType;
				marker.title = locName;
			
				miles = meters * 0.000621371192;
				miles = miles.toFixed(1);
				marker.distance = miles;
				markers.push(marker);	

				gdir.clear();
				
				markers.sort(sortNumber);
				
				for(j=0;j<markers.length;j++) {
					document.getElementById("infoContainer").innerHTML += "<a href=\"#\" onClick=\"getDirections(" + j + ");\">" + markers[j].title + "</a> " + addCommas(markers[j].distance) + " miles. <br/>";
				}
			}
			else {
				marker.bindInfoWindowHtml(locName + " - " + locDescription);
				marker.point = point;
				marker.type = locType;
				marker.title = locName;
				markers.push(marker);	
				
				
				for(j=0;j<markers.length;j++) {
					document.getElementById("infoContainer").innerHTML += "<a href=\"#\"  onClick=\"zoomToPoint(" + j + ");\">" + markers[j].title + "</a><br/>";
				}
			}
		}
		

		mgr.addMarkers(markers,0);
		mgr.refresh(map);
	}	
}
    
function ajaxFindCoords(locId){
	var ajaxRequest;
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		
		if(ajaxRequest.readyState == 4){
			document.getElementById('coords').value = ajaxRequest.responseText;
			animate();
		}
		
	}
	
	var queryString = "?id=" + locId;
	ajaxRequest.open("GET", "getCoords.php" + queryString, true);
	ajaxRequest.send(null); 
}

function ajaxAddGroup(typeId){
	var ajaxRequest;
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
		
			document.getElementById('coords').value = ajaxRequest.responseText;
			addGroup(typeId);
		}
	}
	
	var queryString = "?type=" + typeId;
	ajaxRequest.open("GET", "getCoords.php" + queryString, true);
	ajaxRequest.send(null); 
}

function addCurLoc() {
	
	var geocoder = new GClientGeocoder();
	var address = document.getElementById('curAddress').value;
	document.getElementById('curAddressSubmit').value = "true";
	
	geocoder.getLatLng(address,
								    function(point) {
								    	if (!point) {
								    		alert(address + " not found");
								    	}
								    	else {
								    		map.setCenter(point, 13);
								    		var marker = new GMarker(point);
								    		curLocMarker = point;
								    		map.addOverlay(marker);
								    		marker.openInfoWindowHtml(address);
								    	}    
								    }
								  );
}		
  	
 function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

function sortNumber(a,b)
{
	return a.distance - b.distance;
}

function getDirections(i) {
	
	var dirArray = [];
	var point = markers[i].point;
	
	dirArray.push(curLocMarker);
	dirArray.push(point);
	
	gdir.loadFromWaypoints(dirArray);
	
	
}
	
function pause(millis) 
{
        var date = new Date();
        var curDate = null;

        do { curDate = new Date(); } 
        while(curDate-date < millis)
} 