//Javascript Document

//<![CDATA[


//DEFINE GLOBAL VARIABLES///////////////////////

//the GMap2 object
var map;

//an array of the map-state variables
var storedMapState = new Array();
	storedMapState["isset"]  = true;
	storedMapState["center"] = new GLatLng(35.779525, -78.640223);
	storedMapState["zoom"]   = 14;

//an array of sets of GLatLng objects that represent rectangles
var storedRectangle = null;

//an array of sets of GLatLng objects that represent rectangles
var storedLines   = new Array();

//a sorted list of points that have been selected by user, managed by capturePoint, releasePoint, and sortStoredPoints//
var storedPoints  = new Array();


//////////////////////////////////////////////////////////////////////////////////////////////////////


////////////////////////////////////////////////


function load() {
	
	map = new GMap2(document.getElementById("map"));
	
	//load the controls and center the map on default location
	initMap();
	
	//return map object for use in other functions
	return(map);
	
}






//builds a marker and displays it on the map
function showAddress(address) {
   
   //init geocoder object for use in geocoding address
   var geocoder = new GClientGeocoder();
   
   geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
	  
		//set the center of the map to the specified point
      	map.panTo(point);
		map.setZoom(storedMapState["zoom"]);

		//store the point and the marker in their respective global arrays
		capturePoint(point);
		
		drawMapFeatures(true,false,false);


      }
    }
  );
}	










//THE IDEA IS THAT THIS WILL FIND ALL CASTPOINTS WITHIN A CERTAIN RADIUS OF THE ADDRESS GIVEN,
//THEN WILL STORE THOSE POINTS IN THE CACHEDCASTPOINTS IN JAVASCRIPT, AND WILL STORE THEIR DESCRIPTIVE DATA
//IN A PHP SESSION VARIABLE FOR READING DURING THE PROXIMITY-SEARCH PROCESS
function findCastpointsNear(address,proximity) {




   //init geocoder object for use in geocoding address
   var geocoder = new GClientGeocoder();
   
   geocoder.getLatLng(
    address,
    function(point) {
      if (!point) {
        alert(address + " not found");
      } else {
	  
		//set the center of the map to the specified point
      	map.panTo(point);
		map.setZoom(storedMapState["zoom"]);


		//DO THE PROXIMAL CASTPOINTS QUERY////////////////////////////////////////////////////////////////////////
		var getProximalCastpointsRequest = "/AJAX/getProximalCastpoints.php?point="+point+"&proximity="+proximity;
		sendRequest(getProximalCastpointsRequest);
		var proximityResult = responseValue;
		
		//alert("search result = " + proximityResult);
		
		var saveProximalCastpointsRequest = "/AJAX/addProximityResultToSession.php?proximityResult="+proximityResult;
		sendRequest(saveProximalCastpointsRequest);
		
		//alert("save castpoints to session = " + responseValue);
		
		var proximalCastpoints = proximityResult.split("@@@"); 
		///////////////////////////////////////////////////////////////////////////////////////////////////////////

		//store the points and in the castpoints array in javascript
		for(var i=0;i<proximalCastpoints.length;i++) {
			var thisResult = proximalCastpoints[i].split(";;");
			capturePoint(new GLatLng(thisResult[1],thisResult[2]));
		}


      }
    }
  );
}	









//THE IDEA IS THAT THIS WILL FIND ALL CASTPOINTS WITHIN A CERTAIN RADIUS OF THE ADDRESS GIVEN,
//THEN WILL STORE THOSE POINTS IN THE CACHEDCASTPOINTS IN JAVASCRIPT, AND WILL STORE THEIR DESCRIPTIVE DATA
//IN A PHP SESSION VARIABLE FOR READING DURING THE PROXIMITY-SEARCH PROCESS
function findCastpointsNearByPoint(point,proximity) {
    
		//alert("it's working");
	
		//set the center of the map to the specified point
      	map.panTo(point);
		map.setZoom(storedMapState["zoom"]);


		//DO THE PROXIMAL CASTPOINTS QUERY////////////////////////////////////////////////////////////////////////
		var getProximalCastpointsRequest = "/AJAX/getProximalCastpoints.php?point="+point+"&proximity="+proximity;
		sendRequest(getProximalCastpointsRequest);
		var proximityResult = responseValue;
		
		//alert("search result = " + proximityResult);
		
		var saveProximalCastpointsRequest = "/AJAX/addProximityResultToSession.php?proximityResult="+proximityResult;
		sendRequest(saveProximalCastpointsRequest);
		
		//alert("save castpoints to session = " + responseValue);
		
		var proximalCastpoints = proximityResult.split("@@@"); 
		///////////////////////////////////////////////////////////////////////////////////////////////////////////

		//store the points and in the castpoints array in javascript
		for(var i=0;i<proximalCastpoints.length;i++) {
			var thisResult = proximalCastpoints[i].split(";;");
			capturePoint(new GLatLng(thisResult[1],thisResult[2]));
		}

}	







