var autoOpenTrip=false;
var openTripId = -1;

function callCovWS(key, deppoint, arrpoint, postgisItineraireLine, distanceTotale) {
	var scr = document.getElementById("callLRV")
	if (scr) {
		scr.parentNode.removeChild(scr);
	}
	
	var params = "&pointGeoDepart="+deppoint+"&pointGeoArrivee="+arrpoint;
	params += "&dateDepart="+document.trajetForm.dateAller.value;
	params += "&dateRetour="+document.trajetForm.dateRetour.value;

	if (document.trajetForm.frequenceTrajet[0].checked) {
		params += "&trajetPonctuel=F";
		params += "&heureDepart="+$('horaireDepartR').value+":"+document.trajetForm.minutesDepart.value;
		params += "&heureRetour="+$('horaireRetourR').value+":"+document.trajetForm.minutesRetour.value;
		params += "&trajetAllerRetour=T";
		params += "&trajetSemaine=T";
		params += "&trajetWeekend=T";
	} else {
		if (document.trajetForm.doRetour[0].checked) {
			params += "&trajetAllerRetour="+document.trajetForm.doRetour[0].value;
		} else {
			params += "&trajetAllerRetour="+document.trajetForm.doRetour[1].value;
		}
		params += "&trajetPonctuel=T";
		params += "&heureDepart="+$('horaireDepartP').value+":00";
		params += "&heureRetour="+$('horaireRetourP').value+":00";
	}
	params += "&dateFormat=dd/MM/yyyy";
	params += "&postgisItineraireLine="+postgisItineraireLine;
	params += "&distanceTotale="+distanceTotale;

	if (document.trajetForm.idTrajet != null && document.trajetForm.idTrajet != '') {
		params += "&idTrajet=" + document.trajetForm.idTrajet;
	}
	
	if (document.location.search!=null && document.location.search.indexOf("algo=")!=-1) {
		params += "&algo=newmoteur";
	}

	if (document.trajetForm.vehiculeTrajet[1].checked) {
		params += "&hasVehicle=F";
	} else {
		params += "&hasVehicle=T";
	}
	
	var url = contextPath+"/apis/covoiturageService.do?key="+key+params+"&output=json&callback=showResults";
	eltScript = document.createElement("script");
	eltScript.setAttribute("type", "text/javascript");
	eltScript.setAttribute("src", url);
	
	eltScript.setAttribute("id", "loadedScript1");
	document.getElementsByTagName('head')[0].appendChild(eltScript);
}

function replaceRue(rue) {
	var rueMin = rue.toLowerCase();
	if (rueMin == 'adresse' || rueMin == 'adresse ou choix' || rueMin=='centre' || rueMin=='centre ' || rueMin==' centre' || rueMin=='mairie' || rueMin=='centre-ville' || rueMin=='centre ville' || rueMin=='gare' || rueMin=='bourg' || rueMin=='eglise' || rueMin=='rue principale' || rueMin=='village' || rueMin=='aucun') {
		return "";
	}
	return rue;
}

function replaceVille(ville) {
	var villeMin = ville.toLowerCase();
	if (villeMin=='vienne') {
		return "vienne 38";
	}
	var value1 = 'Ville, N° département';
	if (villeMin == value1.toLowerCase() || villeMin == 'ville ou choix') {
		return "";
	}
	return ville;
}		

function switchcountry() {
	var thisurl=window.location.href;
	if (thisurl.indexOf("country")>0) {
		thisurl=thisurl.replace("country=fr", "country=all");
	} else {
		var coordination = "?";
		if (thisurl.indexOf("?")>0) {
			if (thisurl.indexOf("=")>0) {
				coordination = "&";
			} else {
				coordination = "";
			}	
		}
		thisurl += coordination + "country=all";
	}
	window.location=thisurl;
}

function changeArr() {
	document.getElementById('latitudeArrivee').value="";
	document.getElementById('longitudeArrivee').value="";
}		

