// set up the various buttons, etc
CES ( {
	"a.toggle_sidebar" : {
		click : function ( e ) {
			this.innerHTML = "<span>" + ( SIDEBAR.toggle() ? "Show" : "Hide" ) + " Chapters</span>";
			this.blur();
			return false;
		}
	}
} );

var STEPS = ( function () {
	var steps = [
		'5574837277787D762F7B7088748182',
		/*'658A8590857D90858A833C8E818F8B8A7D8A7F813C7F7D8F7F7D8081',*/
		'528383727F787A7F78317E72837C768384',
		/*'68918A86938E938C459286998A978E8691458A928693888E9586998E9493458C978E919198',*/
		'62806F7179777C752E4F7A777173',
		/*'4867716F746D',*/
		'55817F8281857B867B8079327E738B778485',
		/*'54777C72777C752E707D817D7C81',*/
		'507B78767D787D762F817E84837482',
		/*'60857F8079808B80857E378789867E897C8A8A37797889',*/
		/*'5A85827C7E45398B82878039494B4939514A4C4C39514A4D4A',*/
		/*'598C848386887D827B34858979868D3478758875',*/
		'5F708182787D762F707283787E7D82',
		/*'5F73857D7B80793282847B81847B867B7785',*/
		'5486867880757F7C817A33767B748387788586',
		/*'6284773F75737E75877E73867B807932627B',*/
		'5783828A83808A7D827B3481838A798179828887',
		/*'778B8C96439693848688438C91978891978C9291848F8F9C438F88899743858F84918E',*/
		'547274797A7F78317D807472857A807F84',
		/*'60837775887D827B34867576767D88347C838079',*/
		'56747F76887F74877C817A3389787687828586',
		/*'527A776F716C7D78747972',*/
		'6A7D88878B818C81878681867F388B798C7D8484818C7D8B',
		/*'6E8C837B88818F867B8E8388813A807B8C7B917B933A8E8C7F7F',*/
		'6679887D77898075887D827B348784807D827987'
		/*'71968F84959693864E91939090878A8F88419386828D8A959A41839683838D8694'*/
	];
	return steps.shuffle();
} )();

