﻿ //<![CDATA[
	var map;
	var texttip = [];   //divs for legends
    var texttip_back = [];  //divs to display back shadow for each text tip or legend
    var areatext = [];
    var areatext_back = [];
    var area = [];
    var x = [];
    var y = [];
    var course = [];
    var speed = [];
    var shiptype = [];
    var shipcolor = [];
    var shipstatus = [];
    var shipname = [];
    var flag = [];
    var mmsi = [];
    var ship = [];      //ship divs
    var wp = [];        //waypoint divs
    var n = 100;        //number of ships - 100 for test data
    var k = 0;          //number of areas
    var t = 0;          //number of waypoints
    var shipsshown = 0;
    var totalshipno = 0;
    var refreshInterval = 100;
    var countDownTime = refreshInterval+1;
    var counter;
    var currenttrack;
    var currenttracktype;
    var urlmmsi=0;
    var oldmmsi=0;
    var olddate="";
    var firstload=true;
    
    var arVersion = navigator.appVersion.split("MSIE");
    var version = parseFloat(arVersion[1]);

    function mapload() {
      if (GBrowserIsCompatible()) {
      
    //URL parameters and default values
    var mapcenterx=24.2;
    if(getUrlParam("centerx")!="")
        mapcenterx = parseFloat(getUrlParam("centerx"));
        
    var mapcentery=37.5;    
    if(getUrlParam("centery")!="")
        mapcentery = parseFloat(getUrlParam("centery"));

    var zoom=8;    
    if(getUrlParam("zoom")!="")
        zoom = parseInt(getUrlParam("zoom"));
        
    if(getUrlParam("mmsi")!="")
        urlmmsi = parseInt(getUrlParam("mmsi"));

    if(getUrlParam("oldmmsi")!="")
        oldmmsi = parseInt(getUrlParam("oldmmsi"));
        
    if(getUrlParam("olddate")!="")
        olddate = getUrlParam("olddate");
        
    map = new GMap2(document.getElementById("map_area"));
    map.setCenter(new GLatLng(mapcentery, mapcenterx), zoom);
	map.setMapType(G_NORMAL_MAP);
	map.addControl(new GLargeMapControl());
	map.addControl(new GMapTypeControl());
	map.addControl(new GScaleControl());
	//map.addControl(new GOverviewMapControl());
	
	//map.enableContinuousZoom();
	map.enableDoubleClickZoom();
    //map.enableScrollWheelZoom();
    
    
    shipcolor[0]="lightgray";   //unspecified
    shipcolor[1]="gray";       //Navigation Aids - Shore stations
    shipcolor[3]="cyan";        //Tug, special crafts
    shipcolor[4]="yellow";      //high speed
    shipcolor[6]="blue";        //passenger
    shipcolor[7]="lightgreen";  //cargo
    shipcolor[8]="red";         //tanker
    shipcolor[9]="magenta";     //pleasure yacht - other
    
    shipstatus[0]="Moving";
    shipstatus[1]="Anchored";
    shipstatus[2]="Moored";
        
    //refresh ships after zoom
    GEvent.addListener(map,"zoomend", function() {
        //refreshPositions();
    if(oldmmsi==0)
        getData();
    else
        getOldPos();
            });

    if(oldmmsi==0)
        getData();
    else
        getOldPos();
    }
}