var tripPoints;
function addCovoitureursOnMap(covoitureurs, contextPath) {
	var html = '';
	tripPoints = new Array();
	for (var i = 0; i < covoitureurs.length; i++) {
		if (i <= 50) {
			var cov = covoitureurs[i];
			var depPoint = cov.depart.point;
			var depLat = parseFloat(depPoint.lat);
			var depLong = parseFloat(depPoint.long);
			var markdeptemp = createMarker(depLat, depLong, getColorMarker(i), i);
		  	//map.addOverlay(markdeptemp);
		  	
			var arrPoint = cov.arrivee.point;
			var arrLat = parseFloat(arrPoint.lat);
			var arrLong = parseFloat(arrPoint.long);
			var markarrtemp = createMarker(arrLat, arrLong, getColorMarker(i), i);
		  	//map.addOverlay(markarrtemp);

			bounds.extend(markdeptemp.getPoint());
			bounds.extend(markarrtemp.getPoint());
			
			departMarkers[i] = markdeptemp;
			arriveeMarkers[i] = markarrtemp;
			
			tripPoints[i] = depLat + "," + depLong + ";" + arrLat + "," + arrLong;
			
			html += addCovoitureurToSideSection(cov, i, contextPath);
			if (autoOpenTrip) {
				var qStrPos = cov.url.indexOf('?') + 1;
				if (qStrPos > 1) {
					var queryString = cov.url.substring(qStrPos, cov.url.length);
					if (queryString.indexOf('idTrajet') >= 0) {
						var idTrajetPair = queryString.substring(0, queryString.indexOf('&'));
						var id = idTrajetPair.substring(idTrajetPair.indexOf('=') + 1, idTrajetPair.length);
						if (id != "" && id == document.trajetForm.idTrajet.value) {
							openTripId = i;
						}
					}
				}
			}
	  	}
	}
	return html;
}

