/**
 * @author nlamblin
 */
var map;
var directionsPanel;
var directions;
var geocoder;
var address;



function dessiner_carte(id, lat, longi){
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), 15);
    afficherMarker(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
    GEvent.addListener(map, "click", function(overlay, latlng){
        if (latlng) {
            var gpoint = latlng;
            afficherMarker(gpoint.y, gpoint.x);
        }
    });
    //map.addControl(new GSmallMapControl());
    //map.addControl(new GMapTypeControl());

}

function dessiner_itineraire(id, lat, longi, itineraire){
	console.log(id);
	console.log(lat);
	console.log(longi);
	console.log(itineraire);
    map = new GMap2(document.getElementById(id));
    map.setCenter(new GLatLng(lat, longi), 15);
    directions = new GDirections(map, '');
    directions.load(itineraire);
    //map.addControl(new GLargeMapControl);
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
    
}

function afficherMarker(lat_, longi_){

    map.clearOverlays();
    var marker0 = new GMarker(new GLatLng(lat_, longi_), {
        draggable: true,
        image: 'http://www.covivo.eu/images/icon6.png'
    });
    geocoder = new GClientGeocoder();
    geocoder.getLocations(marker0.getLatLng(), function(response){
        if (!response || response.Status.code != 200) {
            if (response.Status.code == 602) 
                alert('Impossible de récupérer les coordonnées GPS.');
            //            alert("Status Code:" + response.Status.code);
        }
        else {
            place = response.Placemark[0];
            var latipt = place.Point.coordinates[1];
            var longipt = place.Point.coordinates[0];
            recupcor = response.name;
            tabcor = recupcor.split(",");
            adresse = cp = ville = pays = "";
            if (place.AddressDetails) {
                if (place.AddressDetails.Country.CountryName) 
                    pays = place.AddressDetails.Country.CountryName;
                if (place.AddressDetails.Country.AdministrativeArea) {
                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
                                        adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
                                    cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
                                    ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                            }
                        }
                    }
                }
            }
            marker0.openInfoWindowHtml( //'<b>orig latlng:</b>' + response.name + '<br/>' +
            //'<b>latlng:</b>' + latpt + "," + longipt + '<br>' +
            //'<b>Status Code:</b>' + response.Status.code + '<br>' +
            //'<b>Status Request:</b>' + response.Status.request + '<br>' +
            '<div class="carte_infos"><b>Adresse : </b>' + adresse + '<br>' +
            '<b>Code postal : </b>' +
            cp +
            '<br>' +
            '<b>Ville : </b>' +
            ville +
            '<br/>' +
            '<b>Pays : </b>' +
            pays +
            '<br/></div>' //'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
            //'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode
            );
			var regAdr = /adressesperso/;
			if (!regAdr.test(location.href)) {
				document.getElementById('Adresse_Point').value = adresse;
				document.getElementById('CP_Point').value = cp;
				document.getElementById('Ville_Point').value = ville;
				if (document.getElementById('Lat_Point')) 
					document.getElementById('Lat_Point').value = latipt;
				if (document.getElementById('Lon_Point')) 
					document.getElementById('Lon_Point').value = longipt;
				if (document.getElementById('Pays_Point')) 
					document.getElementById('Pays_Point').value = pays;
			}
			/*
            if (document.getElementById('ListePays_Adresse')) {
                var tabPays = $j('#ListePays_Adresse :option');
                for (var i = 0; i < tabPays.length; i++) {
					if(pays == "Luxembourg") pays = "GD"+pays;
                    if (pays == tabPays[i].text) {
                        tabPays[i].selected = "selected";
                    }
                    
                }
            }
			if(document.getElementById('ListePays_Ville_Depart'))
			{
				var tabPays = $j('#ListePays_Ville_Depart :option');
                for (var i = 0; i < tabPays.length; i++) {
					if(pays == "Luxembourg") pays = "GD"+pays;
                    if (pays == tabPays[i].text) {
                        tabPays[i].selected = "selected";
                    }
                    
                }
			}
			if(document.getElementById('ListePays_Ville_Depart_Aire'))
			{
				var tabPays = $j('#ListePays_Ville_Aire :option');
                for (var i = 0; i < tabPays.length; i++) {
					if(pays == "Luxembourg") pays = "GD"+pays;
                    if (pays == tabPays[i].text) {
                        tabPays[i].selected = "selected";
                    }
                    
                }
			}
			if(document.getElementById('ListePays_Ville_Arrivee'))
			{
				var tabPays = $j('#ListePays_Ville_Arrivee :option');
                for (var i = 0; i < tabPays.length; i++) {
					if(pays == "Luxembourg") pays = "GD"+pays;
                    if (pays == tabPays[i].text) {
                        tabPays[i].selected = "selected";
                    }
                    
                }
			}
			if(document.getElementById('ListePays_Ville_Arrivee_Aire'))
			{
				var tabPays = $j('#ListePays_Ville_Arrivee_Aire :option');
                for (var i = 0; i < tabPays.length; i++) {
					if(pays == "Luxembourg") pays = "GD"+pays;
                    if (pays == tabPays[i].text) {
                        tabPays[i].selected = "selected";
                    }
                    
                }
			}
			*/
        }
    });
    GEvent.addListener(marker0, "dragstart", function(){
        map.closeInfoWindow();
    });
    GEvent.addListener(marker0, "dragend", function(){
        geocoder.getLocations(marker0.getLatLng(), function(response){
            if (!response || response.Status.code != 200) {
                if (response.Status.code == 602) 
                    alert('Impossible de récupérer les coordonnées GPS.');
                //                alert("Status Code:" + response.Status.code);
            }
            else {
                place = response.Placemark[0];
                var latipt = place.Point.coordinates[1];
                var longipt = place.Point.coordinates[0];
                recupcor = response.name;
                tabcor = recupcor.split(",");
                adresse = cp = ville = pays = "";
                if (place.AddressDetails) {
                    if (place.AddressDetails.Country.CountryName) 
                        pays = place.AddressDetails.Country.CountryName;
                    if (place.AddressDetails.Country.AdministrativeArea) {
                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
                                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
                                            adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
                                        cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
                                        ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                                }
                            }
                        }
                    }
                }
                marker0.openInfoWindowHtml( //'<b>orig latlng:</b>' + response.name + '<br/>' +
                //'<b>latlng:</b>' + latpt + "," + longipt + '<br>' +
                //'<b>Status Code:</b>' + response.Status.code + '<br>' +
                //'<b>Status Request:</b>' + response.Status.request + '<br>' +
                '<div class="carte_infos"><b>Adresse : </b>' + adresse + '<br>' +
                '<b>Code postal : </b>' +
                cp +
                '<br>' +
                '<b>Ville : </b>' +
                ville +
                '<br/>' +
                '<b>Pays : </b>' +
                pays +
                '<br/></div>'                //'<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
                //'<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode
                );
                document.getElementById('Adresse_Point').value = adresse;
                document.getElementById('CP_Point').value = cp;
                document.getElementById('Ville_Point').value = ville;
                if (document.getElementById('Lat_Point')) 
                    document.getElementById('Lat_Point').value = latipt;
                if (document.getElementById('Lon_Point')) 
                    document.getElementById('Lon_Point').value = longipt;
                if (document.getElementById('Pays_Point')) 
                    document.getElementById('Pays_Point').value = pays;
				if($j('#Lat_Point'))
					$j('#Lat_Point').val(latipt);
				if($j('#Lon_Point'))
					$j('#Lon_Point').val(longipt);
                if (document.getElementById('ListePays_Adresse')) {
                    var tabPays = $j('#ListePays_Adresse :option');
                    for (var i = 0; i < tabPays.length; i++) {
						if(pays == "Luxembourg") pays = "GD"+pays;
                        if (pays == tabPays[i].text) {
                            tabPays[i].selected = "selected";
                        }
                        
                    }
                }
//			if(document.getElementById('ListePays_Ville_Depart'))
//			{
//				var tabPays = $j('#ListePays_Ville_Depart :option');
//                for (var i = 0; i < tabPays.length; i++) {
//					if(pays == "Luxembourg") pays = "GD"+pays;
//                    if (pays == tabPays[i].text) {
//                        tabPays[i].selected = "selected";
//                    }
//                    
//                }
//			}
//			if(document.getElementById('ListePays_Ville_Depart_Aire'))
//			{
//				var tabPays = $j('#ListePays_Ville_Aire :option');
//                for (var i = 0; i < tabPays.length; i++) {
//					if(pays == "Luxembourg") pays = "GD"+pays;
//                    if (pays == tabPays[i].text) {
//                        tabPays[i].selected = "selected";
//                    }
//                    
//                }
//			}
//			if(document.getElementById('ListePays_Ville_Arrivee'))
//			{
//				var tabPays = $j('#ListePays_Ville_Arrivee :option');
//                for (var i = 0; i < tabPays.length; i++) {
//					if(pays == "Luxembourg") pays = "GD"+pays;
//                    if (pays == tabPays[i].text) {
//                        tabPays[i].selected = "selected";
//                    }
//                    
//                }
//			}
//			if(document.getElementById('ListePays_Ville_Arrivee_Aire'))
//			{
//				var tabPays = $j('#ListePays_Ville_Arrivee_Aire :option');
//                for (var i = 0; i < tabPays.length; i++) {
//					if(pays == "Luxembourg") pays = "GD"+pays;
//                    if (pays == tabPays[i].text) {
//                        tabPays[i].selected = "selected";
//                    }
//                    
//                }
//			}
            }
        });
    });
    map.addOverlay(marker0);
}