function getData() {
    //restrict data to current map bounds
    var sw_x = map.getBounds().getSouthWest().lng()-1/map.getZoom();
    var sw_y = map.getBounds().getSouthWest().lat()-1/map.getZoom();
    var ne_x = map.getBounds().getNorthEast().lng()+1/map.getZoom();
    var ne_y = map.getBounds().getNorthEast().lat()+1/map.getZoom();
    //alert(sw_x + " " + ne_x + " " + sw_y + " " + ne_y);
    var path = "getxml.aspx?id=" + Math.random() + "&sw_x=" + sw_x + "&sw_y=" + sw_y + "&ne_x=" + ne_x + "&ne_y=" + ne_y + "&zoom=" + map.getZoom();
    // The path to the PHP proxy
    var url = 'proxy.php?url=' + encodeURIComponent(path);
    GDownloadUrl(url, function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      var xmlposition = xmlDoc.documentElement.getElementsByTagName("V_POS");
      for(var j=0; j<k; j++)    //clear area listeners
        GEvent.clearListeners(area[j], "click");
      map.clearOverlays();
      hideAreaLegends();
      hideLegends();
      hideShips();
      shipsshown=0;
      n = xmlposition.length;
      totalshipno = n;
      for (var i = 0; i < n; i++) {
        x[i] = parseFloat(xmlposition[i].getAttribute("LAT"));
        y[i] = parseFloat(xmlposition[i].getAttribute("LON"));
        shipstatus[i] = parseInt(xmlposition[i].getAttribute("ST"));
        shipname[i] = xmlposition[i].getAttribute("N");
        shiptype[i] = parseInt(xmlposition[i].getAttribute("T"));
        course[i] = parseFloat(xmlposition[i].getAttribute("H"));
        speed[i] = parseFloat(xmlposition[i].getAttribute("S"));
        flag[i] = xmlposition[i].getAttribute("F");
        mmsi[i] = parseInt(xmlposition[i].getAttribute("M"));
        if(mmsi[i]==urlmmsi && firstload==true) {   //mmsi given in URL - show track and details on map, only on first load
            currenttrack=urlmmsi;
            currenttracktype=shiptype[i];
            showInfoWindow(i);
            firstload=false;
            }
        }
      for (var i = 0; i < n; i++) {
        createship(x[i], y[i], shipstatus[i], course[i], speed[i], shiptype[i], shipname[i], flag[i], i);
        }
      
      document.getElementById("shownShips").innerHTML = shipsshown;
      if(map.getZoom()<10)
         getAreas();
      getTracking(currenttrack, currenttracktype);

    });


    //refresh data every <refreshInterval> seconds
    clearTimeout(counter);
    window.setTimeout("countDown()", 1000);

}

function getAreas() {
    var path = "getareasxml.aspx?id=" + Math.random();
    // The path to the PHP proxy
    var url = 'proxy.php?url=' + encodeURIComponent(path);
    GDownloadUrl(url, function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      var xmlposition = xmlDoc.documentElement.getElementsByTagName("V_AREAS");
      k = xmlposition.length;
      var pts = [];
      var sw_x, sw_y, ne_x, ne_y, shipcount, area_id, area_name, zoom;
      for (var i = 0; i < k; i++) {
        sw_x = parseFloat(xmlposition[i].getAttribute("SW_X"));
        sw_y = parseFloat(xmlposition[i].getAttribute("SW_Y"));
        ne_x = parseFloat(xmlposition[i].getAttribute("NE_X"));
        ne_y = parseFloat(xmlposition[i].getAttribute("NE_Y"));
        shipcount = parseInt(xmlposition[i].getAttribute("SHIPCOUNT"));
        area_id = xmlposition[i].getAttribute("AREA_ID");
        area_name = xmlposition[i].getAttribute("AREA_NAME");
        zoom = parseInt(xmlposition[i].getAttribute("ZOOM"));
        totalshipno+=shipcount;

        pts = [new GLatLng(sw_y, sw_x), new GLatLng(sw_y, ne_x),
            new GLatLng(ne_y, ne_x), new GLatLng(ne_y, sw_x), new GLatLng(sw_y, sw_x)];
        area[i] = new GPolygon(pts, "#000", 1, 1, "#000", 0.4);

        area[i].area_name = area_name;
        area[i].center_x=(sw_x+ne_x)/2;
        area[i].center_y=(sw_y+ne_y)/2;
        area[i].zoom = zoom;

        GEvent.addListener(area[i], "click", function() {
            //alert(this.zoom);
            map.setCenter(new GLatLng(this.center_y, this.center_x), this.zoom);
            });
        map.addOverlay(area[i]);

	    var html = area_name + ": " + shipcount + " Vessels. Click on Area.";
        areaLegend(area[i].center_y, area[i].center_x, html, i);
        }
	      document.getElementById("totalShips").innerHTML = totalshipno;

    });
}