//draws all the features that are stored in the storedOverlays global array
//each time a function is called which creates a new overlay, drawMapFeatures should
//be called to add it to the map view
function drawMapFeatures(markers, lines, boundary) {
	
	saveMapPosition();
	
	//remove all existing overlays from the map
	map.clearOverlays();
	
	// Create our "tiny" marker icon
	var gocast_marker = new GIcon();
	gocast_marker.image = "http://www.gocast.org/images/flag.png";
	gocast_marker.shadow = "http://www.gocast.org/images/flag_shadow.png";
	gocast_marker.iconSize = new GSize(18, 30);
	gocast_marker.shadowSize = new GSize(18, 30);
	gocast_marker.iconAnchor = new GPoint(4, 30);
	gocast_marker.infoWindowAnchor = new GPoint(4, 1);
	
	//add stored GMarkers to the map
	if(markers) {
		for(var i = 0;i < storedPoints.length;i++) {
			map.addOverlay(new GMarker(storedPoints[i],gocast_marker));
		}
	}

	//add stored Lines to the map
	if(lines) {
		for(var k=0;k < storedLines.length;k++) {
			map.addOverlay(storedLines[k]);
		}
	}
	
	//add stored Rectangle to the map
	if(boundary && storedRectangle) {
			map.addOverlay(storedRectangle);
	}


}




//stores the argument as an element in the array storedPoints, which is sorted
//in order top-left to bottom-right
//TAKES: GLatLng
function capturePoint(geopoint) {
	
	storedPoints.push(geopoint);

}


//removes the given point from the storedPoints global array
//TAKES: GLatLng 
function releaseStoredPoint(point) {
	for(var i=0;i < storedPoints.length;i++) {
		if(storedPoints[i] == point) {
			storedPoints.splice(i,1);
			break;
		}
	}
	
}




function releaseMarker(marker) {

	releaseStoredPoint(marker.getPoint());
	makeBoundingBox();
	//hideElement("editPoint_layer");
			
    if(storedRectangle) {
		drawMapFeatures(true,false,true);
	} else {
		drawMapFeatures(true,false,false);
	}

}


//stores the argument as an element in the array storedRectangle
//TAKES: Array of GLatLng
function captureLine(points) {

	storedLines.push(new GPolyline(points));

}


//stores the argument as an element in the array storedRectangle
//TAKES: Array of GLatLng
function captureRectangle(points) {

	storedRectangle = new GPolyline(points);

}





//sorts the storedPoints global array from norwest to soueast
function sortStoredPointsByLat() {
	
	var sortedPoints = storedPoints.sort( function(p1,p2){
  		if (p1.lat() > p2.lat()) return 1;
  		if (p1.lat() < p2.lat()) return -1;
  		return 0;
	});
	
	return sortedPoints;
}



//sorts the storedPoints global array from norwest to soueast
function sortStoredPointsByLng() {
	var sortedPoints = storedPoints.sort( function(p1,p2){
  		if (p1.lng() > p2.lng()) return 1;
  		if (p1.lng() < p2.lng()) return -1;
  		return 0;
	});
	
	return sortedPoints;


}



//builds and draws a bounding box with corners set at souwest and noreast most of selected points
function makeBoundingBox() {
	
	if(storedPoints.length <= 1) {
	
		storedRectangle = null;
	
	} else {
	
	var sortedLat = sortStoredPointsByLat();
	var latNoreast    = sortedLat[sortedLat.length-1];
	var latSouwest    = sortedLat[0];
	
	var sortedLng = sortStoredPointsByLng();
	var lngNoreast    = sortedLng[sortedLng.length-1];
	var lngSouwest    = sortedLng[0];
	
	var noreast    = new GLatLng(latNoreast.lat()+0.00075,lngNoreast.lng()+0.00075);
	var norwest    = new GLatLng(latNoreast.lat()+0.00075,lngSouwest.lng()-0.00075);
	var soueast    = new GLatLng(latSouwest.lat()-0.00075,lngNoreast.lng()+0.00075);
	var souwest    = new GLatLng(latSouwest.lat()-0.00075,lngSouwest.lng()-0.00075);
	
	//var rectangle  = new GBounds(souwest, noreast);
	
	var points = new Array()
		points[0] = noreast;
		points[1] = norwest; 
		points[2] = souwest; 
		points[3] = soueast;
		points[4] = noreast;
		
	//load the rectangle into the storedLine global variable
	captureRectangle(points);

	} 
	
}






//adds controls and centers the map
function initMap() {
	
	//alert("InitMap");

    if (GBrowserIsCompatible()) {	
	
		var map_control = new GLargeMapControl();
    	map.addControl(map_control);
		
		var type_control = new GMapTypeControl();
    	map.addControl(type_control);
	
		//set map state from stored map state global variable
		map.setCenter(storedMapState["center"]);
		map.setZoom(storedMapState["zoom"]);

		//setup the click listener to make or remove storedPoints
		initMarkerClick();

	}

}


//implement functions necessary for clickable GMarkers
//TAKES: a GMap2
function initMarkerClick() {

	GEvent.addListener(map, "click", function(marker, point) {

		//if a marker exists at this point, open its info-window////////
		if (marker) {

			map.panTo(marker.getPoint());
			
  		}
		/////////////////////////////////////////////////////
	
	
		


	});

		

}



function archiveMapPosition() {
	
	var currentCenter = map.getCenter();
	var currentZoom   = map.getZoom();


	var url         = "http://www.gocast.org/PHP/MapStateInterface.php";
	var args        = "saveMapState=true;"
					  + "storedMapCenter=" 
					  + currentCenter
					  + ";"
					  + "storedMapZoom=" 
					  + currentZoom;
	args = args.replace(/;/gi,"&"); 
	var request_url = url + "?" + args;
	
	sendRequest(request_url);
	
}




//store the map state to the storedMapState variable, keeps the map view centered properly
function saveMapPosition() {

	storedMapState["center"] = map.getCenter();
	storedMapState["zoom"]   = map.getZoom();

}



    //]]>