/**
* @fileoverview This is the main JavaScript file for the Driving Simulator
* @author Roman Nurik
* @supported Tested in IE6+ and FF2+
*/
var groups;
var chooseGp;
var isReset = false;
var overlayEarthImg;
var overlayGameImg;
var dyViewList = [];
var notShowSelection = false;
var shiftLat =0;
var shiftLon =0;
var updateShift = false;

// Array of cities which is being loaded in the game
var cityArray = [];
// Array of static placemark which will be shown at the beinging
var cityStaticPm = [];
// Array of static placemark which will replace the existing placemark in the route 
var cityReplacePm = [];


/**
* The list of driving steps loaded from google.maps.Directions
* @type {Array.<Object>}
*/
var DS_steps = [];

/**
* The list of path vertices and their metadata for the driving directions
* @type {Array.<Object>}
*/
var DS_path = []; // entire driving path

/**
* The list of route contain paths vertices of different cities
* @type {Array.<Object>}
*/
var routes = []; // entire driving path

/**
* The global simulator instance that conducts the driving simulation
* @type {DDSimulator}
*/
var DS_simulator = null; // instance of the DDSimulator class

/**
* Instead of using the plugin's built-in ID system, which doesn't like when
* IDs are reused, we will use a separate dictionary mapping ID to placemark
* object
* @type {Object}
*/
var DS_placemarks = {};


var gameStart = false;

/**
* Boolean indicate whether the cities flag being loaded or not
*	@type {Boolean}
*/
var citiesLoad = false;

/**
*	The duration time from game Start
*	@type {number}
*/
var playTime = 0;

/**
*	The city choose in the selectPath
*/
var chooseCity = '';
/**
*	The placemarks array in each city
*	@type {Array.<Array>}
*/
var cityPlacemarks = [];


/**
*	Currently loaded placemark
*/

var viewPtPM = false;

/**
*	To check whether the game is initiated when start game
*	@type {boolean}
*/
var initialGame  = false;

var cityDistance = 0;


var INFO_IMG = "http://www.nike.com.hk/local/running10k_2008/images/overlay/googleEarth_img2.png";
var EARTH_IMG = "http://www.nike.com.hk/local/running10k_2008/images/overlay/Layout_SelectCity_img2.png";



//################################################################################################################
//							Game Init Function
//
//################################################################################################################
/**
* Load Cities information from cities.xml file
* After the loading has been done, the placemark will be generate by
* calling function createCityPlacemark
*/
function loadCityXML(opt_cb){
	groups = [];
	if(!citiesLoad){
		//alert('Start Load City XML');
		cityArray = [];
		citiesLoad = true;
		loadXML = function(){
			
			// Open the cities.xml file
			//alert('document Ready XML');
			$.get("data/cities.xml",{},function(xml){
				// Run the function for each city tag in the XML file
				// alert('load XML success');
				$('city',xml).each(function(i) {
					var placemarks = [];
					
					var cityId = $(this).find("cityId").text();
					var normalIcon = $(this).find("normal").text();
					var highlightIcon = $(this).find("highlight").text();
					var lat = $(this).find("lat").text()*1;
					var lon = $(this).find("lon").text()*1;
					var fullname = $(this).find("cityId").attr("fullname");
					cityArray.push({
						cityId: cityId,
						normalIcon: normalIcon,
						highlightIcon: highlightIcon,
						lat: lat,
						lon: lon,
						fullname: fullname						
					});
					cityPlacemarks.push(placemarks);
					$('placemark', this).each(function(){
						type = $(this).find("type").text();
						normal = $(this).find("normalP").text();
						highlight = $(this).find("highlightP").text();
						lat1 = $(this).find("latP").text()*1;
						lon1 = $(this).find("lonP").text()*1;
						expStep = $(this).find("expStep").text()*1;
						desc = $(this).find("descP").text();
						group = $(this).find("group").text();
						
						cityPlacemarks[cityPlacemarks.length-1].push({
							type: type,
							normal: normal,
							highlight: highlight,
							lat: lat1,
							lon: lon1,
							expStep: expStep,
							desc: desc
						});
						
						//	Add placemark to group when exist
						if (group != '') {
							if(!groups[group]){
								groups[group] = [];
							}
							groups[group].push(cityPlacemarks[cityPlacemarks.length-1].length-1);
						};						
					});
	
				// Build row HTML data and store in string
				/*if(fullname != 'Beijing' && fullname!='HK)
					createCityPlacemark(cityId, normalIcon, highlightIcon, lat*1, lon*1, fullname);*/
				});
				createCityPlacemark();
			});
			
			if(opt_cb){
				opt_cb();
			}
		};
	loadXML();
	
	}else{
		alert('Fail Load City XML');
	}
}

