var map;
var markers;
var imgDir = "images/";
var markersArray = [];

var SEARCH_ACCOMS_WITH_ADDRESS = "SEARCH_ACCOMS_WITH_ADDRESS";
var SEARCH_ACCOMS_WITH_CODES = "SEARCH_ACCOMS_WITH_CODES";

function recenter() {
    var lat = document.getElementById("lat");
    var lng = document.getElementById("lng");

    if (map != null && map != "" && lat != null && lat.value != "" && lng != null && lng.value != "") {
        map.panTo(new GLatLng(lat.value, lng.value));
    }
}

function chooseHotel(index, maxResultPerPage) {
    var lat = document.getElementById("lat" + index);
    var lng = document.getElementById("lng" + index);

    if (map != null && map != "" && lat != null && lat.value != "" && lng != null && lng.value != "") {
        var latLng = new GLatLng(lat.value, lng.value);
        
        map.panTo(latLng);
        map.openInfoWindow(latLng, getInfoContentHTML(index));
    }

    var containersCount = document.getElementById('containersCount');
	var end = parseInt(containersCount.value) + 1;
    for (var i = 1; i < end; i++) {
        var container = document.getElementById('littleDescContainer' + i);
        container.className = "descHotelsListMap";
    }
    
    var container = document.getElementById('littleDescContainer' + index);
    container.className = "descHotelsListMap selectedAccom";
    
}

function getInfoTitleHTML(resultId) {
    var infoTitleHTML = null;
    try {
        var infoTitleHTMLTemplate = document.getElementById('infoTitleHTMLTemplate_' + resultId);
        infoTitleHTML = infoTitleHTMLTemplate.innerHTML;
        
        showcellandhideother(resultId);
    } catch (error) {
    }
    return infoTitleHTML;
}

function getBaseMarkerTitle(){
	var name = "";
	var searchType = document.getElementById("searchType");
	if (searchType != null){
		if (SEARCH_ACCOMS_WITH_ADDRESS == searchType.value){
			var poiAddress = document.getElementById("poiAddress");
			if (poiAddress != null){
				name = poiAddress.value;	
			}
		}else if(SEARCH_ACCOMS_WITH_CODES == searchType.value){
			var poiName = document.getElementById("poiName");
			if (poiName != null){
				name = poiName.value;	
			}
		}
	}
	return name;
}

function getInfoContentHTML(resultId) {
    var infoContentHTML = null;
    try {
        var infoContentHTMLTemplate = document.getElementById('infoContentHTMLTemplate_' + resultId);
        infoContentHTML = infoContentHTMLTemplate.innerHTML;
        
        showcellandhideother(resultId);
    } catch (error) {
    }
    return infoContentHTML;
}

function getLetterByNumber(nb) {
    var letter = String.fromCharCode("A".charCodeAt(0) + nb - 1);
    return letter;
}

function createIcon() {
	// Create a base icon for all of our markers that specifies the
    // shadow, icon dimensions, etc.
    var baseIcon = new GIcon();
    baseIcon.iconSize = new GSize(32, 32);
    baseIcon.shadowSize = new GSize(32, 32);
    baseIcon.iconAnchor = new GPoint(16, 16);
    baseIcon.infoWindowAnchor = new GPoint(16, 16);

    // Create a lettered icon for this point using our icon class
    return new GIcon(baseIcon);
}

function createMarker(point, index) {
	var onRequest = document.getElementById('onRequest' + index).value;
	
	var baseIcon = createIcon();
    
    // Create a lettered icon for this point using our icon class
    var gicon = new GIcon(baseIcon);
    gicon.image = imgDir + "picto_carte/picto" + index + ".png";

    // Set up our GMarkerOptions object
    markerOptions = {
        icon :gicon
    };
    var marker = new GMarker(point, markerOptions);

    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(getInfoContentHTML(index));
    });

    return marker;
}

