// JavaScript Document
	var highlightCircle;
    var currentMarker;
    var map;
	var latTxtBox;
	var lonTxtBox;
	var speedTxtBox;
	var altitudeTxtBox;
	var heartbeatTxtBox;
	var puckStatusTxtBox;
	var currentMarkerOnMap=false;
	var lastLat;
	var lastLong;
	var lastMsgAgo;
	var isNewMessage=false;
	var lastTimeStamp=0;
	
	function highlightCurrentMarker(){
      var markerPoint = currentMarker.getPoint();

      var polyPoints = Array();

      if (highlightCircle) {
        map.removeOverlay(highlightCircle);
      }

      var mapNormalProj = G_NORMAL_MAP.getProjection();
      var mapZoom = map.getZoom();
      var clickedPixel = mapNormalProj.fromLatLngToPixel(markerPoint, mapZoom);

      var polySmallRadius = 20;

      var polyNumSides = 20;
      var polySideLength = 18;

      for (var a = 0; a<(polyNumSides+1); a++) {
	    var aRad = polySideLength*a*(Math.PI/180);
	    var polyRadius = polySmallRadius; 
       	    var pixelX = clickedPixel.x + polyRadius * Math.cos(aRad);
	    var pixelY = clickedPixel.y + polyRadius * Math.sin(aRad);
	    var polyPixel = new GPoint(pixelX,pixelY);
	    var polyPoint = mapNormalProj.fromPixelToLatLng(polyPixel,mapZoom);
	    polyPoints.push(polyPoint);
      }
      // Using GPolygon(points,  strokeColor?,  strokeWeight?,  strokeOpacity?,  fillColor?,  fillOpacity?)
     // highlightCircle = new GPolygon(polyPoints,"#000000",2,0.0,"#FF0000",.4);
      highlightCircle = new GPolygon(polyPoints,"#000000",2,0.0,"#000000",.4);
	  map.addOverlay(highlightCircle);
   }
	
    function initialize() {
	  roundCorners();
	  currentMarkerOnMap=false;
	  latTxtBox = document.getElementById("latTxt");
	  lonTxtBox = document.getElementById("lonTxt");
	  speedTxtBox = document.getElementById("speedTxt");
	  altitudeTxtBox = document.getElementById("altitudeTxt");
	  heartbeatTxtBox = document.getElementById("heartbeatTxt");
	  puckStatusTxtBox = document.getElementById("puckstatusTxt");
     
	  if (GBrowserIsCompatible()) {
	     
        map = new GMap2(document.getElementById("map_canvas"));
		map.addControl(new GSmallMapControl());
		map.addControl(new GOverviewMapControl());
		map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(37.4419, -122.1419), 13);
	    GEvent.addListener(map, "zoomend", function() {
			highlightCurrentMarker();	
        });
			
	    showPanels();
        window.setTimeout(function() {
            getLatestLocation();
			
        }, 1000);     
	  }
    }
    
    function createMarker(point, number) {
	
	      var tinyIcon = new GIcon(G_DEFAULT_ICON);
		  tinyIcon.image = "http://labs.harahap.org/gps/images/gps_marker_x.png"

	      var markerOptions = { 
		  icon:tinyIcon,
		  title: number,
		  bouncy: true
		  };
          var marker = new GMarker(point, markerOptions);
	  
			// This line highlights the marker when it's clicked
				GEvent.addListener(marker, "click", function() {
				currentMarker = marker;
				highlightCurrentMarker();	
				});

			// This line highlights the marker when its moused over
				GEvent.addListener(marker, "mouseover", function() {
				currentMarker = marker;
				highlightCurrentMarker();	
				});

          return marker;
    }
	
	function getLatestLocation(){
	    isNewMessage=false;
	    if (highlightCircle) {
            map.removeOverlay(highlightCircle);
        }
		var currentTime = new Date()
		var id = currentTime.getTime();
	    IAjaxRequest("http://labs.harahap.org/gps/api/getLocation.php?id="+id, function(jsonText, responseXML) {
		    var loc = eval("(" + jsonText + ")");
			var timestamp = loc.timestamp;
			var currLat = loc.lat;
			var currLon = loc.lon;
			var currSpeed=loc.speed;
			var currAltitude=loc.altitude;
			var heartbeat = loc.heartbeat;
			var message = loc.message;
			var messageAgo = loc.messageTimestamp;
		    heartbeatTxtBox.value= heartbeat;
			var puckStatus = loc.puckStatus;
		    var locationStamp=loc.locationTimestamp;
			
			isNewMessage=loc.isNewMessage;
			setPuckStatusTxt(puckStatus);

			if (messageAgo == timestamp){
				   isNewMessage=true;
			}

            if (lastTimeStamp !=timestamp){			
				lastLat=currLat;
				lastLong=currLon;
				
				if (currentMarkerOnMap) {
					map.removeOverlay(currentMarker);
				    currentMarkerOnMap=false;
				}
                
				var point = new GLatLng(currLat, currLon);
			    currentMarker = createMarker(point,locationStamp);
				map.addOverlay(currentMarker);
				
				if ((!currentMarkerOnMap)) { // && (isNewMessage)){
						window.setTimeout(function() {
					     currentMarker.openInfoWindowHtml(getInfoWindowHTML(message,messageAgo,isNewMessage),{maxWidth:180});				
					}, 500);     	
				}
				
			    currentMarkerOnMap = true;
  			    GEvent.addListener(currentMarker, "click", function() {
				     currentMarker.openInfoWindowHtml(getInfoWindowHTML(message,messageAgo,isNewMessage),{maxWidth:180});	
				});
			    map.panTo(point);
				latTxtBox.value = currLat;
	            lonTxtBox.value = currLon;
				speedTxtBox.value=currSpeed + " m/s";
				altitudeTxtBox.value=currAltitude + " m";
		    }	
				
				lastTimeStamp = timestamp;
	
        
               
			 highlightCurrentMarker();
		
			window.setTimeout(function() {
                getLatestLocation();
            }, 15000);     			
		  });
	}
	
	function roundCorners(){
		settings = {
          tl: { radius: 20 },
          tr: { radius: 20 },
          bl: { radius: 20 },
          br: { radius: 20 },
          antiAlias: true,
          autoPad: true,
          validTags: ["div"]
		}
      var myBoxObject = new curvyCorners(settings, "myBox");
      myBoxObject.applyCornersToAll();
	}
	
	function setPuckStatusTxt(stat){
	   switch (stat){
		case "OFF": 
			puckStatusTxtBox.className="puckInputOFF";
			break;
		case "ON": 
			puckStatusTxtBox.className="puckInputON";
			break;
	    default : 
		    puckStatusTxtBox.className="puckInput";
       }
	   puckStatusTxtBox.value = stat;
	}
	
	function showPanels(){
	  var status1= document.getElementById("status1");
	  var status2= document.getElementById("status2");
	  var avatar= document.getElementById("avatar");
	  
	  status1.style.visibility="visible";
	  status2.style.visibility="visible";
	  avatar.style.visibility="visible";
	}
	
	function getInfoWindowHTML(msg, timeTxt,isOnLoc){
	  var htmlString = '<div class="infoWindowDiv"><div align="left"><span class="sayClass">&quot;'
	  htmlString = htmlString + msg + '&quot;</span></div>'
	  htmlString = htmlString + '<div align="left"><span class="agoClass" align="left">'
	  htmlString = htmlString + timeTxt; 
	  if(!isOnLoc){	 
	        htmlString = htmlString + ' from an earlier location';
	  }
        htmlString = htmlString + '</span></div>';
	  return htmlString;
	}
