/**
 * @author apellet
 */

var START = 0;
var END = 1;

var home = null;
var map = null;
var ls = null;
var geocoder = null;
var direction = null;


var cur_cp = "";
var cur_ville = "";
var cpt = 0;

var lastPlacmarks = null;

//Adresse actuellement affiché sur la carte
var cur_adresse = null;

//Adresse de départ validée par l'internaute
var start_adresse = null;

//Adresse d'arrivée validée par l'internaute
var end_adresse = null;

//Type de géocodage en cours : départ ou arrivée
var type_geocodage = -1;

var cpt = 0;

var url_static_start = "";
var url_static_end = "";


$(document).ready(function(){
   $("#title-result").html ( msg_resultat_recherche );
  // $("#selection-result").html ( msg_selection_liste );
   
 });





/**
 * Première fonction appellée lors du chargement de la page.
 * Elle permet d'initialiser tous les composants carto
 */
function loadMap ()
{
	map = new GMap2(document.getElementById("map"));
	map.setCenter ( center, niv_zoom );
   	//map.enableScrollWheelZoom();

	map.addControl ( new GSmallMapControl() );

	ls = new LocalSearch ( map, nb_result );
	
	if ( geocoder == null )
	{
		geocoder = new GClientGeocoder();	
		geocoder.setBaseCountryCode("es");
	}
	if (direction == null)
	{
		direction = new GDirections();
		GEvent.bind(direction, "load", this, GEvent.callbackArgs(this, this.callBackRouting));
		GEvent.bind(direction, "error", this, GEvent.callback(this, this.callBackRoutingError));
	}
	
	
	
}



/**
 * Ouverture de la bulle d'information associée à un marker
 * @param {Object} m	Le marqueur
 * @param {Object} txt	Le texte de la bulle
 */
function openInfoAdresse (m, txt)
{
	/*
	
	var h = "";
	
	
	
	m.openInfoWindowHtml ( h + ls.getDomProxi(false), {maxWidth:400} );*/
	m.openInfoWindowHtml ( txt );
}	





/**
 * Méthode appellée sur le bouton "Chercher"
 * Elle permet de renvoyer la localisation de l'adresse saisie et de l'afficher sur la map.
 */
function searchAdresse()
{
	cpt = 0;
	var adr_txt = document.getElementById ('adr_txt').value;
	var adr_cp = document.getElementById ('adr_cp').value;
	var adr_ville = document.getElementById ('adr_ville').value;
	
	
	if ( cur_adresse != null && cur_adresse._type == 1 )
	{		
		cur_adresse = null;
	}
	
	if ( document.getElementById ('type_search').value == "1" )
	{
		searchLocal ();
	}
	else if ( cur_adresse != null && document.getElementById ('type_search').value != "1" )
	{
		var b_adr = cur_adresse.compare ( new struct_adresse ( {adr:adr_txt, cp:adr_cp, ville:adr_ville} ) );
		
		if ( cur_adresse != null && b_adr == -1 )
		{
			geocoder.getLocations ( adr_txt + " " + adr_cp + " " + adr_ville + " " + "Espagne" + " ", GEvent.callback ( this, this.callbackGeocode ) ) ;
		}
		else if ( cur_adresse != null && b_adr == 0 )
		{
			searchLocal ();
		}
	}	
	else
	{
		geocoder.getLocations ( adr_txt + " " + adr_cp + " " + adr_ville + " " + "" + "Espagne", GEvent.callback ( this, this.callbackGeocode ) ) ;
	}	
	
	
	
}



/**
 * Méthode qui retrouve les "items" à proximité d'une adresse.
 */
function searchLocal ()
{
	//console.log ( "searchlocal" );
	var type_search = parseInt(document.getElementById ('type_search').value);
	
	var txt_local_search = "";
	switch ( type_search )
	{
		case 1:
			txt_local_search = txt_local_search_aeroport;
		break;
		case 2:
			txt_local_search = txt_local_search_port;
		break;
		case 3:
			txt_local_search = txt_local_search_gare;
		break;
		case 4:
			txt_local_search = txt_local_search_hotel;
		break;
		default:
		break;
	}
	
	ls.executeSearch ( txt_local_search );
}




/**
 * Affiche tous les résultats d'une recherche dans la liste des résultats en mode texte.
 * @param {Object} placemarks
 */	