function createBaseMarker(point) {
    
    var baseIcon = new GIcon();
    baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(20, 34);
    baseIcon.shadowSize = new GSize(37, 34);
    baseIcon.iconAnchor = new GPoint(9, 34);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);

    // Create a lettered icon for this point using our icon class
    var letteredIcon = new GIcon(baseIcon);
    letteredIcon.image = "http://www.google.com/mapfiles/marker.png";
    
    // Set up our GMarkerOptions object
    var currentTitle= getBaseMarkerTitle();
    markerOptions = {
        icon :letteredIcon,
        title:currentTitle
    };
    var marker = new GMarker(point, markerOptions);
    
    if (currentTitle != null && currentTitle.length > 0){
	    GEvent.addListener(marker, "click", function() {
	        marker.openInfoWindowHtml(currentTitle);
	    });
    }

    return marker;
}

function loadGoogleMapForMapSearch(){
    // vérification de la compatibilite du navigateur
    if (GBrowserIsCompatible()){
        // Creation d'une carte Google Map dans la balise DIV portant l id "carte"
        var map = new GMap2(document.getElementById("mapWindow"));
        // Initialisation du marqueur par defaut
        var blueIcon = new GIcon(G_DEFAULT_ICON);
        blueIcon.image = "images/pick.png";
        blueIcon.shadow = "";
		// On attribue le marqueur a l'option GMarkerOptions
		markerOptions = { icon:blueIcon };
        var defaultPoint = new GLatLng(48.142403,11.581535);
        marker = new GMarker(defaultPoint,markerOptions); 
        // centrage de la carte sur le point correspondant à ces coordonnées (ville de Lyon)
        map.setCenter(new GLatLng(48.142403,11.581535),4);

		var la = document.getElementById("lat");
		var ln = document.getElementById("lng");
		if (la != null && la.value != "" && ln != null && ln.value != "") {
			var selectPoint = new GLatLng(la.value, ln.value);
			//marker = new GMarker(selectPoint,markerOptions);
			marker.setLatLng(selectPoint);
			map.addOverlay(marker);
			map.setCenter(selectPoint, 4);
		}
        
        // ajout de la barre d'outil permettant de choisir le type de carte
        map.addControl(new GMapTypeControl());
        // ajout de la barre d'outil permettant de zoomer sur la carte
        map.addControl(new GLargeMapControl());
        map.addControl(new GScaleControl());
        
	     // A RecenterControl is a GControl that displays center buttons 
	     // We define the function first
	     function RecenterControl() {}
	
	     // To "subclass" the GControl, we set the prototype object to
	     // an instance of the GControl object
	     RecenterControl.prototype = new GControl();
	
	     // Creates a DIV for the buttons and places him in a container
	     // DIV which is returned as our control element. We add the control
	     // to the map container and return the element for the map class to
	     // position properly.
	     RecenterControl.prototype.initialize = function(map) {
	     	var container = document.createElement("div");
	     	var recenterDiv = document.createElement("div");
	     	this.setButtonStyle_(recenterDiv);
	     	container.appendChild(recenterDiv);
	     	// recenterDiv.appendChild(document.createTextNode("!"));
	     	var recenterImg = document.createElement('img');
	     	recenterImg.setAttribute('src', 'images/recenter.png');
	     	recenterImg.className = 'recenter_button';
	     	recenterDiv.appendChild(recenterImg);
	     	GEvent.addDomListener(recenterDiv, "click", function() {
	     	    var lat = document.getElementById("lat");
	     	    var lng = document.getElementById("lng");
	     	    if (map != null && map != "" && lat != null && lat.value != "" && lng != null && lng.value != "") {
	     	        map.panTo(new GLatLng(lat.value, lng.value));
	     	    }
	     	});    	
	     	map.getContainer().appendChild(container);
	     	return container;
	     }
	     	
	     //- By default, the control will appear in the top left corner of the
	     //- map with 7 pixels of padding.
	     RecenterControl.prototype.getDefaultPosition = function() {
	     	return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(27, 300));
	     }
	     	
	     //- Sets the proper CSS for the given button element.
	     RecenterControl.prototype.setButtonStyle_ = function(button) {
	     	button.style.font = "small Arial";
	     	button.style.textAlign = "center";
	     	button.style.cursor = "pointer";
	     }
        
        map.addControl(new RecenterControl());
        
        // ajout d un observateur d'evenement pour l action click afin d afficher les coordonnées
        GEvent.addListener(map, "click", function(overlay,point) {
                // vérification pour savoir si la variable point est vraie
                if (point) {
                    // sette les nouvelles coordonnées
                    document.getElementById("lat").value = point.lat();
                    document.getElementById("lng").value = point.lng();
                    
                    // met à jour la position du marqueur
                    var point = new GLatLng(point.lat(), point.lng());
                    marker.setLatLng(point);
                    map.addOverlay(marker);
                    
                    // recherche les aéroports autour de ce point
                	var dualInput = document.getElementById("arrivalCode");
                	// on vide la liste déroulante
                	emptySelectList(dualInput);
                	// on recherche les aeroports a 200km autour
                    searchAirport(point.lat(), point.lng(), dualInput, null);
                }
            }
        );
	}
}

