﻿var refreshInterval = 60; 
var numrefresh = 120;
var tooltip = new Element("div", {id: 'tooltip'});
var map;

function loadMap() {
  map = new GMap($("gmap"));
  map.addControl(new GMapTypeControl());
  map.addControl(new GLargeMapControl());
  map.addControl(new GScaleControl());
  map.removeMapType(G_HYBRID_MAP);
  map.addMapType(G_PHYSICAL_MAP);
  //map.setMapType(G_PHYSICAL_MAP);
  var center = new GLatLng(61.602477909996296, 4.785919189453125);
  map.centerAndZoom(center, 8);

  icon = new GIcon();
  icon.shadow = "img/mm_20_shadow.png"; 
  icon.iconSize = new GSize(12, 20); 
  icon.shadowSize = new GSize(22, 20); 
  icon.iconAnchor = new GPoint(6, 20); 
  icon.infoWindowAnchor = new GPoint(5, 1); 
  
  //var body = $(document.body);
  //body.insert(tooltip);
  map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
  tooltip.style.visibility="hidden";
  
  autoUpdate();
}

function getstatus(status) {
 switch (parseInt(status)) {
  case 0: return 'Undervegs';
   break;
  case 1: return 'For anker';
   break;
  case 2: return 'Utan styring';
   break;
  case 3: return 'Begrensa manøvering';
   break;
  case 4: return 'Forhindra grunna djupgåande';
   break;
  case 5: return 'Fortøygd';
   break;
  case 6: return 'På grunn';
   break;
  case 7: return 'I fiske';
   break;
  case 8: return 'Under segl';
   break;
  case 15: return 'Default (15)';
   break;
  default: return status;
   break;
  }
}
function getType(type) {
  var shipType;
  var itype = Math.floor(type/10);
  if (itype == 4) { shipType = "highspeed"; }
  else if (itype == 6) { shipType = "passenger"; }
  else if (itype == 7) { shipType = "cargo"; }
  else if (itype == 8) { shipType = "tank"; }
  else { 
    if (type == 52) { shipType = "tug"; }
    else if (type == 30) { shipType = "fish"; }
    else if (type == 55) { shipType = "coastguard"; }
    else { shipType = "other"; }
  }  
  return shipType;
} 
  
function makeinfo(name, aisstr, type) {
  var ais = aisstr.split('!');
  var mmsi  = ais[0];
  var imo   = ais[1];
  var call  = ais[2];
  var dest  = ais[3];
  var eta   = ais[4];
  var speed = ais[5];
  var course= ais[6];
  var status= getstatus(ais[7]);
  var length= ais[8];
  var width = ais[9];
  var draft = ais[10];
  var mtime = ais[11];
  var out = new Element('div', {'class': 'gpopup'});
  var table = new Element('table', {'cellpadding': '1', 'cellspacing': '0'});
  table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td', {'colspan': '2'}).update('<strong>'+name+'</strong>')));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Kallesignal:')).insert(new Element('td').update(call)));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Type:')).insert(new Element('td', {'class': 'typeCat'}).update(getType(type))));
  table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td').update('Unik ID (mmsi):')).insert(new Element('td').update(mmsi)));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Rammenummer:')).insert(new Element('td').update(imo)));
  table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td').update('Status:')).insert(new Element('td').update(status)));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Destinasjon:')).insert(new Element('td').update(dest)));
  table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td').update('Forventa ankomst:')).insert(new Element('td').update(eta)));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Fart:')).insert(new Element('td').update(speed + ' (kn)')));
  table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td').update('Kurs:')).insert(new Element('td').update(course)));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Lengde:')).insert(new Element('td').update(length + 'm')));
  table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td').update('Breidde:')).insert(new Element('td').update(width + 'm')));
  table.insert(new Element('tr', {'class':'even'}).insert(new Element('td').update('Dybde:')).insert(new Element('td').update(draft + 'm')));
  mtime != '' && table.insert(new Element('tr', {'class':'odd'}).insert(new Element('td').update('Motteke:')).insert(new Element('td').update(mtime)));
  
  out.insert(table);
  return out.innerHTML;
}

