var hover = false;

var Loop = {  
  executor: null,  
 
  start: function(userid,sid)  { 
    var id = 4387;
    var numtickeritems = 422;
    var mintickerid = id;
    var idHash = Object;
    var hashlength = 0;
//    var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(40.813628,-96.702620), 4);
    this.executor = new PeriodicalExecuter(
      function(pe)  {
        var params = 'id=' + id + '&userid=' + userid + '&sid=' + sid;
        var url = '/Espresso/cgi-bin/getCoords.pl';
        new Ajax.Request(
          url,
          {
            method: 'post',
            parameters: params,
            asynchronous:true,
            evalScripts:true,
            onComplete: function(response) {
              if(response.status == 202) {
                var result = response.responseText;
                var splitresult = result.split(";");
                var lat = splitresult[0];
                var long = splitresult[1];
                var headline = splitresult[2];
                id = parseInt(splitresult[3]);
                var maxtickerid = parseInt(splitresult[4]);

                map.panTo(new GLatLng(lat, long), 4);
                map.openInfoWindowHtml(new GLatLng(lat, long), headline, {maxWidth:400, noCloseOnClick:true});
                initMap_hovering(pe);

                id = getRandom(mintickerid,maxtickerid);

                while (idHash[id] == 'true')   {
                   id = getRandom(mintickerid,maxtickerid);
                }
                idHash[id] = 'true';
                hashlength++;
                if (hashlength >= numtickeritems)  {
                  for (var i in idHash)  {
                     idHash[i] = 'false'; 
                  }
                  hashlength = 0;
                }
              }
            }
          }
        );
      },
      7
    )
  },
  cancel: function() {
    if (Loop.executor != null)  {
      Loop.executor.stop();
    }
  }
};

function initMap_hovering(pe)  {
  $('map_popup').observe('mouseover', function(event) {
     hover = true;
     pe.currentlyExecuting = true;
  }.bind(this));
  $('map_popup').observe('mouseout', function(event) {
     hover = false;
     pe.currentlyExecuting = false;
  }.bind(this));
};

function getRandom(min, max)
{		
	var randomNum = Math.random() * (max-min); 

// Round to the closest integer and return it
	return(Math.round(randomNum) + min); 
};
