////////////////////////////////////////////////////////////////////////////////
// Variables 
////////////////////////////////////////////////////////////////////////////////
// Global Variables :
var map;
var mapDiv;
var lastMouseButton;
var latLonPrecision = 100000;
var currentEmailLinkSubject = 'World%20Vantage%20Points';

var vantageIcon = new GIcon();
vantageIcon.image =  "/common/icons/markers/vantage.default.png";
vantageIcon.shadow = "/common/icons/markers/vantage.shadow.default.png";

// 8px radius :
vantageIcon.iconSize = new GSize(16, 16);
vantageIcon.shadowSize = new GSize(20, 12);
vantageIcon.iconAnchor = new GPoint(8, 8);
vantageIcon.infoWindowAnchor = new GPoint(16, 0);

// 12px radius :
vantageIcon.iconSize = new GSize(24, 24);
vantageIcon.shadowSize = new GSize(28, 20);
vantageIcon.iconAnchor = new GPoint(12, 12);
vantageIcon.infoWindowAnchor = new GPoint(24, 0);

// 16px radius :
vantageIcon.iconSize = new GSize(32, 32);
vantageIcon.shadowSize = new GSize(36, 28);
vantageIcon.iconAnchor = new GPoint(16, 16);
vantageIcon.infoWindowAnchor = new GPoint(32, 0);


////////////////////////////////////////////////////////////////////////////////
// Main setup/size methods 
////////////////////////////////////////////////////////////////////////////////
function onLoad() {
  mapDiv = document.getElementById("mapDiv");
  map = new GMap2(mapDiv);
  map.addControl(new GLargeMapControl());
  //map.addControl(new GMapTypeControl());
  map.addControl(new GOverviewMapControl());
  map.setCenter(defaultCenter, defaultZoomLevel);  
  map.setMapType(G_SATELLITE_MAP);   
  GEvent.addListener(map, 'moveend', updateCurrent);  
  GEvent.addListener(map, 'zoomend', updateCurrent);
  //setupMapOverlayTypes();

  GEvent.addDomListener(mapDiv, "DOMMouseScroll", map.wheelZoom);
  GEvent.addDomListener(mapDiv, "mousewheel", map.wheelZoom);
  setupLayers(true); // Setup the current layers by default, or via the url, or cookieXXX
  setURLViewport(); //  Set the viewport based on the url
  updateCurrent();
  loadMarkers();
}

function loadMarkers() {

  var url = baseURL + '/xml';
  url += '?ts=' + Math.random();
  var res = webRequest(url, username, password, false, loadMarkersResults);
}

function loadMarkersResults(res) {
  if ((!res) || (res.nodeName != 'markers')) {
    window.alert('Results invalid : ' + res);
    return;
  }

  for (var i=0; i < res.childNodes.length; i++) {
    var r = res.childNodes[i];
    if (r.nodeType == 1) { // Object.
      var foreignMarkerID = r.getAttribute('id');
      var title = r.getAttribute('title');
      var description = r.getAttribute('description');
      var latitude = parseFloat(r.getAttribute('latitude'));
      var longitude = parseFloat(r.getAttribute('longitude'));
      var altitude = parseFloat(r.getAttribute('altitude'));
      var pos = new GLatLng(latitude, longitude);

      var directions = r.getAttribute('directions');
      var image = r.getAttribute('image');

      var customVantageIcon = vantageIcon;
      var iconURL = r.getAttribute('icon_url');
      var shadowURL = r.getAttribute('shadow_url');
      if (iconURL&&shadowURL) {
	customVantageIcon = new GIcon(vantageIcon);
	customVantageIcon.image =  iconURL;
	customVantageIcon.shadow = shadowURL;
      }
      var marker;
      if (editMode)
	marker = addVantageEditableMarker(pos, title, description, altitude, foreignMarkerID, customVantageIcon, directions, image);
      else
	marker = addVantageMarker(pos, title, description, altitude, foreignMarkerID, customVantageIcon, directions, image);
    }
  }
  setURLViewportCustom(); // Set the popup if one is set in the url after we have loaded the marker info.
};