/**
*	Call by loadCityXML to create city placemark
*		clcik on city placemark will call two functions
*			startGame() ==> startgame
*			selectPath(cityName) ==> To draw corresponding path of a city
*	@param {string} cityName The short form of the cityName
*	@param {string} normalIcon The path of normal icon
*	@param {string} highlightIcon The path of icon when the cursor over the placemark
*	@param {number}lat The latitude position of the placemark
*	@param {number}lon The lon position of the placemark
*	@param {string}fullname The fullname of the city
*	@param {google.icon} normal The icon of a placemark in NOT mouseover state
*	@param {google.icon.style} normalIcon The style of icon of a placemark in NOT mouseover state
*	@param {google.icon} highlight The icon of a placemark in mouseover state
*	@param {google.icon.style} highlightIcon The style of icon of a placemark in mouseover state
*/
function createCityPlacemark(){
	for (var i=0; i < cityArray.length; i++) {
		var cityId = cityArray[i].cityId;
		var normalIcon = cityArray[i].normalIcon;
		var highlightIcon = cityArray[i].highlightIcon;
		var lat = cityArray[i].lat;
		var lon = cityArray[i].lon;
		var fullname = cityArray[i].fullname;
		var placemark = IGE_ge.createPlacemark('');
		var NORMAL_CITY_ICON_SIZE = 10;
		var HIGHLIGHT_CITY_ICON_SIZE = 15;
		
		if(fullname != 'Beijing'){	
			placemark.setName(fullname);
			IGE_ge.getFeatures().appendChild(placemark);
		
			// Create style map for placemark
			var normal = IGE_ge.createIcon('');
			normal.setHref(normalIcon);
			var iconNormal = IGE_ge.createStyle('');
			iconNormal.getIconStyle().setIcon(normal);
			iconNormal.getIconStyle().setScale(NORMAL_CITY_ICON_SIZE);
		
			var highlight = IGE_ge.createIcon('');
			highlight.setHref(highlightIcon);
			var iconHighlight = IGE_ge.createStyle('');
			iconHighlight.getIconStyle().setIcon(highlight);
			iconHighlight.getIconStyle().setScale(HIGHLIGHT_CITY_ICON_SIZE);
		
			var styleMap = IGE_ge.createStyleMap('');
			styleMap.setNormalStyle(iconNormal);
			styleMap.setHighlightStyle(iconHighlight);
			placemark.setStyleSelector(styleMap);
		
			// Create point
			var la = IGE_ge.getView().copyAsLookAt(IGE_ge.ALTITUDE_CLAMP_TO_GROUND);
			var point = IGE_ge.createPoint('');
			point.setLatitude(lat);
			point.setLongitude(lon);
			placemark.setGeometry(point);
			// if(fullname != 'HK'){
				if (highlightIcon.indexOf("comingSoon") == -1)
				{				
					initPlacemarkListener(placemark, cityId, fullname, startGame);
				}
			// }else{
				// google.earth.addEventListener(placemark, 'click', function(event) {
					// event.preventDefault();
				// })	;			
			// }
			// }
			// else{
				// google.earth.addEventListener(placemark, 'click', function(event) {
					// Load the corresponding path of a city
					// event.preventDefault();
					// /*FDC_showFdiv('gameMainOverlay');
					// thisMovie('gameMainOverlay').callRunningSelection();*/
					// gameStart = true;
					// FDC_hideFdiv('gameModeTest');
					// selectPath(cityArray[i].cityId, cityArray[i].fullname, startGame);
				// });
			// }
		}
	};
}

