var map;
var markers = new Array();
var tooltip;
var lineColor = "#0000af";
var fillColor = "#335599";
var lineWeight = 2;
var lineOpacity = .8;
var fillOpacity = .2;
var dragStartLatitude;
var dragStartLongitude;
var dragEndLatitude;
var dragEndLongitude;
var polyPointsArrays = new Array();
var polyIdArrays = new Array();
var polylineIdArrays = new Array();
var polyline;
var mouseMove;
var showAccess= true;
var showLicense= true;
var showParking= true;
var showCrossing= true;
var showCamping= true;
var hideAll= true;
var timer;


function initialize() {
  var latitude = document.getElementById("map_latitude").value;
  var longitude = document.getElementById("map_longitude").value;
  var zoom = document.getElementById("map_zoom").value;
  map = new GMap2(document.getElementById("map_canvas"));

  tooltip = document.createElement("div");
  tooltip.className = "tooltip";
  map.getPane(G_MAP_MARKER_PANE).appendChild(tooltip);
  tooltip.style.display = "none";

  map.setCenter(new GLatLng(latitude, longitude), parseInt(zoom));
  map.addControl(new GLargeMapControl());
  map.addControl(new GMapTypeControl());
  GEvent.addListener(map, "moveend", function()
    {
      loadMarkers();
      loadPolylines();
    }
  );
  GEvent.addListener(map, "maptypechanged", function()
    {
      loadMarkers();
      loadPolylines();
    }
  );

  GEvent.addListener(map, "mousemove", function(latlng)
    {
      mouseMove = latlng;
    }
  );

  var bounds = map.getBounds();
  var southWest = bounds.getSouthWest();
  var northEast = bounds.getNorthEast();
  var lngSpan = northEast.lng() - southWest.lng();
  var latSpan = northEast.lat() - southWest.lat();
  loadMarkers();
  loadPolylines();
  map.addControl(new MoreControl());
}

function loadMarkers() {
  map.clearOverlays();
  var min_latitude = map.getBounds().getSouthWest().lat();
  var max_latitude = map.getBounds().getNorthEast().lat();
  var min_longitude = map.getBounds().getSouthWest().lng();
  var max_longitude = map.getBounds().getNorthEast().lng();

  if (map.getZoom() > 12) {
    var URL = "get_signs.php?min_latitude="+min_latitude+"&max_latitude="+max_latitude+"&min_longitude="+min_longitude+"&max_longitude="+max_longitude;
    GDownloadUrl(URL, function(data)
      {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        if (markers.length > 0) {
          for (var i = 0; i < markers.length; i++) {
            var tegntype = markers[i].getAttribute("sign_type");
              if ((tegntype == 0 && showLicense == true) || (tegntype == 1 && showParking == true) || (tegntype == 2 && showCrossing == true) || (tegntype == 3 && showCamping == true)){
                var id = markers[i].getAttribute("sign_key");
                var point = new GLatLng(parseFloat(markers[i].getAttribute("latitude")),
                  parseFloat(markers[i].getAttribute("longitude")));
                var marker = cm_createMarker(point, tegntype, id);
                map.addOverlay(marker);
              }
          }
        }
      }
    );
  };
}

