//======================
  var nowSec = 0;
    var diffSecServer = 0;
    if (nowSec) {
      diffSecServer = nowSec - getServerDate();
    }
    else  {
      nowSec = getServerDate();
    }
 
 var map;
 var iconTrain;
 var opt = {};
 var trainsCnt = 0;
 var trainsTTCnt = 0;

 
      // arrays to hold copies of the markers and html used by the side_bar
      // because the function closure trick doesnt work there
      var side_bar_html = "";
      var gmarkers = [];
      var htmls = [];

	function isTravellingNow(val)
	{
		var retVal = false;

		for ( t = 0; t < trainsCnt; t++ )
		{
			obj = document.getElementById('t'+t).innerHTML;
			if (val == obj)
			{
				retVal = true;
				break;
			}
		}
		
		return retVal;
	}

	function markTrainsInTT()
	{
		var obj;

		for (i = 0; i < trainsTTCnt; i++)
		{
				
			if(	isTravellingNow(document.getElementById('tt'+i).innerHTML) )
			{
				document.getElementById('tt'+i).style.fontWeight = "bold"; 
				document.getElementById('tt'+i).style.background = "yellow";
			}
			else
			{
				document.getElementById('tt'+i).style.fontWeight = 'normal'; 
				document.getElementById('tt'+i).style.background = "";
			}
		}

	}

	// A function to create the marker and set up the event window
	function createMarker(point,name,html) {
		var marker = new GMarker(point, opt);
				
		GEvent.addListener(marker, 'click', function() {
			marker.openInfoWindowHtml(html);
		});

		GEvent.addListener(marker, 'mouseover', function() {
			marker.openInfoWindowHtml(html);
		});

		GEvent.addListener(marker, 'mouseout', function() {
			map.closeInfoWindow();
		});

		// save the info we need to use later for the side_bar
//		gmarkers[i] = marker;
//		htmls[i] = html;

		//        // add a line to the side_bar html
		//        side_bar_html += '<a href="javascript:myclick(' + i + ')">' + name + '</a><br>';
//		i++;


		return marker;
	}

function processPolyline()
{
      var request = GXmlHttp.create();
      request.open("GET", "line.xml", true);
      request.onreadystatechange = function() {
        if (request.readyState == 4) {

          var xmlDoc = GXml.parse(request.responseText);
          // obtain the array of markers and loop through it
          var markers = xmlDoc.documentElement.getElementsByTagName("marker");
          
          for (var i = 0; i < markers.length; i++) {
            // obtain the attribues of each marker
            var lat = parseFloat(markers[i].getAttribute("lat"));
            var lng = parseFloat(markers[i].getAttribute("lng"));
            var point = new GLatLng(lat,lng);
            var html = markers[i].getAttribute("html");
            var label = markers[i].getAttribute("label");
            // create the marker
            var marker = createMarker(point,label,html);
            map.addOverlay(marker);
          }
  
          // put the assembled side_bar_html contents into the side_bar div
//          document.getElementById("side_bar").innerHTML = side_bar_html;
          
         
          // ========= Now process the polylines ===========
          var lines = xmlDoc.documentElement.getElementsByTagName("line");
          // read each line
          for (var a = 0; a < lines.length; a++) {
            // get any line attributes
            var colour = lines[a].getAttribute("colour");
            var width  = parseFloat(lines[a].getAttribute("width"));
            // read each point on that line
            var points = lines[a].getElementsByTagName("point");
            var pts = [];
            for (var i = 0; i < points.length; i++) {
               pts[i] = new GLatLng(parseFloat(points[i].getAttribute("lat")),
                                   parseFloat(points[i].getAttribute("lng")));
            }
            map.addOverlay(new GPolyline(pts,colour,width));
          }
          // ================================================           
        }
      }

      request.send(null);

}

      // This function picks up the click and opens the corresponding info window
      function myclick(i) {
        gmarkers[i].openInfoWindowHtml(htmls[i]);
      }
 
 function init()
 {

	var zoomfactor = 12;
	
    if (GBrowserIsCompatible()) { 

      // Display the map, with some controls and set the initial location 
      map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(44.10592,9.72882), zoomfactor);
    
		iconTrain = new GIcon();
        iconTrain.image = 'http://www.code4dotnet.com/train.png';
        iconTrain.iconSize = new GSize(38, 17);
        iconTrain.iconAnchor = new GPoint(19, 8);
        iconTrain.infoWindowAnchor = new GPoint(19,8);

		opt.icon = iconTrain;  
		opt.draggable = false;  
		opt.clickable = true;
   
      var i = 0;



      // Read the data from example4.xml
      processPolyline();

    }
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

}