function addCovoitureurToSideSection(cov, compteur, contextPath) {
	var html = '<h3 id="cov-'+compteur+'"><a id="trajet'+cov.trajetId+'" href="#" class="covoitureur-link">';
	var nbCovModulo = compteur % paginationinterval;
	switch (nbCovModulo) {
		case 0:
			html += '<img src="'+contextPath+'/common/img/mm_20_green.png" border="0"/>';
			break;
		case 1:
			html += '<img src="'+contextPath+'/common/img/mm_20_blue.png" border="0"/>';
			break;
		case 2:
			html += '<img src="'+contextPath+'/common/img/mm_20_yellow.png" border="0"/>';
			break;
		case 3:
			html += '<img src="'+contextPath+'/common/img/mm_20_white.png" border="0"/>';
			break;
		case 4:
			html += '<img src="'+contextPath+'/common/img/mm_20_red.png" border="0"/>';
			break;
		case 5:
			html += '<img src="'+contextPath+'/common/img/mm_20_brown.png" border="0"/>';
			break;
		case 6:
			html += '<img src="'+contextPath+'/common/img/mm_20_lightblue.png" border="0"/>';
			break;
		case 7:
			html += '<img src="'+contextPath+'/common/img/mm_20_orange.png" border="0"/>';
			break;
		case 8:
			html += '<img src="'+contextPath+'/common/img/mm_20_rose.png" border="0"/>';
			break;
		case 9:
			html += '<img src="'+contextPath+'/common/img/mm_20_violet.png" border="0"/>';
			break;
	}
	html += '<span class="name" onmouseover="return generateToolTip(';
	html += "'<div class=\\'tooltip\\'>Cliquez pour voir le detail.</div>');";
	html += '" onmouseout="return nd();">'+cov.depart.adresse.ville+' / '+cov.arrivee.adresse.ville+'</span>';
	if (cov.voiture == 'T') {
		html += '<span class="car" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'>Cette personne dispose d\\'une voiture et de "+cov.nbPlaces+" place(s) disponible(s).</div>');";
		html += '" onmouseout="return nd();"><img src="'+contextPath+'/common/img/pictos/car.png"/> '+cov.nbPlaces+' Pl.</span>'; 
	} else {
		html += '<span class="car" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'>Cette personne recherche une voiture ayant "+cov.nbPlaces+" place(s) disponible(s).</div>');";
		html += '" onmouseout="return nd();">'+cov.nbPlaces+' Pl.</span>'; 
	}
	if (cov.fumeur == 'T') {
		html += '<span class="smoke" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'>Cette personne accepte les covoitureurs fumeurs.</div>');";
		html += '" onmouseout="return nd();"><img src="'+contextPath+'/common/img/pictos/smoking.jpg"/></span>'; 
	} else {
		html += '<span class="smoke" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'>Cette personne n\\'accepte pas les covoitureurs fumeurs.</div>');";
		html += '" onmouseout="return nd();"><img src="'+contextPath+'/common/img/pictos/nosmoking.jpg"/></span>'; 
	}
	if (cov.trajetPonctuel == 'F') {
		html += '<span class="tripType" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'>Cette personne effectue ce trajet régulièrement</div>');";
		html += '" onmouseout="return nd();"><img src="'+contextPath+'/common/img/pictos/regularSmall.png"/></span>'; 
	} else {
		html += '<span class="tripType" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'>Cette personne effectue ce trajet ponctuellement</div>');";
		html += '" onmouseout="return nd();"><img src="'+contextPath+'/common/img/pictos/ponctualSmall.png"/></span>'; 
	}
	var compatibility = cov.compatibilite;
	if (compatibility > 79) {
		html += '<span class="compatibilite" onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'><u>Forte compatibilité</u>:<br/>Cette personne fait un trajet similaire au votre à "+compatibility+"%.</div>');";
		html += '" onmouseout="return nd();" ><img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/compat100.jpg" border="0"/></span>';
	} else if (compatibility > 64) {
		html += '<span class="compatibilite"><span onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'><u>Bonne compatibilité</u>:<br/>Cette personne fait un trajet presque similaire au votre, compatible à "+compatibility+"%. Vous pouvez néanmoins la contacter pour voir si un arrangement est possible.</div>');";
		html += '" onmouseout="return nd();" ><img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/compat80.jpg" border="0"/></span></span>';
	} else if (compatibility > 44) {
		html += '<span class="compatibilite"><span onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'><u>Compatibilité moyenne</u>:<br/>Cette personne fait un trajet compatible à "+compatibility+"%. Vous pouvez néanmoins la contacter pour voir si un arrangement est possible.</div>');";
		html += '" onmouseout="return nd();" ><img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/compat60.jpg" border="0"/></span></span>';
	} else if (compatibility > 19) {
		html += '<span class="compatibilite"><span onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'><u>Faible compatibilité</u>:<br/>Cette personne fait un trajet assez différent du votre, compatible à "+compatibility+"%. Vos chances de pouvoir partager tout votre trajet avec elle sont faibles.</div>');";
		html += '" onmouseout="return nd();" ><img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/compat40.jpg" border="0"/></span></span>';
	} else {
		html += '<span class="compatibilite"><span onmouseover="return generateToolTip(';
		html += "'<div class=\\'tooltip\\'><u>Très faible compatibilité</u>:<br/>Cette personne fait un trajet peu compatible avec le votre, à "+compatibility+"% seulement. Vos chances de pouvoir partager tout votre trajet avec elle sont très faibles.</div>');";
		html += '" onmouseout="return nd();" ><img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/compat20.jpg" border="0"/></span></span>';
	}
	html += '<div style="clear: both"></div></a></h3>'
	html += '<div class="cov-details">';
	html += '<p>';
	if (cov.trajetPonctuel == 'T') {
		html += 'Trajet ponctuel';
	} else {
		html += 'Trajet régulier à partir du ' + cov.depart.date;
	}
	html += '</p><p>';
	if (cov.voiture == 'T' ) {
		if (cov.nbPlaces > 0) {
			html += 'Voiture, '+cov.nbPlaces+' place(s) disponible(s)';
		}
	} else {
		html += 'Pas de voiture';
		if (cov.nbPlaces > 0) {
			html += ' - recherche '+cov.nbPlaces+' place(s) disponible(s)';
		}
	}
	html += ' - ';
	if (cov.fumeur == 'T') {
		html += 'Fumeur';
	} else {
		html += 'Non fumeur';
	}
	html += '</p>';
	
	html += '<p><span class="legend"><span class="legendPicto" onmouseover="return generateToolTip(\'<div class=\\\'tooltip\\\'><u>Zoom départ</u>:<br/>Cliquez ici pour voir le départ sur la carte.</div>\');" onmouseout="return nd();" >';
	html +=	'<a href="javascript:myclickDep('+compteur+');">'
	html +=	'<img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/miniloupe2.png" border="0"/>';
	html +=	'</a>';
	html += '</span><a href="javascript:myclickDep('+compteur+')">De : </a></span>'+cov.depart.adresse.voie+' '+cov.depart.adresse.ville+'</p>';
	
	html += '<p><span class="legend"><span class="legendPicto" onmouseover="return generateToolTip(\'<div class=\\\'tooltip\\\'><u>Zoom arrivée</u>:<br/>Cliquez ici pour voir l\\\'arrivée sur la carte.</div>\');" onmouseout="return nd();" >';
	html +=	'<a href="javascript:myclickArr('+compteur+');">'
	html +=	'<img style="vertical-align:middle" src="'+contextPath+'/common/img/pictos/miniloupe2.png" border="0"/>';
	html +=	'</a>';
	html += '</span><a href="javascript:myclickArr('+compteur+')">Vers : </a></span>'+cov.arrivee.adresse.voie+' '+cov.arrivee.adresse.ville+'</p>';
	
	if (cov.trajetPonctuel == 'T') {
		html += '<p><span class="legend">Départ :</span> Le '+cov.depart.date+ ' à ' + cov.depart.heure;
		html += '</p><p><span class="legend">Retour: </span> ';
		if (cov.doRetour == 'T') {
			html += 'Le '+cov.arrivee.date+ ' à ' + cov.arrivee.heure;
		} else {
			html += 'Pas de retour prévu';
		}
		html += '</p>';
	} else {
		html += '<p><span class="legend">Horaires :</span>'+cov.depart.heure+' - ' + cov.arrivee.heure + '</p><p>';
		html += '<p><span class="legend">&nbsp;</span>'

		if (cov.trajetSemaine == 'T' && cov.trajetWeekend == 'T') {
			html += 'En semaine et le weekend'
		} else if (cov.trajetWeekend == 'T') {
			html += 'Le weekend';
		} else if (cov.trajetSemaine == 'T') {
			html += 'En semaine';
		}
		html += '</p>';
	}
	html += '</div>';
	return html;
}

