var gmarkers = [];
var tweetMarkers = [];
var fsMarkers = [];
var mobyMarkers = [];
var map;
//Client side geocoder
var geocoder;

// Check if the api exists
if(typeof GOverlay == 'function') {

  var popupHTML;
  var tooltipHTML;
  var tempMarker = null;
  var openMarker = null;
  var openMarkerID = 0;
  
  // Initialize map
  function initialize(userid,type) {
    if (GBrowserIsCompatible()) {
      geocoder = new GClientGeocoder();
		  map = new GMap2(document.getElementById("map_canvas"));
		  if(parseFloat(readCookie('lat')) >= -90 && !getParameterByName('embed')) {
			  map.setCenter(new GLatLng(readCookie('lat'),readCookie('lon')), parseFloat(readCookie('zoom')));
		  }
		  // If client location was successfully resolved by Google AJAX API
		  else if(google.loader.ClientLocation != null) {
		    map.setCenter(new GLatLng(google.loader.ClientLocation.latitude, google.loader.ClientLocation.longitude), 6);
		  }
		  else {
			  map.setCenter(new GLatLng(31.613471646270444, 2.8125), 3);
		  }
		  map.addControl(new GSmallZoomControl3D());	
			map.setMapType(G_PHYSICAL_MAP);
			map.enableScrollWheelZoom();
		  // Save location
		  GEvent.addListener(map, "moveend", function() {
		    center = map.getCenter();
		    createCookie('lon',center.lng(),1);
				createCookie('lat',center.lat(),1);
				createCookie('zoom',map.getZoom(),1);
		  });
		  // Load Pois
		  getNewPois(userid,type);
		  // Initialize heat map
		  initHeatMap();
		  // Initialize WK2010
		  // RWE: been there done that
		  // initialize_wk2010();
		} else {
			document.getElementById("map_canvas").innerHTML = "<strong>Your Browser is not compatible!</strong>";
		}
  }
  
  // Trim String
  function trim(value) {
    value = value.replace(/^\s+/,'');
    value = value.replace(/\s+$/,'');
    return value;
  }
  
  // Tooltip for label display
  function ToolTip(marker,index,html,width) {
		this.html_ = html;
		this.index_ = index;
		this.width_ = (width ? width + 'px' : 'auto');
		this.marker_ = marker;
  }

  ToolTip.prototype = new GOverlay();

  ToolTip.prototype.initialize = function(map) {
		var div = document.createElement("div");
		div.style.display = 'none';
		map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
		
		this.map_ = map;
		this.container_ = div;
  }

  ToolTip.prototype.remove = function() {
		this.container_.parentNode.removeChild(this.container_);
  }

  ToolTip.prototype.copy = function() {
		return new ToolTip(this.html_);
  }

  ToolTip.prototype.redraw = function(force) {
		if (!force) return;
		
		var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
		this.container_.innerHTML = this.html_;
		this.container_.style.position = 'absolute';
		this.container_.style.left = (pixelLocation.x + 22) + "px";
		this.container_.style.top = (pixelLocation.y - 50) + "px";
		this.container_.style.width = this.width_;
		
		//one line to desired width
		this.container_.style.whiteSpace = 'nowrap';
		if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
		this.container_.style.display = 'block';
  }

  GMarker.prototype.ToolTipInstance = null;

  GMarker.prototype.openToolTip = function(content,index) {
		//don't show the tool tip if there is acustom info window
		if(this.ToolTipInstance == null) {
			this.ToolTipInstance = new ToolTip(this,index,content)
			map.addOverlay(this.ToolTipInstance);
		}
  }

  GMarker.prototype.closeToolTip = function() {
		if(this.ToolTipInstance != null) {
			map.removeOverlay(this.ToolTipInstance);
			this.ToolTipInstance = null;
		}
  }

  //Infowindow for detail popup
  function infoWindow(marker,html,width) {
		this.html_ = html;
		this.width_ = (width ? width + 'px' : 'auto');
		this.marker_ = marker;
  }
  
  infoWindow.prototype = new GOverlay();
  
  infoWindow.prototype.initialize = function(map) {
		var div = document.createElement("div");
		div.style.display = 'none';
		map.getPane(G_MAP_FLOAT_PANE).appendChild(div);
		
		this.map_ = map;
		this.container_ = div;
  }
  
  infoWindow.prototype.remove = function() {
		this.container_.parentNode.removeChild(this.container_);
  }
  
  infoWindow.prototype.copy = function() {
		return new infoWindow(this.html_);
  }
  
  infoWindow.prototype.redraw = function(force) {
		if (!force) return;
		
		var pixelLocation = this.map_.fromLatLngToDivPixel(this.marker_.getPoint());
		this.container_.innerHTML = this.html_;
		this.container_.style.position = 'absolute';
		this.container_.style.left = (pixelLocation.x + 22) + "px";
		this.container_.style.top = (pixelLocation.y - 50) + "px";
		this.container_.style.display = 'block';
		
		//one line to desired width
		//this.container_.style.whiteSpace = 'nowrap';
		if(this.width_ != 'auto') this.container_.style.overflow = 'hidden';
		this.container_.style.display = 'block';
  }
  
  GMarker.prototype.infoWindowInstance = null;
  
  GMarker.prototype.openinfoWindow = function(content) {
		//don't show the tool tip if there is acustom info window
		if(this.infoWindowInstance == null) {
			this.infoWindowInstance = new infoWindow(this,content)
			pixelLocation = map.fromLatLngToDivPixel(this.getPoint());
			allowedBounds = map.getBounds();
			//if(!allowedBounds.contains(map.fromDivPixelToLatLng(GPoint(pixelLocation.x, pixelLocation.y)))){
				//resize
			//}
			map.addOverlay(this.infoWindowInstance);
		}
  }
  
  GMarker.prototype.closeinfoWindow = function() {
		if(this.infoWindowInstance != null) {
			map.removeOverlay(this.infoWindowInstance);
			this.infoWindowInstance = null;
		}
  }

  // Create our marker icon
  var defaultIcon = new GIcon(G_DEFAULT_ICON);
  defaultIcon.image = "/images/markers/icon-normal.png";
  defaultIcon.shadow = "none";
  defaultIcon.iconSize = new GSize(31, 43);
  defaultIcon.shadowSize = new GSize(0,0);
  defaultIcon.iconAnchor = new GPoint(2, 10);
  defaultIcon.infoWindowAnchor = new GPoint(9, 2);

  // Create our base marker icon
  var baseIcon = new GIcon();
  baseIcon.shadow = "none";
  baseIcon.iconSize = new GSize(31, 43);
  baseIcon.iconAnchor = new GPoint(15, 43);
	
	var tweetIcon = new GIcon(baseIcon,'/images/markers/icon-tweet.png');
	var foursquareIcon = new GIcon(baseIcon,'/images/markers/icon-foursquare.png');
	var mobypicIcon = new GIcon(baseIcon,'/images/markers/icon-mobypic.png');

  // Function to place POI's on the MAP
  function createMarker(point, index, label, id, type, lon, lat, user, body) {
		var marker;
		switch(type) {
			case 'twitter':
				marker = new GMarker(point,tweetIcon);
				break;
			case 'foursquare':
				marker = new GMarker(point,foursquareIcon);
				break;
			case 'mobypicture':
				marker = new GMarker(point,mobypicIcon);
				break;
		}
		
	
		// Create popup html for marker detail
		tooltipHTML[id] = '';
		if(trim(label)!=""){
		  tooltipHTML[id] = tooltipHTML[id] + '<div class="tooltip">';
		  tooltipHTML[id] = tooltipHTML[id] + '<div class="tooltip-inner">';
		  tooltipHTML[id] = tooltipHTML[id] + '<span class="title">' + label.replace(/&amp;/gi, "&") + '</span>';
		  tooltipHTML[id] = tooltipHTML[id] + '</div>';
		  tooltipHTML[id] = tooltipHTML[id] + '<div class="pointer"></div>';
		  tooltipHTML[id] = tooltipHTML[id] + '</div>';
		}
		// Create popup html for marker detail
		popupHTML[id] = '';
		if(trim(body)!=""){
		  popupHTML[id] = popupHTML[id] + '<div class="infoPopup">';
		  popupHTML[id] = popupHTML[id] + '<div class="infoPopup-inner">';
		  popupHTML[id] = popupHTML[id] + body.replace(/&amp;/gi, "&");
		  popupHTML[id] = popupHTML[id] + '</div>';
		  popupHTML[id] = popupHTML[id] + '<div class="pointer"></div>';
		  popupHTML[id] = popupHTML[id] + '</div>';
		}
		
		// Add mouseover tootltip
		if(tooltipHTML[id]!=""){
		  GEvent.addListener(marker,'mouseover',function() { marker.openToolTip(tooltipHTML[id],index); });
		  GEvent.addListener(marker,'mouseout',function() { marker.closeToolTip(); });
		}
		// Show popup onClick
		GEvent.addListener(marker,'click',function() { markerClick(id,lon,lat) });
	
		// Save the marker in memory
		gmarkers[id] = marker;
		
		return marker;
  }

  function markerClick(id,lon,lat) {
	// Check if marker still exists
	if(gmarkers[id]){
	  // Close if a popup is open or else close
	  if(gmarkers[id].infoWindowInstance) {
	    gmarkers[id].closeinfoWindow();
	    openMarker = null;
	  } else {
	    if(openMarker){
	      openMarker.closeinfoWindow();
	    }
	    // Open popup
  		gmarkers[id].closeToolTip();
  		gmarkers[id].openinfoWindow(popupHTML[id]);
  		openMarker = gmarkers[id];
      }
	  }
  }
  
  // Draw all poi's
  function getNewPois(userid,type) {
	map.clearOverlays();
	gmarkers = [];
	popupHTML = [];
	tooltipHTML = [];
	
	showLoader();
	$.ajax({
	  url: '/xml.php?alias='+current_alias,
		cache: false,
	  success: function(data, responseCode) {
	    hideLoader();
	    var xml = data; //GXml.parse(data);
			var i = 0;
			$(xml.documentElement).children("marker").each(function(){
				var type = $(this).children('type').text();
				var label = $(this).children('label').text();
				var lon = $(this).children('longitude').text();
				var lat = $(this).children('latitude').text();
				var user = $(this).children('user').text();
				var body = $(this).children('body').text();
				var point = new GLatLng(parseFloat(lat),parseFloat(lon));
				var m = createMarker(point, i, label, 'marker_' + i, type, lon, lat, user, body);
				map.addOverlay(m);
				switch(type) {
					case 'twitter':
						tweetMarkers.push(m);
						break;
					case 'foursquare':
						fsMarkers.push(m);
						break;
					case 'mobypicture':
						mobyMarkers.push(m);
						break;
				}
				i++;
			});
			initUI();
	  }
	});
	
	// Save lon/lat/zoomlvl
	center = map.getCenter();
	createCookie('lon',center.lng(),1);
	createCookie('lat',center.lat(),1);
	createCookie('zoom',map.getZoom(),1);
  }
  
}