/*
 function init_earth()
 {

	var zoomfactor = 12;
	
    if (GBrowserIsCompatible()) { 

      // Display the map, with some controls and set the initial location 
      map = new GMap2(document.getElementById("map"));
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(44.10592,9.72882), zoomfactor);
      map.addMaptype(G_SATELLITE_3D_MAP);
    
		iconTrain = new GIcon();
        iconTrain.image = 'http://www.code4dotnet.com/train.png';
        iconTrain.iconSize = new GSize(38, 17);
        iconTrain.iconAnchor = new GPoint(19, 8);
        iconTrain.infoWindowAnchor = new GPoint(19,8);

		opt.icon = iconTrain;  
		opt.draggable = false;  
		opt.clickable = true;
   
      var i = 0;



      // Read the data from example4.xml
      processPolyline();

    }

    
    // display a warning if the browser was not compatible
    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }

}
*/

//=============================

//----------------------------

    var xmlHttp;
	// remote
    var requestURL = 'webtrain.aspx?';
    var requestTimeTableURL = 'webtraintt.aspx?';
    
    
    
    var is_ie = (navigator.userAgent.indexOf('MSIE') >= 0) ? 1 : 0;
    var is_ie5 = (navigator.appVersion.indexOf("MSIE 5.5")!=-1) ? 1 : 0;
    var is_opera = ((navigator.userAgent.indexOf("Opera6")!=-1)||(navigator.userAgent.indexOf("Opera/6")!=-1)) ? 1 : 0;
    //netscape, safari, mozilla behave the same???
    var is_netscape = (navigator.userAgent.indexOf('Netscape') >= 0) ? 1 : 0;

    function show_data(){

			var nowDate = new Date();
			var nowDateSec = nowDate.getHours()*3600 + nowDate.getMinutes()*60 + nowDate.getSeconds()*1;


            //Append the name to search for to the requestURL
            var url = requestURL + strName;
            
            //Create the xmlHttp object to use in the request
            //stateChangeHandler will fire when the state has changed, i.e. data is received back
            // This is non-blocking (asynchronous)
            xmlHttp = GetXmlHttpObject(stateChangeHandler);
            
            //Send the xmlHttp get to the specified url
            xmlHttp_Get(xmlHttp, url);
    }

