function saveMapState() {
  var lat = window.map.getCenter().y;
  var lon = window.map.getCenter().x;
  var zoom = window.map.getZoom();
  var maptype = window.map.getCurrentMapType().getName();
  document.cookie = 'maptype=' + maptype;
  document.cookie = 'zoom=' + zoom;
  document.cookie = 'lat=' + lat;
  document.cookie = 'lon=' + lon;
}

function updateWidthAndHeight() {
  if (!window.event) {
    w = window.innerWidth;
    h = window.innerHeight;
  } else {
    // IE
    w = document.body.offsetWidth - 4;
    h = document.body.offsetHeight - 4;
  }
  //alert('w=' + w + ',h=' + h);
}

/**
 * Loads map state from cookies or uses default values if no cookies are found.
 */
/*function loadInitialMapState() {
  initialZoom = getCookieValue('zoom');
  if (!initialZoom) {
    initialZoom = 7;
  }
      
  initialLat = getCookieValue('lat');
  if (!initialLat) {
    initialLat = 59.4;
  }
      
  initialLon = getCookieValue('lon');
  if (!initialLon) {
    initialLon = 18.4;
  }
      
  initialMaptype = getCookieValue('maptype');
}*/

function setCookie(name, value, expires, path, domain, secure) {
  // set time, it's in milliseconds
  var today = new Date();
  today.setTime(today.getTime());

  /*
  if the expires variable is set, make the correct 
  expires time, the current script below will set 
  it for x number of days, to make it for hours, 
  delete * 24, for minutes, delete * 60 * 24
  */
  if (expires) {
    expires = expires * 1000 * 60 * 60 * 24;
  }
  var expires_date = new Date(today.getTime() + (expires));

  document.cookie = name + "=" + escape(value) +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) + 
    ( ( path ) ? ";path=" + path : "" ) + 
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

/**
 * param point              GLatLng where to place the marker
 * icon                     GIcon for GMarker
 * bp                       BoatPosition object
 * bd                       BoatData object
 */
function createMarker(point, icon, bp, bd) {
  var m = new GMarker(point, icon);

  GEvent.addListener(m, 'mouseover', function() {
    var pt = map.fromLatLngToDivPixel(m.getPoint());
    var newiw = new PositionInfoWindow(bp, bd, pt.x, pt.y);
   
    var iw = document.getElementById('position_info_window');
    if (iw != null) {
      document.body.removeChild(iw);
    } else {
    }
    document.body.appendChild(newiw);
    showHelpText(helpPositioning);
  });

  GEvent.addListener(m, 'mouseout', function() {
    var iw = document.getElementById('position_info_window');
    if (iw != null) {
      document.body.removeChild(iw);
    }
    hideHelpText();
  });
  return m;
}

function configureRaceBar(pct) {

// 355 + 8
  var totalWidth = 355;
  var leftWidth = totalWidth * pct;
  var rightWidth = totalWidth - leftWidth;
  
  var leftImg = document.getElementById('racebarLeft');
  var rightImg = document.getElementById('racebarRight');
  
  leftImg.width = leftWidth;
  rightImg.width = totalWidth - leftWidth;
  
}

/**
 * Draws lines (GPolyLines) between the boats' positions
 */
function showLines(show) {
  if (!show) {
    // hide the lines
    hideLines();
  } else {
    // show the lines
    for  (i = 0; i < boatdata.length; i++) {
      if (boatdata[i].getLine() != null) {
        // lines are already shown
        break;
      }
      var boatId = boatdata[i].getId();
      var points = [];
      var boatPositions = boatdata[i].positions;
      for (j = 0; j < boatPositions.length; j++) {
        var lat = boatPositions[j].getLatitude();
        var lon = boatPositions[j].getLongitude();
        var point = new GLatLng(lat, lon);
        points.push(point);
      }
      
      if (points.length > 0) { // there might not be any positions yet
        var line = new GPolyline(points, boatdata[i].symbol.lineColor, 2);
        boatdata[i].setLine(line);
        window.map.addOverlay(line);
      }
    }  
  }
}

/**
 * Draws lines between checkpoints
 */
function showRhumbline(show) {
  if (!show) {
    if (rhumbline != null) {
      map.removeOverlay(rhumbline);
      rhumbline = null;
    }
  } else {
    if (rhumbline != null) {
      // line already shown, do nothing
    } else {
      var points = [];
      for (i = 0; i < checkpoints.length; i++) {
        var lat = checkpoints[i].lat;
        var lon = checkpoints[i].lon;
        var point = new GLatLng(lat, lon);
        points.push(point);
      }
      
      if (points.length > 0) {
        rhumbline = new GPolyline(points, '#cccccc', 1);
        map.addOverlay(rhumbline);
        
      }
    
    }
  }
}