function addVector(from, deltax, deltay) {
  if (deltax == 0 && deltay == 0) return null;
  var to = new GPoint(from.x + deltax, from.y + deltay)
  var polyline = new GPolyline([from, to], "#ff0000", 2);
  return polyline;
}


function get_colour(type) {
  if (type == 52)
    return "black";
  if (type == 55)
    return "purple";
  if (type == 30)
    return "yellow";
  if (type > 99)
    return "gray";

  var itype = Math.floor(type/10);
  switch (itype) {
  case 7:
    ball = "green";
    break;
  case 8:
    ball = "red";
    break;
  case 4:
    ball = "white";
    break;
  case 6:
    ball = "blue";
    break;
  default:
    ball = "gray";
    break;
  }
  return ball;
}
function autoUpdate() {
  var request = GXmlHttp.create();
  request.open("GET", "xml/data.xml", true);
  request.onreadystatechange = function() {
    if (request.readyState == 4) {
      var shipmove = $("shipmove").update();
      var shipdock = $("shipdocked").update();
      var xmlDoc = request.responseXML;
      var xmlmarker = xmlDoc.documentElement.getElementsByTagName("marker");

      if(!markers) { markers = new Array(); }
      if (!infoHtml)
        infoHtml = new Array();
      if (!vectors)
        vectors = new Array();
      
      var Lat, Lon, name, deltax, deltay, type, ais, html;
      var shipMoveList = new Element('ul');
      var shipDockedList = new Element('ul');
      
      for (var i = 0; i < xmlmarker.length; i++) {
        Lat = parseFloat(xmlmarker[i].getAttribute("lat"));
        Lon = parseFloat(xmlmarker[i].getAttribute("lon"));
        name = xmlmarker[i].getAttribute("name");
        deltax = parseFloat(xmlmarker[i].getAttribute("dx"));
        deltay = parseFloat(xmlmarker[i].getAttribute("dy"));
        type = parseInt(xmlmarker[i].getAttribute("type"));
        infoHtml[i] = makeinfo(name, xmlmarker[i].getAttribute("ais"), type);

        ball = get_colour(type);
        icon.image = "img/mm_20_" + ball + ".png";
        
        if (markers[i]) {
          GEvent.clearListeners(markers[i], "click");
          map.removeOverlay(markers[i]);
        }
        
        var point = new GPoint(Lon, Lat);
        markers[i] = new GMarker(point, icon);
        markers[i].category = getType(type);
        markers[i].shipId = "ship"+i;
        markers[i].id = i;
        markers[i].deltaX = deltax;
        markers[i].deltaY = deltay;
        markers[i].type = type;
        markers[i].name = name;
        markers[i].tooltip = new Element('div').update(name);
        GEvent.addListener(markers[i], "click", makeOpenerCaller(i));
        map.addOverlay(markers[i]);

        if (vectors[i]) map.removeOverlay(vectors[i]);
        vectors[i] = addVector(point, deltax, deltay);
        if (vectors[i]) map.addOverlay(vectors[i]);
        
        GEvent.addListener(markers[i],"mouseover", function() {
			    showTooltip(markers[this.id]);
		    });
		    GEvent.addListener(markers[i],"mouseout", function() {
				  tooltip.setStyle({visibility: 'hidden'});
		    });
        var li = new Element('li', {'id': 'ship'+i});
        var a = new Element('a', {'href': '#', 'rel': getType(type)}).update(name);
        a.shipId = i;
        a.observe('click', getShip);
        a.observe('mouseover', mOver);
        a.observe('mouseout', mOut);
        li.insert(a);
        
        if (deltax != 0 || deltay != 0) {
            shipMoveList.insert(li);
        } else {
            shipDockedList.insert(li);
        }
      }
      shipmove.insert(shipMoveList);
      shipdock.insert(shipDockedList);
      show_all();
    }
  }
  request.send(null);
  // time out after 1hr.
  if (refreshcounter++ < numrefresh)
    window.setTimeout('countDown()', 1000);
  else {
    if ($("countDownText"))
      $("countDownText").update("Trykk REFRESH for å oppdatere.");
  }
}
function getShip(e) {
	findship(this.shipId);
	Event.stop(e);
}
function show(category) {
  for (var i=0; i<markers.length; i++) { 
    if (markers[i].category == category) {
      markers[i].show();
      $(markers[i].shipId).show();
    }
  }
  $(category).checked = true;
  map.closeInfoWindow();
}
function hide(category, box) {
  for (var i=0; i<markers.length; i++) {
    if (markers[i].category == category) {
      markers[i].hide();
      $(markers[i].shipId).hide();
    }
  }
  box.checked = false;
  map.closeInfoWindow();
}
function boxclick(e) {
  var box = Event.element(e);
  var category = box.id;
  if (box.checked) {
    show(category);
  } else {
    hide(category, box);
  }
  //updateShipList();
  //Event.stop(e);
}
function updateShipList() {
  //alert(markers.length);
  var shipmove = $("shipmove").update();
  var shipdock = $("shipdocked").update();
  
  var shipMoveList = new Element('ul');
  var shipDockedList = new Element('ul');
  
  for (var i=0; i<markers.length; i++) {
    var li = new Element('li', {'id': 'ship'+i});
    var a = new Element('a', {'href': '#', 'rel': getType(markers[i].type)}).update(markers[i].name);
    a.shipId = i;
    a.observe('click', getShip);
    a.observe('mouseover', mOver);
    a.observe('mouseout', mOut);
    li.insert(a);
        
    if (markers[i].deltaX != 0 || markers[i].deltaY != 0) {
      shipMoveList.insert(li);
    } else {
      shipDockedList.insert(li);
    }
    
  }
  shipmove.insert(shipMoveList);
  shipdock.insert(shipDockedList);
}
function show_all() {
  for (var i=0; i<markers.length; i++) {
    markers[i].show();
    $(markers[i].shipId).show();
  }
  var cats = $$('#controlPanel input');
  cats.each(function (e) {
    e.checked = true;
  });
  //updateShipList();
}
function hide_all() {
  for (var i=0; i<markers.length; i++) {
    markers[i].hide();
    $(markers[i].shipId).hide();
  }
  var cats = $$('#controlPanel input');
  cats.each(function (e) {
    e.checked = false;
  });
  //updateShipList();
}