function getTracking(mmsi, tracktype) {
    currenttrack=mmsi;
    currenttracktype=tracktype;
    map.getInfoWindow().hide();
    hideWayPoints();
    var path = "gettrackxml.aspx?mmsi=" + mmsi + "&date=" + olddate + "&id=" + Math.random();
    // The path to the PHP proxy
    var url = 'proxy.php?url=' + encodeURIComponent(path);

    if(mmsi!=null)
    GDownloadUrl(url, function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      var xmlposition = xmlDoc.documentElement.getElementsByTagName("POS");
      t = xmlposition.length;
      var pts = [];
      var lon,lat,speed,course,timestamp,prevlat, prevlon;
      for (var i = 0; i < t; i++) {
        lon = parseFloat(xmlposition[i].getAttribute("LON"));
        lat = parseFloat(xmlposition[i].getAttribute("LAT"));
        speed = parseFloat(xmlposition[i].getAttribute("SPEED"));
        course = parseFloat(xmlposition[i].getAttribute("COURSE"));
        timestamp = xmlposition[i].getAttribute("TIMESTAMP");
        pts[i] = new GLatLng(lat, lon);
        //draw waypoint only if the distance is more than 15 pixels from the previous one
        if(i==0 || shipsDistance(lat,lon,prevlat,prevlon)>=15) {
            drawWayPoint(lat,lon,course,speed,timestamp,i);
            prevlat=lat;
            prevlon=lon;
        }
     }
        
        var color=shipcolor[tracktype];
        if(color=="lightgreen")
            color="green";
        else if(color=="lightgray")
            color="gray";
        else if(color=="magenta")
            color="purple";
        else if(color=="cyan")
            color="aqua";
        var track = new GPolyline(pts, color, 2, 1);

        map.addOverlay(track);
    });
}

function getOldPos() {
    //restrict data to current map bounds
    GDownloadUrl("getoldposxml.aspx?mmsi=" + oldmmsi + "&date=" + olddate, function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      n=1;
      var xmlposition = xmlDoc.documentElement.getElementsByTagName("DAILY_ITINERARIES");
      var x1 = parseFloat(xmlposition[0].getAttribute("LAT"));
      var y1 = parseFloat(xmlposition[0].getAttribute("LON"));
      var shipname1 = xmlposition[0].getAttribute("SHIPNAME");
      var shiptype1 = parseInt(xmlposition[0].getAttribute("SHIPTYPE"));
      var course1 = parseFloat(xmlposition[0].getAttribute("COURSE"));
      var speed1 = parseFloat(xmlposition[0].getAttribute("SPEED"));
      map.setCenter(new GLatLng(x1, y1));
      createship(x1, y1, 0, course1, speed1*10, shiptype1, shipname1, "", 0);

      document.getElementById("shownShips").innerHTML = "1";
      document.getElementById("totalShips").innerHTML = "1";
      
        var infohtml = '<div id="infotitle"><span>'+ shipname1 +'</span></div>';
        infohtml += '<div id="infowindow"><span>';
        infohtml += "Vessel's Position Recorded on: " + olddate;
        infohtml += "<br/>Lon/Lat: " + y1 + " / " + x1; 
        infohtml += "<br/>Speed/Course: " + speed1 + " kn / " + course1 + "&deg;";
        infohtml += "<br/>Vessel's track shown for that day.";
        infohtml += '</span></div>';
	    map.openInfoWindowHtml(new GLatLng(x1, y1), infohtml);
      
      getTracking(oldmmsi, shiptype1);

    });

}

function refreshOnZoom() {
//reposition of ships after zoom
    shipsshown = 0;
    for(i=0; i<n; i++)
        createship(x[i], y[i], status[i], course[i], speed[i], shiptype[i], shipname[i], flag[i], i);
    }            

function refreshPositions() {
//reposition and hide/show depending on options selected
    hideLegends();
    hideShips();
    shipsshown = 0;
    totalshipno = 0;	
    map.clearOverlays();
    hideWayPoints();	
    if(map.getZoom()<10)
        getAreas();

    for(i=0; i<n; i++)
        createship(x[i], y[i], status[i], course[i], speed[i], shiptype[i], shipname[i], flag[i], i);
    document.getElementById("shownShips").innerHTML = shipsshown;
    }            

function createship(lat, lon, shipstatus, angle, speed, shiptype, shipname, flag, shipindex) {
//drawship, depending on selected(checked) shiptypes and status
        if(shipsDistance(lat, lon, x[shipindex+1], y[shipindex+1])>3  || shipindex==n-1) { 
            //show only ships that do not overlap by less than 3 pixels with the next ship
            createLegend(lat, lon, shipname, shipindex);
            drawMovingShip(lat, lon, angle, speed, shiptype, shipname, flag, shipindex);
            //drawCourse(lat, lon, angle,speed,shiptype);
            }
        shipsshown++;
}