function showTracks(selIndex, mode) {
  var url = document.location.toString();
  
  if (selIndex == 0) {
    // don't show any tracks
    document.cookie = mode + '_tracks=off';
    showLines(false);
  } else if (selIndex == 1) {
    // current tracks only
    document.cookie = mode + '_tracks=current';
    if (loadedPositions != 'current') {
      document.location = url;
    } else {
      showLines(true);
    }
  } else if (selIndex == 2) {
    // all tracks
    document.cookie = mode + '_tracks=all';
    if (loadedPositions != 'all') {
      document.location = url;
    } else {
      showLines(true);
    }
  } else {
    alert('showTracks(' + selIndex + '), don\'t know what to do');
  }
}

/**
 * Hides the lines (GPolyLines).
 */
function hideLines() {
  for (i = 0; i < boatdata.length; i++) {
    var line = boatdata[i].getLine();
    if (line != null) {
      map.removeOverlay(line);
      boatdata[i].setLine(null);
    }
  }
}

/**
 * Shows a small marker on each of the boat's past positions.
 *
 * @param show If false, the markers are removed. If true, they are shown.
 */
function showMarkers(show) {
  if (!show) {
    // hide the markers
    hideMarkers();
  } else {
    // show the markers
    for  (i = 0; i < boatdata.length; i++) {
      var boatId = boatdata[i].getId();
      var boatPositions = boatdata[i].positions;
      for (j = 0; j < boatPositions.length; j++) {
        if (boatPositions[j].getMarker() != null) {
          //  markers already shown
          break;
        }
        var lat = boatPositions[j].getLatitude();
        var lon = boatPositions[j].getLongitude();
        var point = new GLatLng(lat, lon);
            
        if (j < boatPositions.length - 1) {
          // add small symbol
          var icon = boatdata[i].getSmallIcon();
          var marker = createMarker(point, icon, boatPositions[j]);
          boatPositions[j].setMarker(marker);
          window.map.addOverlay(marker);
        }
      }
    }  
  }
}

/**
 * Hides the small icons (GMarkers).
 */
function hideMarkers() {
  for (i = 0; i < boatdata.length; i++) {
    var boatPositions = boatdata[i].positions;
    for (j = 0; j < boatPositions.length; j++) {
      if (j >= boatPositions.length - 1) {
        break;
      }
      var marker = boatPositions[j].getMarker();
      map.removeOverlay(marker);
    }
  }
}


/**
 * Shows the boat's current (last known) position.
 */
function showBoats() {
  for (i = 0; i < boatdata.length; i++) {
    if (boatdata[i].positions.length > 0) {
      if (boatdata[i].status != 'Active') {
        // don't show retired etc boats on the map
        continue;
      }
      var lastPosition = boatdata[i].positions[boatdata[i].positions.length - 1];
      var lat = lastPosition.getLatitude();
      var lon = lastPosition.getLongitude();
      var point = new GLatLng(lat, lon);
      var icon = boatdata[i].getIcon(lastPosition.getCog());
      var marker = createMarker(point, icon, lastPosition, boatdata[i]);
      lastPosition.setMarker(marker);
      map.addOverlay(marker);
    }
  }
}

/**
 * Shows checkpoints.
 */
function showCheckpoints(show) {
  if (show) {
    for (i = 0; i < checkpoints.length; i++) {
      var cp = checkpoints[i];
      var point = new GLatLng(cp.lat, cp.lon);
      //if (i == 0 || i == checkpoints.length - 1) { 
      if (cp.no == 0 || cp.no == 1000) {
        var icon = cp.getLargeIcon();
      } else {
        var icon = cp.getSmallIcon();
      }
      var marker = createCheckpointMarker(point, icon, cp);
      map.addOverlay(marker);
    }
  }
}

function createCheckpointMarker(point, icon, cp) {
  var m = new GMarker(point, icon);
  GEvent.addListener(m, 'mouseover', function() {
    var pt = map.fromLatLngToDivPixel(m.getPoint());
    var infowin = new CheckpointInfoWindow(cp, pt.x, pt.y);
    var cpiw = document.getElementById('checkpoint_info_window');
    if (cpiw != null) {
      document.body.removeChild(cpiw);
    }
    document.body.appendChild(infowin);
  });

  GEvent.addListener(m, 'mouseout', function() {
    var cpiw = document.getElementById('checkpoint_info_window');
    if (cpiw != null) {
      document.body.removeChild(cpiw);
    }
  });
    
  return m;
}

