

GazelleUI = {
	
	
	showTeamNumber:0,
	
	init: function(lng, lat, zoom) {
		
		//console.warn('init');
	
		if (GBrowserIsCompatible()) {
			this.map = new GMap2(document.getElementById("map")); 
			this.map.setMapType(G_SATELLITE_MAP);
			this.map.setCenter(new GLatLng(lat,lng), zoom); 
			this.map.addControl(new GLargeMapControl());
			this.slider = null;
		}else{
			alert("Google map can't working with your current browser");	
		}
	},
	
	
	clearRoute: function(){
		if(typeof(GazelleUI.routeOverlay)!='undefined'){
			GazelleUI.map.removeOverlay(GazelleUI.routeOverlay[0]);
			GazelleUI.map.removeOverlay(GazelleUI.routeOverlay[1]);
		}
	},
	
	
	
	
	setSideBarTeams: function(teams){
		
		
		var container = $("containerTeams");
		container.select("div.containerTeam").invoke("hide");
		
		var c = $("containerTeam_parcoursId_" + currentParcours().id);
		
		if(!c){
			var c= new Element("div",{id:"containerTeam_parcoursId_" + currentParcours().id, className: "containerTeam"});
			container.appendChild(c);
			
			teams.each(function(team){
				var node = Builder.node("label",{}, [
					Builder.node("input",{type:"checkbox", className:'checkboxTeam', id:"checkbox_team_" + team.id, value:1, checked:"checked"}),
					Builder.node("span",{},team.num),
					team.name
				]);
				

				c.appendChild(node);
				
				var input = Element.down(node,"input");
				
				input.team = team;
				
			
				input.observe("click",function(e){
					var input = e.element();
					
					GazelleUI.addOverlay(input.checked, input.team, false, true);
					
					
					var ids = GazelleUI.getSelectedTeamsId();
					if(ids.length != 1){
						GazelleUI.clearRoute();
					}else{
						currentParcours().teamFromId(ids[0]).displayRoute();
					}
				});
				
				
			}.bind(this));
		}
		
		GazelleUI.showSideBarTeam(currentParcours().id);
		
	},
	
	
	showSideBarTeam: function(parcoursId){
		if(!parcoursId){
			parcoursId = currentParcours().id;
		}	
		
		
		var container = $("containerTeams");
		container.select("div.containerTeam").invoke("hide");
		
		var c = $("containerTeam_parcoursId_" + parcoursId);
		
		c.show();		
		
	},	
	
	
	
	
	
	
	selectAllTeams: function(){
		$("containerTeam_parcoursId_" + currentParcours().id).select("input.checkboxTeam").each(function(input){
			input.checked = true;
		});	
		currentParcours().displaySelectedTeams();
	},
	
	
	unselectAllTeams: function(){
		$("containerTeam_parcoursId_" + currentParcours().id).select("input.checkboxTeam").each(function(input){
			input.checked = false;
		});	
		
		GazelleUI.clearCurrentMarkersOverlay();
	},	
	
	
	

	
	
		
	
	setSliderFromDateTimes: function(dateTimeMinMax, stayOnTheSameValue){
		
		
		dateMin = dateTimeMinMax['min'];
		dateMax = dateTimeMinMax['max'];
		
		
		
		if(dateMin != dateMax){
			
			
			var dateTimes = [];
			dateTmp = dateMin;
			var cpt = 0;
			while(dateTmp <= dateMax && cpt < 30000){
				cpt++;
				dateTimes.push(dateTmp);
				dateTmp = addMinutes(dateTmp, MONITORING_INTERVAL);
			}
			//console.warn(dateTimes.length);
			//console.warn(dateTmp);
			
		
			$("heure1").update(GazelleUI.dateTimePrettyPrint(dateMin));
			$("heure2").update(GazelleUI.dateTimePrettyPrint(dateMax));
			
			var currentValue = 0;
			

			if(this.slider){
				currentValue = this.slider.value;
				var onMax = false;
				if(currentValue==GazelleUI.currentdateTimes.length -1){
					onMax = true;
				}
				this.slider.dispose();
				delete(this.slider);
			}

		
			GazelleUI.currentdateTimes = dateTimes;
			GazelleUI.maxDateTime = dateMax;
			
			this.slider = new Control.Slider('curseur', 'barre', {
				range: $R(0, dateTimes.length-1),
				values: $R(0, dateTimes.length-1),
				sliderValue: dateTimes[dateTimes.length-1],
				
				onSlide: function(v) { 
					dateTime = GazelleUI.currentdateTimes[v];
					//console.warn(GazelleUI.currentdateTimes[v]);
					$("spanCurrentTime").update(GazelleUI.dateTimePrettyPrint(dateTime));
				},
				
				onChange: function(v) { 
					dateTime = GazelleUI.currentdateTimes[v];
					//console.warn(GazelleUI.currentdateTimes[v]);
					$("spanCurrentTime").update(GazelleUI.dateTimePrettyPrint(dateTime));
					
					currentParcours().displaySelectedTeams(dateTime);
					
				}
				
			});
			

			if((stayOnTheSameValue && onMax) || !currentValue){
				this.slider.setValue(dateTimes.length-1);
			}else{
				this.slider.setValue(currentValue);
			}

		}else{
			this.slider.dispose();
			delete(this.slider);
			
			$("heure1").update(".");
			$("heure2").update(".");
			$("spanCurrentTime").update("?");
		}
		
	},
	
	

	
	
	
	currentDateTime: function(){
		return GazelleUI.currentdateTimes[this.slider.value];
	},
	
	
	
	dateTimeToHash: function(value){
		var o={};
		o.day = value.substr(2,2);
		o.h = value.substr(4,2);
		o.m = value.substr(6,2);
		return o;
	},
	
	dateTimePrettyPrint: function(value){
		var o = GazelleUI.dateTimeToHash(value);
		//var moroccoTime = (parseInt(parseFloat(o.h)) + 4)%24;
		var moroccoTime = o.h
		var moroccoDay = o.day;
		/*if( (parseInt(parseFloat(o.h)) + 4) > 23){
			o.day = parseFloat(parseInt(o.day)) + 1;
		}*/
		return I18N.le + " " + o.day+ " "+ I18N.agrave +" " + moroccoTime +"h"+ o.m;
	},
	
	
	
	sliderPrevious: function(){
		if(!this.slider){ return false; }
		var v = GazelleUI.slider.value;
		if(v>0){
			this.slider.setValue(v-1);	
		}
	},
	
	
	sliderNext: function(){
		if(!this.slider){ return false; }
		var v = GazelleUI.slider.value;
		if(v<GazelleUI.currentdateTimes[GazelleUI.currentdateTimes.length-1]){
			this.slider.setValue(v+1);	
		}
	},
	
	
	
	
	
	getSelectedTeamsId: function(parcoursId){
		if(!parcoursId){
			parcoursId = currentParcours().id;
		}
		
		container = $("containerTeam_parcoursId_" + parcoursId);
		var a=[];
		container.select("input.checkboxTeam").each(function(el){
			if(el.checked){
				a.push(el.id.substr(14));
			}
		});
		return a;
	},
	
	
	
	clearCurrentMarkersOverlay: function(){
		if(GazelleUI.currentMarkersDateTime){
			//remove all the current marker from the map
			currentParcours().teams.each(function(team){
				if(team.overlay){
					GazelleUI.addOverlay(false, team);
				}
			});
		}
		GazelleUI.clearRoute();
	},	
	
	
	
	addOverlay: function(state, team, dateTime){
		
		if(state){
			if(!dateTime){
				dateTime = GazelleUI.currentDateTime();	
			}		
		
			var p = team.positions["p" + dateTime];
			if(!p){
				console.debug("error 45sdf");
				return false;
			}
			

			if(parseInt(p.dir)>0){
				team.defaultIcon = new GIcon(G_DEFAULT_ICON);
				team.defaultIcon.image = "../uploads/customTexts/" + team.num + "_" + p.dir + ".png";
				team.defaultIcon.iconSize = new GSize(38,38);
				team.defaultIcon.shadowSize = new GSize(0,0);					
				team.defaultIcon.iconAnchor  = new GPoint(19,19);	
				team.defaultIcon.dragCrossAnchor  = new GPoint(19,19);
				team.defaultIcon.imageMap = [11,11,  29,11,  29,29,  11,29];
				 	
				
			}else{
				team.defaultIcon = new GIcon(G_DEFAULT_ICON);
				team.defaultIcon.image = "../uploads/customTexts/" + team.num + ".png";
				team.defaultIcon.iconSize = new GSize(23,14);
				team.defaultIcon.shadowSize = new GSize(0,0);
				team.defaultIcon.iconAnchor  = new GPoint(19,19);
				team.defaultIcon.dragCrossAnchor  = new GPoint(19,19);	
			}
			
			//team.defaultIcon.image = "http://www.rallyeaichadesgazelles.com/ui/img/icons_gmap/drapeau.png";
			
			
			var overlay = new GMarker(new GLatLng(p.lat,p.lng), {icon: team.defaultIcon, title:team.name, zIndexProcess:function(){return(1000)}});
			
			GEvent.addListener(overlay, "click", function() {
				team.loadFullData();
				team.displayRoute();
			});
			
			
			
			
			team.overlay = overlay;
			GazelleUI.map.addOverlay(overlay);

			

			
				
		}else{
			if(team.overlay){
		
				GazelleUI.map.removeOverlay(team.overlay);
				delete(team.overlay);
				team.overlay = null;
			}
		}

	},
	
	
	
	centerOnTeam: function(team){
		var p = team.positions["p" + GazelleUI.currentDateTime()];
		GazelleUI.map.setCenter(new GLatLng(p.lat,p.lng,9));
	},
	
	
	
	setBottomBar: function(team){
		
		
		if(team){
			
			$("numero").down("span").update(team.num);
		
			$("numero").show();
			var t = "<p class='containerTeammateInfo'><img height='68' src='#{image}' align='left'>#{nationality}<br><b>#{fullName}</b><br>#{job}<br>#{participation} participation<br></p>";
			var template = new Template(t);
			
			

			var html = "";
			team.teammates.each(function(teammate){
				html += template.evaluate(teammate);
			});
			
			$("containerTeammates").update(html);
			
			GazelleUI.currentTeam = team;
			//team.showFiche()
			
			
		}else{
			$("containerTeammates").update("");
			$("numero").hide();
		}
		
	},
	
	
	
	viewFicheCurrentTeam: function(){
		if(GazelleUI.currentTeam){
			GazelleUI.currentTeam.showFiche();
		}
	}
	
	
	
	

}





