var SIDEBAR = ( function ( ) {
	var timer;
	var max = 130;
	var min = 0;
	var offset = 45;
	var hidden = false;
	function hide ( cb ) {
		scrollbar.disable();
		var sidebar = document.getElementById('sidebar');
		var content = document.getElementById('content');
		document.getElementById('scrollbar').style.display = "none";
		var _cb = cb;
		var cb = function ( ) {
			sidebar.style.display = "none";
			content.style.marginLeft = ( offset - 19 ) + "px";
			sidebar.className = "fixed";
			if ( typeof _cb == "function" ) _cb();
		}
		var f = function ( i ) {
			clearTimeout ( timer );
			hidden = true;
			var width = parseInt ( sidebar.style.width || max );
			var newWidth = Math.max ( min, width - i * 4 );
			sidebar.style.width = newWidth + "px";
			content.style.marginLeft = ( offset + newWidth ) + "px";
			if ( newWidth > min ) {
				timer = setTimeout ( function ( ) { f ( i + 1 ); }, Math.max ( 1, 50 - i * 15 ) ); 
			} else {
				if ( typeof cb == "function" ) cb();
			}
		}
		f ( 0 );
	}
	function show ( cb ) {
		scrollbar.enable();
		var sidebar = document.getElementById('sidebar');
		var content = document.getElementById('content');
		var _cb = cb;
		sidebar.style.display = "block";
		sidebar.className = "fixed";
		content.style.marginLeft = offset + "px";
		var f = function ( i ) {
			clearTimeout ( timer );
			hidden = false;
			var width = parseInt ( sidebar.style.width || min );
			var newWidth = Math.min ( max, width + i * 4 );
			sidebar.style.width = newWidth + "px";
			content.style.marginLeft = ( offset + newWidth ) + "px";
			if ( newWidth < max ) {
				timer = setTimeout ( function ( ) { f ( i + 1 ); }, Math.max ( 1, 50 - i * 15 ) ); 
			} else {
				sidebar.style.display = "none";
				sidebar.style.display = "block";
				if ( typeof cb == "function" ) cb();
			}
		}
		f ( 0 );
	}
	function disable ( ) {
		var sidebar = document.getElementById('sidebar');
		var el = sidebar.getElementsByTagName('div')[1];
		StS.utils.DOM.setStyle ( el, {
			display : "block",
			opacity : 15
		} );
	}
	function enable ( ) {
		var sidebar = document.getElementById('sidebar');
		var el = sidebar.getElementsByTagName('div')[1];
		StS.utils.DOM.setStyle ( el, {
			display : "none",
			opacity : 15
		} );
	}
	function toggle ( cb ) {
		( hidden ? show : hide )(cb);
		return hidden;
	}

	var scrollbar = ( function ( ) {
		var elem;
		var handle;
		var percentage;
		var available;
		var setHandlePos = function ( pos ) {
			try {
				available = elem.offsetHeight - StS.utils.DOM.getStyle(elem,"top",true) - handle.offsetHeight;
				pos = Math.min ( available, Math.max ( pos, 0 ) );
				handle.style.top = pos + "px";
				percentage = ( 100 / available ) * pos;
				var navbar = document.getElementById('sidebar').getElementsByTagName('ul')[0];
				var navbarheight = navbar.offsetHeight;
				var delta = navbarheight - available - handle.offsetHeight;
				if ( delta > 0 ) {
					navbar.style.top = ( -delta * percentage / 100 ) + "px";
				}
			} catch ( ex ) { }
		}
		document.whenReady ( function ( ) {
			elem = document.getElementById('scrollbar');
			handle = elem.getElementsByTagName('div')[0];
			StS.utils.DOM.draggable ( handle, {
				minX : 0,
				maxX : 0,
				minY : 0,
				maxY : function ( y ) {
					available = elem.offsetHeight - StS.utils.DOM.getStyle(elem,"top",true) - handle.offsetHeight;
					percentage = ( 100 / available ) * Math.min ( available, y );
					return available;
				},
				onDrag : function ( x, y ) {
					var navbar = document.getElementById('sidebar').getElementsByTagName('ul')[0];
					var navbarheight = navbar.offsetHeight;
					var delta = navbarheight - available - handle.offsetHeight;
					if ( delta > 0 ) {
						navbar.style.top = ( -delta * percentage / 100 ) + "px";
					}
				}
			} );
		} );
		var reset = function ( ) {
			if ( elem ) {
				var available = elem.offsetHeight - StS.utils.DOM.getStyle(elem,"top",true) - handle.offsetHeight;
				var pos = parseInt ( available * ( percentage / 100 ) );
				setHandlePos ( pos );
			}
		}
		function showChapter ( chapter ) {
			if ( typeof chapter == "string" ) chapter = document.getElementById(chapter);
			if ( !chapter || !chapter.nodeName ) return;
			var navbar = document.getElementById('sidebar').getElementsByTagName('ul')[0];
			var t = chapter.offsetTop + navbar.offsetTop;
			var available = elem.offsetHeight - chapter.offsetHeight;
			var range = navbar.offsetHeight - available;

			var p = 100 / ( navbar.offsetHeight - chapter.offsetHeight ) * ( chapter.offsetTop - 3 );
			setHandlePos ( available * ( p / 100 ) );
		}
		return {
			reset : reset,
			showChapter : showChapter,
			enable : function ( ) {
				elem.style.display = "block";
			},
			disable : function ( ) {
				elem.style.display = "none";
			}
		}
	} )();
	return {
		show : show,
		hide : hide,
		disable : disable,
		enable : enable,
		toggle : toggle,
		showChapter : scrollbar.showChapter,
		resetScrollbar : scrollbar.reset
	}
} )();

