var map;

var MapsHandler = new Class({
	initialize: function(){
		this.geocoder = new GClientGeocoder();
		this.map = null;
		this.directions = null;
		this.language = "de";
		if (GBrowserIsCompatible()) {
			
        	this.map = new GMap2($("map"));
        	this.map.addControl(new GLargeMapControl());
			//this.map.addControl(new GMapTypeControl());
			$('search').addEvent('submit', function(e){
				new Event(e).stop();
				this.searchForRoute();
			}.bind(this));
			$('submit').addEvent('click', function(e){
					this.searchForRoute();
			}.bind(this));
        	this.showAddress('Feuerseeplatz 14, Stuttgart');
        	
        	if ($('map').hasClass('en')) {
        		this.language = "en";
        	}
     	 }
	},
	
	showAddress: function(address){
		this.geocoder.getLatLng(address, this.geoCodeCallback.bind(this));
	},
	
	geoCodeCallback: function(point){
		this.map.setCenter(point, 17);
		
        this.directions = new GDirections(this.map, $('panel'));
        GEvent.addListener(this.directions , "error", this.handleErrors.bind(this));
		
			
      
		var station = new GMarker(new GLatLng(48.784191,9.182253), this.getIcon('train'));
		this.map.addOverlay(station);
		
		var airport = new GMarker(new GLatLng(48.690365,9.191587), this.getIcon('airport'));
		this.map.addOverlay(airport);
		
		var sbahn = new GMarker(new GLatLng(48.77273,9.165612), this.getIcon('sbahn', {size:30, iconAnchor:15 }) );
		this.map.addOverlay(sbahn);
		
		var home = new GMarker(point, this.getHomeIcon());
		this.map.addOverlay(home);

		var infoBoxOptions = {
        "content": '<strong>Intuity Media Lab</strong><br />Feuerseeplatz 14,<br /> 70176 Stuttgart',
        "offsetHorizontal": 0,
        "offsetVertical": -80,
        "height": 80,
        "width": 150,
        "className": "infoBox"
      	};
      	var homeBox = new InfoBox(point, infoBoxOptions);
      	home.infoBox = homeBox;
      	GEvent.addListener(home, "click", function () {
        	if (this.map.infoBox) {
          		this.map.removeOverlay(this.map.infoBox);
        	}
       		this.map.infoBox = home.infoBox;
        	this.map.addOverlay(this.map.infoBox);
      	}.bind(this));
      	
		var sbahnBoxOptions = {
        "content": '<strong>Haltestelle Feuersee</strong><br />S4, S5, S6<br />',
        "offsetHorizontal": -20,
        "offsetVertical": -60,
        "height": 80,
        "width": 150,
        "className": "infoBox"
      	};
      	var sbahnBox = new InfoBox(new GLatLng(48.77273,9.165612), sbahnBoxOptions);
      	sbahn.infoBox = sbahnBox;
      	
      	GEvent.addListener(sbahn, "click", function () {
        	if (this.map.infoBox) {
          		this.map.removeOverlay(this.map.infoBox);
        	}
       		this.map.infoBox = sbahn.infoBox;
        	this.map.addOverlay(this.map.infoBox);
      	}.bind(this));

		
		this.map.setMapType(G_SATELLITE_TYPE);
        this.map.setZoom(17);
	},

	searchForRoute: function(){
		var startAddress = $('start').getValue();
		if (!startAddress.contains('deutschland','Deutschland','germany','Germany')) {
			startAddress += ', Deutschland';
		}
		this.directions.load('from: ' + startAddress + ' to: Feuerseeplatz 14, Stuttgart', { "locale": this.language });
		this.map.setMapType(G_MAP_TYPE);
	},
	
	handleErrors: function(){
		if (this.language=="en") {
			$('panel').innerHTML = 'Sorry we could\'t find your address. Please try another one ...';
		} else {
			$('panel').innerHTML = 'Leider konnten wir Ihre Adresse nicht finden. Bitte versuchen Sie eine andere ...';
		}
		
	},
	
	getHomeIcon: function(){
		var icon = new GIcon();
		icon.image = _root + "/workspace/img/map/ity.png";
		icon.iconSize = new GSize(87, 47);
		icon.iconAnchor = new GPoint(5, 43);
		icon.infoWindowAnchor = new GPoint(5, 43);
		return icon;
	},
	
	getIcon: function(id, options){
		var icon = new GIcon();
		icon.image = "http://test.intuity.de/cms/workspace/img/map/"+id+".png";
		if (options && options.size) {
			icon.iconSize = new GSize(options.size, options.size);
		} else {
			icon.iconSize = new GSize(47, 47);
		}// end if
		if (options && options.iconAnchor) {
			icon.iconAnchor = new GPoint(options.iconAnchor, options.iconAnchor);
		} else {
			icon.iconAnchor = new GPoint(5, 43);
		}// end if
		icon.infoWindowAnchor = new GPoint(40, 6);
		return icon;
	}

});