function newMarker() {
  // Create a new blank marker, and edit it :
  //var marker = addEditableMarker(map.getCenter(), '', '', 0, -1, vantageIcon);
  var marker = addVantageEditableMarker(map.getCenter(), '', '', 0, -1, vantageIcon, '', '');
  marker.editForm();
}

function updateCurrent() {
  // Update information about the current lat, lon and zoom
  var zoom = map.getZoom();
  var center = map.getCenter();
  var lat = center.y;
  var lon = center.x;
  var status = document.getElementById('currentLocation');
  if (status) status.innerHTML = Math.round(lon*latLonPrecision)/latLonPrecision + ', ' + Math.round(lat*latLonPrecision)/latLonPrecision; // + ' @ ' + zoom + '(' + (17-zoom) + ')';

  updateCurrentLinks();
}

function updateCurrentLinks() {
    var currentWebLink = document.getElementById('currentWebLink');
    var currentEmailLink = document.getElementById('currentEmailLink');
    var url = getBaseURL(document.location.href);
    if (currentWebLink)
      currentWebLink.href = url + '?' + getCurrentCurrentLinkParams(false) + '&' + getCustomLinkParams(false);

    if (currentEmailLink)
        currentEmailLink.href = "mailto:?subject=" + currentEmailLinkSubject +"&body=" + url + '%3F' + getCurrentCurrentLinkParams(true) + '%26' + getCustomLinkParams(true);
}

function getCustomLinkParams(isEmailLink) {
    var sep = '&';
    if (isEmailLink) sep = '%26';
    //return 'month=' + mapBackgroundMonth + sep + 'showMap=' + mapOverlayEnabled;
    if (currentMarker)
      return 'fid=' + currentMarker.foreignMarkerID;
    else
      return '';
}

function setupMapOverlayTypes() {
  // Setup the custom map overlay types :
  customMapType = setupHybridMapType('Rdr,Sat', new Array(getRadarOverlayURL), 3, 8, 'Copyright Australian BoM');
  customMapType = setupHybridMapType2('Rdr,Sat,Map', new Array(getRadarOverlayURL), 3, 8, '');
  map.setMapType(customMapType);

}

var radarExtents = new Array();
radarExtents[9] = new Array(192, 255, 128, 191);
radarExtents[10] = new Array(96, 127, 64, 95);
radarExtents[11] = new Array(48, 63, 32, 47);
radarExtents[12] = new Array(24, 31, 16, 23);
radarExtents[13] = new Array(12, 15, 8, 11);
radarExtents[14] = new Array(6, 7, 4, 5);
radarExtents[15] = new Array(3, 3, 2, 2);

function getRadarOverlayURL(pt, zoom){
  var x = pt.x;
  var y = pt.y;
  zoom = 17-zoom;

  var range = radarExtents[zoom]
  if (!range)  return 'http://www.thesnowchaser.com/maps/blank_tile.png';
  if ((pt.x < range[0])||(pt.x > range[1])||(pt.y < range[2])||(pt.y > range[3])) {
    GLog.writeHtml("<font color=black>Outside : " + pt.x + "," + pt.y + "@" + zoom + "</font>");
    return 'http://www.thesnowchaser.com/maps/blank_tile.png';
  }
  baseTileURL = 'http://www.thesnowchaser.com/maps/radar_tiles3/tile.';
  return baseTileURL + x + '.' + y + '.' + zoom + '.gif';
};


function setURLViewportCustom() {
    // Show the particular picture if we have one we know about :
    var q = getQueryString();
    var fid = q['fid'];
    if (typeof fid == 'undefined') return;
    fid = parseInt(fid);

    marker = markersLookup[fid];
    //window.alert(fid + ' ' + marker);
    if (marker == null)  return;

    marker.viewDetails(); // Show the popup
}