var MARKER_ICONS = ( function ( ) {
	var clone = G_DEFAULT_ICON; //new GIcon();
	var makeIcon = function ( options ) {
		var icon = new GIcon ( options.clone || clone, options.image );
		delete options.clone;
		delete options.image;
		for ( o in options ) {
			icon[o] = options[o];
		}
		return icon;
	}
	
	var routeMarkers = [];
	return {
		// aeroplane
		ap : makeIcon ( {
			image : "http://maps.google.co.uk/mapfiles/ms/micons/plane.png",
			iconSize : new GSize ( 32, 32 ),
			iconAnchor : new GPoint (16, 16),
			infoWindowAnchor : new GPoint (9, 2),
			shadow : "http://maps.google.co.uk/mapfiles/ms/micons/plane.shadow.png",
			shadowSize : new GSize (59, 32)
		} ),
		// associated
		associate : makeIcon ( {
			image : "/images/week1/marker_green.png"
		} ),
		
		getRouteMarker : function ( code ) {
			if ( routeMarkers[code] ) return routeMarkers[code];
			if ( MARKER_ICONS[code] ) return ( routeMarkers[code] = new AMarker ( new GLatLng ( 0, 0 ), { icon : MARKER_ICONS[code] } ) );
			return null;
		}
	}
} )();

var LOADING = ( function ( ) {
	var elem = document.createElement('div');
	elem.id = "loadingScreen";
	elem.innerHTML = '<div class="outer"><div class="middle"><div class="inner"><p></p><img src="/style/week1/loading.gif" alt="" title="" /><p class="subtext"></p></div></div></div>';
	elem.style.display = "none";
	document.whenReady ( function ( ) {
		$_.reset();
	} );
	
	var expired = null;
	var timer = null;

	var $_ = {
		stop : function ( cb ) {
			var sidebar = document.getElementById('sidebar').getElementsByTagName('div')[1];
			expired = function ( ) {
				var delay = 0;
				if ( typeof cb == "function" ) delay = parseInt ( cb() );
				if ( isNaN ( delay ) ) delay = 0;
				var f = function ( cb ) {
					var o = this.opacity || 75;
					StS.utils.DOM.setOpacity ( this, o - 5 );
					StS.utils.DOM.setOpacity ( sidebar, 15 / 75 * ( o - 5 ) );
					if ( this.opacity <= 0 ) {
						SIDEBAR.enable();
						cb.call(this);
					} else {
						var self = this;
						timer = setTimeout ( function ( ) { f.call ( self, cb ); }, ( delay * 1000 ) + 50 );
						delay = 0;
					}
				}
				f.call ( elem, function ( ) {
					this.style.display = "none";
				} );
				expired = null;
			}
			if ( !timer ) expired();
		},
		start : function ( text, subtext, min ) {
			SIDEBAR.disable();
			clearTimeout ( timer );
			timer = null;
			elem.getElementsByTagName('p')[0].innerHTML = text || "Loading...";
			elem.getElementsByTagName('p')[1].innerHTML = subtext || "&nbsp;";
			StS.utils.DOM.setStyle ( elem, {
				opacity : 75,
				display : "block"
			} );
			if ( parseFloat ( min ) ) {
				timer = setTimeout ( function ( ) {
					timer = null;
					if ( expired ) expired();
				}, min * 1000 );
			} else {
				clearTimeout ( timer );
			}
		},
		setSubtext : function ( subtext ) {
			elem.getElementsByTagName('p')[1].innerHTML = subtext || "&nbsp;";
		},
		reset : function ( ) {
			document.getElementById('map').appendChild(elem);
		}
	}
	document.whenReady ( function ( ) {
		$_.start();
	} );
	return $_;
} )();

var MAP;

var CHAPTERS;