function listeAdresses ( placemarks )
{
	$("#title-result").css ( 'display', 'block' );
   //	$("#selection-result").css ( 'display', 'block' );
	
	document.getElementById ('listeAdresses').innerHTML = '';
	
	var tmp = "<ul><li>"+msg_selection_liste+"<ol>";
	for ( var i=0; i<placemarks.length; i++ )
	{
		tmp += displayAdresseListe ( placemarks [i], i );
	}
	
	tmp += "</ol></li></ul>"
	
	document.getElementById ('listeAdresses').innerHTML = tmp;
	//console.log ( placemarks );
}


/**
 * Affiche un resultat de recherche sur la carte.
 * @param {Object} placemark L'objet resultat de recherche à afficher.
 */
function displayAdresseMap ( placemark )
{
	//console.log ( placemark );
	
	//Ville
	try{
		//console.log ( placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName );
		$("#adr_ville").val ( placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName );
	}
	catch ( error )
	{
		$("#adr_ville").val ( '' );
	}	
	
	
	//CP
	try{
		//console.log ( placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber );
		$("#adr_cp").val ( placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber );
	}
	catch ( error )
	{
		$("#adr_cp").val ( '' );
	}	
	
	
	//ADRESSE
	try{
		//console.log ( placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName );
		$("#adr_txt").val ( placemark.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName );
	}
	catch ( error )
	{
		$("#adr_txt").val ( '' );
	}	
	
	
	var o = placemark.Point.coordinates;
	var latlng = new GLatLng ( o[1], o[0] );
	map.setCenter(latlng, niv_zoom);
	home = new GMarker ( latlng ,{ title:placemark.address, icon:i_start, draggable:true } );
	map.addOverlay ( home );
	
	
	ls.current = home.getLatLng ();
	ls.marker = home;
	
	cur_adresse = new struct_adresse ({ 
			adr:document.getElementById('adr_txt').value,
			cp:document.getElementById('adr_cp').value, 
			ville:document.getElementById('adr_ville').value });
	cur_adresse.setType ( $("#type_search").val() );
	cur_adresse.setLatLng ( latlng );
	//console.log ( cur_adresse );
	
	
	adresseValide ();
	addDragEndEvent ( )
	
	
	
	GEvent.addListener ( home, "click", function (){openInfoAdresse(home, placemark.address)} );
    
	setTimeout ( function(){ openInfoAdresse ( home, placemark.address); }, 50 );
	
	searchLocal ();
}



function addDragEndEvent ( )
{
	GEvent.addListener ( home, "dragend", function ()
	{
		var p = home.getLatLng();
		cur_adresse.setLatLng ( p );
		/*if ( home != null )
		{
			map.removeOverlay ( home );
			delete m;
		}
		cur_adresse.setLatLng ( p );
		marker = new GMarker( p, { draggable:true, icon:i_start });
		//home = new GMarker ( latlng ,{ title:placemark.address, icon:i_start, draggable:true } );
		map.addOverlay ( marker );
		addDragEndEvent ( );*/
				
		
	});
}


/**
 * Affiche un resultat de la recherche courante dans la liste des résultats au format texte.
 * @param {Object} placemark
 * @param {Object} ind
 */
function displayAdresseListe ( placemark, ind )
{	
	//var h = document.getElementById ('listeAdresses');
	
	//h.innerHTML += "<div>" + placemark.address + "<a href='javascript:localiseAdresse(" + ind + ");'>voir</a></div>"
	return  "<li><a href='javascript:localiseAdresse(" + ind + ");'>" + placemark.address + "</a></li>"
}


/**
 * Localisation d'une adresse après son choix dans la liste des résultats.
 * @param {Object} ind Indice dans le tableau des résultats.
 */
function localiseAdresse ( ind )
{
	map.clearOverlays();
	var place = lastPlacmarks[ind];
	displayAdresseMap ( place );
}


/**
 * Localisation d'un élément de recherche à proxilité après son choix dans la liste des résultats.
 * @param {Object} ind Indice dans le tableau des résultats.
 */
function localiseItemLocalSearch ( ind )
{
	map.clearOverlays();
	ls.locateItem ( ind );
	adresseValide ();
}

/**
 * Lorsque l'utlisateur saisie une adesse éronnée, cette fonction le rappelle à l'ordre.
 */
function adresseInvalide()
{
	
	document.getElementById ('listeAdresses').innerHTML = msg_adresse_invalide + "("+ $("#adr_txt").val() +")";
	$("#btn-validate-geoc").attr('disabled', 'true');
	
	$("#title-result").css ( 'display', 'none' );
   	//$("#selection-result").css ( 'display', 'none' );
}