function showInfosTrajetR() {
	$('infosDepartR').style.display = '';
	$('infosDepartP').style.display = 'none';
	$('horaireDepartR').disabled = false;
	$('horaireDepartP').disabled = true;

	$('infosRetourR').style.display = '';
	$('infosRetourP').style.display = 'none';
	$('horaireRetourR').disabled = false;
	$('horaireRetourP').disabled = true;
	
	$('doRetourChoiceT').style.display = 'none';
	$('doRetourChoiceF').style.display = 'none';
	showAllerRetourT();
}
function showInfosTrajetP() {
	$('infosDepartR').style.display = 'none';
	$('infosDepartP').style.display = '';
	$('horaireDepartR').disabled = true;
	$('horaireDepartP').disabled = false;

	$('infosRetourR').style.display = 'none';
	$('infosRetourP').style.display = '';
	$('horaireRetourR').disabled = true;
	$('horaireRetourP').disabled = false;

	$('doRetourChoiceT').style.display = '';
	$('doRetourChoiceF').style.display = '';
	if (document.trajetForm.doRetour[1].checked) {
		showAllerRetourT();
	} else {
		showAllerRetourF();
	}
}

function showAllerRetourF() {
	jQ('#trajetAllerRetour').hide();
}
function showAllerRetourT() {
	jQ('#trajetAllerRetour').show();
}
// Init
addLoadEvent(function() {
	document.trajetForm.doRetour[0].checked = true;
	if (typeof(isPonctuel) == 'undefined') {
		document.trajetForm.frequenceTrajet[0].checked = true;
		showInfosTrajetR();
	} else {
		if (isPonctuel) {
			document.trajetForm.frequenceTrajet[1].checked = true;
			showInfosTrajetP();
		} else {
			document.trajetForm.frequenceTrajet[0].checked = true;
			showInfosTrajetR();
		}
	}
	addCalendarSupport();
});