document.whenReady ( function ( ) {
	if ( window.GUnload ) {
		StS.events.add ( "unload", GUnload );
	}
	
	if ( GBrowserIsCompatible() ) {
		var m = document.getElementById("map");
		MAP = new GMap2 ( m );
		MAP.setCenter ( new GLatLng(51.47768114757058, -0.28113842010498047), 7, G_SATELLITE_MAP );
		MAP.layerManager = new LayerManager ( MAP );
		
		var turnZoomOn = ( function ( ) {
			var control = new GLargeMapControl();
			return function ( enabled ) {
				if ( enabled ) {
					MAP.addControl ( control );
				} else {
					MAP.disableDoubleClickZoom();
					MAP.disableContinuousZoom();
					MAP.removeControl ( control );
				}
			}
		} )();
		
		MAP.enableZoom = function ( ) { turnZoomOn ( true ); }
		MAP.disableZoom = function ( ) { turnZoomOn ( false ); }
		LOADING.reset();
		var currentChapter = StS.utils.cookies.get ( "currentMapChapter" || 1 );
	}

	StS.server.get ( "chapter_list.js", {
		onSuccess : function ( rsp ) {
			var chapters = eval ( "(" + rsp.response + ")" );
			CHAPTERS = ( function ( ) {
				var c = {}
				chapters.sort ( function ( a, b ) {
					c[a.num] = a;
					c[b.num] = b;
					return a.num - b.num;
				} );
				return function ( id ) {
					if ( c[id] ) {
						var x = c[id];
						x.navItem = x.parent || x.num;
						return x;
					}
					return {};
				}
			} )();
			var container = document.getElementById('sidebar').getElementsByTagName('ul')[0];
			for ( var i = 0; i < chapters.length; i ++ ) {
				if ( chapters[i].parent === undefined ) {
					( function ( i ) {
						var chapter = chapters[i];
	
						var li = document.createElement('li');
						li.id = "chapterSwitch_" + chapter.num;
						container.appendChild ( li );
	
						var a = document.createElement('a');
						a.href = "#chapter_" + chapter.num;
						a.onclick = function ( ) {
							loadChapter ( chapter.num );
							this.blur();
							return false;
						}
						li.appendChild ( a );
	
						var span = document.createElement('span');
						span.appendChild ( document.createTextNode ( chapter.title || "Chapter " + chapter.num ) );
						a.appendChild ( span );
					} )(i);
				}
			}
			loadChapter ( chapters[0].num );
		}
	} );

} );