function drawMovingShip(x, y, angle, speed, shiptype, shipname, flag, shipindex) {
	//prepare divs to display the ship icon and the legend of each point
	if(!ship[shipindex]) {
   	    ship[shipindex] = document.createElement("div");
        map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).appendChild(ship[shipindex]);  //append on top of shadows but under infowindows
    }
	
    //ship icon dynamically created
    var imgsrc;
    if(speed<=5)
        imgsrc = 'http://syros-observer.aegean.gr/ais/shipicons/' + shipcolor[shiptype] + "0.png";
    else
    {
        var angle5 = (Math.floor(angle / 5)) * 5;
        imgsrc = 'http://syros-observer.aegean.gr/ais/shipicons/' + shipcolor[shiptype] + '1_' + angle5 + '.png';
    }
	var shiphtml = '<div id="ship"><span ';
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {   
        //handle correctly transparent PNG images in IE 5.5 and 6
        shiphtml += ' style="display:inline-block;width:24px;height:24px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader'
        + '(src=\'' + imgsrc + '\', sizingMethod=\'scale\');"'	
        + ' title="' + shipname + ' [' + flag + ']\n' + speed/10 + ' knots / ' + angle + '&deg;"'    
        + ' onclick="showInfoWindow(' + shipindex + ');">';
    }
    else
    {
        shiphtml += '><img width="24" height="24" src="' + imgsrc 
	    + '" title="' + shipname + ' [' + flag + ']\n' + speed/10 + ' knots / ' + angle + '&deg;'
	    + '" onclick="showInfoWindow(' + shipindex + ');"/>';
	}
	shiphtml += '</span></div>';
    //alert(shiphtml);
    ship[shipindex].innerHTML = shiphtml;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(x,y), map.getZoom());
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x -12, offset.y - point.y -12)); //icon anchor at 12,12
    pos.apply(ship[shipindex]);
    ship[shipindex].style.visibility="visible";
}


function drawCourse(x, y, angle, speed, shiptype) {
    //not used
    //draws line in front of ship, dpending on heading and speed
    if(!speed || speed<=5 || speed>600 )
        return;
    var rad=Math.PI*angle/180;
    var sinf=Math.sin(rad);
    var cosf=Math.cos(rad);
    var scaleunit=0.1/Math.pow(2,map.getZoom());  //size of ship analogue to 2 ^zoom level - to keep same size of ship
    var distorty=1.2;   //x shows longer than y on map - correct it!
    var pts = [new GLatLng(x+(8+speed)*scaleunit*cosf, y+(8+speed)*scaleunit*sinf*distorty),    //speed course
       new GLatLng(x,y)];   //line till center
    var course = new GPolygon(pts, shipcolor[shiptype], 1, 1, shipcolor[shiptype], 1);
    
    map.addOverlay(course);
    

}    

function drawWayPoint(x, y, angle, speed, timestamp, wpindex) {
	//prepare divs to display the wpoint icon and the legend of each point
	if(!wp[wpindex]) {
   	    wp[wpindex] = document.createElement("div");
        map.getPane(G_MAP_MARKER_SHADOW_PANE).appendChild(wp[wpindex]);  //append under ships and above tracks
    }
	
    //wp icon dynamically created
    var angle5 = (Math.floor(angle / 5)) * 5;
    var imgsrc = 'http://syros-observer.aegean.gr/ais/shipicons/waypoint_' + angle5 + '.png';
	var wphtml = '<div id="ship"><span ';
    if ((version >= 5.5) && (version < 7) && (document.body.filters)) 
    {   
        //handle correctly transparent PNG images in IE 5.5 and 6
        wphtml += ' style="display:inline-block;width:11px;height:11px;filter:progid:DXImageTransform.Microsoft.AlphaImageLoader'
        + '(src=\'' + imgsrc + '\', sizingMethod=\'scale\');"'	
        + ' title="' + speed/10 + ' knots / ' + angle + '&deg;\n' + timestamp + '">';    
    }
    else
    {
        wphtml += '><img width="11" height="11" src="' + imgsrc 
	    + '" title="' + speed/10 + ' knots / ' + angle + '&deg;\n' + timestamp + '"/>';
	}
	wphtml += '</span></div>';
	//alert(wphtml);
    wp[wpindex].innerHTML = wphtml;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(x,y), map.getZoom());
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x -5, offset.y - point.y -5)); //icon anchor at 5,5
    pos.apply(wp[wpindex]);
    wp[wpindex].style.visibility="visible";
}