function initPlacemarkListener(placemark, routeNo, cityFullname, opt_cb){
	google.earth.addEventListener(placemark, 'click', function(event) {
		//Load the corresponding path of a city
		event.preventDefault();
		if(!gameStart && gameMode != -1){
			//alert('Start to init Game');
			gameStart = true;
			FDC_hideFdiv('gameModeTest');
			selectPath(routeNo, cityFullname, startGame);
		}
	})	
}
/**
*	Read the routes.xml file
*	Parse the xml file and push the value to route, which then push to routes(i.e. store all the route of different city)
*	After xml is parsed, call the camera to rotate by function rotateEarth();
*	@param {number}	count  The number of path in each route, set to zero after a route is being loaded
*	@param {array}	route Array which contain the step and path information of a city
*			route[0] => step information
*			route[1] => path information
*			route[2] => Total distance of this route
*
*/
function loadRouteXML(){
	loadXML = function(){
	// Open the cities.xml file
	$.get("data/routes.xml",{},function(xml){
		
		$('routes',xml).each(function(i) {
			var routesNo = $(this).find('route').size();	//Number of routes in routes.xml
			$('route',xml).each(function(i) {
				var loadedStep = 0; // The number of steps(paths) currently loaded in this route
				var routeId = $(this).attr('id'); // The name of the route
				var route= []; // Create an new array for each route
				route[0] = []; // Step
				route[1] = []; // Path
				route[2] = $(this).find("pathDistance").text(); //Path distance of each route
				
				var step = $(this).find("step");
			
				
				paths = step.find('path').size(); // Number of steps(paths) in this route
				
				//alert("paths size: "+ paths);
				$('path', step).each(function(){
					loadedStep++;
					var lat = parseFloat($(this).find("lat").text());
					var lon = parseFloat($(this).find("lon").text());
					var thisLoc = new GLatLng(lat, lon);
					/*var distance = 30;
					var duration = 10;*/

					route[0].push({
						loc: thisLoc,
						desc: loadedStep,
						distanceHtml: '',
						pathIndex: ''
					});

					// this segment's time duration is proportional to its length in
					// relation to the length of the step
					/*route[1].push({
						loc: thisLoc,
						step: loadedStep,
						distance: distance,
						duration: duration
					});*/


					if(route[0].length == paths){
						//alert('Load routes '+routes.length+' Being');
						for (var i = 0; i < route[0].length; i++){
							var thisLoc = route[0][i].loc;
							var thisStep = route[0][i].desc;
							var distance;
							var duration;
							if(i != route[0].length -1){
								var nextLoc = route[0][i+1].loc;
								distance = IGE_geHelpers.distance(thisLoc, nextLoc);
								duration = distance*0.36;							
							}else{
								distance = 0;
								duration = 0;
							}
							route[1].push({
								loc: thisLoc,
								step: thisStep,
								distance: distance,
								duration: duration
							});
							/*if(i != route[1].length -1){
								route[1][i].distance = IGE_geHelpers.distance(route[1][i].loc, route[1][i+1].loc);
								route[1][i].duration = route[1][i].distance *0.36;
							}else{
								route[1][i].distance = 0;
								route[1][i].duration = 0;
							}*/
						}
						//alert('Load routes '+routes.length+' Done');
						routes.push(route);
					}
				});
				//alert('routes Length ' + routes.length);
				//alert('routes No ' + routesNo);
				if(routes.length == routesNo){
					//alert('Load All Route Done');
					/*alert("routes.length: "+routes.length);
					for (var i = 1; i < routes.length-1; i++) {
						alert("routes "+i+" "+routes[i][0].length+" "+routes[i][1].length);
					}*/
					testListener();
					enableMouse();
					mainNavControl(true);
					//Todo: After loading the gameMode, rotate the earth
					if(gameMode == -1){
						// Open the gameMainOverlay.swf for user to choose gameMode			
						loadSwfOverlay();
					}else{
						// If gameMode is choosed (New registration)
						// Draw overlay on the screen which show user selection
						overlayTest();
						if(thisMovie('gameModeTest'))
							setTimeout("FDC_showFdiv('gameModeTest')", 1000);
						else
							setTimeout("FDC_openFdiv('gameModeTest')", 1000);
						setTimeout("FDC_hideFdiv('gameMainOverlay')", 1000);
					}
				}
			});
		});
	});
};
loadXML();
}


