// JavaScript Document

 /* buddy tracker */
 var myAddressgeocoded = "";
  var geocoderPlace = null;
 function setMap(xmlString)
 {
	
    if (GBrowserIsCompatible()) {
      // this variable will collect the html which will eventualkly be placed in the side_bar
      var side_bar_html = "";
    
      // arrays to hold copies of the markers used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];

      // A function to create the marker and set up the event window
      function createMarker(point,userAddress,html) {
        var marker = new GMarker(point);

        
        GEvent.addListener(marker, "click", function() {
    	var html1=  html;
        marker.openInfoWindowTabsHtml([new GInfoWindowTab("Address",myAddressgeocoded), new GInfoWindowTab("Vital Info",html1)]);

        });
        // save the info we need to use later for the side_bar
        gmarkers.push(marker);
        // add a line to the side_bar html
        side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
        return marker;
      }


      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        GEvent.trigger(gmarkers[i], "click");
      }


      // create the map
      document.getElementById("displayMAPDiv").style.display="block";
      document.getElementById("displayMAP").style.display="block";
      var map = new GMap2(document.getElementById("displayMAP"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
 
      // Read the data from example.xml
        var xmlDoc = GXml.parse(xmlString);
        var markers = xmlDoc.documentElement.getElementsByTagName("marker");
      	
        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker
          var lat = parseFloat(markers[i].getAttribute("lat"));
          var lng = parseFloat(markers[i].getAttribute("lng"));
          var point = new GLatLng(lat,lng);
          var systolic = markers[i].getAttribute("systolic");
          var diastolic = markers[i].getAttribute("diastolic");
          var weight = markers[i].getAttribute("weight");
          var oxygen = markers[i].getAttribute("oxygen"); 
          var heartrate = markers[i].getAttribute("heartrate");
          var medicalDevice = markers[i].getAttribute("devicetype");
          var time = markers[i].getAttribute("time");
          var userAddress = "Address: "+ markers[i].getAttribute("address");
          
          geocoderPlace = new GClientGeocoder();
    	  showGeoCodeAddress(point);


          var html = "";
          
          if(medicalDevice != null && medicalDevice != 'undefined' && ((medicalDevice.toLowerCase().match('mytech') != null && medicalDevice.toLowerCase().match('mytech') != 'null') || (medicalDevice.toLowerCase().match('and') != null && medicalDevice.toLowerCase().match('and') != 'null')))
          	html = '<table border="0" class="cont" align="left"><tr><td> Heart Rate:' +  heartrate + "<br>Systolic (mmHg): " + systolic+ "<br>Diastolic (mmHg): " + diastolic+ "<br>Time: " + time + '</td></tr></table>';
          else if(medicalDevice != null && medicalDevice != 'undefined' && medicalDevice.toLowerCase().match('nonin') != null && medicalDevice.toLowerCase().match('nonin') != 'null')
          	html = '<table border="0" class="cont" align="left"><tr><td> Heart Rate:' +  heartrate + "<br>Blood Oxyzyn Level (Spo2 %): " + oxygen+ "<br>Time: " + time + '</td></tr></table>';
          else
          	html = '<table border="0" class="cont" align="left"><tr><td> Heart Rate:' +  heartrate + "<br>Blood Oxyzyn Level (Spo2 %): " + oxygen+ "<br>Systolic (mmHg): " + systolic+ "<br>Diastolic (mmHg): " + diastolic+ "<br>Time: " + time + '</td></tr></table>';
          
          var label = userAddress;
          // create the marker
          
          if(myAddressgeocoded != null && myAddressgeocoded != 'undefined' && myAddressgeocoded != "" )
              label = myAddressgeocoded;
                    
          var marker = createMarker(point,label,html);
          
          map.addOverlay(marker);
         // map.addOverlay(gSmallIcon); 
          map.setCenter(new GLatLng( lat,lng), 9);
        }
        // put the assembled side_bar_html contents into the side_bar div
        //document.getElementById("side_bar").innerHTML = side_bar_html; 
    }
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
    
    
  }
  
  function getUserInfo()
  {
  	document.getElementById("midlecontainer").innerHTML = '<a href="javascript:displayMap()" > MAP </a>';
  }
  
  function displayMap(id, type)
  {
  		var xmlString = "";
		var url = "";
		if (type == 'vital_signs')
			url='/hmsWebApp/secure/getMapXML?vitalId='+id+'&time='+new Date().getTime();
		else
			url='/hmsWebApp/secure/getMapXMLForAbnormalCondition?vitalId='+id+'&time='+new Date().getTime();
			
		//document.getElementById("midlecontainer").innerHTML = loader;
		new Ajax.Request(url,
		{
		method:'get', 
		onSuccess: function(transport)
		{
			var response = transport.responseText || "Internal error occurred while processing your request. Please try again later";
			//alert(response);
			if(response != 'FAIL'){
				xmlString = response;
				//alert(xmlString);
				setMap(xmlString);
			}else{	
				//document.getElementById('midlecontainer').innerHTML = 'The User does not having geo co-ordinates';
				alert ("Map cannot be displayed. No Geographic Co-ordinates found for this record."); 
			} 
		},
		onFailure: function()
		{
			//document.getElementById('midlecontainer').innerHTML = "Unable to load the page. Please try again later";
			alert ("Error loading the map. Please try again later.");
		}
		});
		
  	//var xmlString = '<markers><marker lat="43.65654" lng="-79.90138" bp="100" heartrate="80" oxygen="70" address="hyderabad" label="Marker One" /></markers>';
  	
  }
  
  function closeMapDiv()
  {
  	
      document.getElementById("displayMAP").style.display="none";
      document.getElementById("displayMAPDiv").style.display="none";
  }
  
  function showGeoCodeAddress(latlng) {
	var myHtml;
      if (latlng) {
        geocoderPlace.getLocations(latlng, function(addresses) {
          if(addresses.Status.code != 200) {
            alert("reverse geocoder failed to find an address for " + latlng.toUrlValue());
            myHtml = "reverse geocoder failed to find an address for " + latlng.toUrlValue();

          }
          else {
            address = addresses.Placemark[0];
            myHtml = address.address;
          }
          displayAddress123(myHtml);
        });
      }

}

function displayAddress123(myaddress)
{
	myAddressgeocoded = myaddress;
  }