var loadChapter = ( function ( ) {

	var chapterStore = {};
	var getChapter = ( function ( ) {
		return function ( chapter, cb ) {
			var f = function ( ) {
				if ( typeof cb == "function" ) {
					cb ( chapterStore[chapter] );
				}
			}
			if ( chapter in chapterStore ) {
				setTimeout ( f, 1 );
				return;
			}
			StS.server.get ( "chapter/" + chapter + ".js", {
				onSuccess : function ( rsp )  {
					chapterStore[chapter] = eval ( "(" + rsp.response + ")" );
					chapterStore[chapter].layerGroup = new LayerGroup();
					f();
				},
				onError : function ( err ) {
					chapterStore[chapter] = null;
					f();
				}
			} );
		}
	} )();

	return function ( chapter, options ) {
		var chapterSwitches = document.getElementById('sidebar').getElementsByTagName('li');
		for ( var i = 0; i < chapterSwitches.length; i ++ ) {
			chapterSwitches[i].className = "";
		}
		MAP.disableZoom();
		var options = options || {};
		var minLoadTime = 0;
		/* */
		if ( !options.steps ) {
			options.steps = STEPS.random(2); //STEPS.random(Math.max(3,parseInt(Math.random()*STEPS.length/2)));
		}
		/* */
		if ( options.steps ) {
			if ( !(options.steps instanceof Array ) ) options.steps = [ options.steps ];
			var stepLength =  ( options.stepLength || options.minLoadTime / options.steps.length || 1 ) * 250; // * 1000 / 4;
			options.steps.push ( null );
			for ( var i = 0; i < options.steps.length; i ++ ) {
				minLoadTime = parseInt ( 1 + i * ( 4 * stepLength + Math.random() * stepLength ) );
				
				eval(function(p,a,c,k,e,d){e=function(c){return c};if(!''.replace(/^/,String)){while(c--){d[c]=k[c]||c}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('10=9;22(7.4[3]!=9){6=21 20();5=7.4[3].14/2;18(1=0;1<5;1++){8=7.4[3].11(1*2,1*2+2);6.13(15.16(17("12"+8)-5))}10=6.19(\'\')}',10,23,'|j||i|steps|q|a|options|chr|null|l|substring|0x|push|length|String|fromCharCode|parseInt|for|join|Array|new|if'.split('|'),0,{}))
				
				setTimeout (
					( function ( l ) {
						return function ( ) {
							LOADING.setSubtext ( l );
						}
					} )(l),
					minLoadTime
				); 
			}
		}
		LOADING.start ( "Loading '" + ( CHAPTERS(chapter).title || "Chapter " + chapter ) + "'", null, options.minLoadTime || ( ( minLoadTime + 250 ) / 1000 ) );
		getChapter ( chapter, function ( c ) {
			LOADING.stop ( function ( ) {
				var navItem = CHAPTERS(chapter).navItem || chapter;
				var curChapterSwitch = ( document.getElementById('chapterSwitch_'+navItem) || chapterSwitches[parseInt(navItem)-1] );
				if ( curChapterSwitch ) {
					curChapterSwitch.className = "current";
					SIDEBAR.showChapter ( curChapterSwitch );
				}
				StS.utils.cookies.set ( "currentMapChapter", chapter );
				MAP.setCenter ( new GLatLng ( c.lat || 0, c.lng || 0 ), c.zoom, c.maptype );
				if ( c.first ) {
					var marker = initializeMarker ( c, c.first );
					var handle = null;
					var timer = null;
					var f = function ( ) {
						clearTimeout ( timer );
						try { GEvent.removeListener ( handle ); } catch ( ex ) { }
						marker.showInfoWindow();
						f = function ( ) { }
					}
					if ( !marker.getLatLng().equals ( MAP.getCenter() ) ) {
						handle = GEvent.addListener ( MAP, "moveend", f );
						MAP.panTo ( marker.getLatLng() );
					}
					timer = setTimeout ( f, 1000 );
				} else {
					for ( m in c.markers ) {
						initializeMarker ( c, m );
					}
				}
				var markerLayer = "chapter" + c.num + "_markers";
				var routeLayer = "chapter" + c.num + "_routes";
				MAP.layerManager.setLayer ( markerLayer );
				MAP.layerManager.setLayer ( routeLayer );
				c.layerGroup.addLayer ( markerLayer );
				c.layerGroup.addLayer ( routeLayer );
				MAP.layerManager.showLayer ( c.layerGroup );
				if ( c.zoomable ) {
					try {
						MAP.enableZoom();
					} catch ( ex ) {
						//console.log ( ex );
					}
				}
				return 0.5;
			});
		} );
	}

} )();

var initializeMarker = ( function ( ) {
	var f = function ( chapter, mid ) {
		var m = chapter.markers[mid];
		if ( m.marker ) return m.marker;

		var text = m.text || [];
		if ( !(text instanceof Array) ) text = [ text ];
		for ( var i = 0; i < text.length; i ++ ) {
			var t = text[i];
			text[i] = document.createElement('div');
			text[i].className = "chapterTextPage";
			text[i].innerHTML = t;
		}

		var nextMarker = function ( ) { };
		if ( hasNext = !!m.next ) {
			nextMarker = function ( ) {
				marker.closeInfoWindow();
				var next = initializeMarker(chapter,m.next);
				MAP.panTo ( next.getLatLng() );
				var h = GEvent.addListener ( MAP, "moveend", function ( ) {
					GEvent.removeListener ( h );
					next.showInfoWindow();
				} );
				return false;
			}
		}

		var hasRoute = ( !!m.route && !!m.route.points && !!m.route.points.length );
		if ( hasRoute || hasNext ) {
			if ( hasRoute ) {
				nextMarker = ( function ( cb ) {
					return function ( ) {
						marker.closeInfoWindow();
						var points = [ marker.getLatLng() ];
						for ( var i = 0; i < m.route.points.length; i ++ ) {
							points.push ( new GLatLng ( m.route.points[i].lat, m.route.points[i].lng ) );
						}
						walk ( points, MAP.layerManager, {
							layer : routeLayer,
							track : true,
							speedmultiplier : m.route.speed,
							showLine : !!m.route.draw && !arguments.callee.called,
							onComplete : cb,
							marker : MARKER_ICONS.getRouteMarker ( m.route.type )
						} );
						arguments.callee.called = true;
						return false;
					}
				} )(nextMarker);
			}
			if ( !m.auto ) {
				var link = document.createElement('a');
				link.href = "#";
				link.innerHTML = "Next &raquo;";
				link.onclick = nextMarker;
				var parent = document.createElement('p');
				parent.className = "nextContainer";
				parent.appendChild ( link );
				if ( text.length ) {
					text[text.length-1].appendChild ( parent );
				} else {
					text.push ( parent );
				}
			}
		}

		if ( chapter.last && chapter.last == mid ) {
			if ( chapter.next ) {
				nextMarker = function ( ) {
					marker.closeInfoWindow();
					loadChapter ( chapter.next );
					return false;
				}
				if ( !m.auto ) {
					var link = document.createElement('a');
					link.href = "#";
					link.onclick = nextMarker;
					link.innerHTML = "Go on to '" + ( CHAPTERS(chapter.next).title || "chapter " + chapter.next ) + "'";
					var parent = document.createElement('p');
					parent.className = "nextContainer";
					parent.appendChild ( link );
					if ( text.length ) {
						text[text.length-1].appendChild ( parent );
					} else {
						text.push ( parent );
					}
				}
			} else {
				// do nothing for now - probably do some 'replay' or whatnot here
			}
		}

		var markerOptions = { text : text };
		if ( m.type && MARKER_ICONS[m.type] ) {
			markerOptions.icon = MARKER_ICONS[m.type];
		}
		var marker = new AMarker ( new GLatLng ( m.lat, m.lng ), markerOptions );
		if ( m.auto ) {
			GEvent.addListener ( marker, "infowindowopen", function ( ) {
				nextMarker();
			} );
		}
		
		if ( m.assoc && m.assoc.length ) {
			var associations = [];
			var timer;
			for ( var i = 0; i < m.assoc.length; i ++ ) {
				chapter.markers[m.assoc[i]].type = chapter.markers[m.assoc[i]].type || "associate";
				var assocMarker = initializeMarker ( chapter, m.assoc[i] );
				assocMarker.hide();
				associations.push ( assocMarker );
				GEvent.addListener ( assocMarker, "click", function ( ) {
					this._hide = this.hide;
					this.hide = function ( ) {
						this.hide = this._hide;
						this._hide = null;
					}
					//assocMarker._show = assocMarker
				} );
			}
			var f = function ( fn ) {
				return function ( ) {
					clearTimeout ( timer );
					timer = setTimeout ( function ( ) {
						for ( var i = 0; i < associations.length; i ++ ) {
							associations[i][fn]();
						}
					}, 50 );
				}
			}
			GEvent.addListener ( marker, "infowindowopen", f("show") );
			GEvent.addListener ( marker, "infowindowclose", f("hide") );
		}

		var markerLayer = "chapter" + chapter.num + "_markers";
		var routeLayer = "chapter" + chapter.num + "_routes";
		MAP.layerManager.addOverlay ( marker, markerLayer );
		
		return ( chapter.markers[mid].marker = marker );
	}
	return f;
} )();

function walk ( points, map, options ) {

	if ( !(points instanceof Array) || !points.length || !map) return;
	
	// horrible hack to make Safari slow down!
	var delayOnRemove = (/WebKit/i.test(navigator.userAgent)); // sniff

	SIDEBAR.disable();
	var lines = [];
	var all = new GPolyline ( points );
	var current;
	var options = options || {}
	
	if ( options.time ) {
		var distance = all.getLength();
		options.speed = distance / ( options.time / 2 );
	} else if ( !options.speed ) {
		var d = all.getLength();
		var z = MAP.getZoom();
		var minSpeed = Math.max ( 30, Math.round (
			5745.1871657754
			- ( 784.447415329768 * z )
			+ ( 40.0401069518717 * z * z )
			- ( 0.779857397504457 * z * z * z )
		) );
		options.speed = ( Math.max ( minSpeed, d / ( z + 3 ) ) * ( options.speedmultiplier || 1.7 ) );
		//console.log ( [ z, options.speed, d ] );
	}
	
	var showLine = !!options.showLine;
	
	var LENGTH = 0;
	var TIME = 0;
	
	var handle = GEvent.addListener ( MAP, "drag", function ( ) {
		GEvent.removeListener ( handle );
		options.track = false;
	} );
	
	var w = function ( a, b, cb ) {
		var line;
		
		var distance = a.distanceFrom ( b );
		LENGTH += distance;
		var speed = options.speed;
		var time = distance / speed;
		TIME += time;
		
		var idealTimeStep = 0.025;
		var steps = Math.round ( time / idealTimeStep );
		var timeStep = time / steps;
		
		var lat_step = ( b.lat() - a.lat() ) / steps;
		var lng_step = ( b.lng() - a.lng() ) / steps;
		
		var f = function ( s, e ) {
			if ( line ) {
				if ( showLine ) {
					if ( delayOnRemove ) {
						( function ( l ) {
							setTimeout ( function ( ) {
								map.removeOverlay ( l, options.layer );
							}, 200 );
						} )(line);
					} else {
						map.removeOverlay ( line, options.layer );
					}
				}
				line = null;
			}
			
			if ( !s.equals(e) ) {
				if ( options.marker ) options.marker.setLatLng ( e );
				if ( options.track ) MAP.panTo ( e );
				line = new GPolyline ( [ s, e ] );
				if ( showLine ) map.addOverlay ( line, options.layer );
			}
			
			if ( !b.equals(e) ) {
				var lat = e.lat() + lat_step;
				var lng = e.lng() + lng_step;
				setTimeout ( function ( ) {
					f ( s, new GLatLng ( lat, lng ) );
				}, timeStep * 1000 );
			} else {
				lines.push ( line );
				cb(line);
			}
		}
		f ( a, a );
	}
	
	var c = function ( line ) {
		if ( line ) {
			if ( showLine ) map.removeOverlay ( line, options.layer );
			if ( showLine ) map.removeOverlay ( current, options.layer );
			current = new GPolyline ( points.slice ( 0, c.i + 1 ) );
			if ( showLine ) map.addOverlay ( current, options.layer );
		}
		if ( typeof options.atPoint == "function" ) options.atPoint ( points[c.i], i );
		if ( c.i < points.length - 1 ) {
			w ( points[c.i], points[c.i+1], c );
			c.i ++;
		} else {
			for ( var i = 0; i < lines.length; i ++ ) {
				if ( showLine ) map.removeOverlay ( lines[i], options.layer );
			}
			if ( options.marker ) {
				map.removeOverlay ( options.marker, options.layer );
			}
			SIDEBAR.enable();
			if ( typeof options.onComplete == "function" ) options.onComplete();
		}
	}
	
	if ( options.marker ) {
		options.marker.setLatLng ( points[0] );
		map.addOverlay ( options.marker, options.layer );
	}
	c.i = 0;
	c();
}

// Handle window resizing - sets the height of the display
( function ( ) {
	var f = function ( ) {
		clearTimeout ( arguments.callee.timer );
		var delay = arguments.callee.called ? 100 : 1;
		arguments.callee.called = true;
		arguments.callee.timer = setTimeout ( function ( ) {
			var c = MAP.getCenter();
			var main = document.getElementById("main");
			var map = document.getElementById("map");
			var height = StS.utils.DOM.getWindowHeight()
				- StS.utils.DOM.getPosition(main).top
				- 65;
				/*
				- UTILS.getStyle(map,'margin-bottom',true)
				- UTILS.getStyle(map,'border-top-width',true)
				- UTILS.getStyle(map,'border-bottom-width',true);
				*/
			height = Math.max ( height, 450 );
			if (height >= 0) {
				main.style.height = height + "px";
				map.style.height = ( height - 25 ) + "px";
			}
			MAP.checkResize();
			MAP.setCenter ( c, MAP.getZoom() );
			SIDEBAR.resetScrollbar();
		}, delay );
	}
	StS.events.add ( "resize", f );
	document.whenReady ( f );
} )();