var Parcours = Class.create();  
Parcours.prototype = {
 
 
	initialize: function(parcoursId) {
		
		this.id = parcoursId;
		this.teams = null;
		this.loadedPositions = [];
		
		
		this.loadTeams();
				
	},
	
	
	defaultView: function(){
		this.kmlOverlay.gotoDefaultViewport(GazelleUI.map);
	},
	
	
	display: function(){
		
		if(!this.kmlOverlay){
			var url = document.location.href.substring(0, document.location.href.split('?')[0].lastIndexOf('/')+1) + "kml.php?p=" + this.id;
			console.debug(url);
			this.kmlOverlay = new GGeoXml(url);
			GazelleUI.map.addOverlay(this.kmlOverlay);
		}
			
		
		if(this.kmlOverlay.isHidden()){
			this.kmlOverlay.show();
		}
		this.defaultView();
		this.loadDateTimes();

	},
	
	
	
	
	hide: function(){
		this.kmlOverlay.hide();
	},
	
	showHide: function(state){
		if(state){
			this.show();	
		}else{
			this.hide();	
		}
	},
	
	hideAll: function(){
		this.hide();
		GazelleUI.clearCurrentMarkersOverlay();	
	},
	
	
	displaySelectedTeams: function(dateTime){
	
		
		if(!dateTime){
			dateTime = GazelleUI.currentDateTime();	
		}
		
		
		if(!this.loadedPositions.include(dateTime)){
		
			var ar = new Ajax.Request('positions.php?action=getPositions&parcours='+ this.id + "&dateTime=" + dateTime + "&year=" + year, {});
			ar.options.onSuccess = function(origReq){
				var json = origReq.responseText.evalJSON();
				json.each(function(positions){
					var team = this.teamFromNum(positions.team);
					if(!team.positions){
						team.positions = {};
					}
					team.positions["p" + dateTime] = positions;
					
				}.bind(this));
				
				this.loadedPositions.push(dateTime);
				this.displaySelectedTeams(dateTime);
			}.bind(this);
			
			
			
		}else{
			GazelleUI.clearCurrentMarkersOverlay();	
			
			var team = this.teamFromId(GazelleUI.showTeamNumber);
			if(GazelleUI.showTeamNumber && team){
				
				GazelleUI.centerOnTeam(team);
				team.loadFullData();
				$("containerTeam_parcoursId_" + this.id).select("input.checkboxTeam").each(function(input){
					input.checked = (input.id == "checkbox_team_" + GazelleUI.showTeamNumber);	
				}.bind(this));
				
				GazelleUI.showTeamNumber=0;
				
			}			
			
			
			var teamsIds = GazelleUI.getSelectedTeamsId();
			
			teamsIds.each(function(teamId){
				
				var team = this.teamFromId(teamId);
				if(team){
					
					if(team.positions && team.positions["p" + dateTime]){
						GazelleUI.addOverlay(true, team, dateTime);
						
					}else{
						console.debug("No position for " + dateTime + " (team id: " + team.id + ")");	
					}
					

					
					
				}else{
					console.debug("oups... error 45s");
				}
			}.bind(this));
			
			if(teamsIds.length == 1){
				this.teamFromId(teamsIds[0]).displayRoute();
			}
			
			GazelleUI.currentMarkersDateTime = GazelleUI.currentDateTime();
			
			

			
			
		}

		
			
	},

	


	
	loadDateTimes: function(){
		var ar = new Ajax.Request('positions.php?action=getDateTimes&parcours='+ this.id, {});
		ar.options.onSuccess = function(origReq){
			var dateTimes = origReq.responseText.evalJSON();
			GazelleUI.setSliderFromDateTimes(dateTimes);
		}.bind(this);
			
	},
	
	
	refresh: function(){
		var ar = new Ajax.Request('positions.php?action=getDateTimes&parcours='+ this.id, {});
		ar.options.onSuccess = function(origReq){

			var dateTimeMinMax = origReq.responseText.evalJSON();
			if(dateTimeMinMax['max'] != GazelleUI.maxDateTime && this.id == currentParcours().id){
			//if(dateTimes.length != GazelleUI.currentdateTimes.length && this.id == currentParcours().id){
				GazelleUI.setSliderFromDateTimes(dateTimeMinMax, true);
			}else{
				console.debug("no new dateTimes");	
			}
		}.bind(this);		
	},
	
	
	
	loadTeams: function(){
		
		
		if(!this.teams){
			
			
			var ar = new Ajax.Request('teams.php?action=getTeams&parcours='+ this.id, {});
			ar.options.onSuccess = function(origReq){

				var dataTeams = origReq.responseText.evalJSON();
				
				this.teamsKey = {};
				this.teamsKeyId = {};
				this.teams = [];
				
				
				dataTeams.each(function(teamData, index){
					var key = "t" + teamData.num;
					var keyId = "t" + teamData.id;
					this.teamsKey[key] = index;
					this.teamsKeyId[keyId] = index;
					
					this.teams.push(new Team(teamData));
					
				}.bind(this));
				
				
				this.loadTeams();
				
				this.display();
				
			}.bind(this);
		}else{
			
			GazelleUI.setSideBarTeams(this.teams);
		}
	},
	
	
	
	teamFromNum: function(teamNum){
		var key = "t" + teamNum;
		return this.teams[this.teamsKey[key]];
	},
	
	teamFromId: function(id){
		var key = "t" + id;
		return this.teams[this.teamsKeyId[key]];
	}
	
	
	
}











