
function random_fact() {
  var id = $('fact').title;
	new Ajax.Updater('quote','/facts/random_fact/'+id, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', 'quote']});
	return false;
}


var map;
var currentPhotoWindow = null;
var locationWindow = null;

function load_home(c_lat,c_lng, tour_id) {
	if (GBrowserIsCompatible()) {

		var point = new GLatLng(c_lat,c_lng);
		map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(c_lat+0.02,c_lng+0.25), 9);

		var marker = createLocationMarker(point);
		map.addOverlay(marker);

		createHomeWindows(point);

	}

}

function load_small(c_lat,c_lng,location_id) {
	if (GBrowserIsCompatible()) {

		var point = new GLatLng(c_lat,c_lng)
		map = new GMap2(document.getElementById("map"));
		map.setCenter(point, 9);

		var marker = createLocationMarker(point);
		map.addOverlay(marker);

	}

}

function load_mammoth_map(c_lat,c_lng,location_id) {
	if (GBrowserIsCompatible()) {

		var point = new GLatLng(c_lat,c_lng);
		map = new GMap2(document.getElementById("map"));
		map.setCenter(point, 7);
		map.addControl(new MammothMapControl());

		//Comments
		GDownloadUrl("/comments/list_as_xml", function(data, responseCode) {
		  var xml = GXml.parse(data);
		  var comment_markers = xml.documentElement.getElementsByTagName("marker");
		  for (var i = 0; i < comment_markers.length; i++) {

				var label = new TLabel();
				label.id = 'label_'+i;
				var point = new GLatLng(parseFloat(comment_markers[i].getAttribute("lat")),
			                            parseFloat(comment_markers[i].getAttribute("lng")));

			  	var marker = createCommentMarker(point, comment_markers[i].getAttribute("postcode"));
				map.addOverlay(marker);

		  }
		});

		//tour locations
		GDownloadUrl("/tour_locations/list_as_xml", function(data, responseCode) {
		  var xml = GXml.parse(data);
		  var tour_locations = xml.documentElement.getElementsByTagName("marker");
		  var markers = new Array(tour_locations.length);
		  for (var i = 0; i < tour_locations.length; i++) {
			  var point = new GLatLng(parseFloat(tour_locations[i].getAttribute("lat")),
		                            parseFloat(tour_locations[i].getAttribute("lng")));


			  //draw path
		      if(i!=(tour_locations.length-1)) {
			  var polyline = new GPolyline([
		  				point,
		  				new GLatLng(parseFloat(tour_locations[i+1].getAttribute("lat")),parseFloat(tour_locations[i+1].getAttribute("lng")))
					], "#ff0000", 10);
			  }

			  tour_id = tour_locations[i].getAttribute("tour_id").toString();
			  var marker = createLocationMarker(point, tour_id);
			  map.addOverlay(marker);
			  markers[i] = marker;
			  map.addOverlay(polyline);
			  //trigger current tour location
			  if(tour_id == location_id) {
			    GEvent.trigger(marker, "click");
		      }
		  }
		});
	}
}
function createHomeWindows(point) {
		var picWindow = new TLabel();
		picWindow.id = 'home-pic-window';
		picWindow.anchorLatLng = point;
		picWindow.anchorPoint = 'bottomLeft'
		picWindow.content = '<div id="loader"></div>';

		var commentWindow = new TLabel();
		commentWindow.id = 'home-comment-window';
		commentWindow.anchorLatLng = point;
		commentWindow.anchorPoint = 'topLeft'
		commentWindow.content = '<div id="loader"></div>';

		map.addTLabel(picWindow);
		map.addTLabel(commentWindow);
		new Ajax.Updater('home-comment-window','/comments/count_ajax/', {asynchronous:true, evalScripts:true})
		new Ajax.Updater('home-pic-window','/photos/count_ajax/', {asynchronous:true, evalScripts:true})
}

function createLocationWindow(point, id) {
		var clWindow = new TLabel();
		clWindow.id = 'location-window';
		clWindow.anchorLatLng = point;
		clWindow.content = '<div id="loader"></div>';
		map.addTLabel(clWindow);
		locationWindow = clWindow;
		new Ajax.Updater('location-window','/tour_locations/location_ajax/'+id, {asynchronous:true, evalScripts:true})
}

function createPhotoWindow(marker, point, tour_id) {
		var photoWindow = new TLabel();
		photoWindow.id = 'photo-window';
		photoWindow.anchorLatLng = point;
		photoWindow.markerOffset=new GSize(0,15);
		photoWindow.anchorPoint = 'bottomCenter'
		photoWindow.content = '<div id="loader"></div>';
		map.addTLabel(photoWindow);
		currentPhotoWindow = photoWindow;
		getTourPhotos(tour_id);
}

