var cpoint;
var map;
var iconsizes = new Array(5, 7, 9, 11, 13, 15, 17, 20)
var iconcenters = new Array(3, 4, 5, 6, 7, 8, 9, 10)
var icons = new Array();


window.onload=drawMap;

function drawMap ()
{
  cpoint = new GPoint (2.646418, 39.618251);
  for (i=0; i<8; i++) {
  	icons[i] = new GIcon ();
  	icons[i].iconSize = new GSize (iconsizes[i], iconsizes[i]);
  	icons[i].image = "http://mnm.uib.es/gallir/map/icons/circle-red-" + iconsizes[i] + ".png";
  	icons[i].iconAnchor = new GPoint (iconcenters[i], iconcenters[i]);
  	icons[i].infoWindowAnchor = new GPoint (5, 1);
  }

  // Center the map
  map = new GMap (document.getElementById ("map"));
  map.addControl (new GLargeMapControl ());
  map.addControl (new GMapTypeControl ());
  map.centerAndZoom (cpoint, 16);

  load ();
}


// Creates a marker whose info window displays the given number
function createMarker (point, ip, city, country)
{
  ip=parseInt(ip);
  var index= ip-1;
  if (index > 7) index=7;


  var marker = new GMarker (point, icons[index]);

  // Show this marker's index in the info window when it is clicked
  var msg = "<div style='width:200px;'><small><b>Number:</b> " + ip + "<br/>";
  msg = msg + "<b>City:</b> " + city + "<br/>";
  msg = msg + "<b>Country:</b> " + country;
  msg = msg + "</small></div>";

  GEvent.addListener (marker, "click", function ()
		      {
		      marker.openInfoWindowHtml (msg);
		      }
  );

  return marker;
}

function load ()
{
  // Download the data in map.xml and load it on the map.
  var request = GXmlHttp.create ();
  var time;
  request.open ("GET", "/gallir/map/xml.php?period=300", true);
  request.onreadystatechange = function ()
  {
    if (request.readyState == 4)
      {
	map.clearOverlays ();
	var xmlDoc = request.responseXML;
	var markers = xmlDoc.documentElement.getElementsByTagName ("marker");
	for (var i = 0; i < markers.length; i++)
	  {
	    var point =
	      new GPoint (parseFloat (markers[i].getAttribute ("lng")),
			  parseFloat (markers[i].getAttribute ("lat")));
	    var marker = createMarker (point, markers[i].getAttribute ("ip"),
				       markers[i].getAttribute ("city"),
				       markers[i].getAttribute ("country"));
	    map.addOverlay (marker);
	  }
          if((element = document.getElementById("clock"))) {
      	    time = dat_time();
      	    element.innerHTML=time;
          }
          window.setTimeout ("load()", 30000);
      }
  }
  request.send (null);
}

function dat_time() {
   var d = new Date();
   var hour = d.getHours();
   var min = d.getMinutes();
   var sec = d.getSeconds();
   if (hour < 10) hour = "0" + hour;
   if (min < 10) min = "0" + min;
   if (sec < 10) sec = "0" + sec;
   var t = hour + ":" + min + ":" + sec;
   return t;
}