/******
    function stateChangeHandlerDateList()
    {
        //readyState of 4 or 'complete' represents that data has been returned
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
            //Gather the results from the callback
            var str = xmlHttp.responseText;



            //Populate the innerHTML of the div with the results
            document.getElementById('datecontent').innerHTML = "<pre>" + str + "</pre>";
			loadFP();
        }
    }
**********/

    function stateChangeHandlerTimetable()
    {
        //readyState of 4 or 'complete' represents that data has been returned
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
            //Gather the results from the callback
            var str = xmlHttp.responseText;

//alert(str);

			var xmlDoc = GXml.parse(str);
			var lbl_start_station = "";
			var lbl_end_station = "";
			
			var html = "";
			var bodytable = "";

			trainsTTCnt = 0;

			var markers = xmlDoc.documentElement.getElementsByTagName("train_a");
			for (var i = 0; i < markers.length; i++) 
			{
			
				var train_type = markers[i].getElementsByTagName("train_type")[0].firstChild.nodeValue;
				var train_number = markers[i].getElementsByTagName("train_number")[0].firstChild.nodeValue;
				
				var start_station = markers[i].getElementsByTagName("start_station")[0].firstChild.nodeValue;
				if (lbl_start_station.length == 0)
					lbl_start_station = start_station;
					
				var start_time = markers[i].getElementsByTagName("start_time")[0].firstChild.nodeValue;
				
				var end_station = markers[i].getElementsByTagName("end_station")[0].firstChild.nodeValue;
				if (lbl_end_station.length == 0)
					lbl_end_station = end_station;
				
				var end_time = markers[i].getElementsByTagName("end_time")[0].firstChild.nodeValue;
			
				bodytable += "<tr class='" + ((i%2)==0?"evenrow":"oddrow") + "'>";
				bodytable += "<td><label id=\"tt" + trainsTTCnt + "\">" + train_type + " " + train_number + "</label></td>";
				bodytable += "<td>" + start_time + "</td>";
				bodytable += "<td>" + end_time + "</td>";
				bodytable += "</tr>";

				trainsTTCnt++;

			}
						
			html += "<table width='100%'>";
			html += "<tr>";
			html += "<td colspan='3'>Today Timetable<br/>travelling trains now are marked in yellow</td>";
			html += "</tr>";
			html += "<tr>";
			html += "<th width='33%'>Train</th>";
			html += "<th width='33%'>" + lbl_start_station + "</th>";
			html += "<th>" + lbl_end_station + "</th>";
			html += "</tr>";
			html += bodytable;

			bodytable = "";
			lbl_start_station = "";
			lbl_end_station = "";

			markers = xmlDoc.documentElement.getElementsByTagName("train_r");
			for (var i = 0; i < markers.length; i++) 
			{
			
				var train_type = markers[i].getElementsByTagName("train_type")[0].firstChild.nodeValue;
				var train_number = markers[i].getElementsByTagName("train_number")[0].firstChild.nodeValue;
				
				var start_station = markers[i].getElementsByTagName("start_station")[0].firstChild.nodeValue;
				if (lbl_start_station.length == 0)
					lbl_start_station = start_station;
					
				var start_time = markers[i].getElementsByTagName("start_time")[0].firstChild.nodeValue;
				
				var end_station = markers[i].getElementsByTagName("end_station")[0].firstChild.nodeValue;
				if (lbl_end_station.length == 0)
					lbl_end_station = end_station;
				
				var end_time = markers[i].getElementsByTagName("end_time")[0].firstChild.nodeValue;
			
				bodytable += "<tr class='" + ((i%2)==0?"evenrow":"oddrow") + "'>";
				bodytable += "<td><label id=\"tt" + trainsTTCnt + "\">" + train_type + " " + train_number + "</label></td>";
				bodytable += "<td>" + start_time + "</td>";
				bodytable += "<td>" + end_time + "</td>";
				bodytable += "</tr>";

				trainsTTCnt++;

			}
			html += "<tr>";
			html += "<td colspan='3'>&nbsp;</th>";
			html += "</tr>";

			html += "<tr>";
			html += "<th>Train</th>";
			html += "<th>" + lbl_start_station + "</th>";
			html += "<th>" + lbl_end_station + "</th>";
			html += "</tr>";
			html += bodytable;
			html += "</table>";
						
			document.getElementById('timetable').innerHTML = html;
			
			markTrainsInTT();
		}
	}	

    //stateChangeHandler will fire when the state has changed, i.e. data is received back
    // This is non-blocking (asynchronous)
    function stateChangeHandler()
    {
        //readyState of 4 or 'complete' represents that data has been returned
        if (xmlHttp.readyState == 4 || xmlHttp.readyState == 'complete'){
            //Gather the results from the callback
            var str = xmlHttp.responseText;

//alert(str);

			var xmlDoc = GXml.parse(str);
			// obtain the array of markers and loop through it
			var markers = xmlDoc.documentElement.getElementsByTagName("train");

			var maincont = "";
			
			for (var t = 0; t < trainsCnt; t++)
			{
				map.removeOverlay(gmarkers[t]);
				htmls[t] = "";
			}
			trainsCnt = 0;
			
			for (var i = 0; i < markers.length; i++) 
			{
				// obtain the attribues of each marker
				var lat = parseFloat(markers[i].getElementsByTagName("lat")[0].firstChild.nodeValue);
				var lng = parseFloat(markers[i].getElementsByTagName("lng")[0].firstChild.nodeValue);
	            
				var point = new GLatLng(lat,lng);
				var train_type = markers[i].getElementsByTagName("train_type")[0].firstChild.nodeValue;
				var train_number = markers[i].getElementsByTagName("train_number")[0].firstChild.nodeValue;
				var start_station = markers[i].getElementsByTagName("start_station")[0].firstChild.nodeValue;
				var end_station = markers[i].getElementsByTagName("end_station")[0].firstChild.nodeValue;
				var nextstation = markers[i].getElementsByTagName("nextstation")[0].firstChild.nodeValue;
				var station = markers[i].getElementsByTagName("station")[0].firstChild.nodeValue;
				var estimated_time = markers[i].getElementsByTagName("estimated_time")[0].firstChild.nodeValue;
				var real_time = markers[i].getElementsByTagName("real_time")[0].firstChild.nodeValue;
				
				var late_time = markers[i].getElementsByTagName("late_time")[0].firstChild.nodeValue;
				var last_station = markers[i].getElementsByTagName("last_station")[0].firstChild.nodeValue;
				
				var next_estimatedtime = markers[i].getElementsByTagName("next_estimatedtime")[0].firstChild.nodeValue;
				
				var html = "";
				
//				html = "<table width=\"100%\">";
				html += "<tr><td class=\"head_train\">";
				html += "<a href=\"javascript:myclick(" + i + ")\">";
				html += "Train: <b><label id=\"t" + trainsCnt + "\">" + train_type + " " + train_number + "</label></b><br/>";
				html += "</a>";
				html += "</td></tr>";

				html += "<tr><td>";
				//html += " from " + start_station + " to " + end_station + "<br/><br/>";
				html += " direction " + end_station; // + "<br/><br/>";
				html += "</td></tr>";

//				html += "station: <b>" + station + "</b><br/>";
//				html += "estimated arrival: " + estimated_time + "<br/>";
//				html += "actual arrival: " + real_time + "<br/><br/>";
//				html += "next station: <b>" + nextstation + "</b><br/>";
//				html += "estimated arrival: " + next_estimatedtime + "<br/>";
	            
//				html += "last station: " + last_station + "<br/>";

				html += "<tr><td>";
				html += "Last station: " + last_station; // + "<br/>";
				html += "</td></tr>";

	            if (late_time.length > 0)
	            {
				html += "<tr><td>";
					html += "<font color=\"red\">Train is " + late_time + " minutes late.</font>"; // + "<br/>";
				html += "</td></tr>";
	            }
//	            html += "<br/>";
	            
	            
				var label = train_type + " " + train_number;

				maincont += html;
				
				html = "<html><body><table>" + html + "</table></body></html>";
				
				// create the marker
				var marker = createMarker(point,label,html);
				
				map.addOverlay(marker);
				
				htmls[ trainsCnt ] = html;				
				gmarkers[ trainsCnt ] = marker;
				trainsCnt++;
			}

			
	

            //Populate the innerHTML of the div with the results
			var currentTime = new Date();
			var tm = currentTime.getHours()+ ":" + currentTime.getMinutes();
	

            document.getElementById('message').innerHTML = "";


//            document.getElementById('maincontent').innerHTML = tm + "<br/>" + maincont;
            document.getElementById('maincontent').innerHTML = "<table width=\"100%\">" + maincont + "</table>";
            
			

			if (document.getElementById('ttlink').style.visibility == 'hidden')
			{
				document.getElementById('ttlink').style.visibility = 'visible';
			}
			if (document.getElementById('timetable').innerHTML != '')
			{
				markTrainsInTT();
			}
			
		}
    }

    // XMLHttp send GET request
    function xmlHttp_Get(xmlhttp, url) {
        xmlhttp.open('GET', url, true);
        xmlhttp.send(null);
    }

    function GetXmlHttpObject(handler) {
        var objXmlHttp = null;    //Holds the local xmlHTTP object instance

        //Depending on the browser, try to create the xmlHttp object
        if (is_ie){
            //The object to create depends on version of IE
            //If it isn't ie5, then default to the Msxml2.XMLHTTP object
            var strObjName = (is_ie5) ? 'Microsoft.XMLHTTP' : 'Msxml2.XMLHTTP';
            
            //Attempt to create the object
            try{
                objXmlHttp = new ActiveXObject(strObjName);
                objXmlHttp.onreadystatechange = handler;
            }
            catch(e){
            //Object creation errored
                alert('IE detected, but object could not be created. Verify that active scripting and activeX controls are enabled');
                return;
            }
        }
        else if (is_opera){
            //Opera has some issues with xmlHttp object functionality
            alert('Opera detected. The page may not behave as expected.');
            return;
        }
        else{
            // Mozilla | Netscape | Safari
            objXmlHttp = new XMLHttpRequest();
            objXmlHttp.onload = handler;
            objXmlHttp.onerror = handler;
        }
        
        //Return the instantiated object
        return objXmlHttp;
    }

    function UseValue(strVal){
        document.frmStuff.txtName.value = strVal;
    }