var createMarkerOnPlacemark = function(nom_, lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_), {
        icon: new GIcon({
            iconAnchor: new GPoint(lat_, longi_),
            infoWindowAnchor: new GPoint(9, 4),
            image: 'http://www.covivo.eu/images/icon7.png'
        })
    });
    GEvent.addListener(marker, "click", function(){
    
        var text = nom_;
        paren1 = text.indexOf('(');
        paren2 = text.indexOf(')');
        pipe = text.indexOf('|');
        ville = text.substring(0, paren1);
        cp = text.substring(paren1 + 1, paren2);
        if (pipe > paren2) 
            adresse = text.substring(pipe + 1, text.length);
        else 
            adresse = '';
        var html = '<div class="carte_infos">';
        html = '<b>Adresse : </b>' + adresse + '<br/>';
        html += '<b>Code postal : </b>' + cp + '<br/>';
        html += '<b>Ville : </b>' + ville + '<br/></div>';
		if($j('#Addrese_Point'))
			$j('#Adresse_Point').val(adresse);
		if($j('#CP_Point'))
			$j('#CP_Point').val(cp);
		if($j('#Ville_Point'))
			$j('#Ville_Point').val(ville);
		if($j('#Pays_point'))
			$j('#Pays_point').val(1);
		if($j('#Lat_Point'))
			$j('#Lat_Point').val(lat_);
		if($j('#Lon_Point'))
			$j('#Lon_Point').val(longi_);
        marker.openInfoWindowHtml(html);
    });
    map.addOverlay(marker);
};
var createMarkerOnPlacemark2 = function(nom_, lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_), {
        icon: new GIcon({
            iconAnchor: new GPoint(lat_, longi_),
            infoWindowAnchor: new GPoint(9, 4),
            image: 'http://www.covivo.eu/images/icon39.png'
        })
    });
    GEvent.addListener(marker, "click", function(){
    
        var text = nom_;
        paren1 = text.indexOf('(');
        paren2 = text.indexOf(')');
        pipe = text.indexOf('|');
        ville = text.substring(0, paren1);
        cp = text.substring(paren1 + 1, paren2);
        if (pipe > paren2) 
            adresse = text.substring(pipe + 1, text.length);
        else 
            adresse = '';
        var html = '<div class="carte_infos">';
        html = '<b>Adresse : </b>' + adresse + '<br/>';
        html += '<b>Code postal : </b>' + cp + '<br/>';
        html += '<b>Ville : </b>' + ville + '<br/></div>';
		if($j('#Addrese_Point'))
			$j('#Adresse_Point').val(adresse);
		if($j('#CP_Point'))
			$j('#CP_Point').val(cp);
		if($j('#Ville_Point'))
			$j('#Ville_Point').val(ville);
		if($j('#Pays_point'))
			$j('#Pays_point').val(1);
		if($j('#Lat_Point'))
			$j('#Lat_Point').val(lat_);
		if($j('#Lon_Point'))
			$j('#Lon_Point').val(longi_);
        marker.openInfoWindowHtml(html);
    });
    map.addOverlay(marker);
};