// Add calendar support
function addCalendarSupport() {
		dateNow=new Date();
		month=dateNow.getMonth()+1;
		monthString=month;
		if(month<10)
		monthString="0"+month;
		year = dateNow.getYear();
		if (year < 1000) year += 1900;
		dayNow = dateNow.getDate();
		dayString=dayNow;
		if(dayNow<10)
		dayString="0"+dayString;
		dateFormated=dayString+"/"+monthString+"/"+year;
		if(document.getElementById('trajetForm').datealler.value.length<2) 
			document.getElementById('trajetForm').datealler.value=dateFormated;
		if(document.getElementById('trajetForm').dateretour.value.length<2) 
			document.getElementById('trajetForm').dateretour.value=dateFormated;
			dateNow=new Date();
		month=dateNow.getMonth()+1;
		monthString=month;
		if(month<10)
		monthString="0"+month;
		year = dateNow.getYear();
		if (year < 1000) year += 1900;
		if(document.getElementById('trajetForm').datealler.value.length<2) 
			document.getElementById('trajetForm').datealler.value=dateFormated;
		if(document.getElementById('trajetForm').dateretour.value.length<2) 
			document.getElementById('trajetForm').dateretour.value=dateFormated;
		
		
		    Calendar.setup({
		        inputField     :    "dateAller",     // id of the input field
		        ifFormat       :    "%d/%m/%Y",      // format of the input field
		        button         :    "imgAller",  // trigger for the calendar (button ID)
		        singleClick    :    true,
		        weekNumbers : false,
		      	firstDay : 1,          
		        dateStatusFunc :    function (date) {
		                              return (date<new Date() ) ? true : false;
		                            }
		    });
		    
		    Calendar.setup({
		        inputField     :    "dateRetour",     // id of the input field
		        ifFormat       :    "%d/%m/%Y",      // format of the input field
		        button         :    "imgRetour",  // trigger for the calendar (button ID)
		        singleClick    :    true,
		        weekNumbers : false,
		      	firstDay : 1,          
		        dateStatusFunc :    function (date) { 
		                              return (date<new Date() ) ? true : false;
		                            }
		    });
}

var tripGDir = '';
function displayTrip(id) {
	window.covoitureursDirections.displayRemoteTrip(id);
}

function createMarker(lat, long, style, id){
	var marktemp=new GMarker(new GLatLng(lat, long), {icon:getIcon(style)});
	var infoTabs = [
		new GInfoWindowTab("Trajet", "<p style=\"margin-right:0px;\">Enregistrez cette recherche dans votre compte pour contacter ce covoitureur.</p>")
	];
			
	GEvent.addListener(marktemp, "click", function() {
		marktemp.openInfoWindowTabsHtml(infoTabs);
		autoPaginate(id);

		toActivateSelector = '#cov-' + id;
		toActivate = jQ(toActivateSelector);
		
		if (!toActivate.hasClass('ui-state-active')) {
			jQ('.accordionCovoitureurs').accordion('activate', toActivateSelector);
		}
	});
	return 	marktemp;	
}	

function autoPaginate(id) {
	if (id >= paginationfrom+paginationinterval) {
		while (id >= paginationfrom+paginationinterval) {
			paginate('plus');
		}
	} else if (id < paginationfrom) {
		while (id < paginationfrom) {
			paginate('minus');
		}
	}
}

