var map = "";
var baseIcon = new GIcon(G_DEFAULT_ICON);

 // A function to create the marker and set up the event window
      function createMarker(point,name,html, mIcon) {
      	
        var marker = new GMarker(point, {icon:mIcon, title:name});
        GEvent.addListener(marker, "click", function() {
          marker.openInfoWindowHtml(html);
        });
        // save the info we need to use later for the side_bar
        return marker;
      }

/****************************************************************
Name			: loadMap
Purpose		: Load the map if valid data is retrieved from the specified URL
Variables	:
1.	requestSettings
 		Datatype	: Array
 		Detail		: AJAX Request related variables
		1.	url
				Datatype 	: string
				Detail		: URL that returns the data to load the map. Devices, Start location, etc.
		2.	formName
				Datatype	: string
				Detail		: Name of the form. 
										Used to retrieve the form elements as POST variables for sending request to the URL
2.	loadingSettings
 		Datatype	: Array
 		Detail		: Map loading related parameters
		1. 	mapDiv
				Datatype	: Object
				Detail		:	Div tag where the map should be displayed
		2. 	sideBarDiv
				Datatype	: Object
				Detail		: Div tag to display Side Bar on the map
										Markers on the map can have their coressponding list in the side bar
3.	mapSettings
 		Datatype	: Array
 		Detail		: Buttons/tools that need to be displayed on the map
		1. 	overviewMap
				Datatype	: Boolean
				Detail		: TRUE - display overviewMap on the map
		2. 	mapLarge
				Datatype	: Boolean
				Detail		: TRUE - display Zoom feature on the map
		3. 	mapType
				Datatype	: Boolean
				Detail		: TRUE - display Map Type buttons on the map
		4. 	mapScale
				Datatype 	: Boolean
				Detail		: TRUE - display the Scale on the map
		5. 	zoomLevel
				Datatype	: integer
				Detail		: Zoom level for the map
4.	startSettings
 		Datatype	: Array
 		Detail		: Settings for Start Address on the map
		1. 	startLocation
				Datatype 	: Boolean
				Detail		: TRUE - if startLocation needs to be displayed with marker on the map
		2. 	showLocation
				Datatype 	: Boolean
				Detail		: TRUE - 
		3. 	centerAddress
				Datatype	: Boolean
				Detail		: TRUE - if the Start Location needs to be centered with a circle displaying the proximity
5.	markerSettings
		Datatype	: Array
		Detail		: Settings for markers	
		1. 	newMarker
				Datatype 	: Boolean
				Detail		: TRUE - if new marker should be allowed to be added by the user to the map
		2. 	dragMarker
				Datatype	: Boolean
				Detail		: TRUE - if the markers need to be set as draggable in the map
****************************************************************/
function loadMap
					(
						requestSettings, 
						loadingSettings, 
						mapSettings, 
						startSettings, 
						markerSettings,
						layerSettings,
						postFunction
					)
{

	// Set default values to parameters if not specified
	//  a = typeof(a) != 'undefined' ? a : 42;
	url = (requestSettings['url'] == null) ? false : requestSettings['url'];
	formName = (requestSettings['formName'] == null) ? false : requestSettings['formName'];

	mapDiv = (loadingSettings['mapDiv'] == null) ? false : loadingSettings['mapDiv'];

	// Check if url or mapDiv is empty
	if ( (!url) || (!mapDiv) ) {
		return false;
	}

	// Set POST variables as serialized if formName is specified
	post = "";
	if (formName) {
		post = $(formName).serialize();
	}
	
	// Set default variables for calling funtion setMap
	var popupSettings = new Array();
	popupSettings['addressDiv'] = false;
	popupSettings['showPopupDiv'] = false;
	
	// Make the AJAX request to retrieve data to load map
	new Ajax.Request 
			(
				url, 
				{
					method:'post',
					postBody:post,
					onComplete: function(response)
												{
													responseText = response.responseText;
													setMap
													(
														responseText, 
														loadingSettings, 
														popupSettings, 
														mapSettings, 
														startSettings, 
														markerSettings,
														layerSettings,
														postFunction
													); 
												}
				}
			);
}