function dessiner_carte_perso(id, lat, longi){
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), 15);
    afficherMarker_perso(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
}

function afficherMarker_perso(lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_));
    map.addOverlay(marker);
}

var i= 0;
var etape;
var panel;
var direction;

function DessinerCarteItineraire(id,directions){
//	i = 0;
	etape = new Array();
	
	if (GBrowserIsCompatible()) { 
 
      map = new GMap2(document.getElementById(id));
	  panel = document.getElementById('directions');
	  direction = new GDirections(map,panel);
	  var customUI = map.getDefaultUI();
    	customUI.controls.scalecontrol = false;
		customUI.controls.menumaptypecontrol = false;
    
   	  map.setUI(customUI);
      map.setCenter(new GLatLng(48.860801696777,2.34579992294308),13);
      
	    GEvent.addListener(map, "click", function(overlay, latlng){
	        if (latlng) {
				
	            var gpoint = latlng;
	            etape[i] = new Array();
				etape[i]['Lat'] = gpoint.y;
	            etape[i]['Long'] = gpoint.x;
				ajouterMarker(gpoint.y, gpoint.x);
				$j('#Click').append('<p><p>Point '+ i + ' : </p>lat : ' + etape[i]['Lat'] + '<br/>long : ' + etape[i]['Long'] + '</p>');
//				console.log(etape[i]);
				i++;
	        }
	    });
	 
    }else {
      alert("Désolé vous ne pouvez pas avoir google map sur votre navigateur.");
    }
}