window.addEvent('domready', function(){
	map = new MapsHandler();
});










/* An InfoBox is like an info window, but it displays
 * under the marker, opens quicker, and has flexible styling.
 * @param {GLatLng} latlng Point to place bar at
 * @param {Object} opts Passes configuration options - content, 
 *   offsetVertical, offsetHorizontal, className, height, width
 */
function InfoBox(latlng, opts) {
  this.latlng_ = latlng;
  this.content_ = opts.content || "Hello World";
  this.offsetVertical_ = opts.offsetVertical || -5;
  this.offsetHorizontal_ = opts.offsetHorizontal || -5;

  this.className_ = opts.className || "";  
  this.height_ = opts.height || 200;
  this.width_ = opts.width || 300;
}

/* InfoBox extends GOverlay class from the Google Maps API
 */
InfoBox.prototype = new GOverlay();

/* Creates the DIV representing this InfoBox
 * @param {GMap2} map The map to add infobox to
 */
InfoBox.prototype.initialize = function(map) {
  // Create the DIV representing our Bar
  var div = document.createElement("div");

  if (this.className_ != "") {
    div.className = this.className_;
  } else {
    div.style.border = "1px solid #000000";
    div.style.position = "absolute";
    //div.style.background = "url('http://ace.imageg.net/images/WIZ_ACE_myStore/mapBubble.png')";
    //div.style.backgroundColor = "#FFFFFF";
    div.style.padding = "2px";
    div.style.width = this.width_ + "px";
    div.style.height = this.height_ + "px";
  } 

  var contentDiv = document.createElement("div");
  contentDiv.innerHTML = this.content_;

  var topDiv = document.createElement("div");
  
  var closeImg = document.createElement("img");
  closeImg.src = "/cms/workspace/img/map/close.gif";
  topDiv.appendChild(closeImg);
  $(topDiv).addClass("close-link");
  function removeInfoBox(ib, m) {
    return function() { 
      GEvent.trigger(ib, "closeclick");
      m.removeOverlay(ib);
    };
  }
  
  GEvent.addDomListener(closeImg, 'click', removeInfoBox(this, map));
 
  div.appendChild(topDiv);
  div.appendChild(contentDiv);
  div.style.display = 'none';

  map.getPane(G_MAP_MARKER_PANE).appendChild(div);

  this.map_ = map;
  this.div_ = div;
}

/* Remove the main DIV from the map pane
 */
InfoBox.prototype.remove = function() {
  this.div_.parentNode.removeChild(this.div_);
}

/* Copy our data to a new InfoBox
 * @return {InfoBox} Copy of infobox
 */
InfoBox.prototype.copy = function() {
  var opts = {};
  opts.latlng = this.latlng_;
  opts.content = this.content_;
  opts.offsetVertical = this.offsetVertical_;
  opts.offsetHorizontal = this.offsetHorizontal_;

  opts.className = this.className_ || "";  
  opts.height = this.height_;
  opts.width = this.width_;
  return new InfoBox(this.latlng, opts);
}

/* Redraw the Bar based on the current projection and zoom level
 * @param {boolean} force Helps decide whether to redraw overlay
 */
InfoBox.prototype.redraw = function(force) {
  // We only need to redraw if the coordinate system has changed
  if (!force) return;

  // Calculate the DIV coordinates of two opposite corners of our bounds to
  // get the size and position of our Bar
  var pixPosition = this.map_.fromLatLngToDivPixel(this.latlng_);

  // Now position our DIV based on the DIV coordinates of our bounds
  this.div_.style.width = this.width_ + "px";
  this.div_.style.left = (pixPosition.x + this.offsetHorizontal_) + "px";
  this.div_.style.height = this.height_ + "px";
  this.div_.style.top = (pixPosition.y + this.offsetVertical_) + "px";
  this.div_.style.display = 'block';

  // if we go beyond map, pan map
  var mapWidth = this.map_.getSize().width;
  var mapHeight = this.map_.getSize().height;
  var bounds = this.map_.getBounds();
  var boundsSpan = bounds.toSpan();
  var longSpan = boundsSpan.lng();
  var latSpan = boundsSpan.lat();
  var degWidth = (this.width_/mapWidth) * longSpan;
  var degHeight = (this.height_/mapHeight) * latSpan;

  if (this.latlng_.lng() + degWidth > bounds.getNorthEast().lng()) {
    this.map_.panTo(this.latlng_);
  }   

  var bottompt = new GLatLng( (this.latlng_.lat() - degHeight), this.latlng_.lng());
  if (!bounds.contains(bottompt)) {
    this.map_.panTo(this.latlng_);
  }
  
}