function initUI() {
  if(tweetMarkers.length > 0) {
    $('.twitter.service').addClass('on');
  }
  else if(!$('.twitter.service').hasClass('not-connected')) {
    $('.twitter.service').removeClass('connected');
    $('.twitter.service').addClass('not-available');
    $('.twitter.service').unbind('click');
  }
  
  if(fsMarkers.length > 0) {
    $('.foursquare.service').addClass('on');
  }
  else if(!$('.foursquare.service').hasClass('not-connected')) {
    $('.foursquare.service').removeClass('connected');
    $('.foursquare.service').addClass('not-available');
    $('.foursquare.service').unbind('click');
  }
  
  if(mobyMarkers.length > 0) {
    $('.mobypicture.service').addClass('on');
  }
  else if(!$('.mobypicture.service').hasClass('not-connected')) {
    $('.mobypicture.service').removeClass('connected');
    $('.mobypicture.service').addClass('not-available');
    $('.mobypicture.service').unbind('click');
  }
}

function showLoader() {
  $('#logo').append('<div id="loader">Loading data...</div>');
}

function hideLoader() {
  $('#loader').remove();
}

function getParameterByName(name) {
  name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
  var regexS = "[\\?&]"+name+"=([^&#]*)";
  var regex = new RegExp(regexS);
  var results = regex.exec(window.location.href);
  if(results == null)
    return false;
  else
    return results[1];
}
