var xmlHttp


function GetXmlHttpObject()
{
	var xmlHttp=null;
	try
	{
		// Firefox, Opera 8.0+, Safari
		xmlHttp=new XMLHttpRequest();
	}
	catch (e)
	{
		// Internet Explorer
		try
		{
			xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch (e)
		{
			xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		}
	}
	return xmlHttp;
}
var working = false;
var statusBox;
function showRSS()
{
	statusBox = document.getElementById("status");
	//statusBox.innerHTML += "<p>showRSS()</p>";
	if(working == false) {
		working = true;
		//statusBox.innerHTML += "<p>updating</p>";
		xmlHttp=GetXmlHttpObject()
		if (xmlHttp==null)
		{
			alert ("Browser does not support HTTP Request")
			return
		}
		var url="getTrafficMsg.php"
	
		xmlHttp.onreadystatechange=stateChanged;
		xmlHttp.open("GET",url,true);
		xmlHttp.send(null);
	} else {
		//statusBox.innerHTML += "<p><b>already called</b></p>";	
	}
}

function stateChanged()
{
	if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
	{
		var trafficMsg = eval( "(" + xmlHttp.responseText + ")" );
		addTrafficMsg(trafficMsg);
	}
}

var itemList = new Array();
var markerList = new Array();

var outdate = 24*60*60*1000; //1 day in milliseconds
function addTrafficMsg(trafficMsg) {
	/*remove outdated items and find the latest pubDate we display already
	var now = new Date().getTime();
	for(var i=0;i<itemList.length();i++) {
		var item = itemList[i];
		if (item.pubDate < (now - outdate)) {
			//remove from map.. i.e. map to the markerList...		
		}
	}*/
	removeAllMarkers();
		
	var div = document.getElementById("rssOutput");
	
	for(var i=0; i<trafficMsg.items.length; i++) {
		var item = trafficMsg.items[i];
		
		var date = new Date();
		date.setTime(item.pubDate);
		item.pubDate = date;
        var point = new GLatLng(item.latitude, item.longitude);
		var marker = createMarker(point, item);
		map.addOverlay(marker);
		
		itemList.push(item);
	}
	//statusBox.innerHTML += "<p>finished</p>";
	working = false;
}

function createMarker(point, item) {
	var marker = new GMarker(point);
	markerList.push(marker);
	
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(
        	item.description + 
        	"<br/><small>Published: " + item.pubDate.toDateString() + " " + item.pubDate.toTimeString());
	});
	
	return marker;
}

function removeAllMarkers() {
	for(var i=0; i<markerList.length;i++) {
		map.removeOverlay(markerList[i]);
	}
}

var map;
function load() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    map.addControl(new GSmallMapControl());
	map.setMapType(G_HYBRID_MAP);
    var mapControl = new GMapTypeControl();
    map.addControl(mapControl);
	
    map.enableScrollWheelZoom();
    
    map.setCenter(new GLatLng(63.0, 8.0), 5);
    
    showRSS();
    setInterval("showRSS()", 60000);//update every minute
  }
}