function loadGoogleMap() {
    if (GBrowserIsCompatible() && map == null) {
        var mapWindowDiv = document.getElementById("mapWindow");
        if (mapWindowDiv != null) {
            map = new GMap2(mapWindowDiv);
            var lat = document.getElementById("lat");
            var lng = document.getElementById("lng");
            if (lat != null && lat.value != "" && lng != null && lng.value != "") {
                var point = new GLatLng(lat.value, lng.value);
            	var POImarker = createBaseMarker(point);
            	map.addOverlay(POImarker);
            	
            	var zoom = 10;
                var address = "ad";
                var point = new GLatLng(lat.value, lng.value);
                map.setCenter(point, zoom);

                map.addControl(new GLargeMapControl());
                map.addControl(new GMapTypeControl());
                map.addControl(new GScaleControl());
                // map.addControl(new GOverviewMapControl()) ;
                geocoder = new GClientGeocoder();


                var bounds = new GLatLngBounds();
                markers = new Array;
                var containersCount = document.getElementById('containersCount');
                var end = parseInt(containersCount.value) + 1;
                for (var i = 1; i < end; i++) {
                    var lati = document.getElementById("lat" + i);
                    var lngi = document.getElementById("lng" + i);
                    if (lati != null && lati.value != "" && lngi != null && lngi.value != "") {
                        var point = new GLatLng(lati.value, lngi.value);
                        var marker = createMarker(point, i);
                        
                        markers[i] = marker;
                        bounds.extend(new GLatLng(lati.value, lngi.value));
                        map.addOverlay(marker);
                    }
                }
                
                map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
            }
        }
    }
}

function showcellandhideother(ind) {
	var containersCount = document.getElementById('containersCount');
	var end = parseInt(containersCount.value) + 1;
	 
    for (var i = 1; i < end; i++) {
    	var lati = document.getElementById("lat" + i);
        var lngi = document.getElementById("lng" + i);
        if (lati != null && lati.value != "" && lngi != null && lngi.value != "") {
	    	changeIcon(i, "picto_carte");
        }
        hideElement('littleDesc' + i);
    }
    
	var lat = document.getElementById("lat" + ind);
    var lng = document.getElementById("lng" + ind);
    if (lat != null && lat.value != "" && lng != null && lng.value != "") {
		changeIcon(ind, "picto_carte_select");
    }

    showElement('littleDesc' + ind);
}

function getSelected(i) {
	var picto_bouton = document.getElementById('picto_bouton' + i);
	var marker = markers[i];
    
    marker.setImage(imgDir + "picto_carte/selected.gif");
    picto_bouton.src = imgDir + "picto_carte/selected.gif";
}

function changeIcon(i, iconType) {
	var marker = markers[i];
    
   	marker.setImage(imgDir + iconType + "/picto" + i + ".png");
}

function showcell(ind) {
	var container = document.getElementById('littleDescContainer' + ind);
	container.style.border = "1px solid #DDDDDD";
	container.style.color = "#DDDDDD";
	showElement('littleDesc' + ind);
}

function hidecell(ind) {
	var container = document.getElementById('littleDescContainer' + ind);
	container.style.border = "none";
	container.style.color = "#444444";
	hideElement('littleDesc' + ind);
}