function cm_createMarker(point, tegntype) {
  var filename;
  var nIcon = new GIcon();
  var title;
  var importance;
  if (tegntype == 0) {
    filename = "images/spot";
    if ((map.getCurrentMapType().getName()== 'Kort')||
      (map.getCurrentMapType().getName()== 'Map'))
    {
      filename = filename+"_black";
    } else {
      filename = filename+"_white";
    }
    if (map.getZoom() < 13) {
      filename = filename+"_12";
      nIcon.iconSize = new GSize(1, 1);
      nIcon.iconAnchor = new GPoint(1, 1);
    }
    else
    {
      filename = filename+"_"+map.getZoom().toString();
      var iSize = 3*Math.pow(2, map.getZoom()-13);
      nIcon.iconSize = new GSize(iSize, iSize);
      var iAnchor = Math.floor(iSize/2);
      nIcon.iconAnchor = new GPoint(iAnchor, iAnchor);
      nIcon.infoWindowAnchor = new GPoint(iAnchor, iAnchor);
    }
    filename = filename + ".png";
    nIcon.shadow = "";
    nIcon.shadowSize = new GSize(0, 0);
    nIcon.infoShadowAnchor = new GPoint(0, 0);
    nIcon.imageOut = filename;
    nIcon.imageOver = filename;
    nIcon.imageSelected = filename;
    title = "Her må du fiske";
    importance = 1;
  } else if (tegntype == 1) {
    filename = "images/parking";
    nIcon.shadow = "";
    nIcon.iconSize = new GSize(16, 16);
    nIcon.shadowSize = new GSize(0, 0);
    nIcon.iconAnchor = new GPoint(8, 8);
    nIcon.infoWindowAnchor = new GPoint(0, 0);
    nIcon.infoShadowAnchor = new GPoint(0, 0);
    nIcon.imageOut = "images/parking.png";
    nIcon.imageOver = "images/parking.png";
    nIcon.imageSelected = "images/parking.png";
    title = "Parkering";
    importance = 4;
  } else if (tegntype == 2) {
    filename = "images/spang";
    nIcon.shadow = "";
    nIcon.iconSize = new GSize(16, 16);
    nIcon.shadowSize = new GSize(0, 0);
    nIcon.iconAnchor = new GPoint(8, 8);
    nIcon.infoWindowAnchor = new GPoint(0, 0);
    nIcon.infoShadowAnchor = new GPoint(0, 0);
    nIcon.imageOut = "images/spang.png";
    nIcon.imageOver = "images/spang.png";
    nIcon.imageSelected = "images/spang.png";
    title = "Spang eller bro";
    importance = 3;
  } else {
    filename = "images/camping";
    nIcon.shadow = "";
    nIcon.iconSize = new GSize(16, 16);
    nIcon.shadowSize = new GSize(0, 0);
    nIcon.iconAnchor = new GPoint(8, 8);
    nIcon.infoWindowAnchor = new GPoint(0, 0);
    nIcon.infoShadowAnchor = new GPoint(0, 0);
    nIcon.imageOut = "images/camping.png";
    nIcon.imageOver = "images/camping.png";
    nIcon.imageSelected = "images/camping.png";
    title = "Camping";
    importance = 2;
  }

  nIcon.image = nIcon.imageOut;
  var marker = new GMarker(point,{icon:nIcon,title:title,zIndexProcess:orderOfCreation});
  marker.importance= importance;
  return marker;
}

function loadPolylines() {
  if (showAccess==true){
    polyPointsArrays =[];
    polyIdArrays =[];
    polylineIdArrays =[];
    var activePoly_Id = -1;
    if (map.getZoom() > 12) {
      var URL = "get_all_polylines.php";
      GDownloadUrl(URL, function(data)
        {
          var xml = GXml.parse(data);
          var markers = xml.documentElement.getElementsByTagName("marker");
          if (markers.length > 0) {
          // var oldPolyline = polyline;
            for (var i = 0; i < markers.length; i++) {
              var poly_Id = markers[i].getAttribute("poly_id");
              var id = markers[i].getAttribute("id");
              var point = new GLatLng(parseFloat(markers[i].getAttribute("latitude")),
                parseFloat(markers[i].getAttribute("longitude")));
              if (activePoly_Id !== poly_Id) {
                var polyPointsArray = new Array();
                polyPointsArrays.push(polyPointsArray);
                var polyIdArray = new Array();
                polyIdArrays.push(polyIdArray);
                activePoly_Id = poly_Id;
                polylineIdArrays.push(poly_Id);
              }
              polyPointsArray.push(point);
              polyIdArray.push(id);
            }
            for (var j = 0; j < polyPointsArrays.length; j++) {
              if ((map.getCurrentMapType().getName()== 'Kort')||
                (map.getCurrentMapType().getName()== 'Map')) {
                //polyline = new GPolyline(polyPointsArrays[j], "#000000", 3, 0.5);
                polyline = new GPolyline(polyPointsArrays[j], "#797774", 3, 1);
              } else {
                polyline = new GPolyline(polyPointsArrays[j], "#ffffff", 3, 1);
              }

              polyline.id = j;
              polyline.polylineId = polylineIdArrays[j];
              polyline.tooltip = 'Adgang til fiskevandet';
              GEvent.addListener(polyline, "mouseover", function()
                {
                  showTooltip(this);
                }
              );

              GEvent.addListener(polyline, "mouseout", function()
                {
                  tooltip.style.display = "none";
                }
              );
              map.addOverlay(polyline);
            }
          // polyline = activePolyline;
          }
        }
      );
    }
  }
}