var refreshcounter = 0;
var icon;
var markers;
var infoHtml;
var vectors;
var map;
var countDownTime=refreshInterval+1;
var counter;

function countDown(){
  countDownTime--;
  if ($("countDownText"))
    $("countDownText").update("Oppdatering om " + countDownTime + " sek.");
  if (countDownTime<=0){
    countDownTime=refreshInterval;
    clearTimeout(counter);
    autoUpdate();
    return;
  }
  counter=setTimeout("countDown()", 1000);
}

// Open the info box for the specified marker.
function findship(i){
  markers[i].openInfoWindowHtml(infoHtml[i]);
}

function makeOpenerCaller(i) {
  return function() { findship(i); };
}
function showTooltip(marker) {
  tooltip.innerHTML = marker.tooltip.innerHTML;
  var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
  var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
  var anchor=marker.getIcon().iconAnchor;
  var width=marker.getIcon().iconSize.width;
  var height=tooltip.clientHeight;
  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height));
  pos.apply(tooltip);
  tooltip.setStyle({visibility: 'visible'});
}
function mOver(e) {
  showTooltip(markers[this.shipId]);
  Event.stop(e);
}
function mOut(e) {
  tooltip.setStyle({visibility: 'hidden'});
  Event.stop(e);
}
function init() {
  $('cargo').observe('click', boxclick);
  $('passenger').observe('click', boxclick);
  $('tank').observe('click', boxclick);
  $('fish').observe('click', boxclick);
  $('highspeed').observe('click', boxclick);
  $('tug').observe('click', boxclick);
  $('coastguard').observe('click', boxclick);
  $('other').observe('click', boxclick);
  
  $('showAll').observe('click', show_all);
  $('hideAll').observe('click', hide_all);

	initFlash();
	
  if (!GBrowserIsCompatible()) {
    alert("Sorry, the Google Maps API is not compatible with this browser");
  } else {
   loadMap();
  }
}
function initFlash() {
	var flash = new SWFObject("flash/768x150.swf", "header", "768", "150", "8", "#ffffff");
	flash.addVariable("clickTAG", "http://www.sigurd-solberg.no/");
	flash.write("flashBanner");
}

document.observe("dom:loaded", init);