function ajouterMarker(lat_,longi_){
    var marker0 = new GMarker(new GLatLng(lat_, longi_), {
        draggable: false,
        image: 'http://www.covivo.eu/images/icon6.png'
    });
	map.addOverlay(marker0);
}

function itineraire(){
	waypoints = '';
	var k=i;
	for(var j=0;j<i;j++){
		waypoints +=etape[j]['Lat'] + ','+ etape[j]['Long'];
		waypoints += ' to:';
	}
	waypoints = waypoints.substr(0,waypoints.length-3);
//	var depart = $j('#VilleDeDepart').val();
//	var arrivee = $j('#VilleDArrivee').val();
//	waypoints += depart + ' to:' + arrivee;
//	console.log(waypoints);
	map.clearOverlays();
	direction.load(waypoints);
//	console.log(direction);
}
var latlon;
function coordonnees(){
	map.clearOverlays();
	$j('#Click').html('');
	geocoder = new GClientGeocoder();
	var adresse = $j('#Coord').val();
	 geocoder.getLocations(adresse, function(response){
        if (!response || response.Status.code != 200) {
            if (response.Status.code == 602) 
                alert('Impossible de récupérer les coordonnées GPS.');
            //            alert("Status Code:" + response.Status.code);
        }
        else {
//			console.log(response);
			for(var i = 0;i<response.Placemark.length;i++){
	            place = response.Placemark[i];
	            var latipt = place.Point.coordinates[1];
	            var longipt = place.Point.coordinates[0];
				var latlon = new GLatLng(latipt,longipt);
//				afficherMarker(latipt,longipt);
//				afficherMarker(latipt,longipt);
				afficherMarker_perso(latipt,longipt);
				$j('#Click').append("<p><p>Lat:" + latipt + "</p><p>Lon:" + longipt + "</p><p>Adresse: "+ place.name + "</p></p>");
				$j.ajax({url:'/outils/pause',
						data:{d:1},
						async: false,
						success: function(data){
							getAddress(latlon);
						}
				});
			}
//            recupcor = response.name;
//            tabcor = recupcor.split(",");
//            adresse = cp = ville = pays = "";
//            if (place.AddressDetails) {
//                if (place.AddressDetails.Country.CountryName) 
//                    pays = place.AddressDetails.Country.CountryName;
//                if (place.AddressDetails.Country.AdministrativeArea) {
//                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
//                        if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) {
//                            if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) {
//                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare) 
//                                    if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName) 
//                                        adresse = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.Thoroughfare.ThoroughfareName;
//                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) 
//                                    cp = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
//                                if (place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName) 
//                                    ville = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
//                            }
//                        }
//                    }
//                }
//            }
			
			$j('#Lat_Point').val(latipt);
			$j('#Lon_Point').val(longipt);
		}
	});
}