function showTooltip(line)
{
  var myPoint;
  if(mouseMove != null)
  {
    myPoint = mouseMove;
    //myPoint = map.getCenter();
  }
  else
  {
    myPoint = map.getCenter();
  }

  tooltip.innerHTML = line.tooltip;
  tooltip.style.display = "block";
  //if(typeof(tooltip.style.filter)=="string")
  //{
  //tooltip.style.filter = "alpha(opacity:70)";
  //}
  var currtype = map.getCurrentMapType().getProjection();
  var point = currtype.fromLatLngToPixel(map.fromDivPixelToLatLng
    (new
      GPoint(0, 0), true), map.getZoom()
  );
  var offset = currtype.fromLatLngToPixel(myPoint, map.getZoom());
  var ancho = 1;
  var width = 6;
  var height = 10;
  var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize
    (offset.x-
      point.x-ancho+width, offset.y-point.y-ancho-height)
  );
  pos.apply(tooltip);
}

function switchBlock(id,initialblock) {
  var myblock = document.getElementById(id);
	if (myblock.style.display == 'none') {
	  myblock.style.display = 'block';
	} else if (myblock.style.display == 'block') {
	  myblock.style.display = 'none';
	} else if (initialblock == 0) {
	  myblock.style.display = 'none';
	} else {
	  myblock.style.display = 'block';
	}
}

function showhideAll() {
  if (hideAll){
    showAccess= false;
    showLicense= false;
    showParking= false;
    showCrossing= false;
    showCamping= false;
    hideAll= false;
    document.getElementById("boxlink").innerHTML="Vis alle";
    var boxes = document.getElementsByName("mark");
    for(var i = 0; i < boxes.length; i++) {
      boxes[i].checked = false;}
    } else {
    showAccess= true;
    showLicense= true;
    showParking= true;
    showCrossing= true;
    showCamping= true;
    hideAll= true;
    document.getElementById("boxlink").innerHTML="Skjul alle";
    var boxes = document.getElementsByName("mark");
    for(var i = 0; i < boxes.length; i++) {
      boxes[i].checked = true;}
    }
 map.clearOverlays();
 loadPolylines();
 loadMarkers();
}


function toggleSymbol(checked, symbol) {

 if(symbol==5) {
  if (checked==false){
    showAccess= false;
  } else {
    showAccess= true;
  }
}

 if(symbol==0) {
  if (checked==false){
    showLicense= false;
  } else {
    showLicense= true;
  }
}

 if(symbol==1) {
  if (checked==false){
    showParking= false;
  } else {
    showParking= true;
  }
}

 if(symbol==2) {
  if (checked==false){
    showCrossing= false;
  } else {
    showCrossing= true;
  }
}

 if(symbol==3) {
  if (checked==false){
    showCamping= false;
  } else {
    showCamping= true;
  }
}
 map.clearOverlays();
 loadPolylines();
 loadMarkers();
}

function showLayerbox() {
 if(window.timer) clearTimeout(timer);
 document.getElementById("box").style.visibility = "visible";
 var button = document.getElementById("more_inner");
 button.style.borderBottomWidth = "4px";
 button.style.borderBottomColor = "white";
}


function setClose() {
  var layerbox = document.getElementById("box");
  timer = window.setTimeout(function() {
  layerbox.style.visibility = "hidden";
  var button = document.getElementById("more_inner");
  button.style.borderBottomWidth = "1px";
  button.style.borderBottomColor = "#c0c0c0";
 }, 400);
}

function MoreControl() {};
MoreControl.prototype = new GControl();
MoreControl.prototype.initialize = function(map) {

 var more = document.getElementById("outer_more");
 var buttonDiv = document.createElement("div");
 buttonDiv.id = "morebutton";
 //buttonDiv.title = "Show/Hide Layers";
 buttonDiv.style.border = "1px solid black";
 buttonDiv.style.width = "86px";
 var textDiv = document.createElement("div");
 textDiv.id = "more_inner";
 textDiv.appendChild(document.createTextNode("Symboler"));
 buttonDiv.appendChild(textDiv);

 // Register Event handlers
 more.onmouseover = showLayerbox;
 more.onmouseout = setClose;

 // Insert the button just after outer_more div
 more.insertBefore(buttonDiv, document.getElementById("box").parentNode);
 // Remove the whole div from its location and reinsert it to the map
 map.getContainer().appendChild(more);
 return more;
};


MoreControl.prototype.getDefaultPosition = function() {
 return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(491, 7));
};

function orderOfCreation(marker,b) {
  return marker.importance;
}