//-----------------------------

function getTimeTable()
{
	var spanDate = document.getElementById('dateServer');
	var par = "";
	par= "year=" + spanDate.innerHTML.substring(0,4) + "&month=" + spanDate.innerHTML.substring(5,7) + "&day=" + spanDate.innerHTML.substring(8,10);


	document.getElementById('timetable').innerHTML = "getting timetable...";
	xmlHttp = GetXmlHttpObject(stateChangeHandlerTimetable);

	//Send the xmlHttp get to the specified url
	xmlHttp_Get(xmlHttp, requestTimeTableURL + par);

}

function UpdatetrainPos()  {
  var spanDate = document.getElementById('dateServer');
  var par = "";
  par= "year=" + spanDate.innerHTML.substring(0,4) + "&month=" + spanDate.innerHTML.substring(5,7) + "&day=" + spanDate.innerHTML.substring(8,10);
  
  var spanTime = document.getElementById('timeServer');
  par = par + "&time=" + spanTime.innerHTML.substring(0,5);
  
            //Create the xmlHttp object to use in the request
            //stateChangeHandler will fire when the state has changed, i.e. data is received back
            // This is non-blocking (asynchronous)
            
//            document.getElementById('maincontent').innerHTML = "Updating trains' data...";
            document.getElementById('message').innerHTML = "Updating trains' data...";
            xmlHttp = GetXmlHttpObject(stateChangeHandler);
            
            //Send the xmlHttp get to the specified url
            xmlHttp_Get(xmlHttp, requestURL + par);
  
  
  
  setTimeout( function () {
    UpdatetrainPos();
  }, 60000);
}


