/* Globale */
var map = null;
var gdir = null;
var geocoder = null;
var mm = null;
var allMarkers = null;
var allItineraireMarkers = new Array();
var coord = null;

// Call this function when the page has been loaded
function initialize() {
	if (GBrowserIsCompatible()) {
		
		// New Instance of GMap
		map = new google.maps.Map2( document.getElementById( "gmap" ) );
		
		// Control
		map.addControl( new google.maps.LargeMapControl() );
		map.addControl( new google.maps.MapTypeControl() );
		map.enableScrollWheelZoom();
		
		// New instance of Geocoder
		geocoder = new google.maps.ClientGeocoder();
		
		// New instance of Directions
		gdir = new google.maps.Directions( map, document.getElementById( "directions" ) );
		
		// Init event for direction error
	    GEvent.addListener(gdir, "error", handleErrors);
		
	    // Show address of real estate
		if ( document.getElementById( "address" ).value != '' ){
//			displayGMapStreet( document.getElementById( "address" ).value );
			showAddress( document.getElementById( "address" ).value );
			
			// Itineraire marker
			if ( allItineraireMarkers.length > 0 ) {
				
				// Create itineraire markers
				for ( var i = 0; i < allItineraireMarkers.length; i++ ) showItineraireAddress( allItineraireMarkers[i]['libelle'], allItineraireMarkers[i]['address'] );
				
			}
			
		}
		else alert( 'Aucune adresse de saisie' );
		
	}
}

/* Functions to set way between to address */
function setDirections(fromAddress, toAddress, locale) {
	gdir.load( "from: " + fromAddress + " to: " + toAddress, { "locale": locale } );
	setTimeout( "displayDirections();", 1000 );
}

function displayDirections(){
	var directions = $( '#directions' );
	directions.slideDown( 'slow' );
	document.getElementById('from').value = '';
}

function displayFormDirections(){
	var form = $( '#form_directions' );
	form.slideDown( 'slow' );
	document.getElementById('from').value = '';
}

function hideDirections(){
	var directions = $( '#directions' );
	directions.slideUp( 'slow' );
}

function hideFormDirections(){
	var form = $( '#form_directions' );
	form.slideUp( 'slow' );
}

function hide(){
	hideDirections();
	hideFormDirections();
}

/* Function to place marker with address */
function showAddress( address ) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function( point ) {
				if ( !point ) {
					alert(address + " not found");
				} else {
					map.setCenter(point, 7);
					addAddressMarker( point, address );
				}
			}
		)
	}
}

function showItineraireAddress( libelle, address ) {
	if (geocoder) {
		geocoder.getLatLng(
			address,
			function( point ) {
				if ( !point ) {
					alert(address + " not found");
				} else {
					addItineraireAddress( point, libelle, address );
				}
			}
		)
	}
}

/* Function to generate GMap street with address */
function displayGMapStreet( address ){
	if (geocoder) 
		geocoder.getLatLng(
			address,
			function( point ){
				if ( !point ) alert(address + " not found");
				else{
					panoramaOptions = { latlng:point };
					var myPano = new google.maps.StreetviewPanorama( document.getElementById("gmap_street"), panoramaOptions );
					GEvent.addListener(myPano, "error", handleNoStreet);
				}
			} );
}

/* Function to create marker */
function createMarker( point, html, icone ) {
	
	// New instance of Marker
	var marker = new google.maps.Marker( point, { icon:icone } );
	
	// Add propertie onclick
	GEvent.addListener( marker, "click", function() {
		marker.openInfoWindowHtml( "<div class='infoBulle'>" + html + "</div>" );
	} );
	
	return marker;
	
}

/* Function to add address marker */
function addAddressMarker( point, address ){
	
	// Init coord
	coord = point;
	
	// Create address marker
	var html = "<p><b>" + address + "</b></p>"
		   	 + "<p><img src='" + imgPath + "urhere_icon.gif' />"
		     + "<a id='linkBulle' href='javascript:displayFormDirections();'>" + document.getElementById( "linkBulleText" ).value + "</a></p>";
//		     + "<p><a href='#' id='linkStreet'>" + document.getElementById( "linkStreetText" ).value + "</a></p>";
	var marker = createMarker( point,
							   html,
							   getIcon( "house_icon.gif" ) );

	// Add marker
	map.addOverlay(marker);
	
	// Display info
    marker.openInfoWindowHtml( "<div class='infoBulle'>" + html + "</div>" );
							   
}

function addItineraireAddress( point, libelle, address ){
	
	// Init Array
	allMarkers = new Array();
	
	// New instance of MarkerManager
	mm = new google.maps.MarkerManager( map, { borderPadding:true, trackMarkers:true } );

	// Create address marker
	var html = "<p><b>" + libelle + "</b></p>"
		   	 + "<p>" + address + "</p>"
		   	 + "<p><u>" + document.getElementById( 'txtDistance' ).value + "</u> : " + distance( point, coord ) + " Km</p>";
		   	 
	var marker = createMarker( point,
							   html,
							   getInitIcon() );
							   
	// Add marker to global markers' array
	allMarkers.push( marker );

	// Add global array in MarkerManager
	mm.addMarkers( allMarkers, 0, 17 );
	
	// Display
	mm.refresh();
	
}

function distance( pointTO, pointFROM ) {
	return Math.round( ( pointTO.distanceFrom( pointFROM ) / 1000 ) * 100 ) / 100;
}

function selectAddress( address ){
	document.getElementById('from').value = address;
	document.getElementById('submitAddress').click();
}

/* Function to take icon */
function getIcon( name ){
	
	// New instance of Icon
	var icon = new google.maps.Icon();
	
	// All properties are required
	icon.image = imgPath + name;
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    icon.iconSize = new google.maps.Size(14, 14);
    icon.shadowSize = new google.maps.Size(30, 14);
    icon.iconAnchor = new google.maps.Point(7, 7);
    icon.infoWindowAnchor = new google.maps.Point(7, 0);
    
	return icon;
	
}

function getInitIcon(){
	// New instance of Icon
	var icon = new google.maps.Icon( G_DEFAULT_ICON );
	
	icon.image = "http://www.google.com/intl/en_us/mapfiles/ms/micons/red-dot.png";
	
	return icon;
}

/* HANDLE ERRORS FOR GMap Directions */
function handleErrors(){
	if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
		alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
		alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
		alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_BAD_KEY)
		alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);
	
	else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
		alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);
	
	else alert("An unknown error occurred.");
}

/* HANDLE ERRORS FOR GMap Street */
function handleNoStreet() {
	return;
}