/**
*	Select the corresponding route from routes when city is click
*	Clear existing Placemarks
*	Gameinfo div is being loaded and route total distance is passed to gameinfo
*	After the route is selected from routes, the route as well as placemark is draw on the gogle earth
*	Cityplacemark information is loaded and activate once the simulator start
*	Fly to start point of the route and disable the mouse navigation
*	@param {function} opt_cb The option call back after the function is completely done
*	@param {number} routeNo The coressponding number of a city in array
*	@param {google.location} startPt The starting point of the route
*	@param {google.location} endP The end point of the route
*	@param {String} lineStringKml The kml string of a path used to draw path on the google earth
*/
function selectPath(routeNo, fullname, opt_cb){
	//alert('StartPath');
	tracking('ap>hk>ru>10K_2008>game>city>'+chooseCity, 's_channel');
	
	//IGE_ge.getNavigationControl().setVisibility(ge.VISIBILITY_HIDE);
	IGE_ge.getNavigationControl().setVisibility(false);
	disableMouse();
	

	// Submit info at the beinging when play in Nike+ mode
	if(gameMode==0)
		submitInfo(maxDistance, durationTime, false);


	//Clear all existing placemark and Current Route array (i.e. DS_steps, DS_path)
	DS_steps = [];
	DS_path = [];
	IGE_geHelpers.clearFeatures();
	DS_placemarks = {};

	chooseCity = fullname;


	//alert(routeNo);
	DS_steps = routes[routeNo][0];
	DS_path = routes[routeNo][1];
	cityDistance = routes[routeNo][2];
	cityPlacemark = cityPlacemarks[routeNo];

	
	

	/*
	startPt = DS_path[0].loc;
	endPt = DS_path[DS_path.length - 1].loc;
	//alert(startPt);	
	
	//Create placemark on the google earth
	
	DS_placemarks['start'] = IGE_geHelpers.createPointPlacemark(
	new google.maps.LatLng(startPt.lat(),
	startPt.lng()),
	{description: '', icon: ''});

	for (var i = 1; i < DS_steps.length-1; i++) {
		var step = DS_steps[i];
		var placemark = IGE_geHelpers.createPointPlacemark(
		step.loc, {description: step.desc, icon: ''});
		DS_placemarks['step-' + i] = placemark;
	}

	DS_placemarks['end'] = IGE_geHelpers.createPointPlacemark(
	new google.maps.LatLng(endPt.lat(), endPt.lng()),
	{description: '', icon: ''});
	
	//End create step placemark*/
	
	
	// Create the route placemark
	// == Generate placemark string from route Array
	var lineStringKml = '<LineString><coordinates>\n';
	//alert("DS_path length: "+DS_path.length);
	for (var i = 0; i < DS_path.length; i++){
		lineStringKml +=
		DS_path[i].loc.lng().toString() + ',' +
		DS_path[i].loc.lat().toString() +
		',30 \n';
		//alert(DS_path[i].loc.lng().toString() + " "+DS_path[i].loc.lat().toString());
	}
	lineStringKml += '</coordinates></LineString>';
	// == Append placemark string to Google earth
	var routeLineString = IGE_ge.parseKml(lineStringKml);
	routeLineString.setAltitudeMode(IGE_ge.ALTITUDE_CLAMP_TO_GROUND);
	routeLineString.setTessellate(true);
	var routePlacemark = IGE_ge.createPlacemark('');
	routePlacemark.setGeometry(routeLineString);
	DS_placemarks['route'] = routePlacemark;
	routePlacemark.setStyleSelector(
	IGE_geHelpers.createLineStyle({width: 8, color: '8800fffc'}));
	IGE_ge.getFeatures().appendChild(routePlacemark);
	
	//Append Gameinfo once init Game
	infoOverlay();
	FDC_openFdiv("gameInfo", {aCallback:function(){
		thisMovie('gameInfo').initInfo(routes[routeNo][2],chooseCity);
		thisMovie('gameInfo').disableCityBtn();
	}});
	
	if(opt_cb){
		opt_cb();
	}
	
}
//################################################################################################################
//							Common Function 
//
//################################################################################################################


/**
* Formats a time given in seconds to a human readable format
* @param {number} s Time in seconds
* @return {string} A string formatted in hh:mm form representing the given
*     number of seconds
*/
function DS_formatTime(s) {
	s = parseFloat(s);
	var m = Math.floor(s / 60);
	s %= 60;
	var h = Math.floor(m / 60);
	m %= 60;
	s = Math.round(s);
	return ((h < 10) ? ('0' + h) : h) + ':' + ((m < 10) ? ('0' + m) : m)+ ':' + ((s< 10) ? ('0' + s) : s);
}

/**
*	General function to return float to any deciaml point
*	@return The float number which in certain decial point
*/
function round(number,X) {
	X = (!X ? 2 : X);
	return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
}

/**
*	Set focus to the body when keyboard mode is ON
*	@param {DOM element} The element being focus when keyboard mode on (i.e. body)
*/
function setFocus(){
	//allowFocus = false;
	var x = window.document.getElementById('bodyElement');
	x.focus();
	//setTimeout("setTimerTrue()", 500);
}