function UpdateMapTime()  {
  var spanDate = document.getElementById('dateServer');
  spanDate.innerHTML = getSrvDate();
  
  var spanTime = document.getElementById('timeServer');
  var timeSec = getServerDate();
  spanTime.innerHTML = SecToHMS(timeSec); 
  setTimeout( function () {
    UpdateMapTime();
  }, 1000);
}

function SecToHMS(timeSec) {
  var timeH = Math.floor(timeSec/3600);
  if (timeH < 10) {
    timeH = '0' + timeH; 
  }
  var timeM = Math.floor((timeSec-timeH*3600)/60);
  if (timeM < 10) {
    timeM = '0' + timeM; 
  }
  var timeS = timeSec-timeH*3600-timeM*60;
  if (timeS < 10) {
    timeS = '0' + timeS; 
  }
  
  var timeSecHTML = timeH + ':' + timeM + ':' + timeS;
  
  return timeSecHTML;
}

function getSrvDate()  {
	var d = new Date();
	var offset = 1; //gmt+1 italy zone
	
   // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (d.getTimezoneOffset() * 60000);
   
    // create new Date object for different city
    // using supplied offset
    currentTime = new Date(utc + (3600000*offset));
   
	

	var month = currentTime.getMonth() + 1;
	if (month < 10)
		month = '0' + month;

	var day = currentTime.getDate();
	if (day < 10)
		day = '0' + day;

	var year = currentTime.getFullYear();


	return (year + "/" + month + "/" + day);
}

	
function getServerDate()  {
	var d = new Date();
	var offset = 1; //gmt+1 italy zone
	
	
	
   // convert to msec
    // add local time zone offset
    // get UTC time in msec
    utc = d.getTime() + (DST() * 60 * 60000) + (d.getTimezoneOffset() * 60000);
   
    // create new Date object for different city
    // using supplied offset
    nowDate = new Date(utc + (3600000*offset) );


//  var nowDate = new Date();
  var nowDateSec = nowDate.getHours()*3600 + nowDate.getMinutes()*60 + nowDate.getSeconds()*1;
  //log(nowDateSec + ' ' + diffSecServer);
  return (nowDateSec + diffSecServer);
}

 function DST()
 {
	var gmt = new Date;
	var lsm = new Date;
	var lso = new Date;

	lsm.setMonth(2); // March
	lsm.setDate(31);

	var day = lsm.getDay();// day of week of 31st
	lsm.setDate(31-day); // last Sunday


	lso.setMonth(9); // October
	lso.setDate(31);
	day = lso.getDay();
	lso.setDate(31-day);

	if (gmt >= lsm && gmt < lso) 
		dst = 1;
	else
	{
		dst = 0;
	}
	return dst;
 }