var Team = Class.create();  
Team.prototype = {
	
	initialize: function(data) {
		this.id = data.id;
		this.name = data.name;
		this.num = data.num
		this.positions = {};
		this.routeData = [];
		this.routeLastestPointDate = 0;
	},


	loadFullData: function(){
		if(!this.loadedFullData){
			var ar = new Ajax.Request('teams.php?action=getFullData&team='+ this.id, {});
			ar.options.onSuccess = function(origReq){
				var json = origReq.responseText.evalJSON();
				this.teammates = json;
				this.loadedFullData = true;
				GazelleUI.setBottomBar(this);
			}.bind(this);
		}else{
			GazelleUI.setBottomBar(this);
		}

	},
	
	
	
	showFiche: function(){
		showGazellesFile(this.id, this.num,null);	
	},
	
	
	displayRoute: function(tryAjax){
		
		
		if(typeof(tryAjax) == 'undefined'){
			tryAjax = true;
		}
		
		if(tryAjax && GazelleUI.currentDateTime() > this.routeLastestPointDate){
		
			var ar = new Ajax.Request('teams.php?action=getRoute&teamId='+ this.id + '&parcoursId=' + currentParcours().id, {});
			ar.options.onSuccess = function(origReq){
				var json = origReq.responseText.evalJSON();
				
				//this.routeLastestPointDate = json[json.length-1].date
				this.routeLastestPointDate = GazelleUI.currentDateTime();
				this.routeData = json;
				
				this.displayRoute(false);
				
			}.bind(this);		
			
		}else{

			var a = [];
			
			var currentDateTime = GazelleUI.currentDateTime();
			
			this.routeData.each(function(points){
				if(points.date <= currentDateTime){
					a.push(new GLatLng(points.lat, points.lng));
				}
			});
			
			GazelleUI.clearRoute();
			
			var polyline1 = new GPolyline(a, "#000000", 5, 1);
			GazelleUI.map.addOverlay(polyline1);
			
			var polyline2 = new GPolyline(a, "#ffffff", 2, 1);
			GazelleUI.map.addOverlay(polyline2);
			
			GazelleUI.routeOverlay = [polyline1, polyline2];
				
		}
		
		
	}
	
	
	
}




function twoDigits(v){
	var v = ''+v;
	if(v.length<2){
		return '0'+v;
	}
	return v;
}



function addMinutes(MMddhhmm,minToAdd){
	var month = parseInt(parseFloat(MMddhhmm.substr(0,2)));
	var day = parseInt(parseFloat(MMddhhmm.substr(2,2)));
	var hours = parseInt(parseFloat(MMddhhmm.substr(4,2)));
	var minutes = parseInt(parseFloat(MMddhhmm.substr(6,2)));

	var x = new Date(2000, month-1, day, hours, minutes + minToAdd, 0, 0)
	var res = twoDigits(x.getMonth() + 1 ) + twoDigits(x.getDate()) + twoDigits(x.getHours()) + twoDigits(x.getMinutes());
	if(MMddhhmm == res){
		console.warn(res);
	}
	return res
}