/**
*	Allow simulator to update the display and focus on the 
*/
function setTimerTrue(){
	allowFocus=true;
	updateFocus=true;
}

//#################################################################################################################
//							Flash Interface Function
//
//################################################################################################################

function flashCountDown(){
	if(thisMovie('gameMainOverlay'))
		thisMovie('gameMainOverlay').countDown();
}

/**
*	Called when game is ended to notice flash
*/
function endGameMsg(){

	distance = round(DS_simulator.totalDistance/1000,2);
	setTimeout('tracking('+'"ap>hk>ru>10K_2008>game>end_game"'+ ',"s_channel")', 2000);
	time = playTime /2;
	enableMouse();
	mainNavControl(true);
	if(gameMode != 0){
		submitInfo(distance, time, true);
	}else{
		submitInfo(maxDistance, durationTime, true);
	}
}

/**
*	Enable the mouse navigation in google earth
*/
function enableMouse(){
	IGE_ge.getOptions().setMouseNavigationEnabled(true);
}

/**
*	Disable the mouse navigation in google earth
*/
function disableMouse(){
	IGE_ge.getOptions().setMouseNavigationEnabled(false);
}

/**
*	Pause the mouse navigation in google earth
*/
function pauseGame(){
	enableMouse();
	DS_simulator.stop();
}

/**
*	Resume the game after pause
*/
function resumeGame(){
	startGame();
}

/**
*	Load the quit Game msg when press choose another city
*/
function quitGameMsg(){
	pauseGame();

	if(!thisMovie('gameMainOverlay')){
		FDC_openFdiv('gameMainOverlay', {aCallback: function(){thisMovie('gameMainOverlay').callQuitMsgBox();}});
	}else{
		FDC_showFdiv('gameMainOverlay');
		thisMovie('gameMainOverlay').callQuitMsgBox();
	}
}



/**
*	Call when Mode has been change to update the gameModeTest Panel
*/
function reqGameMode(opt_cb){
	var curMode = '';
	switch(gameMode){
		case 0: curMode = 'SB'; break;
		case 1: curMode = 'KB'; break;
		case 2: curMode = 'WC'; break;
	}
	//if(thisMovie('gameModeTest'))
	//thisMovie('gameModeTest').updateGameMode(curMode);
	//if(opt_cb)
	//	alert(opt_cb);
	//overlayTest();
}


//#################################################################################################################
function tracking(key, type){
	switch(type){
		case 's_channel': trackSChannel(key);  break;
		case 's_link': trackSLink(key);break;
		case 'file_download': trackFileDownload(key);break;
	}
}
//#################################################################################################################
//							Game Logic Function 
//
//################################################################################################################
/**
* Rotate the camera 360 degree at the begining by setting the camera position with certain high speed and
* divded into several time to avoid zoom in and zoom out effect
* @param {number} count The number of time the internal function go being called
* @param {number} oldFlyToSpeed The speed of camera move, default is 1
* @param {google.earth.lookAt} lookAtThe view of current camera
* @param {google.earth.lookAt} la Create empty look at object
* @param {function} go The function being called to change the view by 10 degree at very high altitude level
*
*/
function rotateEarth(opt_cb){
	var count = 0;
	var oldFlyToSpeed = IGE_ge.getOptions().getFlyToSpeed();
	IGE_ge.getOptions().setFlyToSpeed(100);
	go = function(count) {
		var lookAt = IGE_ge.getView().copyAsLookAt(IGE_ge.ALTITUDE_RELATIVE_TO_GROUND);

		var la = IGE_ge.createLookAt('');
		la.set(lookAt.getLatitude() , lookAt.getLongitude() + 10,
				 20000000, IGE_ge.ALTITUDE_RELATIVE_TO_GROUND, 0, 0, 0 );
		IGE_ge.getView().setAbstractView(la);

		if (count < 37) {
			setTimeout('go(' + (count+1) + ')', 5);
		} else {
			IGE_ge.getOptions().setFlyToSpeed(oldFlyToSpeed);
			tracking('ap>hk>ru>10K_2008>game>choose_city', 's_channel');
		}
	}
	go(0);
	
}

function setGroup(groupId){
	chooseGp = groupId;
}