/****************************************************************
Name			: setMap
Purpose		: Display the map along with the markers
Variables	:
1. 	responseJSONText
		Datatype 	: string
		Detail		: JSON containing the data to load the map. Devices, Start location, etc.
2.	loadingSettings
 		Datatype	: Array
 		Detail		: Map loading related parameters
		1. 	mapDiv
				Datatype	: Object
				Detail		:	Div tag where the map should be displayed
		2. 	sideBarDiv
				Datatype	: Object
				Detail		: Div tag to display Side Bar on the map
										Markers on the map can have their coressponding list in the side bar
3.	popupSettings
 		Datatype	: Array
 		Detail		: Popup map related parameters
		1. 	showPopupDiv
				Datatype 	: Boolean
				Detail		: TRUE - if popup map needs to be displayed
	 	2. 	addressDiv
				Datatype 	: object
				Detail		: div tag name where the address needs to be displayed. This is specifically for Popup Maps
4.	mapSettings
 		Datatype	: Array
 		Detail		: Buttons/tools that need to be displayed on the map
		1. 	overviewMap
				Datatype	: boolean
				Detail		: TRUE - display overviewMap on the map
		2. 	mapLarge
				Datatype	: boolean
				Detail		: TRUE - display Zoom feature on the map
		3. 	mapType
				Datatype	: boolean
				Detail		: TRUE - display Map Type buttons on the map
		4. 	mapScale
				Datatype 	: boolean
				Detail		: TRUE - display the Scale on the map
		5. 	zoomLevel
				Datatype	: integer
				Detail		: Zoom level for the map
5.	startSettings
 		Datatype	: Array
 		Detail		: Settings for Start Address on the map
		1. 	startLocation
				Datatype 	: Boolean
				Detail		: TRUE - if startLocation needs to be displayed with marker on the map
		2. 	showLocation
				Datatype 	: Boolean
				Detail		: TRUE - 
		3. 	centerAddress
				Datatype	: Boolean
				Detail		: TRUE - if the Start Location needs to be centered with a circle displaying the proximity
6.	markerSettings
		Datatype	: Array
		Detail		: Settings for markers	
		1. 	newMarker
				Datatype 	: Boolean
				Detail		: TRUE - if new marker should be allowed to be added by the user to the map
		2. 	dragMarker
				Datatype	: Boolean
				Detail		: TRUE - if the markers need to be set as draggable in the map
****************************************************************/
function setMap
					(
						responseJSONText, 
						loadingSettings, 
						popupSettings, 
						mapSettings, 
						startSettings, 
						markerSettings,
						layerSettings,
						postFunction
					) 
{

	// Set default values to parameters if not specified
	responseJSONText = (responseJSONText == null) ? false : responseJSONText;
	mapDiv = (loadingSettings['mapDiv'] == null) ? false : loadingSettings['mapDiv'];
	
	// This is commented since, sideBarDiv is loaded with separate AJAX call.
	//sideBarDiv = (loadingSettings['sideBarDiv'] == null) ? false : loadingSettings['sideBarDiv'];
	
	showPopupDiv = (popupSettings['showPopupDiv'] == null) ? false : popupSettings['showPopupDiv'];
	addressDiv = (popupSettings['addressDiv'] == null) ? false : popupSettings['addressDiv'];
	startLocation = (startSettings['startLocation'] == null) ? false : startSettings['startLocation'];
	showLocation = (startSettings['showLocation'] == null) ? false : startSettings['showLocation'];
	centerAddress = (startSettings['centerAddress'] == null) ? false : startSettings['centerAddress'];
	newMarker = (markerSettings['newMarker'] == null) ? false : markerSettings['newMarker'];
	dragMarker = (markerSettings['dragMarker'] == null) ? false : markerSettings['dragMarker'];
	resetMarker = (markerSettings['resetMarker'] == null) ? false : markerSettings['resetMarker'];
	toggleMarker = (markerSettings['toggleMarker'] == null) ? false : markerSettings['toggleMarker'];
	markerHtml = (markerSettings['markerHtml'] == null) ? true : markerSettings['markerHtml'];
	markerTooltip = (markerSettings['markerTooltip'] == null) ? true : markerSettings['markerTooltip'];
	showLayer = (layerSettings['showLayer'] == null) ? false : layerSettings['showLayer'];
	zoomLayer = (layerSettings['zoomLayer'] == null) ? false : layerSettings['zoomLayer'];
	hiliteMarkers = (layerSettings['hiliteMarkers'] == null) ? false : layerSettings['hiliteMarkers'];
	postFunctionName = (postFunction['name'] == null) ? false : postFunction['name'];
	postFunctionArgs = (postFunction['args'] == null) ? false : postFunction['args'];
	// Check if Response JSON or mapDiv is empty
	if ( (!responseJSONText) || (!mapDiv) ) {
		return false;
	}
	// set map to FALSE before loading the next map
	map = false;
	mapErrorText = "";
	// get the Response JSON text
	jsonText = responseJSONText;
	var recCount = 0;
	if (jsonText == "") {
		mapErrorText = mapErrorText + "Error retrieving devices \n";
		// set startLocation to FALSE
		startLocation = false;
	}
	else {
		// parse the Response JSON as JSON object
		jsonObj = jsonText.parseJSON();
		// check if map coordinates could be retrieved from location address if requested
		var getTheMap = (jsonObj.getMap == null) ? true : jsonObj.getMap;
		
		if (!getTheMap) {
			errorMap(loadingSettings, postFunctionName, postFunctionArgs)
			return false;
		}
	
		// get count of records in the Response JSON
		recCount = jsonObj.Device.count;
	}
	// if records are retrieved
	if (recCount > 0) {
		jsonRec = jsonObj.Device.record[0];
		if(jsonObj.proximity==''){
			lat = (parseFloat(jsonObj.Device.minLat)+parseFloat(jsonObj.Device.maxLat))/2;
			lon = (parseFloat(jsonObj.Device.minLon)+parseFloat(jsonObj.Device.maxLon))/2;;
		}
		else{
			lat = jsonObj.lat;
			lon = jsonObj.lon;
		}
		address = jsonRec.address;
		locationSettings = new Array();
		locationSettings['lat'] = lat;
		locationSettings['lon'] = lon;
		mapDiv.style.display = 'block';
		map = new GMap2(mapDiv);
		map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    map.setCenter(new GLatLng(lat,lon), 3);
		//var sideBarClass = 'trow2';
		
		var settempBound = '';
		var browserName=navigator.appName; 
		if(jsonObj.proximity==''){
			//bds = '((jsonObj.Device.minLat, jsonObj.Device.minLon), (jsonObj.Device.maxLat, jsonObj.Device.maxLon))';
			var bds = new GLatLngBounds(new GLatLng(jsonObj.Device.minLat, jsonObj.Device.minLon), new GLatLng(jsonObj.Device.maxLat, jsonObj.Device.maxLon));
			//if(bds=='')// && browserName!="Microsoft Internet Explorer")
				//window.location.reload();
			/*else if(bds=='' && browserName=="Microsoft Internet Explorer"){
				bds = '((jsonObj.Device.minLat, jsonObj.Device.minLon), (jsonObj.Device.maxLat, jsonObj.Device.maxLon))';
				var settempBound = 3;
			}*/
			if(map.getBoundsZoomLevel(bds)!=0) settempBound = map.getBoundsZoomLevel(bds);
			//if(settempBound=='') // && browserName!="Microsoft Internet Explorer")
				//window.location.reload();
			/*else if(settempBound=='' && browserName=="Microsoft Internet Explorer")
				settempBound = 4;
			*/
			map.setZoom(settempBound);
		}
		else if(jsonObj.proximity==5){
			map.setZoom(12);
		}
		else if(jsonObj.proximity==10){
			map.setZoom(11);
		}
		else if(jsonObj.proximity==20){
			map.setZoom(10);
		}
		else if(jsonObj.proximity==30){
			map.setZoom(9);
		}
		else if(jsonObj.proximity==100){
			map.setZoom(8);
		}
		else if(jsonObj.proximity==500){
			map.setZoom(7);
		}
		else if(jsonObj.proximity==1000){
			map.setZoom(6);
		}
		// Add markers for devices
		for (var ctr=0; ctr<recCount; ctr=ctr+1) {
			jsonRec = jsonObj.Device.record[ctr];
			address = (jsonRec.address == null) ? '' : ( jsonRec.address );
			numPorts = (jsonRec.numPorts == null) ? '' : ( jsonRec.numPorts );
			port1Status = (jsonRec.port1 == null) ? jsonRec.statusName : ( jsonRec.port1 );
			port2Status = (jsonRec.port2 == null) ? '' : ( jsonRec.port2 );
            description = (jsonRec.description == null) ? '' : ( jsonRec.description );
            port1description = (jsonRec.port1description == null) ? '' : (jsonRec.port1description);
            port2description = (jsonRec.port2description == null) ? '' : (jsonRec.port2description);
            action = (jsonRec.submitButton == null) ? '' : (jsonRec.submitButton) + '<br/>';
            lastKnown = (jsonRec.lastKnown == null) ? '' : (jsonRec.lastKnown);
            lastKnownDate = (jsonRec.lastKnownDate == null) ? '' : (jsonRec.lastKnownDate);
            
// ANKIT - Just added for Mockup....			
            markerHtml = "<div><div class='mapInfoWindow'><b> "+_("Name")+": </b>"+ jsonRec.deviceName + "<br/> <b> "+_("Address")+": </b>"+ address + "<br/>";
			markerHtml += (description !=''? "<b> "+_("Description")+": </b>" + description +" <br />" : '');
			
            if(lastKnown != '' && lastKnownDate != '')
            {
                markerHtml += "<strong>" + lastKnown + ":</strong> " + lastKnownDate + "<br/>";
            }
            
            if (numPorts == 2) 
            {
                markerHtml += "<b>Port 1:</b> " + port1description;
                if(port1Status != '')
                    markerHtml += ":<strong><i>" + port1Status + "</i></strong>";
                markerHtml += "<br/>";
                
                markerHtml += "<b>Port 2:</b> " + port2description;
                if(port2Status != '')
                    markerHtml += ":<strong><i>" + port2Status + "</i></strong>";
                markerHtml += "<br/>";
            }
            else if (port2Status != '') 
            {
                markerHtml += "<b>Port 2:</b>" + port2description;
                if(port2Status != '')
                    markerHtml += ":<strong><i>" + port2Status + "</i></strong>";
                markerHtml += "<br/>";
            }
            else 
            {
                markerHtml += "<b>Port 1:</b> " + port1description;
                if(port1Status != '')
                    markerHtml += ":<strong><i>" + port1Status + "</i></strong>";
                markerHtml += "<br/>";
            }
            markerHtml += action;
            markerHtml += "</div>";
///////////////////////////////////////////////
            
            imageName = jsonRec.imageName;
			//typeImage = iconDir + imageName;
			var markerIcon = new GIcon(G_DEFAULT_ICON);
			// set icon image if provided
			
			var typeImage = false;
			if (imageName) {
				typeImage = iconDir + imageName;
				markerIcon.image = typeImage;
				markerIcon.iconSize = new GSize(30,30);
				markerIcon.iconAnchor = new GPoint(10,20);
				markerIcon.shadowSize = new GSize(0,0); //new GSize(50,30);
			}
 
			markerOptions = {icon:markerIcon};
			
			lat = jsonRec.lat;
			lon = jsonRec.lon;
			point = new GLatLng(lat,lon);
      marker = createMarker(point,address,markerHtml, markerIcon);
      map.addOverlay(marker);
      my_markers['device'+jsonRec.deviceID] = marker;
		}
		
		if(jsonObj.location!='')
		{
			centerMap(jsonObj.lat, jsonObj.lon, jsonObj.proximity);	
		}
		
	} // end if - if there is atleast one device
	
	else
	{
		if(jsonObj.proximity==''){
			lat = (parseFloat(jsonObj.Device.minLat)+parseFloat(jsonObj.Device.maxLat))/2;
			lon = (parseFloat(jsonObj.Device.minLon)+parseFloat(jsonObj.Device.maxLon))/2;;
		}
		else{
			lat = jsonObj.lat;
			lon = jsonObj.lon;
		}
		
		locationSettings = new Array();
		locationSettings['lat'] = lat;
		locationSettings['lon'] = lon;
		mapDiv.style.display = 'block';
		map = new GMap2(mapDiv);
		map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(lat,lon), 3);
		//var sideBarClass = 'trow2';
		
		var settempBound = '';
		var browserName=navigator.appName; 
		if(jsonObj.proximity==''){
			//bds = '((jsonObj.Device.minLat, jsonObj.Device.minLon), (jsonObj.Device.maxLat, jsonObj.Device.maxLon))';
			var bds = new GLatLngBounds(new GLatLng(jsonObj.Device.minLat, jsonObj.Device.minLon), new GLatLng(jsonObj.Device.maxLat, jsonObj.Device.maxLon));
			//if(bds=='')// && browserName!="Microsoft Internet Explorer")
				//window.location.reload();
			/*else if(bds=='' && browserName=="Microsoft Internet Explorer"){
				bds = '((jsonObj.Device.minLat, jsonObj.Device.minLon), (jsonObj.Device.maxLat, jsonObj.Device.maxLon))';
				var settempBound = 3;
			}*/
			if(map.getBoundsZoomLevel(bds)!=0) settempBound = map.getBoundsZoomLevel(bds);
			//if(settempBound=='') // && browserName!="Microsoft Internet Explorer")
				//window.location.reload();
			/*else if(settempBound=='' && browserName=="Microsoft Internet Explorer")
				settempBound = 4;
			*/
			map.setZoom(settempBound);
		}
		else if(jsonObj.proximity==5){
			map.setZoom(12);
		}
		else if(jsonObj.proximity==10){
			map.setZoom(11);
		}
		else if(jsonObj.proximity==20){
			map.setZoom(10);
		}
		else if(jsonObj.proximity==30){
			map.setZoom(9);
		}
		else if(jsonObj.proximity==100){
			map.setZoom(8);
		}
		else if(jsonObj.proximity==500){
			map.setZoom(7);
		}
		else if(jsonObj.proximity==1000){
			map.setZoom(6);
		}
	}
	//alert(jsonObj.proximity);
	// call the postfunction
	if (postFunctionName) {
		if (postFunctionArgs)
			eval(postFunctionName)(postFunctionArgs);
		else
			eval(postFunctionName)();
	}
	
	
	
}