/**
 * Lorsque l'utlisateur saisie une adesse correcte.
 */
function adresseValide ()
{
	$("#btn-validate-geoc").removeAttr('disabled');
	$("#msg-valide").css ( 'display', 'block');
	$("#msg-valide").html ( msg_valide );
}



/**
 * Fonction qui lance un calcul d'itinéraire afin de récupérer le kilométrage uniquement.
 */
function calculKm ()
{
	//alert("111");
	if ( start_adresse == null || end_adresse == null )
	{
		alert( msg_saisir_adresse );
		return;
	}
	var bounds = new GLatLngBounds ();
	bounds.extend ( start_adresse._latlng );
	bounds.extend ( end_adresse._latlng );
	
	//var z = map.getBoundsZoomLevel( bounds );			
	//this.map.setCenter ( bounds.getCenter (), z );
	
	//alert("333");
	direction.loadFromWaypoints ( [start_adresse._latlng, end_adresse._latlng], {getPolyline:false,getSteps:false} );
}




function callBackRoutingError ()
{
	alert("Error itineraire");
}







/**
 * Méthode qui traite le retour du géocodage d'une adresse
 * 
 * @param {Object} ret L'objet renvoyé par le service GMap
 */
function callbackGeocode ( ret )
{
	var cur_cp = document.getElementById ('adr_cp').value;
	var cur_ville = document.getElementById ('adr_ville').value;
	
	//console.log ( "callbackGeocode" );
	
	lastPlacmarks = null;
	var statut = ret.Status.code;
	
	if ( statut == 602 )
	{
		adresseInvalide();
		return false;
	}
	
	
	map.clearOverlays();
	var placemarks = ret.Placemark;
	lastPlacmarks = placemarks;
	
	if ( placemarks.length > 0 )
	{		
		if ( placemarks.length == 1 )
		{
			displayAdresseMap ( placemarks[0] );	
			
		}			
	}
	else if ( placemarks.length == 0 )
	{
		adresseValide ();
		
		cpt ++;
		//if ( latlng == null || latlng == undefined )
		{
			var address = "";
			if	 ( cpt == 1 )
			{
				address = cur_cp + " ";
				geocoder.getLocations ( address, GEvent.callback ( this, this.callbackGeocode ) ) ;
				return;
			}
			else if	 ( cpt == 2 )
			{
				address = cur_ville + " ";
				geocoder.getLocations ( address, GEvent.callback ( this, this.callbackGeocode ) ) ;
				return;
			}
			else if	 ( cpt == 3 )
			{
				alert ( "Nous sommes dans l'impossibilite de localiser le lieu sur le plan." );
				return;
			}
			else
			{
				return;
			}					
		}
	}
	
	listeAdresses ( placemarks );
	
	
}					




/**
 * Structure permettant de stocker les infos sur l'adresse actuellement affiché sur la map.
 * @param {Object} opt
 */
struct_adresse = function ( opt )
{
	
	this.init ( opt );
};
struct_adresse.prototype = {
	_adresse: '',
	_cp: '',
	_ville: '',
	_lat : null,
	_lng : null,
	_latlng : null,
	_type : '',
	_name : '',
	
	init : function ( opt )
	{
		this._adresse = opt.adr;
		this._cp = opt.cp;
		this._ville = opt.ville;
	},
	compare : function ( other )
	{
		//console.log ( this );
		//console.log ( other );
		if ( 	this._adresse == other._adresse &&
				this._cp == other._cp &&
				this._ville == other._ville
		)
		{
			return 0;
		}
		else
		{
			return -1;
		}
	},
	setLatLng : function ( latlng )
	{
		this._latlng = latlng;
		this._lat = latlng.lat();
		this._lng = latlng.lng();
	},
	setType : function ( type )
	{
		this._type = type;
	},
	setName : function ( name )
	{
		this._name = name;
	}
};


/**
 * Méthode appellé sur le click du bouton "Valider". Le géocodage est accepté par l'internaute.
 * Son but est de remplir des variables qui permettront de calculer des distances en km.
 */