/**
*	Start the game when click on the country flag
*
*	It also initialize udpate Display progress (i.e. pass parameter to flash)
*/
function startGame(){
	Xspeed = 0;
	disableMouse();

	//alert(gameMode);

	if (!DS_simulator){
		//alert('startGame');
		resetSimulator(
		function() {
			//alert('simulator start');
			mainNavControl(false);
			//alert('call back in start game');
			DS_simulator.start();
		});
	}
	else {
		//alert('Simulator exist');
		DS_simulator.start();
		mainNavControl(false);



	}
};

/**
*	Reset the game and craete DS_simulator instance
*	@param {function} on_tick The function will run when each graphic being rendered
*	@param {function} on_tick The function will run after the simulator reach each step
*		=> it will check whether the step have corresponding city placemark
*			if coressponding placemark exist, create placemark and feature ballon to display coressponding msg
*/
function resetSimulator(opt_cb){
	//alert('resetSimulator');
	if (DS_simulator)
	DS_simulator.destroy();
	// create a DDSimulator object for the current DS_path array
	// on the IGE_ge Earth instance
	DS_simulator = new DDSimulator(IGE_ge, DS_path, {
		// as the simulator runs, reposition the map on the right and the
		// car marker on the map, and update the status box on the bottom
		on_tick: function() {
			//IGE_ge.getOptions().setFlyToSpeed(1000);
		},

		on_changeStep: function() {
			//alert('step change '+cityPlacemark.length);
			if(cityPlacemark.length){
				var expStep = false;
				//var loadedPlacemark = 0;
				
				//Clear last view point placemark when exist
				if (viewPtPM) {
					IGE_ge.getFeatures().removeChild(DS_placemarks[viewPtPM]);
					viewPtPM = false;
				};
				
				//Reset the ballon when pass each step
				if(!expStep)
					IGE_ge.setBalloon(null);
				
				for (var i = 0; i < cityPlacemark.length; i++){
					
					
					//alert(cityPlacemark[i].expStep);
					

					
					if(cityPlacemark[i].expStep == DS_simulator.currentStep_){
						
						var currPlacemarkId = cityStaticPm.shift();
						
						if(!expStep){
							/*
							loadedPlacemark++;
							if(chooseCity == 'HK' && loadedPlacemark != 3){
								alert('True: loadedPlacemark: '+loadedPlacemark);
								expStep = false;
							}else{
								alert('False: loadedPlacemark: '+loadedPlacemark);
								expStep = true;
							}*/
							
							//alert('Find expStep '+cityPlacemark[i].expStep);
							//	Remove placemark if it is static type 
							if (cityPlacemark[i].type == 'static' && cityPlacemark[i].expStep!=0){
								if (cityPlacemark[i-1].expStep ==0) {
									var removeId = currPlacemarkId;
									//alert('static Placemark create is ' + i);
									//alert('static Placemark destroy is ' + removeId);
									IGE_ge.getFeatures().removeChild(DS_placemarks['cityPlacemark'+removeId]);
									DS_placemarks['cityPlacemark'+i] = IGE_geHelpers.createPointPlacemark(
									new google.maps.LatLng(cityPlacemark[i].lat, cityPlacemark[i].lon),
									{description: cityPlacemark[i].desc, icon: cityPlacemark[i].normal, iconSize: 20});	
									viewPtPM = 'cityPlacemark'+i;
								}
							};
							
							//If the placemark is dynamic
							if(cityPlacemark[i].type!= 'static'){
								//f(chooseCity != 'HK'){
									//alert('Load dynamic content');
									var vNum = Math.floor(Math.random()*dyViewList.length);
									//alert('Total Number is ' + dyViewList.length + " Random No: "+ vNum);
																	
									var removeId = currPlacemarkId;
	
									// alert('dynamic Placemark create is ' + dyViewList[vNum]);
									// alert('dynamic Placemark destroy is ' +removeId);
									var currLat = DS_placemarks['cityPlacemark'+removeId].getGeometry().getLatitude() ;
									var currLon = DS_placemarks['cityPlacemark'+removeId].getGeometry().getLongitude();
									//alert('before create placemark');
									IGE_ge.getFeatures().removeChild(DS_placemarks['cityPlacemark'+removeId]);
									DS_placemarks['cityPlacemark'+dyViewList[vNum]] = IGE_geHelpers.createPointPlacemark(
									new google.maps.LatLng(currLat, currLon),
									{description: cityPlacemark[dyViewList[vNum]].desc, icon: cityPlacemark[dyViewList[vNum]].normal, iconSize: 20});
									//alert('After create placemark');
									viewPtPM = 'cityPlacemark'+dyViewList[vNum];
								/*}else{
									var removeId = currPlacemarkId;
									IGE_ge.getFeatures().removeChild(DS_placemarks['cityPlacemark'+removeId]);
									
									var vNum = Math.floor(Math.random()*dyViewList.length);
								google.earth.addEventListener(DS_placemarks['cityPlacemark'+dyViewList[vNum]],
								 'click', function(event) {
									//Load the corresponding path of a city
									event.preventDefault();
									openLink("http://www.nike.com.hk/local/running10k_2008/images/user_shadow.png",
									 "Photo", "status=yes,location= yes,menubar=yes,scrollbars=yes,toolbar=yes,resizable=yes,width=800,height=600");});	
								}*/
							}
						}
					}
				}

			}
		}
	});
	DS_simulator.initUI(opt_cb);
}

