/* Recherche groupe */
function showFormCreaGroupe()
{
	hide('indexGroup');
	show('divFormCreate');
	$("#contentGroupe").animate( { height:"500px"  }, { queue:true, duration:300 } );
}

function submitFormSearchGroup1(){	
	document.getElementById("searchAdress").value='1';
	document.formRechGroupe.submit();
}

function submitFormSearchGroup2(){
	
	document.getElementById("searchname").value='1';
	document.formRechGroupe.submit();
}

/* Cartographie */
var markerRechGroupe = null;
var errorLieu = 0;
function searchAdresseGroupe()
{
	var adresse = $("#lieu").val() + ", France";
	// Recherche des coordonnees d'un point dont on connait l'adresse :
	geocoder.getLatLng(adresse, function (coord)
	{
		
		if (coord == null){
			errorLieu = 1;
			show('messErreurLieu');
			return;
		}
		map.clearOverlays();
		map.setCenter(coord, 16);
		
		$("#lat").val(coord.lat());
		$("#lng").val(coord.lng());

		var Icon = new GIcon(); 
		Icon.image = web_path + "/images/groupe_icon.png"; 
		//Icon.shadow = web_path + "/images/groupe_ombre.png";
		Icon.iconSize = new GSize(31, 31); 
		//Icon.shadowSize = new GSize(43, 34); 
		Icon.iconAnchor = new GPoint(10, 31); 
		Icon.infoWindowAnchor = new GPoint(6, 1); 
		//Icon.infoShadowAnchor = new GPoint(13, 13);
		
		if(markerRechGroupe!=null)
			map.removeOverlay(markerRechGroupe);
		
		markerRechGroupe = new GMarker(coord,{icon:Icon, draggable:true, bouncy:false});
		
		// Get the new waypoints from the newMarkers array and call loadFromWaypoints by dragend
		GEvent.addListener(markerRechGroupe, "dragend", function()
		{							
		  getAddressGroupeDD(markerRechGroupe.getLatLng());	  
		  
		  var coord = markerRechGroupe.getLatLng();
		  
		  document.getElementById("lat").value = coord.lat();
		  document.getElementById("lng").value = coord.lng();
		  
		});
		errorLieu = 0;
		hide('messErreurLieu');
		map.addOverlay(markerRechGroupe);   
	});
}

/* Validation du formulaire de création */
function validateCreateGroup (){
	var error = 0;
	if ($('#nom').val() == "") {
		error = 1;
		$("#nom").addClass("errorForm");
	}
	else
		$("#nom").removeClass("errorForm");
	if ($('#lieu').val() == "" || errorLieu == 1) {
		error = 1;
		$("#lieu").addClass("errorForm");
	}
	else
		$("#lieu").removeClass("errorForm");
	
	if (error != 1){
		$('#formCreateGroupe').submit();
	}
}

/* Gestion de la map pour les résultats de trajets compatibles */
function CreateMarkerEventGroupe(marker,id_trajet,id_depart,data)
{	
	GEvent.addListener(marker, "click", function() {
		clicked=true;
		
		/*var bounds = tabDirMouseOver[id_depart].getBounds();
		var center = bounds.getCenter();
		map.setCenter(center);*/
		
		if(data[1]=="1" && tabPolysMouseOver[id_depart])
			tabPolysMouseOver[id_depart].show();
				
		var code = '<div class="infobulle">';
		if(data[1]=="0")
			code += '<img src="'+web_path + '/images/icoResGpePassager.png" /> <span>'+data[7]+'</span>';
		else
			code += '<img src="'+web_path + '/images/icoResGpeConducteur.png" /> <span>'+data[7]+'</span>';
		code += '<BR/>'+data[10];		
		code += "</div>";
		marker.show();
		marker.openInfoWindowHtml(code);
	});
	  
	GEvent.addListener(marker, "mouseover", function() {
		if(document.getElementById('lineResult'+id_depart))
			document.getElementById('lineResult'+id_depart).className = "trajetSelected";
		
		if(document.getElementById('sens_groupe')){
			if(document.getElementById('sens_groupe').value==1)			
				tabMarkers[id_depart][0].show();
			else if(document.getElementById('sens_groupe').value==2)			
				tabMarkers[id_depart][1].show();
		}
		
		if(data[1]=="1")
			tabPolysMouseOver[id_depart].show();
		
		var code = '<div class="infobulle">';
		if(data[1]=="0")
			code += '<img src="'+web_path + '/images/icoResGpePassager.png" /> <span>'+data[7]+'</span>';
		else
			code += '<img src="'+web_path + '/images/icoResGpeConducteur.png" /> <span>'+data[7]+'</span>';
		code += '<BR/>'+data[10];
		code += "</div>";		
		
		marker.openInfoWindowHtml(code);
	});
	
	GEvent.addListener(marker, "mouseout", function() {
		if(!clicked){			
			/*tabMarkers[id_depart][0].hide();				
			tabMarkers[id_depart][1].hide();					
			
			if(document.getElementById('lineResult'+id_depart))
				document.getElementById('lineResult'+id_depart).className = "resultatsTrajets";
			
			if(tabPolysMouseOver[id_depart])
				tabPolysMouseOver[id_depart].hide();*/
			
			marker.closeInfoWindow();
			showAllMarkers();
		}
	});
}