function click_sidebar(idx) {
	GEvent.trigger(my_markers[idx], 'click');
}

function centerMap(centerLat, centerLon, proximity)
{
	minLat = maxLat = centerLat = parseFloat(centerLat);
	minLon = maxLon = centerLon = parseFloat(centerLon);
	proximity = parseFloat(proximity);

	var d2r = Math.PI / 180;   // degrees to radians
	var r2d = 180 / Math.PI;   // radians to degrees
	var earthsradius = 3963; // 3963 is the radius of the earth in miles

	var points = 80;

	// find the raidus in lat/lon
	var rlat = (proximity / earthsradius) * r2d;
	var rlng = rlat / Math.cos(centerLat * d2r);
	
	var extp = new Array();
	for (var i=0; i < points+1; i++) // one extra here makes sure we connect the
	{
		var theta = Math.PI * (i / (points/2));
		ex = centerLon + (rlng * Math.cos(theta)); // center a + radius x * cos(theta)
		ey = centerLat + (rlat * Math.sin(theta)); // center b + radius y * sin(theta)
		extp.push(new GPoint(ex, ey));

		if (ey < minLat)
			minLat = ey;
		if (ey > maxLat)
			maxLat = ey;
		
		if (ex < minLon)
			minLon = ex;
		if (ex > maxLon)
			maxLon = ex;

	}
	
	map.addOverlay(new GPolyline(extp, "#000000", 2));

	// Set Center
	map.setCenter(new GLatLng(centerLat, centerLon), 13);

	// Set Zoom level so that all markers are visible
  var bds = new GLatLngBounds(new GLatLng(minLat, minLon), new GLatLng(maxLat, maxLon));
  map.setZoom(map.getBoundsZoomLevel(bds));
}