/**
*	Reset all elements in the game
*	Set chooseCity to empty String
*	Hide the game info div
*	Clear the status HTML
*	Reset the playTime
*	Reset City Loaded
*	Clear the load interval
*	Destroy simulator
*	Clear interval
*	Remove all placemark
*	Fly to original point
*	Redraw city  flag  again..
*/
function resetGame(opt_cb){
	IGE_ge.getNavigationControl().setVisibility(IGE_ge.VISIBILITY_SHOW);
	var navControl = IGE_ge.getNavigationControl();
	var screenXY = navControl.getScreenXY();
	screenXY.setXUnits(IGE_ge.UNITS_PIXELS);
	screenXY.setYUnits(IGE_ge.UNITS_INSET_PIXELS);  
	
	cityStaticPm = [];
	
	groups = [];
	chooseGp = '';
	
	gameStart = false;
	initialGame = false;
	citiesLoad = false;
	
	viewPtPM = false;
	isReset = true;



	$('#status').html('');
	chooseCity = '';
	playTime = 0;
	Xspeed = 0;

	
	enableMouse();
	//alert('reset game test 0');

	dyViewList = [];
	//alert('reset game test 1');
	FDC_showFdiv('gameModeTest');
	FDC_closeFdiv('gameInfo');
	//alert('reset game test 2');
	if (DS_simulator){
		DS_simulator.destroy();
		DS_simulator = null;
	}
	//alert('reset game test 3');
	
	IGE_ge.setBalloon(null);

	IGE_geHelpers.clearFeatures();
	DS_placemarks = {};
	flyToLocation(orgLookAt, false);
	overlayTest();	
	createCityPlacemark();
	if(opt_cb){
		if(opt_cb.hide)
			mainNavControl(true);
	}
}

/**
*	Loading placemark when countdown to 2
*	
*/
function preloadCityPlacemark(opt_cb){

	//	Create view point placemark
	if(cityPlacemark.length){
		
		// if (chooseCity == 'HK') {
			// setGroup(1);
			//alert(chooseGp);
			// dyViewList = groups[chooseGp];
		// };
		
		for (var i = 0; i < cityPlacemark.length; i++){
			// if (chooseCity != 'HK'){
				if(cityPlacemark[i].type =='dynamic'){
					var dynamicId = i;
					dyViewList.push(dynamicId);
				}
			//}
			if(cityPlacemark[i].type == 'static' && cityPlacemark[i].expStep == 0){
				DS_placemarks['cityPlacemark'+i] = IGE_geHelpers.createPointPlacemark(
					new google.maps.LatLng(cityPlacemark[i].lat, cityPlacemark[i].lon),
					{description: cityPlacemark[i].desc, icon: cityPlacemark[i].normal, iconSize: 12});
				cityStaticPm.push(i);
				//alert(i);	
			}
		}	
	}
	
	if(opt_cb.from){
		//alert('Call preloadCityPlacemark from '+opt_cb.from);
	}
		
}

/**
*	Call the flash movie to submit game info when the mode is 0 and once the game is started
*	Control whether to show the game result screen by third parameter
*	@param distance: distance which will then be submited to database
*	@param time:	time which will then be submited to database
*	@param showEndGame: to indicate whether to show the game result Panel
*/
function submitInfo(distance, time, showEndGame){

	var mode;
	switch(gameMode){
		case 0: mode ='SB';break;
		case 1: mode ='KB';break;
		case 2: mode ='WC';break;
	}
	
	if(distance > 100)
		distance = round(distance / 1000, 2);
		
	if(gameMode == 0)
		distance = maxDistance/1000;
		
	if(showEndGame)
		thisMovie('gameMainOverlay').callEndGame(chooseCity, time, distance);
	//alert('submitInfo Mode' + mode+'    City: '+chooseCity+'    Distance: '+distance+'    Time: '+time+'    ');
	if(!(gameMode == 0 && showEndGame))
		thisMovie('gameMainOverlay').gameSubmission(mode, chooseCity, distance, time);
}
//#################################################################################################################
//							Build in Google Earth function
//
//################################################################################################################
/**
	* To update whether to display building layer on Google Map
	*	option: boolean => 
	*		true : display the google earth building layer
	*		false: disable the whole building layer
	*/