function showTeamInfoWindow(e, id) {
  var iw = document.getElementById('team_info_window');
  if (iw != null) {
    document.body.removeChild(iw);
  }
  
  var bd = getBoatData(id);
  if (bd == null) {
    // something's wrong
    alert('bd == null');
    return;
  }
  
  var x, y;
  if (e.pageX) {
    x = e.pageX;
    y = e.pageY;
  } else {
    x = e.clientX;
    y = e.clientY;
  }
  document.body.appendChild(new TeamInfoWindow(bd, x, y));
  //var cb = document.getElementById('fav');
  //cb.checked = isFavourite(id);
}

/**
 * Picks the right BoatData entry from the array.
 */
function getBoatData(boatId) {
  var bd = null;
  for (i = 0; i < boatdata.length; i++) {
    if (boatdata[i].id == boatId) {
      bd = boatdata[i];
    }
  }
  return bd;
}
/**
 * Opens the 'Select favourites' window.
 */ 
function showFavourites() {  
  var params = "width=700,height=540,resizable=yes,status=no," +
    "left=" + Math.ceil(screen.availWidth/2 - 700/2) + "," +
    "top=" + Math.ceil(screen.availHeight/2 - 500/2);
  var url = 'frontend_favourites.php';

  favWindow = window.open(url, 'LiveTracker', params);  
}

/**
 * Opens the 'Teams' window.
 */ 
function showTeams() {  
  var params = "width=700,height=540,resizable=yes,status=no," +
    "left=" + Math.ceil(screen.availWidth/2 - 700/2) + "," +
    "top=" + Math.ceil(screen.availHeight/2 - 500/2);
  var url = 'frontend_teams.php';

  favWindow = window.open(url, 'LiveTracker', params);  
}

/**
 * Opens the 'Help' window.
 */ 
function showHelp() {  
  var params = "width=700,height=500,resizable=yes,status=no,scrollbars=yes," +
    "left=" + Math.ceil(screen.availWidth/2 - 700/2) + "," +
    "top=" + Math.ceil(screen.availHeight/2 - 500/2);
  var url = 'frontend_help.php';

  helpWindow = window.open(url, 'LiveTracker', params);  
}

function setFavourite(id) {
  var a = getCookieValue('favourites');
  if (isFavourite(id)) {
    // remove from favourites
    var favs = getCookieValue('favourites').split(',');
    if (favs.length == 0) {
      // only 1 favourite
      document.cookie = 'favourites=';
    } else {
      var commaSeparatedFavs = '';
      for (i = 0; i < favs.length; i++) {
        if (favs[i] == id) {
          continue;
        }
        if (i > 0 && commaSeparatedFavs != '') {
          commaSeparatedFavs += ',';
        }
        commaSeparatedFavs += favs[i];
      }
      document.cookie = 'favourites=' + commaSeparatedFavs;
    }
  } else {
    // add to favourites
    var currentFavs = getCookieValue('favourites');
    if (currentFavs && currentFavs != '') {
      document.cookie = 'favourites=' + currentFavs + ',' + id;
    } else {
      document.cookie = 'favourites=' + id;
    }
  }
  var b = getCookieValue('favourites');
  //alert('first: ' + a + ', now: ' + b);
}

/**
 * Checks if a specific boat is one of user's favourites.
 */
function isFavourite(id) {
  var isFav = false;
  if (document.cookie && getCookieValue('favourites')) {
    var favs = getCookieValue('favourites').split(',');
    if (favs && favs.length > 0) {
      for (i = 0; i < favs.length; i++) {
        if (favs[i] == id) {
          isFav = true;
        }
      }
    }
  }
  //alert(id + ' isFav == ' + isFav);
  return isFav;
}

function showFullScreen(queryString) {

  var w = screen.availWidth;
  var h = screen.availHeight;
  //w = 1000;
  //h = 750;
  
  var params = 'width=' + w + ',height=' + h + ',resizable=yes,status=no';
  //  "left=" + Math.ceil(screen.availWidth/2 - /2) + "," +
  //  "top=" + Math.ceil(screen.availHeight/2 - 500/2);
  var url = 'frontend_fullscreen.php?' + queryString;
  
  fullscreen = window.open(url, 'LiveTracker2', params);  
}

function hideTeamInfoWindow() {
  document.body.removeChild(document.getElementById("team_info_window"));
}

function toDegMinSecPos(dec) {
  var degrees = Math.floor(dec);
  var frac = (dec - degrees) * 100;
  frac = frac * 60 / 100;
  var min = Math.floor(frac);
  frac = (frac - min) * 100;
  frac = frac * 60 / 100;
  var sec = Math.floor(frac);
  
  return new DegMinSecPos(degrees, min, sec);
}