function paginate(ptype) {
	
	nbTotal = jQ('.accordionCovoitureurs > h3').size();

	if ((ptype == 'first') || (ptype == 'plus') || (ptype == 'minus')) {

		if ((ptype == 'plus') || (ptype == 'minus')) {

			if ((ptype == 'minus') && ((paginationfrom - paginationinterval) >= 0)) {
				paginationfrom -= paginationinterval;
			} else if ((ptype == 'plus') && ((paginationfrom + paginationinterval) < nbTotal)) {
				paginationfrom += paginationinterval;
			}

			if (paginationfrom <= 0) {
				jQ('#paginatePrev').hide();
			} else {
				jQ('#paginatePrev').show();
			}

			if (paginationfrom + paginationinterval >= nbTotal) {
				jQ('#paginateNext').hide();
			} else {
				jQ('#paginateNext').show();
			}

		}

		jQ('.accordionCovoitureurs').accordion('activate', false);
		
		for (i = 0; i < nbTotal; i++) {
			if ((paginationfrom <= i) && (i < paginationfrom + paginationinterval)) {
				jQ('.accordionCovoitureurs > h3:eq(' + i + ')').show();
				map.addOverlay(departMarkers[i]);
				map.addOverlay(arriveeMarkers[i]);
			} else {
				jQ('.accordionCovoitureurs > h3:eq(' + i + ')').hide();
				map.removeOverlay(departMarkers[i]);
				map.removeOverlay(arriveeMarkers[i]);
			}
		}
		

		if (document.getElementById('currentPage')) {
			var currentPage = Math.ceil(paginationfrom / paginationinterval) + 1;
			document.getElementById('currentPage').innerHTML = currentPage;
		}
	}
}

/* Code commun à covoiturageTerritoire.js, resultatCarte.js, communityCovoiturage.js */

var paginationfrom = 0;
var paginationinterval = 10;
var departMarkers = [];
var arriveeMarkers = [];

var colors = new Array("common/img/mm_20_green.png",
		   "common/img/mm_20_blue.png",
		   "common/img/mm_20_yellow.png",
		   "common/img/mm_20_white.png",
		   "common/img/mm_20_red.png",
		   "common/img/mm_20_brown.png",
		   "common/img/mm_20_lightblue.png",
		   "common/img/mm_20_orange.png",
		   "common/img/mm_20_rose.png",
		   "common/img/mm_20_violet.png");

function getColorMarker(i) {
	return colors[i % 10];
}

var tripGDir = '';
function displayOneTrip(depLat, depLong, arrLat, arrLong) {
	if (tripGDir != '') {
		tripGDir.clear();
	}
	tripGDir = new GDirections(map);
	GEvent.addListener(tripGDir, "load", function(){
		tripGDir.getPolyline().color='#FF00C9';
	});
	GEvent.addListener(tripGDir, "addoverlay", function(){
		tripGDir.getMarker(0).hide();
		tripGDir.getMarker(1).hide();
	});
	GEvent.addListener(tripGDir, "error", handleErrors);
	tripGDir.loadFromWaypoints([(new GLatLng(depLat, depLong)),(new GLatLng(arrLat, arrLong))],{getPolyline:true, preserveViewport: true});
}

function myclickDep(i) {
	GEvent.trigger(departMarkers[i], "click");
}
function myclickArr(i) {
	GEvent.trigger(arriveeMarkers[i], "click");
}

function hidePolylines(polylines) {
	if (polylines != undefined) {
		for (i = 0; i < polylines.length; i++) {
			polyline = polylines[i];
			polyline.hide();
		}
	}
}

function showPolylines(polylines) {
	if (polylines != undefined) {
		for (i = 0; i < polylines.length; i++) {
			polyline = polylines[i];
			polyline.show();
		}
	}
}

//calls the request to get the parkings
function onGDirectionsLoad(){
	if (typeof getParkings == 'function') {
		getParkings();
	}
}