function shipsDistance(x1, y1, x2, y2) {
    //returns the distance in pixels between two ships
    var ship1=map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(x1,y1), map.getZoom());
    var ship2=map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(x2,y2), map.getZoom());
    //alert(ship1.x + " " + ship1.y + " " + ship2.x);
    var dist = Math.sqrt(Math.pow(Math.abs(ship1.x)-Math.abs(ship2.x),2)+Math.pow(Math.abs(ship1.y)-Math.abs(ship2.y),2));
    return dist;
    }

function showInfoWindow(i) {
var path = "shipinfo.aspx?mmsi=" + mmsi[i] + "&id=" + Math.random();
var url = 'proxy.php?url=' + encodeURIComponent(path);

if(mmsi[i])
    GDownloadUrl(url, function(data, responseCode) {
        var infohtml = '<div id="infotitle"><span>'+ shipname[i] +'</span></div>';
        infohtml += '<div id="infowindow"><span>';
        infohtml += data;
        infohtml += '</span></div>';
	    map.openInfoWindowHtml(new GLatLng(x[i], y[i]), infohtml);
    });
    
}
    
function createLegend(x, y, titletext, shipindex) {    
	//prepare divs to display the ship icon and the legend of each point
	if(!texttip[shipindex]) {
        texttip_back[shipindex] = document.createElement("div");
        map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(texttip_back[shipindex]);
   	    texttip[shipindex] = document.createElement("div");
        map.getPane(G_MAP_FLOAT_SHADOW_PANE).appendChild(texttip[shipindex]);
    }
	
    //text next to ship
	var title_front = '<div id="texttip"><span>'+ titletext +'</span></div>';
	var title_back = '<div id="texttip_back"><span>'+ titletext +'</span></div>';
    texttip[shipindex].innerHTML = title_front;
    texttip_back[shipindex].innerHTML = title_back;   //same text with diff color as background for better visibility
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(x,y), map.getZoom());
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x, offset.y - point.y +5)); 
    var pos_back = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x + 1, offset.y - point.y +5 - 1)); 
    pos.apply(texttip[shipindex]);
    pos_back.apply(texttip_back[shipindex]);
  if(document.getElementById("CheckLegends").checked) {
     texttip[shipindex].style.visibility="visible";
     texttip_back[shipindex].style.visibility="visible";
    }
  else {
     texttip[shipindex].style.visibility="hidden";
     texttip_back[shipindex].style.visibility="hidden";
    }
}

function areaLegend(x, y, text, index) {    
	//prepare divs to display the ship icon and the legend of each point
	if(!areatext_back[index]) {
        areatext_back[index] = document.createElement("div");
        map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).appendChild(areatext_back[index]);
   	    areatext[index] = document.createElement("div");
        map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).appendChild(areatext[index]);
    }
	
    //text next to area
	var title_front = '<div id="areatext"><span>'+ text +'</span></div>';
	var title_back = '<div id="areatext_back"><span>'+ text +'</span></div>';
    areatext[index].innerHTML = title_front;
    areatext_back[index].innerHTML = title_back;   //same text with diff color as background for better visibility
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(new GLatLng(x,y), map.getZoom());
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x, offset.y - point.y +5)); 
    var pos_back = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x + 1, offset.y - point.y +5 - 1)); 
    pos.apply(areatext[index]);
    pos_back.apply(areatext_back[index]);
    areatext[index].style.visibility="visible";
    areatext_back[index].style.visibility="visible";
}

function showLegends() {
    if(document.getElementById("CheckLegends").checked)
    for(var i=0; i<n; i++)
if (texttip[i]) {
        texttip[i].style.visibility="visible";
        texttip_back[i].style.visibility="visible";
    }
}

function hideLegends() {
    for(var i=0; i<n; i++)
        if(texttip[i]) {
            texttip[i].style.visibility="hidden";
            texttip_back[i].style.visibility="hidden";
        }
}

function hideAreaLegends() {
    for(var i=0; i<k; i++)
        if(areatext[i]) {
            areatext[i].style.visibility="hidden";
            areatext_back[i].style.visibility="hidden";
            GEvent.clearListeners(area[i], "click");

        }
}