var tabTrajetIsConducteur = [];

function createLigneResultat (results, i, id_groupe, sens, max) {
	var ul = $(document.createElement('ul'));
	ul.addClass("resultatsTrajets");
	ul.attr("style", "margin:0px;cursor:pointer;");
	ul.attr("id", "lineResult"+results[11]);
	ul.bind("click", function (){chooseResult(results[0], results[11]);});
	ul.bind("mouseover", function (){survoleTrajetListe(results[11],1,results[1], 1);});
	ul.bind("mouseout", function (){survoleTrajetListe(results[11],2,results[1], 1);});

	//Rôle et markeur
	var li = $(document.createElement('li'));
	li.addClass("iconeMapGroupe");	
	li.attr("style", "width:40px;");				
	var markeur = $(document.createElement('img'));					
	markeur.attr("src", tabImagesMarkers[i%10]);
	markeur.attr("style", "float: left;height:20px;");
	li.append(markeur);
	var ico = $(document.createElement('img'));
	if (results[1] == 1){
		src = web_path + "/images/icoResGpeConducteur.png";
		ico.attr("style", "float:left;");
		ico.addClass("margint-1");
	}
	else {
		src = web_path + "/images/icoResGpePassager.png";
		ico.attr("style", "float:left;width:12px;");
		ico.addClass("marginl-1");
	}
	ico.attr("src", src);
	li.append(ico);
	ul.append(li);
	//Nom
	li = $(document.createElement('li'));
	li.addClass("identifiant_groupe");
	
	var identifiantGroupe = results[7];	
				
	li = $(document.createElement('li'));
	if (identifiantGroupe.length < 15)
		li.attr('style', 'width:90px;line-height:29px;font-size:12px;');
	else
		li.attr('style', 'width:90px;font-size:9px;');
	if (identifiantGroupe.length > 30)
		li.text(identifiantGroupe.substring(0, 30)+'...');
	else
		li.text(identifiantGroupe);
		
	ul.append(li);
	//Date et heure
	li = $(document.createElement('li'));
	li.attr("style", "margin-left: 0px;");
	var span = $(document.createElement("span"));
	span.attr("id", "spanHoraire_"+i);
	var tabTmp2 = results[3].split("-");
	var dateCmp = new Date(tabTmp2[0],(tabTmp2[1]-1),tabTmp2[2]);
	var dateToday = new Date();
	dateCmp = dateCmp.getDate()+"-"+dateCmp.getMonth()+"-"+dateCmp.getFullYear();
	dateToday = dateToday.getDate()+"-"+dateToday.getMonth()+"-"+dateToday.getFullYear();
	var tabTmp3;
	tabTmp3 = results[2].split(":");
	var tmpTabDate = results[3].split("-");
	if(dateToday == dateCmp)
	{
		span.addClass("fontsize19");
		txt = tabTmp3[0]+"H"+tabTmp3[1];
	} 
	else 
	{
		txt = tmpTabDate[2]+"-"+tmpTabDate[1]+"-"+tmpTabDate[0] + " " + tabTmp3[0] + "H" + tabTmp3[1];
	}
	span.text(txt);

	
	li.append(span);
	li.append('<input type="hidden" name="datePassageGroupe'+i+'" id="datePassageGroupe'+i+'" value="'+tmpTabDate[0]+'-'+ tmpTabDate[1] + '-' + tmpTabDate[2]+'"/><input type="hidden" name="heurePassageGroupe'+i+'" id="heurePassageGroupe'+i+'" value="'+tabTmp3[0]+':'+tabTmp3[1]+'"/>');
	ul.append(li);
	
	/*
	 * Mis en Commentaire demande 118 - 22/04/2010
	 */
	//Drapeau si ça provient du groupe
	/*li = $(document.createElement('li'));
	li.addClass('iconeMapGroupe');	
	li.attr('style', 'margin-left: 15px;');	
	if (id_groupe == results[27]){
		img = $(document.createElement('img'));
		img.attr("src", web_path + "/images/groupe_icon.png");
		li.append(img);
	}
	ul.append(li);
	//Prix
	li = $(document.createElement('li'));
	li.addClass('identifiant');
	li.attr('style', 'width:30px;margin-left:30px;');
	if (results[1] == 0)
		li.text(Math.ceil(results[24]/10) + '€');
	else
		li.text('-');
	ul.append(li);*/
	//Affichage de la destination selon le sens de recherche
	var destinationGroupe = "";	
	if (sens == 1)
		destinationGroupe = results[10];
	else
		destinationGroupe = results[20];			
	li = $(document.createElement('li'));
	li.addClass('destination_groupe');
	if (destinationGroupe.length < 20)
		li.attr('style', 'width:130px;line-height:29px;font-size:12px;');
	else
		li.attr('style', 'width:130px;font-size:9px;');
	if (destinationGroupe.length > 25)
		li.text(destinationGroupe.substring(0, 25)+'...');
	else
		li.text(destinationGroupe);
	ul.append(li);
	
	$("#contenuResultatsTrajets").append(ul);
	
	function importanceOrder (marker,b) 
	{return max;}	
	
	var pointTmp = new GLatLng(results[8],results[9]);
	var monicone = new GIcon();
	monicone.image = tabImagesMarkers[i%10];
	monicone.shadow = web_path + "/images/ombre.png"; 
	monicone.iconSize = new GSize(35,35); 
	monicone.shadowSize = new GSize(22, 20); 
	monicone.iconAnchor = new GPoint(18,35); 
	monicone.infoWindowAnchor = new GPoint(6, 1); 
	monicone.infoShadowAnchor = new GPoint(13, 13);
	
	var marker = new GMarker(pointTmp,{icon:monicone,zIndexProcess:importanceOrder,bounceGravity:5});

	CreateMarkerEvent(marker, results[0],results[11],results, 1, 1);											
	map.addOverlay(marker);
	if (sens == 2)
		marker.hide();
	//boundsMapGlobal.extend(marker.getLatLng());
	tabMarkers[results[11]] = [];
	tabMarkers[results[11]].push(marker);

	pointTmp = new GLatLng(results[12], results[13]);
	marker = new GMarker(pointTmp,{icon:monicone,zIndexProcess:importanceOrder,bounceGravity:5});
	CreateMarkerEvent(marker, results[0],results[11],results, 2, 1);
	map.addOverlay(marker);	
	if (sens == 1)
		marker.hide();
	//boundsMapGlobal.extend(marker.getLatLng());
	tabMarkers[results[11]].push(marker);
	CreateDirectionMap(results[11],results[12],results[13],results[8],results[9]);
	
	tabTrajetIsConducteur[results[11]] = results[1];
}