function getAddress(latlon) {
	console.log(latlon)
  if (latlon != null) {
    geocoder.getLocations(latlon, showAddress);
  }
}

function showAddress(response) {
	console.log(response.Status.code);
	console.log(response);
  if (!response || response.Status.code != 200) {
//  	var latlon new GLatLng()
    alert("Status Code:" + response.Status.code);
  } else {
    place = response.Placemark[0];
    var info = $j(
        '<p><b>orig latlng:</b>' + response.name + '<br/>' + 
        '<b>latlng:</b>' + place.Point.coordinates[1] + "," + place.Point.coordinates[0] + '<br>' +
        '<b>Status Code:</b>' + response.Status.code + '<br>' +
        '<b>Status Request:</b>' + response.Status.request + '<br>' +
        '<b>Address:</b>' + place.address + '<br>' +
        '<b>Accuracy:</b>' + place.AddressDetails.Accuracy + '<br>' +
        '<b>Country code:</b> ' + place.AddressDetails.Country.CountryNameCode + '<br/>-------------------------------------</p>');
	$j('#Click').append(info);
  }
  
}
function pause( iMilliseconds )
{
  var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
  window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

function dessiner_carte_perso(id, lat, longi){
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat, longi), 15);
    afficherMarker_perso(lat, longi);
    //map.addControl(new GLargeMapControl);
    geocoder = new GClientGeocoder();
    var customUI = map.getDefaultUI();
    customUI.controls.scalecontrol = false;
    customUI.controls.menumaptypecontrol = false;
    
    map.setUI(customUI);
}

function afficherMarker_perso(lat_, longi_){
    var marker = new GMarker(new GLatLng(lat_, longi_));
    map.addOverlay(marker);
}
function dessiner_carte_evt(id, lat_, longi_, titre){
//	console.log(document.getElementById(id));
    map = new GMap2(document.getElementById(id));
    directions = new GDirections(map, '');
    map.setCenter(new GLatLng(lat_, longi_), 15);
    afficherMarker_evt(lat_, longi_, titre);
}


function afficherMarker_evt(lat_, longi_, titre){
    map.clearOverlays();
   var marker0 = new GMarker(new GLatLng(lat_, longi_), {
        draggable: false,
        image: 'http://www.covivo.eu/images/icon6.png'
    });
	map.addOverlay(marker0);
//    marker0.openInfoWindowHtml('<b>TItre : </b>' + titre + '<br/>');
}