function updateBuildingLayer(option){
	IGE_ge.getLayerRoot().enableLayerById(IGE_ge.LAYER_BUILDINGS, option);
}


//#################################################################################################################
//							Overlay Related Function
//
//#################################################################################################################
function overlayTest(){
	if(IGE_ge){
		createImgOverlay(EARTH_IMG, 824.5, 442.5, 309, 319, 'earth');		
	}
}

function infoOverlay(){
	//alert('infoOverlay');
	createImgOverlay(INFO_IMG, 846, 260, 270, 328, 'info');
}

/**
*	To Create img overlay with certain properties
*	_path: image path
*/
function createImgOverlay(_path, _x, _y, _width, _height, _type) {
	removeOverlay();
	
	var screenOverlay = IGE_ge.createScreenOverlay('');
	screenOverlay.setIcon(IGE_ge.createIcon(''));
	screenOverlay.getIcon().setHref(_path);

	// anchor point.
	screenOverlay.getOverlayXY().setXUnits(IGE_ge.UNITS_PIXELS);
	screenOverlay.getOverlayXY().setYUnits(IGE_ge.UNITS_PIXELS);
	screenOverlay.getOverlayXY().setX(0);
	screenOverlay.getOverlayXY().setY(0);

	// Set screen position in fractions.
	screenOverlay.getOverlayXY().setXUnits(IGE_ge.UNITS_PIXELS);
	screenOverlay.getOverlayXY().setYUnits(IGE_ge.UNITS_PIXELS);
	screenOverlay.getOverlayXY().setX(_x);
	screenOverlay.getOverlayXY().setY(_y);
	
	// Set object's size in pixels.
	screenOverlay.getSize().setXUnits(IGE_ge.UNITS_PIXELS);
	screenOverlay.getSize().setYUnits(IGE_ge.UNITS_PIXELS);
	screenOverlay.getSize().setX(_width);
	screenOverlay.getSize().setY(_height);
	
	switch(_type){
		case 'info': overlayEarthImg = screenOverlay;
		case 'earth': overlayGameImg = screenOverlay;
	}
	
	IGE_ge.getFeatures().appendChild(screenOverlay);
}


/**
	*	Remove all overlay in the game
	*	@param overlayGameImg: 	google earth placemark 
	*	@param overlayEarthImg:	google earth placemark 
	*/
function removeOverlay(){

	if(overlayGameImg){
		IGE_ge.getFeatures().removeChild(overlayGameImg);
	}
	if(overlayEarthImg){
		IGE_ge.getFeatures().removeChild(overlayEarthImg);
	}
}
//#################################################################################################################
//							DEBUG / Testing Function
//
//#################################################################################################################
/**
*	Listener to detect mouse click on GE
*/
function testListener(){
	if (!window.globeWindowEventListener) {
	  window.globeWindowEventListener = function(event) {
	    var text = '';

	    function addToMessage(append1, append2) { 
	      text += ' ' + append1 + ' ' + append2  ;
	    }
	
	    addToMessage('<path><lat>', event.getLatitude());
	    addToMessage('</lat><lon>', event.getLongitude());
	    addToMessage('</lon>', '</path>\n');
	    
		//$('#status').html(text);
		$('#myarea').val(text) ;
		
	  }
	}

	google.earth.addEventListener(IGE_ge.getGlobe(), "mousedown",
	                              window.globeWindowEventListener);
	google.earth.addEventListener(IGE_ge.getWindow(), "mousedown",
	                              window.globeWindowEventListener);
}
//#################################################################################################################
/**
*	Control the the navigation bar on the top of the screen
*		flag => set the navigation enable of disable
*				=>true: Enable flase: Disable
*/
function mainNavControl(flag){
	if(flag){
		thisMovie('home').enable();
	}else{
		thisMovie('home').disable();
	}
}
//#################################################################################################################

