


    var globals = {};
    
    var tubemap; //the GMap2 Tubemap Viewer
    var map; //the GMap2 itself
    
    var centreLat= 20;
    var centreLng= -10;
    var maxResolution = 4;
    var minResolution = 2;
    var initialZoom=2;
	var tubemapLimits = {top: 79.5, bottom: -71, left: -179, right: 179};	// The allowed region which the whole map must be within
    var stationsInfo = [];
    
	var alertcount = 0;
	var alertlimit = 1;
   	
   	var totalmapWidth = 950;
   	//Set default world map starting coords (centre of London)
   	var worldStartLat = 51.51006459971262;
   	var worldStartLng = -0.1344752311706543;
   	var worldStartZoom = 12;
   	
   	//if station coords are avaialable from page.tpl.php centre on them and zoom in.
   	if (stationLongitude && stationLatitude) {
   		worldStartLat = stationLatitude;
   		worldStartLng = stationLongitude;
   		worldStartZoom = 16;
   		centreLat = (tubeTop + tubeBottom) / 2;
   		centreLng = (tubeLeft + tubeRight) / 2;
   		initialZoom=3;
   	}
   	
   	//reduce map width and run function if places to meet are assigned to station page
   	if (placesToMeet) {
   		//var totalmapWidth = 785;
   		var placesInfo = [];
   		var placesLatLng = [];
   	}
   	
   	var latlngbounds;
   	//var latlngbounds = new GLatLngBounds(GLatLng(stationLatitude, stationLongitude), GLatLng(stationLatitude+1, stationLongitude-1));
   	//alert(GLatLngBounds());
   	
   	var divWidth = 10;
    
    var mapMode = "advanced";
    
   
   	function TubemapMain (){
   		
   		
   			SelectMapMode();
   			var totalmapWidth = 950;
			
			
			//if(mapMode == "advanced"){
			 	
			 	
			 	if (placesToMeet) {
   					var totalmapWidth = 785;
   					LoadPlacesToMeet ();
   					
   				}
			LoadStationInfo();
		
			BuildTubemap ();

			BuildLondonMap ();	
			
			DrawStations ();
			
			if (placesToMeet) {
				
   				
   				DrawPlacesToMeet ();
   				
   				latlngbounds = new GLatLngBounds( );
   				//console.log(placesLatLng);
   				for (var i = 0; i < placesLatLng.length; i++) {
   					//console.log(placesLatLng[i]);
   					latlngbounds.extend(placesLatLng[i])
   				}
				
				//console.log(latlngbounds.getCenter( ))
				
				//map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );
   				worldStartLat = latlngbounds.getCenter( ).y;
   				worldStartLng = latlngbounds.getCenter( ).x;  
   				worldStartZoom = map.getBoundsZoomLevel( latlngbounds )-1;
/*    				console.log(worldStartZoom); */
   				if (worldStartZoom < 16) {
   					worldStartZoom = worldStartZoom+1;
/*    					console.log(worldStartZoom); */
   				}
   			}
			
			ActiveMapDivider();
			
			ActivateStationSearch();
			
			var leftWidth = $(".map-left").width();
   			var remainingWidth = (totalmapWidth-divWidth)/2;
   			
   			leftWidth = totalmapWidth - remainingWidth - divWidth;
   			
   			
   			$(".map-left").width(leftWidth)
   			tubemap.checkResize();
        	tubemap.setCenter(new GLatLng(centreLat, centreLng), initialZoom);
   			
   			
   			
   			$(".map-right").width(remainingWidth);
   			map.checkResize();
			map.setCenter(new GLatLng(worldStartLat, worldStartLng), worldStartZoom);
			
			//if front page, map mode is set to basic
			
			if (front) {
				mapMode = "basic";
			}
			
			if (mapMode == "basic") {
				jQuery(this).addClass('active');
   				
   				if ($('.mode-advanced').hasClass('active')) {
   					$('.mode-advanced').removeClass('active');
   				}
   				if ($('.mode-street').hasClass('active')) {
   					$('.mode-street').removeClass('active');
   				}
   				



				$(".map-left").width(totalmapWidth-divWidth);
    			$(".map-right").width(0);
    			tubemap.checkResize();
   				map.checkResize();
   				tubemap.setCenter(new GLatLng(centreLat, centreLng), initialZoom);

			}
			
			if (mapMode == "street") {
				jQuery(this).addClass('active');
   				
   				if ($('.mode-advanced').hasClass('active')) {
   					$('.mode-advanced').removeClass('active');
   				}
   				if ($('.mode-basic').hasClass('active')) {
   					$('.mode-basic').removeClass('active');
   				}
   				
   				
   				


				$(".map-right").width(totalmapWidth-divWidth);
    			$(".map-left").width(0);
    			tubemap.checkResize();
   				map.checkResize();
				map.setCenter(new GLatLng(worldStartLat, worldStartLng), worldStartZoom);

			}
		
		//} 
		
		/* else if (mapMode == "basic") {
		
			LoadStationInfo();
		
			BuildTubemap ();
	
			
			DrawStations ();
		
			$(".map-divider").hide();
			$(".map-right").hide();
   			$(".map-left").width(totalmapWidth);
   			tubemap.checkResize();
        	tubemap.setCenter(new GLatLng(centreLat, centreLng), initialZoom);
        	
			
		} else {
			if (placesToMeet) {
   					var totalmapWidth = 785;
   					LoadPlacesToMeet ();
   				}
   				
			BuildLondonMap ();
			
				
			
			$(".map-divider").hide();
			$(".map-left").hide();
			$(".map-left").width(0);
			$(".map-right").width(totalmapWidth)
			map.checkResize();
			map.setCenter(new GLatLng(worldStartLat, worldStartLng), worldStartZoom);
			if (placesToMeet) {
   					DrawPlacesToMeet ();
   				}
		} */
		
		ActiveMapModeSelection();
		checkBorder (0);
   	
   	}
   	
   	function SelectMapMode(){
   	
   		//$(".map-footer").append('<p class="accent">You\'re using ' + BrowserDetect.browser + ' ' + BrowserDetect.version + ' on ' + BrowserDetect.OS + '!</p>')
   		if (stationLongitude && stationLatitude) {
   			return "advanced";
   		}
   		
   		
   		// check cookies for selection
   		var cookieMapMode = readCookie("mapMode");
   		if(cookieMapMode){
   			mapMode = cookieMapMode;
   			
   			// only use cookie once
   			eraseCookie("mapMode");
   			return mapMode;
   		}
   		
   		// if no cookie, pick the default mode for the browser
   		
   		// firefox, chrome = advanced
   		//if(BrowserDetect.browser.toLowerCase().indexOf("firefox") != -1 || BrowserDetect.browser.toLowerCase().indexOf("chrome") != -1){
   			mapMode = "advanced";
   			//mapMode = "basic";
   		//} else {
   			//mapMode = "basic";
   		//}
   		
   		return mapMode;
   	   	
   	}
   	function ActiveMapModeSelection(){
   	if (placesToMeet) {
   			totalmapWidth = 785;
   		}
   	
   		//if(mapMode == "advanced"){
   				$(".map-mode").each(function () {
   					
   					
   					if ($('this').hasClass('active')) {
   						$('this').removeClass('active');
   					}
   					
   									
   				
   				});
   				if (mapMode == "basic") {
   					$('.mode-basic').addClass('active');
   				}
   				if (mapMode == "advanced") {
   					$('.mode-advanced').addClass('active');
   				}
				if (mapMode == "street") {
   					$('.mode-street').addClass('active');
   				}
   				
   			
   			
   				$(".mode-basic").click(function(){

   				goToBasic(0);
   				
   				
   				});
   				
   				$(".mode-street").click(function(){
   				
   				
   				
   					goToStreet(0);
   				
   				});
   				
   				$(".mode-advanced").click(function(){
   				
   				jQuery(this).addClass('active');
   				
   				if ($('.mode-basic').hasClass('active')) {
   					$('.mode-basic').removeClass('active');
   				}
   				if ($('.mode-street').hasClass('active')) {
   					$('.mode-street').removeClass('active');
   				}
   				
   				mapMode = "advanced"
   				createCookie("mapMode", mapMode, 90);
   				
/*    				window.location.href=window.location.href; */


				$(".map-right").width((totalmapWidth/2)-divWidth);
    			$(".map-left").width((totalmapWidth/2)-divWidth);
    			
    			
    			
    			tubemap.checkResize();
   				map.checkResize();
   				checkBorder (0);
   				
   				});
   		//}
   		/*
   		
   		else if (mapMode == "basic") {
   			$(".mode-basic").addClass("active");
   			
			$(".mode-advanced").click(function(){
   				mapMode = "advanced"
   				createCookie("mapMode", mapMode, 90);
   				window.location.href=window.location.href;
   			});
   			$(".mode-street").click(function(){
   				mapMode = "street"
   				createCookie("mapMode", mapMode, 90);
   				window.location.href=window.location.href;
   			});
   		}else if (mapMode == "street") {
   			$(".mode-street").addClass("active");
   			
			$(".mode-advanced").click(function(){
   				mapMode = "advanced"
   				createCookie("mapMode", mapMode, 90);
   				window.location.href=window.location.href;
   			});
   			$(".mode-basic").click(function(){
   				mapMode = "basic"
   				createCookie("mapMode", mapMode, 90);
   				window.location.href=window.location.href;
   			});
   		} */
   		
   		
   	}
   	
   	function checkBorder (move) {
   		if ($(".map-right").width() == "0") {
   			
   			$(".map-right").css('border-right', '#CDDBEB');
   			$(".map-left").css( 'border', '1px solid #A0B3D1');
   			$('.map-divider-right').css('display','none');
   			
   			if (!move) {
   				goToBasic(1);
   			}
   			
   		} else if ($(".map-left").width() == "0") {
   			$(".map-left").css('border-left', '#CDDBEB');
   			$(".map-right").css( 'border', '1px solid #A0B3D1');
   			$('.map-divider-right').css('display','block');
   			if (!move) {
   				goToStreet(1);
   			}
   		} else {
   			$(".map-right").css( 'border', '1px solid #A0B3D1');
   			$(".map-left").css( 'border', '1px solid #A0B3D1');
   			$('.map-divider-right').css('display','block');
   			
   			if (!move) {
   			jQuery('.mode-advanced').addClass('active');
   				
   				if ($('.mode-basic').hasClass('active')) {
   					$('.mode-basic').removeClass('active');
   				}
   				if ($('.mode-street').hasClass('active')) {
   					$('.mode-street').removeClass('active');
   				}
   				
   				mapMode = "advanced"
   				createCookie("mapMode", mapMode, 90);
   				
   				}
   		}
   	}
   	
   	function goToBasic (move) {
   				jQuery('.mode-basic').addClass('active');
   				
   				if ($('.mode-advanced').hasClass('active')) {
   					$('.mode-advanced').removeClass('active');
   				}
   				if ($('.mode-street').hasClass('active')) {
   					$('.mode-street').removeClass('active');
   				}
   				
   				mapMode = "basic"
   				createCookie("mapMode", mapMode, 90);
/*    				window.location.href=window.location.href; */


				if (move == 0) {
					
				
				$(".map-left").width(totalmapWidth-divWidth);
    			$(".map-right").width(0);
    			
    			checkBorder (0);
    			
    			
    			
    			
    			tubemap.checkResize();
   				map.checkResize();
   				checkBounds();
   				
   				}
   	}
   	
   	
	function goToStreet (move) {
				jQuery('.mode-street').addClass('active');
   				
   				if ($('.mode-advanced').hasClass('active')) {
   					$('.mode-advanced').removeClass('active');
   				}
   				if ($('.mode-basic').hasClass('active')) {
   					$('.mode-basic').removeClass('active');
   				}
   				
   				mapMode = "street"
   				createCookie("mapMode", mapMode, 90);

				if (move == 0) {

				$(".map-right").width(totalmapWidth-divWidth);
    			$(".map-left").width(0);
    			
    			checkBorder (0);
    			tubemap.checkResize();
   				map.checkResize();
   				
   				}

	}   	
	//createCookie('ppkcookie','testcookie',7);
   	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/";
	}
	
	/*var x = readCookie('ppkcookie1')
	if (x) {
		[do something with x]
	}
	*/
	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function eraseCookie(name) {
		createCookie(name,"",-1);
	}

   	
   	function TubemapEdit (){
   		
   		EditModeInsertMaps ();
		if (stationAdd) {
			AddModeInsertMaps ();
		}
		
		
		BuildTubemap ();
		
		BuildLondonMap ();	
		
		EditModeInsertMarkers();
   	
   	}
   	
   	function MeetingPlaceEdit () {
   		//insert map into node add/edit form
		$("#edit-field-place-latittude-0-value-wrapper").before('<div id="map" class="map"></div>');
		//find marker position if it exists for map center coords
	
		
		var startLat = getOrDefault("#edit-field-place-latittude-0-value", 0);
		var startLng = getOrDefault("#edit-field-place-longitude-0-value", 0);
		var centre;
		
		LoadStationInfo();

		
		BuildLondonMap();
		
		if (startLat && startLng) {
			centre = new GLatLng(startLat, startLng);
			map.setCenter(centre, 15);
			
		} else {
			if ($('#edit-field-station-reference-nid-nid')[0]['selectedIndex']) {
				var centre = FindStation($('#edit-field-station-reference-nid-nid')[0]['options'][$('#edit-field-station-reference-nid-nid')[0]['selectedIndex']].text)
				centre = new GLatLng(centre.lat, centre.lng);
			} else  {
				centre = new GLatLng(51.51006459971262, -0.1344752311706543);
			}
		
			
		}
		
		var marker = new GMarker(centre, {draggable: true});
		map.addOverlay(marker);
		GEvent.addListener(marker, 'dragend', function(a) {  
			
			$("#edit-field-place-latittude-0-value").val(a.lat());
			$("#edit-field-place-longitude-0-value").val(a.lng());
		});
		
		GEvent.addListener(map, "click", function(a, b) {
			if (!a) {
				marker.setLatLng(new GLatLng(b.lat(), b.lng()));
  				$("#edit-field-place-latittude-0-value").val(b.lat());
				$("#edit-field-place-longitude-0-value").val(b.lng());
			}
			
			
		});
		
		$('#edit-field-station-reference-nid-nid').change(function (a) {
				var stationCoords = FindStation($(this).find('option:selected').text());
				map.setCenter(new GLatLng(stationCoords.lat, stationCoords.lng), 15);
				
		});
		 
   	}
   	
   	function FindStation (targetStation) {
   		
   		var coords = {};
   		
   		
   		
   		for (var i = 0; i < stationsInfo.length; i++){
    		var station = stationsInfo[i];
    		if (station.title == targetStation) {
    			coords.lat = station.worldlat;
    			coords.lng = station.worldlng;
    		}
    	}
    	
    	return coords;
	
   	}
   	
   	function EditModeInsertMaps(){
   		// must be called before edit maps are built
   	
		//$("#edit-field-tubetop-0-value-wrapper").before('<div id="tubemap" class="map"></div>');
		//$("#edit-field-worldlat-0-value-wrapper").before('<div id="map" class="map"></div>');
		
   	}
   	
   	function AddModeInsertMaps(){
   		// must be called before edit maps are built
   		
		$("#edit-field-tubetop-0-value-wrapper").before('<div id="tubemap" class="map"></div>');
		$("#edit-field-worldlat-0-value-wrapper").before('<div id="map" class="map"></div>');
		
   	}
   	function EditModeInsertMarkers(){
   		// must be called after edit maps are built
   	
		var starttubetop = getOrDefault("#edit-field-tubetop-0-value", centreLat+10);
		var starttubeleft = getOrDefault("#edit-field-tubeleft-0-value", centreLng-10);
		var starttubebottom = getOrDefault("#edit-field-tubebottom-0-value", centreLat-10);
		var starttuberight = getOrDefault("#edit-field-tuberight-0-value", centreLng+10);
		var startworldlat = getOrDefault("#edit-field-worldlat-0-value", 51.51006459971262);
		var startworldlng = getOrDefault("#edit-field-worldlng-0-value", -0.1344752311706543);
		
		var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(32, 32);
        baseIcon.iconAnchor = new GPoint(15, 32);
        baseIcon.shadowSize = new GSize(50, 32);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);

        var greenIcon = new GIcon(baseIcon);
        greenIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/green-dot.png";
        
        var blueIcon = new GIcon(baseIcon);
        blueIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/blue-dot.png";
        
        var redIcon = new GIcon(baseIcon);
        redIcon.image = "http://www.google.com/intl/en_us/mapfiles/ms/icons/red-dot.png";
        
        var tubeTopLeftMarker = new GMarker(new GLatLng(starttubetop, starttubeleft), {icon: greenIcon, draggable: true});  
		tubemap.addOverlay(tubeTopLeftMarker);
		GEvent.addListener(tubeTopLeftMarker, 'dragend', function(a) {  
			//alert("The Top Left of the Tubemap Station Text has been set to: " + a);
			$("#edit-field-tubetop-0-value").val(a.lat());
			$("#edit-field-tubeleft-0-value").val(a.lng());
		}); 
		
		var tubeBottomRightMarker = new GMarker(new GLatLng(starttubebottom, starttuberight), {icon: blueIcon, draggable: true});  
		tubemap.addOverlay(tubeBottomRightMarker);
		GEvent.addListener(tubeBottomRightMarker, 'dragend', function(a) {  
			//alert("The Bottom Right of the Tubemap Station Text has been set to: " + a);
			$("#edit-field-tubebottom-0-value").val(a.lat());
			$("#edit-field-tuberight-0-value").val(a.lng());
		}); 
		
		
		var worldMarker = new GMarker(new GLatLng(startworldlat, startworldlng), {icon: redIcon, draggable: true});  
		map.addOverlay(worldMarker);
		GEvent.addListener(worldMarker, 'dragend', function(a) {  
			//alert("The Worldmap marker for the station has been set to: " + a);
			$("#edit-field-worldlat-0-value").val(a.lat());
			$("#edit-field-worldlng-0-value").val(a.lng());
		}); 

   	}
   	    function LoadStationInfo(){
    	// loads data into stationsInfo from the page html
    	// requires a station-info block on the page
    	
    	$(".station-info").each(function(){
			var newStation = {};
			newStation.nid = parseInt($(this).find(".nid").text());
			newStation.title = $(this).find(".title").text();
			newStation.body = $(this).find(".body").text();
			newStation.tubetop = parseFloat($(this).find(".tubetop").text());
			newStation.tubeleft = parseFloat($(this).find(".tubeleft").text());
			newStation.tubebottom = parseFloat($(this).find(".tubebottom").text());
			newStation.tuberight = parseFloat($(this).find(".tuberight").text());
			newStation.worldlat = parseFloat($(this).find(".worldlat").text());
			newStation.worldlng = parseFloat($(this).find(".worldlng").text());
			newStation.url = $(this).find(".path").text();
			stationsInfo.push(newStation);
		});

    }
    
    function BuildTubemap (){
    	
		/////////////////////////////////////////////////////////////////////////////////////
		// Begin Tubemap Map Init
	
        //resizeMapDiv();
        var copyright = new GCopyright(1,
        	new GLatLngBounds(new GLatLng(-90, -180), new GLatLng(90, 180)), 0
        	,"Map Data &copy;2012 TFL Version J Reg. user No. 11/IT/2122/P <br/> <a target=\"_blank\" href=\"http://www.indulgemedia.com\">Indulge Media</a>"
        	//,"<a target=\"_blank\" href=\"http://www.indulgemedia.com\">Indulge Media</a>"
            );
        var copyrightCollection = new GCopyrightCollection("");
        copyrightCollection.addCopyright(copyright);

        //create a custom picture layer
        var pic_tileLayers = [ new GTileLayer(copyrightCollection , minResolution, maxResolution)];
        pic_tileLayers[0].getTileUrl = customGetTileURL;
        pic_tileLayers[0].isPng = function() { return false; };
        pic_tileLayers[0].getOpacity = function() { return 1.0; };
        /*var pic_customMap = new GMapType(pic_tileLayers, new GMercatorProjection(7), "Pic",
            {maxResolution:maxResolution, minResolution:minResolution, errorMessage:""});*/
        var pic_customMap = new GMapType(pic_tileLayers, G_HYBRID_MAP.getProjection(), "Pic",
            {maxResolution:maxResolution, minResolution:minResolution, errorMessage:""});

        //Now create the custom map. Would normally be G_NORMAL_MAP,G_SATELLITE_MAP,G_HYBRID_MAP
        tubemap = new GMap2(document.getElementById("tubemap"),{mapTypes:[pic_customMap]});
        
		// ====== Restricting the range of Zoom Levels =====
      	// Get the list of map types      
      	var mt = tubemap.getMapTypes();
      	// Overwrite the getMinimumResolution() and getMaximumResolution() methods
      	for (var i=0; i<mt.length; i++) {
        	mt[i].getMinimumResolution = function() {return minResolution;}
        	mt[i].getMaximumResolution = function() {return maxResolution;}
      	}
      	
	    // Add a move listener to restrict the bounds range
	    GEvent.addListener(tubemap, "move", function() {
	        checkBounds();
	    }); 
	    
	    GEvent.addListener(tubemap, "dragend", function() {
			alertcount = 0;
	    }); 
	    
	      
		tubemap.addControl(new GLargeMapControl3D ());
		
		//tubemap.addControl(new GOverviewMapControl());
        //tubemap.enableDoubleClickZoom();
		
		tubemap.enableContinuousZoom();
		tubemap.enableScrollWheelZoom();
		
        tubemap.setCenter(new GLatLng(centreLat, centreLng));
        
     	
		// End Tubemap Map Init
		/////////////////////////////////////////////////////////////////////////////////////

    }
    
    function BuildLondonMap (){
    
		/////////////////////////////////////////////////////////////////////////////////////
		// Begin London Map Init 		
		
        map = new GMap2(document.getElementById("map"));
		map.setCenter(new GLatLng(51.51006459971262, -0.1344752311706543), 13);
		//map.addControl(new GSmallMapControl());
		map.addControl(new GLargeMapControl3D  ()); 
		//map.addControl(new GMapTypeControl());      
		map.addControl(new GMenuMapTypeControl() ); 
		//map.setUIToDefault();

		map.enableContinuousZoom();
		map.enableScrollWheelZoom();
		
		// End London Map Init
		/////////////////////////////////////////////////////////////////////////////////////
    
    }
    
    function LoadPlacesToMeet () {
    	$("#block-views-places_to_meet-block_2 .views-row").each(function(){
				var newPlace = {};
				newPlace.no = parseInt($(this).find(".place-number").text());
				newPlace.lat = parseFloat($(this).find(".views-field-field-place-latittude-value").text());
				newPlace.lng = parseFloat($(this).find(".views-field-field-place-longitude-value").text());
				placesInfo.push(newPlace);
		});
    }
    
    
   

 function DrawPlacesToMeet () {
		for (var i=0; i < placesInfo.length; i++) {
			var place = placesInfo[i];
			
			// Create our marker icon
			var placeIcon = new GIcon(G_DEFAULT_ICON);
			placeIcon.image = markerImage+"?n="+(i+1);
            placeIcon.iconSize = new GSize(32, 32);
			placeIcon.shadow = "";
			placeIcon.iconAnchor = new GPoint(16, 32);

            //image.iconSize.width = 32;
                
			// Set up our GMarkerOptions object
			markerOptions = { icon:placeIcon };
			
			placeLatLng = new GLatLng(place.lat, place.lng);
			//placesLatLngOpp = new GLatLng();
			
			
			placesLatLng.push(placeLatLng);
			
	
			
			
			var bring = bearing(placeLatLng, new GLatLng(worldStartLat, worldStartLng));
			var distance = placeLatLng.distanceFrom(new GLatLng(worldStartLat, worldStartLng))
			
			var pointB = destinationPoint(worldStartLat, worldStartLng, bring, distance);
			
			
			
			placesLatLng.push(pointB);
			
			//map.addOverlay(new GMarker(pointB));
			map.addOverlay(new GMarker(placeLatLng, markerOptions));

		}
    }
    
    
