﻿/*
* TimeTravel Explorer xJavascript
* -------------------------------
* J Barr
* -------------------------------
* Map functionality
* rev 0.98.1
* 24.03.2010 
* -------------------------------
*/

// init
var map;
var allowedBounds;

function loadMap(div, callback, lat, lng) {

    if (mapData !== "undefined") {
        if (GBrowserIsCompatible()){
	    
	        map = new GMap2(document.getElementById(div));
	        
            var mt = map.getMapTypes();
            
            // Overwrite the getMinimumResolution() and getMaximumResolution() methods
            if (typeof(mapData.zoom.min) !== 'undefined' && typeof(mapData.zoom.min) !== 'undefined') {
            
                for (var i=0; i<mt.length; i++) {
                    mt[i].getMinimumResolution = function() { return mapData.zoom.min; }
                    mt[i].getMaximumResolution = function() { return mapData.zoom.max; }
                }
            }
            
            if (typeof(mapData.topleft) !== 'undefined') {
                addMapMarker(mapData.topleft.Latitude, mapData.topleft.Longitude, "");
            }

            if (typeof(mapData.bottomright) !== 'undefined') {
                addMapMarker(mapData.bottomright.Latitude, mapData.bottomright.Longitude, "");
            }
            
            if (typeof (mapData.noControls) == "undefined") {
                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
            }
            
            if (typeof(lat) != "undefined" && typeof(lng) != "undefined"
            && lat != 0 && lng != 0) {
                map.setCenter(new GLatLng(lat, lng), mapData.zoom.center);
            } else {
                map.setCenter(new GLatLng(mapData.center.latitude, mapData.center.longitude), mapData.zoom.center);
            }
            // move listener: check and limit bounds
            if (typeof(mapData.bounds) !== "undefined") {
            
                GEvent.addListener(map, "move", function() {
                    checkBounds();
                });
                
                allowedBounds = new GLatLngBounds(
                    new GLatLng(mapData.bounds.sw.latitude, mapData.bounds.sw.longitude),
                    new GLatLng(mapData.bounds.ne.latitude, mapData.bounds.ne.longitude)
                );
            }
            
            // callbacks
            if (typeof(callback) !== 'undefined') {
                callback();
            }
	    }
	    else {
          alert("Sorry, the Google Maps API is not compatible with this browser");
        }
    }
}

function checkBounds() {
    // Perform the check and return if OK
    if (allowedBounds.contains(map.getCenter())) {
      return;
    }
    // It`s not OK, so find the nearest allowed point and move there
    var C = map.getCenter();
    var X = C.lng();
    var Y = C.lat();

    var AmaxX = allowedBounds.getNorthEast().lng();
    var AmaxY = allowedBounds.getNorthEast().lat();
    var AminX = allowedBounds.getSouthWest().lng();
    var AminY = allowedBounds.getSouthWest().lat();

    if (X < AminX) {X = AminX;}
    if (X > AmaxX) {X = AmaxX;}
    if (Y < AminY) {Y = AminY;}
    if (Y > AmaxY) {Y = AmaxY;}
    //alert ("Restricting "+Y+" "+X);
    map.setCenter(new GLatLng(Y,X));
}

function moveEnd() {

}

function zoomEnd() {

}

function addOverlay(callback) {
   
    var counter = 0;
    var mapTiles = function (a,b) { 
       var f = "/x.tile.provider.ashx?mapID=" + mapData.id
		            + "&quad=" + TileToQuadKey(a.x,a.y,b);
       return f;
    };
   	    
    var tilelayer = new GTileLayer(GCopyrightCollection(''), 5, 10);
    tilelayer.opacity = 1.0; // Default opacity value
    tilelayer.getTileUrl = mapTiles;
    tilelayer.isPng = function() { return true;}; // Transparency is active
    tilelayer.getOpacity = function() { return this.opacity; }
    overlay = new GTileLayerOverlay( tilelayer );
    map.addOverlay(overlay);

    if (typeof (mapData.noControls) == "undefined") {
        map.addControl(new OpacityControl(overlay));
    }
		
    if (typeof(callback) !== 'undefined') {
        callback();
    }
}

function addMapMarker(lat, lon, info) {

    var point = new GLatLng(lat, lon);
    var marker = new GMarker(point);

    if (typeof(info) !== "undefined") {
    
        GEvent.addListener(marker, "click", function() {
            marker.openInfoWindowHtml(info);
        });
    }
    
    map.addOverlay(marker);
}