function calculHeurePassageGroupe (nb){
	
	var latDep = tabResultsGroupe[nb][0];
	var lngDep = tabResultsGroupe[nb][1];
	var latGroupe = tabResultsGroupe[nb][2];
	var lngGroupe = tabResultsGroupe[nb][3];
	var date = tabResultsGroupe[nb][4];
	var heure = tabResultsGroupe[nb][5];
	var i = tabResultsGroupe[nb][6];	
	var directionCalcul = new GDirections();
	departTrajet = new GLatLng(latDep, lngDep);
	pointGroupe = new GLatLng(latGroupe, lngGroupe);
	
	GEvent.addListener(directionCalcul, "error", function() {
		calculHeurePassageGroupe (nb);
	});
	
	GEvent.addListener(directionCalcul, "load", function() {
		//Récupération du temps de parcours
		var duration = directionCalcul.getDuration();
		time = secondsToTime(duration.seconds);
		//Ajout à l'heure de départ du trajet
		tabDate = date.split("-");
		tabHeure = heure.split(":");
		var dateFormat = new Date (tabDate[0], tabDate[1]-1, tabDate[2],tabHeure[0], tabHeure[1], '');
		timeCalc = parseInt(time.h)*60 + parseInt(time.m);
		dateFormat.setMinutes(dateFormat.getMinutes()+timeCalc);
		span = $("#spanHoraire_"+i);
		var h = ""+dateFormat.getHours();
		var m = ""+dateFormat.getMinutes();
		var j = ""+dateFormat.getDate();
		var mo = ""+(dateFormat.getMonth()+1);
		if (h.length == 1) h = "0"+h;
		if (m.length == 1) m = "0"+m;
		if (j.length == 1) j = "0"+j;
		if (mo.length == 1) mo = "0"+mo;
		if (dateFormat.getDate() != tabDate[2] || tabDate[2] != new Date().getDate())
		{
			span.removeClass("fontsize19");
			span.text(j + "-" + mo + "-" +dateFormat.getFullYear()+" " + h + "H" + m);
		}
		else 
		{
			span.text(h+"H"+m);
		}
		$("#datePassageGroupe"+i).val(dateFormat.getFullYear()+'-'+ mo + '-' + j);
		$("#heurePassageGroupe"+i).val(h + ':' + m);
		//span.append('<input type="hidden" name="datePassageGroupe'+i+'" id="datePassageGroupe'+i+'" value="'+dateFormat.getFullYear()+'-'+ mo + '-' + j+'"/><input type="hidden" name="heurePassageGroupe'+i+'" id="heurePassageGroupe'+i+'" value="'+h+':'+m+'"/>');
		nb++;
		if (tabResultsGroupe[nb])
			calculHeurePassageGroupe (nb);
	});
	var tabPoints = new Array();
	tabPoints.push(departTrajet);
	tabPoints.push(pointGroupe);
	directionCalcul.loadFromWaypoints(tabPoints,{preserveViewport:true});
}