function toRad (deg) {
   return deg * Math.PI / 180;
}

function toDeg (rad) {
   return rad * 180 / Math.PI;
}

    
function destinationPoint (lat1, lon1, brng, dist) {
   dist = dist / 6371000;  
   brng = toRad(brng);  

   //var lat1 = this.lat().toRad(), lon1 = this.lng().toRad();

	var lat1 = toRad(lat1) 
	var lon1 = toRad(lon1);
	
   var lat2 = Math.asin(Math.sin(lat1) * Math.cos(dist) + 
                        Math.cos(lat1) * Math.sin(dist) * Math.cos(brng));

   var lon2 = lon1 + Math.atan2(Math.sin(brng) * Math.sin(dist) *
                                Math.cos(lat1), 
                                Math.cos(dist) - Math.sin(lat1) *
                                Math.sin(lat2));

   if (isNaN(lat2) || isNaN(lon2)) return null;

   return new GLatLng(toDeg(lat2), toDeg(lon2));
}
    
function bearing( from, to ) {

var degreesPerRadian = 180.0 / Math.PI;
			var radiansPerDegree = Math.PI / 180.0; 

// See T. Vincenty, Survey Review, 23, No 176, p 88-93,1975.
// Convert to radians.
var lat1 = from.latRadians();
var lon1 = from.lngRadians();
var lat2 = to.latRadians();
var lon2 = to.lngRadians();
// Compute the angle.
var angle = - Math.atan2( Math.sin( lon1 - lon2 ) * Math.cos( lat2 ), Math.cos( lat1 ) * Math.sin( lat2 ) - Math.sin( lat1 ) * Math.cos( lat2 ) * Math.cos( lon1 - lon2 ) );
if ( angle < 0.0 )
angle += Math.PI * 2.0;
// And convert result to degrees.
angle = angle * degreesPerRadian;
angle = angle.toFixed(1);
return angle;
} 

    
    