function addClickListener(txtLatitudeID, txtLongitudeID, txtZoomID) {

    // click event listener
    GEvent.addListener(map, 'click', function(overlay, point) {
        if (overlay) {
            //map.removeOverlay(overlay);
        } else if (point) {
            //map.clearOverlays(); 
            var marker = new GMarker(point);
            map.addOverlay(marker);         

            var matchll = /\(([-.\d]*), ([-.\d]*)/.exec( point );
            if ( matchll ) { 
	            lat = parseFloat( matchll[1] );
	            lon = parseFloat( matchll[2] );
	            lat = lat.toFixed(6);
	            lon = lon.toFixed(6);
            } 
            $(txtLatitudeID).attr("value", lat);
            $(txtLongitudeID).attr("value", lon);
            $(txtZoomID).attr("value", map.getZoom());
        }
    });
}

function TileToQuadKey ( x, y, zoom){
    var quad = "";
    for (var i = zoom; i > 0; i--){
        var mask = 1 << (i - 1);
        var cell = 0;
        if ((x & mask) != 0) {
            cell++;
        }
        if ((y & mask) != 0) {
            cell += 2;
        }
        quad += cell;
    }
    return quad;
}

// hmmm needs work
function autoMove() {
    var centerLat = map.getCenter().lat(); 
    var centerLng = map.getCenter().lng() - 0.01; 
    map.setCenter(new GLatLng(centerLat, centerLng), 2); 
    setTimeout(autoMove, 500); 
}   	    

// Opacity slider control
function OpacityControl( overlay ) {
  this.overlay = overlay;
}
OpacityControl.prototype = new GControl();

// This function positions the slider to match the specified opacity
OpacityControl.prototype.setSlider = function(pos) {
  var left = Math.round((58*pos));
  this.slide.left = left;
  this.knob.style.left = left+"px";
  this.knob.style.top = "0px"; // correction001
}

// This function reads the slider and sets the overlay opacity level
OpacityControl.prototype.setOpacity = function() {
  this.overlay.getTileLayer().opacity = this.slide.left/58;
  this.map.removeOverlay(this.overlay);
  this.map.addOverlay(this.overlay);
}

// This gets called by the API when addControl(new OpacityControl())
OpacityControl.prototype.initialize = function(map) {
  var that=this;
  this.map = map;

  // Is this MSIE, if so we need to use AlphaImageLoader
  var agent = navigator.userAgent.toLowerCase();
  if ((agent.indexOf("msie") > -1) && (agent.indexOf("opera") < 1)){this.ie = true} else {this.ie = false}

  // create the background graphic as a <div> containing an image
  var container = document.createElement("div");
  container.style.width="70px";
  container.style.height="21px";

  // Handle transparent PNG files in MSIE
  if (this.ie) {
    var loader = "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader("+
      "src='/images/furniture/opacity-slider.png', sizingMethod='crop');";
    container.innerHTML = '<div style="height:21px; width:70px; ' +loader+ '" ></div>';
  } else {
    container.innerHTML = '<div style="height:21px; width:70px; background-image: url(/images/furniture/opacity-slider.png)" ></div>';
  }

  // create the knob as a GDraggableObject
  // Handle transparent PNG files in MSIE
  if (this.ie) {
    var loader = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='/images/furniture/opacity-slider.png', sizingMethod='crop');";
    this.knob = document.createElement("div");
    this.knob.style.height="21px";
    this.knob.style.width="13px";
    this.knob.style.overflow="hidden";
    this.knob_img = document.createElement("div");
    this.knob_img.style.height="21px";
    this.knob_img.style.width="83px";
    this.knob_img.style.filter=loader;
    this.knob_img.style.position="relative";
    this.knob_img.style.left="-70px";
    this.knob.appendChild(this.knob_img);
  } else {
    this.knob = document.createElement("div");
    this.knob.style.height="21px";
    this.knob.style.width="13px";
    this.knob.style.backgroundImage="url(/images/furniture/opacity-slider.png)";
    this.knob.style.backgroundPosition="-70px 0px";
  }
  container.appendChild(this.knob);
  this.slide=new GDraggableObject(this.knob, {container:container});
  this.slide.setDraggableCursor('pointer');
  this.slide.setDraggingCursor('pointer');
  this.container = container;

  // attach the control to the map
  map.getContainer().appendChild(container);

  // init slider
  this.setSlider( this.overlay.getTileLayer().opacity );

  // Listen for the slider being moved and set the opacity
  GEvent.addListener(this.slide, "dragend", function() {that.setOpacity()});
  //GEvent.addListener(this.container, "click", function( x, y ) { alert(x, y) });

  return container;
}

// Set the default position for the control
OpacityControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 47));
}