function createLocationMarker(point, tour_id) {
		var Icon = new GIcon();
		Icon.image = "/img/mammoth_icon.png";
  		Icon.iconSize = new GSize(68, 52);
  		Icon.iconAnchor = new GPoint(34, 26);

		var marker = new GMarker(point, Icon);

		if (tour_id!=null) {
		  GEvent.addListener(marker, "click", function() {
		    destroyPhotoWindow();
		    destroyLocationWindow();
			createPhotoWindow(marker, point, tour_id);
			createLocationWindow(point, tour_id);
		  });
		}
	  return marker;
}

function createCommentMarker(point, postcode) {
		var Icon = new GIcon();
		Icon.image = "/img/comment_icon.png";
  		Icon.iconSize = new GSize(19, 16);
  		Icon.iconAnchor = new GPoint(10, 7);

		var marker = new GMarker(point, Icon);
		marker.postcode = postcode

	  GEvent.addListener(marker, "click", function() {
			getComments(this.postcode)
		});
	  return marker;
}

function getTourPhotos(id,page) {
    if (page==null) { page = 1 };
    new Element.update('photo-window', '<div id="loader"></div>');
		new Ajax.Updater('photo-window','/photos/list_ajax/'+id+'?page='+page, {asynchronous:true, evalScripts:true})
		return false;
}

function destroyPhotoWindow() {
  if (currentPhotoWindow!=null) {
		map.removeTLabel(currentPhotoWindow);
	}
	currentPhotoWindow = null;
	return false;
}
function destroyLocationWindow() {
  if (locationWindow!=null) {
		map.removeTLabel(locationWindow);
	}
	locationWindow = null;
	return false;
}



function createCommentWindow() {
  destroyCommentWindow();
	new Insertion.After('map', '<div id="comment-window"></div>')
	if (document.all) {
		new Insertion.Before('comment-window', '<div id="comment-window-shadow"></div>')
	}
}

function destroyCommentWindow() {
  if ($('comment-window')) {
	  new Element.remove('comment-window');
	}
	if ($('comment-window-shadow')) {
    new Element.remove('comment-window-shadow');
	}
}

function destroyWindow(id) {
	map.removeTLabel($(id));
}

function getComments(id) {
	createCommentWindow();
	new Ajax.Updater('comment-window','/comments/show/'+id, {asynchronous:true, evalScripts:true})
}

function getPhoto(type,id) {
	createCommentWindow();
	new Ajax.Updater('comment-window','/photos/show_ajax/'+ type +'/'+id, {asynchronous:true, evalScripts:true});
	return false;
}

// MammothMapControl is a GControl
function MammothMapControl() {
}
MammothMapControl.prototype = new GControl();

// Creates the custom gmap control
MammothMapControl.prototype.initialize = function(map) {
  var container = document.createElement("div");
  container.style.width = "56px";
  container.style.height = "106px";
  container.style.position = "relative";
  container.style.background = "url(/img/map_controls.png)";
  container.id = "controls";

  // Fix IEs rubbish alpha support
  if (document.all) {
	  container.style.background = "none";
	  var bg = document.createElement("div");
	  bg.style.height = "100%";
	  bg.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=scale, src='/img/map_controls.png');";
    container.appendChild(bg);
  }

  var moveNorthDiv = this.createButton_(6,20);
  container.appendChild(moveNorthDiv);
  GEvent.addDomListener(moveNorthDiv, "click", function() {
    map.panDirection(0, +1);
  });

  var moveEastDiv = this.createButton_(20,7);
  container.appendChild(moveEastDiv);
  GEvent.addDomListener(moveEastDiv, "click", function() {
    map.panDirection(+1, 0);
  });

  var moveSouthDiv = this.createButton_(33,20);
  container.appendChild(moveSouthDiv);
  GEvent.addDomListener(moveSouthDiv, "click", function() {
    map.panDirection(0, -1);
  });

  var moveWestDiv = this.createButton_(20,33);
  container.appendChild(moveWestDiv);
  GEvent.addDomListener(moveWestDiv, "click", function() {
    map.panDirection(-1, 0);
  });

  var zoomInDiv = this.createButton_(63,20);
  container.appendChild(zoomInDiv);
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn();
  });

  var zoomOutDiv = this.createButton_(82,20);
  container.appendChild(zoomOutDiv);
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut();
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
MammothMapControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(7, 7));
}

// Sets the proper CSS for the given button element.
MammothMapControl.prototype.createButton_ = function(top, left) {
  var button = document.createElement("div");
  button.style.position = "absolute";
  button.style.display = "block";
  button.style.width = "15px";
  button.style.height = "15px";
  button.style.top = top+"px";
  button.style.left = left+"px";
  button.style.cursor = document.all ? "hand" : "pointer";
  return button;
}