function createDemandeCovoiturageFromGroupe(){
	var adresse = $(".content #adresseEntree").val();
	adresseToSearch = adresse + " , FRANCE";	
	geocoder.getLatLng(adresseToSearch, function (coord) {
		if (coord == null){
			$("#erreurDemandeAdresse").show();
			$.facebox($("#demandeAdresse").html());
			return true;
		}
		if ($("#sensDemande").val() == 1){
			departLat = $("#latDepDemande").val();
			departLng = $("#lngDepDemande").val();
			arriveeLat = coord.lat();
			arriveeLng = coord.lng();
		}
		else {
			departLat = coord.lat();
			departLng = coord.lng();
			arriveeLat = $("#latDepDemande").val();
			arriveeLng = $("#lngDepDemande").val();
		}
		
		var departLatLng = new GLatLng(departLat, departLng);
		var arriveeLatLng = new GLatLng(arriveeLat, arriveeLng);
		//avec paramètre map => affiche dans le conteneur map défini de l'application Quivaou
		var directions = new GDirections();
		GEvent.addListener(directions,"error",function(){
			$("#erreurDemandeAdresse").show();
			$.facebox($("#demandeAdresse").html());
			return true;
		});
		GEvent.addListener(directions,"load",function(){						
			var distance = directions.getDistance().meters;
			createCovoiturageFromGroupe($("#id_trajetDemande").val(), $("#id_groupeDemande").val(), 0, adresse, coord, distance);          	
		});
		var tabPoints = new Array();
		tabPoints.push(departLatLng);
		tabPoints.push(arriveeLatLng);
		directions.loadFromWaypoints(tabPoints, {preserveViewport:false, getSteps:false,getPolyline:true});
	});
	return true;
}