function removeLegends() {
    //removes all Legend divs
    for(var i=0; i<n; i++)
        if(texttip[i]) {
            map.getPane(G_MAP_FLOAT_SHADOW_PANE).removeChild(texttip_back[i]);
            texttip_back[i]=null;
            map.getPane(G_MAP_FLOAT_SHADOW_PANE).removeChild(texttip[i])
            texttip[i]=null;
        }
}

function hideShips() {
    for(var i=0; i<n; i++)
        if(ship[i])
            ship[i].style.visibility="hidden";
}

function hideWayPoints() {
    for(var i=0; i<t; i++)
        if(wp[i])
            wp[i].style.visibility="hidden";
}

function removeShips() {
    //removes all divs with ship icons
    for(var i=0; i<n; i++)
        if(ship[i])
            map.getPane(G_MAP_MARKER_MOUSE_TARGET_PANE).removeChild(ship[i])
            ship[i]=null;
}

function changeLegends() {
    if(document.getElementById("CheckLegends").checked)
        showLegends();
    else
        hideLegends();
}

function countDown(){
    countDownTime--;
    if (document.getElementById("countDownSecs"))
        document.getElementById("countDownSecs").innerHTML= countDownTime;
    if (countDownTime<=0){
        countDownTime=refreshInterval;
        clearTimeout(counter);
        getData();
        return;
    }
counter=setTimeout("countDown()", 1000);
}

function getUrlParam( name ) {
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    if( results == null ) 
        return "";
    else
        return results[1];
}

function getPorts() {
    GDownloadUrl("getportxml.aspx", function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      //clear previous positions
      for(var i=0; i<portcount; i++)
        if(portdiv[i])
            portdiv[i].style.visibility="hidden";

      var xmlposition = xmlDoc.documentElement.getElementsByTagName("V_PORTS");
      portcount = xmlposition.length;
      var portx, porty, port_id, portname, portzoom;
      for (var i = 0; i < portcount; i++) {
        porty = parseFloat(xmlposition[i].getAttribute("CENTERX"));
        portx = parseFloat(xmlposition[i].getAttribute("CENTERY"));
        port_id = parseInt(xmlposition[i].getAttribute("PORT_ID"));
        portname = xmlposition[i].getAttribute("PORT_NAME");
        portzoom = parseInt(xmlposition[i].getAttribute("ZOOM"));
        drawPort(port_id, portx, porty, portname, i);
        }
    });
}

function focusPort(port_id) {
    if(port_id==0)
        port_id = document.getElementById("PORT").value;
    GDownloadUrl("getportxml.aspx?port_id=" + port_id + "&id=" + Math.random(), function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      var xmlposition = xmlDoc.documentElement.getElementsByTagName("V_PORTS");
      if(xmlposition.length==0) return;
      var lon,lat,zoom;
    lon = parseFloat(xmlposition[0].getAttribute("CENTERX"));
    lat = parseFloat(xmlposition[0].getAttribute("CENTERY"));
    zoom = parseInt(xmlposition[0].getAttribute("ZOOM"));
        
    //if(map.getZoom()!=zoom-2)    //avoid refreshing twice if zoomed to different level

        map.setCenter(new GLatLng(lat, lon), zoom-2);
        getData();
    });
}

function focusVessel(vessel_id) {
    if(vessel_id==0)
        vessel_id = document.getElementById("VESSEL").value;
    GDownloadUrl("getvesselxml.aspx?mmsi=" + vessel_id + "&id=" + Math.random(), function(data, responseCode) {
      var xmlDoc = GXml.parse(data);
      if (!xmlDoc.documentElement) return;
      var xmlposition = xmlDoc.documentElement.getElementsByTagName("V_POS");
      if(xmlposition.length==0) return;
      var lon,lat;
    lon = parseFloat(xmlposition[0].getAttribute("LON"));
    lat = parseFloat(xmlposition[0].getAttribute("LAT"));
        
    urlmmsi=vessel_id;
    firstload=true;
    if(map.getZoom()>10)    //avoid calling getData twice if zoomed to different level
        map.setCenter(new GLatLng(lat, lon), 10);
    else {
        map.setCenter(new GLatLng(lat, lon), 10);
        urlmmsi=vessel_id;
        firstload=true;
        getData();
        }        
        
    });
}

    //]]>
    
    