function ValidateGeocoder()
{
	switch ( type_geocodage )
	{
		case START : 
			start_adresse = cur_adresse;
			url_static_start = createStaticUrl ( start_adresse, START );
			if ( start_adresse._type == 1)
			{
				b_aeroport_start = true;
				cur_adresse._adresse = document.getElementById('adr_txt').value;
			}
			document.getElementById('start3').innerHTML = cur_adresse._adresse.toString() + "<br/>" + cur_adresse._cp.toString() + " " + cur_adresse._ville.toString() + " ";
			document.getElementById('start7').value = cur_adresse._adresse.toString() + ", " + cur_adresse._cp.toString() + " " + cur_adresse._ville.toString() + " ";
		break;
		
		case END : 
			end_adresse = cur_adresse;
			url_static_end = createStaticUrl ( end_adresse, END );
			if ( end_adresse._type == 1)
			{
				b_aeroport_end = true;
				cur_adresse._adresse = document.getElementById('adr_txt').value;
			}
			document.getElementById('end3').innerHTML = cur_adresse._adresse.toString() + "<br/>" + cur_adresse._cp.toString() + " " + cur_adresse._ville.toString() + " ";
			document.getElementById('end7').value = cur_adresse._adresse.toString() + ", " + cur_adresse._cp.toString() + " " + cur_adresse._ville.toString() + " ";
		break;
		
		default:
	}
	type_geocodage = -1;
	cur_adresse = null;
	//console.log ( "start_adresse : %o", start_adresse);
	//console.log ( "end_adresse : %o", end_adresse);
	dlg.close();
}


function createStaticUrl ( adresse, type_geoc )
{
	return "http://maps.google.com/maps/api/staticmap?center="+adresse._lat+"," + adresse._lng + "&zoom="+zoom_static+"&size="+size_static+"&maptype=roadmap&markers=color:green|label:S|"+adresse._lat+","+adresse._lng+"&markers=color:green&sensor=false&key=ABQIAAAAdf9-4DSj9b3-S1L0a0P_hxR8p68NDnfEcz6ZqfDTJ2Vfb6GzvRTrEwYQ7cIAjrwA4W-F3qgDAkm5UQ";
}


/**
 * Méthode appellée sur l'un des boutons "départ" ou "arrivée".
 */		
function showGeocoder ( type_geoc )
{
	type_geocodage = type_geoc;
	cur_adresse = null;
	cur_cp = "";
	cur_ville = "";
	cpt = 0;
	lastPlacmarks = null;

	openPopup ();
}	


/**
 * Méthode appellée sur l'annulation de la popup.
 */
function cancelGeocoder ()
{
	switch ( type_geocodage )
	{
		case START : 
			start_adresse = null;
		break;
		
		case END : 
			end_adresse = null;
		break;
		
		default:
	}
	type_geocodage = -1;
}

function loadAeroports ()
{
	var t1 = new GMarker( new GLatLng ( 40.464861, -3.570773 ), {title:'Aeropuerto T1',icon:i_proxi} );
	GEvent.addListener ( t1, "click", function(){
		t1.openInfoWindowHtml ( "<div style='font-weight:bold;font-size:12px;margin-bottom:6px;'>" + "Aeropuerto T1" + "</div>" + "<div>"  + "</div><div><a href='javascript:choixAeroport (t1, 'Aeropuerto T1');'>"+txt_choix_aeroport+"</a></div>" );
	});
	this.map.addOverlay ( t1 );
	//bounds.extend ( t1.getLatLng () );
	
	
	
	var t2 = new GMarker( new GLatLng ( 40.469483, -3.569444 ), {title:'Aeropuerto T2-T3',icon:i_proxi} );
	GEvent.addListener ( t2, "click", function(){
		t2.openInfoWindowHtml ( "<div style='font-weight:bold;font-size:12px;margin-bottom:6px;'>" + "Aeropuerto T2-T3" + "</div>" + "<div>"  + "</div>" );
	});
	this.map.addOverlay ( t2 );
	
	var t3 = new GMarker( new GLatLng ( 40.491743, -3.593625 ), {title:'Aeropuerto T-4',icon:i_proxi} );
	GEvent.addListener ( t3, "click", function(){
		t3.openInfoWindowHtml ( "<div style='font-weight:bold;font-size:12px;margin-bottom:6px;'>" + "Aeropuerto T4" + "</div>" + "<div>"  + "</div>" );
	});
	this.map.addOverlay ( t3 );
	
	/*this.arrResults.push ( m );
	tmp += "<li><a href='javascript:localiseItemLocalSearch(" + i + ");'>" + arguments[0].results[i].titleNoFormatting + " (" + arguments[0].results[i].streetAddress + ")" + "</a></li>";
	
	
	*/
	
}

function choixAeroport (t, l)
{
	adresseValide ();
}

