var icons_url = "icons";
//var icons_url = "http://mnm.uib.es/gallir/map/icons";
var xml_file = "xml.php?period=300";
var refresh = 30; // In seconds

var my_site = new GPoint (2.646418, 39.618251);
var cpoint = new GPoint (2.646418, 39.618251);

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 ()
{
  my_site = new GPoint (2.646418, 39.618251);
  for (i=1; i<9; i++) {
        icons[i] = new GIcon ();
        icons[i].iconSize = new GSize (iconsizes[i], iconsizes[i]);
        icons[i].image = icons_url + "/circle-orange-" + 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, 15);


  load ();
}

function cz (p, z)
{
  map.centerAndZoom (p, z);
}

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

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

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

  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", xml_file, 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()", refresh*1000);
      }
  }
  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;
}