/*

    function DrawStations (){
    	for (var i = 0; i < stationsInfo.length; i++){
			var station = stationsInfo[i];
       	  	var polygon = new GPolygon([
          	  	new GLatLng(station.tubetop, station.tubeleft),
          	  	new GLatLng(station.tubetop, station.tuberight),
          	  	new GLatLng(station.tubebottom, station.tuberight),
          	  	new GLatLng(station.tubebottom, station.tubeleft),
          	  	new GLatLng(station.tubetop, station.tubeleft)
		  	], "#FFFFFF", 0, 0, "#FFFFFF", 0);
		  	//], "#FF0000", 1, 1, "#FF0000", 0.25);
		  	
		  	tubemap.addOverlay(polygon);
		  	polygon.station = station;
		  	station.polygon = polygon;
		  	var index = i;
		  	polygon.id = i;
		  	
		  	polyClick(polygon);
		}
    }
*/
	function DrawStations (){
		GEvent.addListener(tubemap, "click", function(a, b) {
			if (!a) {
				//marker.setLatLng(new GLatLng(b.lat(), b.lng()));
  				//$("#edit-field-place-latittude-0-value").val(b.lat());
				//$("#edit-field-place-longitude-0-value").val(b.lng());
				
				for (var i = 0; i < stationsInfo.length; i++){
    			var station = stationsInfo[i];
   					//station.tubetop, station.tubebottom, station.tubeleft, station.tuberight ;
   					
   					
   					
   					if (b.y <= station.tubetop && b.y >= station.tubebottom && b.x <= station.tuberight && b.x >= station.tubeleft) {
   						//alert(station.title)
   						location.href = station.url;
   					}
    			}
			}
			
			
		});
	
	GEvent.addListener(tubemap, "mousemove", function(a) {
			var foundStation = false;
			
			for (var i = 0; i < stationsInfo.length; i++){
    			var station = stationsInfo[i];
    				
   					
   					
   					
   					if (a.y <= station.tubetop && a.y >= station.tubebottom && a.x <= station.tuberight && a.x >= station.tubeleft) {
   					foundStation = true;
   						
   					}
    			}
			
			if (foundStation) {
				$("#tubemap img").css('cursor','pointer');
			} else {
				$("#tubemap img").css('cursor','inherit');
			}
		});	
	
	}
    
   	function polyClick (polygon){
   		GEvent.addListener(polygon, "click", function() {
   		
   			//PanStationWorldMap(polygon.station);
		  	location.href = polygon.station.url;		
		});
   	}


   	
   	function PanStationTubemap(station){
   		tubemap.checkResize();
		if(tubemap.getZoom() < 3){
			tubemap.setZoom(3);
		}
		tubemap.panTo(new GLatLng((station.tubetop + station.tubebottom) / 2, (station.tubeleft + station.tuberight) / 2));	
   	}
   	
   	function PanStationWorldMap(station){
   	
   		
   		var leftWidth = $(".map-left").width();
   		var remainingWidth = totalmapWidth - divWidth - leftWidth;
   		
   		if (remainingWidth < 250){
   		    remainingWidth = 250;
   		}
   		leftWidth = totalmapWidth - remainingWidth - divWidth;
   		
   		$("#map").width(remainingWidth);
   		map.checkResize();
		map.setZoom(15);
		map.panTo(new GLatLng(station.worldlat, station.worldlng));		
		
   		$(".map-left").animate({width: leftWidth}, 500, function (){
   		    tubemap.checkResize();
   		});
   		$(".map-right").animate({width: remainingWidth}, 500, function (){
   		    $("#map").css("width", "100%");
   		    map.checkResize();
   		});

   	}
   	
   	function ActiveMapDivider() {
   		if (placesToMeet) {
   			totalmapWidth = 785;
   		}
   				
   		var $selectedElement;
   		
   		$(".map-divider").width(divWidth);
		
   		$(".map-divider  div").mousedown(function(e){
   			if(e.preventDefault)
 			{
 				
  				e.preventDefault();
 			}
 			
 			
 			
 			
 			$selectedElement = $(this);
 			
 
 			$selectedElement.addClass('divider-active');
 			
 			var startMouseX = e.pageX;
 			
 			if ($selectedElement.hasClass('map-divider-center')) {
 			
 			
 			
   			$("body").mousemove(function(e){
				
				checkBorder (1);
   				//$('.map-container').css('cursor', 'ew-resize');
   				

   				var mouseX = e.pageX;
   				
   				var mapX = $(".map-left").offset().left;
   				var mapWidth = mouseX - mapX;
   				if (mapWidth < 5){
   					
   					mapWidth = 0;
   				} else if (mapWidth > totalmapWidth - divWidth - 5){
   					mapWidth = totalmapWidth - (divWidth);
   				}
   				var remainingWidth = totalmapWidth - divWidth - mapWidth;
   				
   				$(".map-left").width(mapWidth);
   				$(".map-right").width(remainingWidth);
   				
   				tubemap.checkResize();
   				
   				if (mapWidth > 50){
   					
	        		checkBounds();
	        	
	        	}
   				
   				map.checkResize();
    		});
    		}
    		
    		
    		$("body").mouseup(function(u){
    		checkBorder (0);
    		$selectedElement.removeClass('divider-active');
    		
    		$('body').unbind('mousemove');
    			//snap to
    			if (u.pageX-$(".map-left").offset().left < 100) {
    				$(".map-right").width(totalmapWidth-divWidth);
    				$(".map-left").width(0);
    				tubemap.checkResize();
	        		//checkBounds();
   					map.checkResize();
   					//console.log('meow');
    			} else if (u.pageX-$(".map-left").offset().left > totalmapWidth - 100) {
    				$(".map-left").width(totalmapWidth-divWidth);
    				$(".map-right").width(0);
    				tubemap.checkResize();
	        		checkBounds();
   					map.checkResize();
   					//console.log('woof');
    			} 
    			
    			if (u.pageX < (startMouseX + 5) && u.pageX > (startMouseX - 5)) {
    			checkBorder (0);
    			//alert(e.currentTarget);
    				//if (e.currentTarget.className == "map-divider-left") {
						//alert($(e.currentTarget).hasClass("map-divider-left"));
						var ieDirection;
						if (e.srcElement) {
							if (e.srcElement.className == "map-divider-left") {
								ieDirection = "left";
								
							} else if (e.srcElement.className == "map-divider-right") {
								ieDirection = "right";
							}
						}
						
    				if ($(e.currentTarget).hasClass("map-divider-left") || ieDirection == "left") {
    					if ($(".map-right").width() < Math.floor((totalmapWidth/2)-(divWidth/2))) {
    					    
    					    $(".map-right").width((totalmapWidth/2)-(divWidth/2));
    						$(".map-left").width((totalmapWidth/2)-(divWidth/2));
    						tubemap.checkResize();
	        				//checkBounds();
   							map.checkResize();
    					} else {
    					
    					
    						$(".map-right").width(totalmapWidth-divWidth);
    						$(".map-left").width(0);
    						tubemap.checkResize();
	        				//checkBounds();
   							map.checkResize();
   							
   						}
    				//} else if (e.currentTarget.className == "map-divider-right") {
    				} else if ($(e.currentTarget).hasClass("map-divider-right") || ieDirection == "right") {
    					if ($(".map-left").width() <  Math.floor((totalmapWidth/2)-(divWidth/2))) {
    					    
    					    $(".map-right").width((totalmapWidth/2)-(divWidth/2));
    						$(".map-left").width((totalmapWidth/2)-(divWidth/2));
    						tubemap.checkResize();
	        				//checkBounds();
   							map.checkResize();
    					} else {

    				
    						$(".map-left").width(totalmapWidth-divWidth);
    						$(".map-right").width(0);
    						tubemap.checkResize();
	        				checkBounds();
   							map.checkResize();
   							
   						}
    				}
    			}
    			checkBorder (0);
    			$('body').unbind('mouseup');
    		});

   		});
   			
   		
   		$(".map-divider").bind( "touchstart", function(e){
			
   			if(e.preventDefault)
 			{
  				e.preventDefault();
 			}
   			$("body").bind( "touchmove", function(event){
   				var e = event.originalEvent;
   				if(e.targetTouches.length == 1){
   					var touch = e.touches[0];
   					var mouseX = touch.pageX;
   					var mapX = $(".map-left").offset().left;
   					var mapWidth = mouseX - mapX;
   					if (mapWidth < 250){
   						mapWidth = 250;
   					} else if (mapWidth > totalmapWidth - divWidth){
   						mapWidth = totalmapWidth - divWidth;
   					}
   					var remainingWidth = totalmapWidth - divWidth - mapWidth;
   					
   					$(".map-left").width(mapWidth);
   					$(".map-right").width(remainingWidth);
   					
   					tubemap.checkResize();
	        		checkBounds();
   					map.checkResize();
   				} else if (e.touches.length == 0){
    				$('body').unbind('touchmove');
   				}
    		});
    		
    		$("body").bind( "touchend", function(event){
    				$('body').unbind('touchmove');
    		
    		});

   		});

   	}
   	
   	function ActivateStationSearch(){
		/*
$(".stationsearch-section").show();
		
   		$(".stationsearch").focus(function(){
   			$(this).css("color", "#333333");
   			$(this).val("");
   			$(this).unbind('focus');
   		});
   		$(".stationsearch-submit").click(function(){
   		
     		RunStationSearch();
   			    		
   		});
   		$(".stationsearch").keypress(function(e) {
  			if (e.keyCode == '13') {
     			e.preventDefault();
     			RunStationSearch();
   			}
		});
*/
	$(".stationsearch").autocomplete(stationsInfo, {
  		formatItem: function(item) {
    		return item.title;
  		}
	}).result(function(event, item) {
  		//alert(item.url);
  		location.href = item.url;
	});
	
	$("#station-search-submit").click(function () {
		RunStationSearch();
		//alert('this');
	})

   	}
   	
   	function RunStationSearch (){
   			var searchString = $(".stationsearch").val();
   			
   			//first search for stations beginning with search query
   			for (var i = 0; i < stationsInfo.length; i++){
    			var station = stationsInfo[i];
    			
   				//alert(searchString +" > "+station.title);
   				
    			if (station.title.toLowerCase().indexOf(searchString.toLowerCase()) == 0){
    				i == stationsInfo.length;
    				//PanStationWorldMap(station);
    				//PanStationTubemap(station);
    				location.href = station.url;
    				return false;
    			}
    		}
    		
    		//alert('test alert, please ignore');
   			
   			//if that fails, now search for stations that contain search query
   			for (var i = 0; i < stationsInfo.length; i++){
    			var station = stationsInfo[i];
    			
   				//alert(searchString +" > "+station.title);
   				
    			if (station.title.match(new RegExp(searchString,"gi")) != null){
    				i == stationsInfo.length;
    				PanStationWorldMap(station);
    				PanStationTubemap(station);
    				return false;
    			}
    		}
    		
    		alert('No station matches '+searchString);

   	}

   	function getOrDefault(jstring, defaultValue){
    	var string = $(jstring).val();
    	if (string == null || string == ""){
    		return defaultValue;
    	} else {
    		return parseFloat(string);
    	} 
    }
   
	function checkBounds() {
   		// If the map position is out of range, move it back
	        // Perform the check and return if OK
	        
	        var viewBounds = tubemap.getBounds(); //GLatLngBounds(sw?:GLatLng, ne?:GLatLng) 
	        var viewX = tubemap.getCenter().lng();
	        var viewY = tubemap.getCenter().lat();
	        
	        var vLeft = viewBounds.getSouthWest().lng();
	        var vTop = viewBounds.getNorthEast().lat();
	        var vRight = viewBounds.getNorthEast().lng();
	        var vBottom = viewBounds.getSouthWest().lat();
	        
	        if (vTop < tubemapLimits.top && vBottom > tubemapLimits.bottom && vLeft > tubemapLimits.left && vRight < tubemapLimits.right && vLeft < vRight){
	        	
	        	return null
	        	
	        }
	         if ($('.map-left').width() == 0) {
				return null;
				
		    } 
	        
	       	
	        if(vLeft > vRight){ // over border
	        	//trace(vLeft + " " + vRight)
	        	if(viewX < 0){
	        		// on left of map, left is wrong
	        		vLeft -= 360;
	        	} else {
	        		// on right of map, right is wrong
	        		vRight += 360;
	        	}
	        } 
	        
	        if (vTop > tubemapLimits.top){
	        	viewY -= (vTop - tubemapLimits.top)*2;
	        } 
	        if (vBottom < tubemapLimits.bottom){
	        	viewY -= (vBottom - tubemapLimits.bottom)*2;
	        }
	        if (vLeft < tubemapLimits.left){
	        	viewX -= (vLeft - tubemapLimits.left)*1.01;
	        }
	        if (vRight > tubemapLimits.right){
	        	viewX -= (vRight - tubemapLimits.right)*1.01;
	        }
	        
	       
	        	tubemap.setCenter(new GLatLng(viewY,viewX));
	        
			
	       
	}
   	   	
    function customGetTileURL(a,b) {// a == {x, y} b == zoom
    	//trace(a + " " + b);
      	//converts tile x,y into keyhole string
      	
      	
      	var c=Math.pow(2,b);
        var d=a.x;
        var e=a.y;
        var f="t";
        for(var g=0;g<b;g++){
            c=c/2;
            if(e<c){
                if(d<c){f+="q"}
                else{f+="r";d-=c}
            }
            else{
                if(d<c){f+="t";e-=c}
                else{f+="s";d-=c;e-=c}
            }
        }
        //return debugTile;
        return tileDirectory + f + ".jpg";
    }


    function getWindowHeight() {
        if (window.self&&self.innerHeight) {
            return self.innerHeight;
        }
        if (document.documentElement&&document.documentElement.clientHeight) {
            return document.documentElement.clientHeight;
        }
        return 0;
    }


    function resizeMapDiv() {
        //Resize the height of the div containing the map.
        //Do not call any map methods here as the resize is called before the map is created.
    	var d=document.getElementById("tubemap");
        var offsetTop=0;
        for (var elem=d; elem!=null; elem=elem.offsetParent) {
            offsetTop+=elem.offsetTop;
        }
        var height=getWindowHeight()-offsetTop-16;
        if (height>=0) {
            d.style.height=height+"px";
        }
    }
	
	function trace(message){
		if (alertcount < alertlimit){
			alertcount++;
			alert(message);
		}
	}
	
   	

