/* geral */
var map;
var openInfowindow;
var mapMarkers = [];
var mapHTMLS = [];

/* pesquisa de direcções */
var errorMessageNotFound;
var errorMessageZeroResults;
var directionDisplay;
var directionsService = new google.maps.DirectionsService();


/*
 * cálculo de direcções
 */

function calcRoute(start, end){
    var lastChar = start.substring(start.length - 1);

    if (lastChar == '-')
        start = start.substring(0, start.length - 1);

    var request = {
        origin: start,
        destination: end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };

    directionsService.route(request, function(response, status){

        if (status == google.maps.DirectionsStatus.OK) {
            document.getElementById('directionsContainer').style.display = 'block';
            directionsDisplay.setDirections(response);
        }
        else
            if (status == google.maps.DirectionsStatus.NOT_FOUND) {
                alert(errorMessageNotFound);
            }
            else
                if (status == google.maps.DirectionsStatus.ZERO_RESULTS) {
                    alert(errorMessageZeroResults);
                }
                else {
                    alert(errorMessageNotFound);
                }
    });
}

function goToMarker(markerIndex){

    var infowindow = new google.maps.InfoWindow({
        content: mapHTMLS[markerIndex]
    });

    infowindow.open(map, mapMarkers[markerIndex]);
    setInfowindow(infowindow);
}

/*
 * função que define qual o marcador / baloon info activo
 */

function setInfowindow(newInfowindow){
    if (openInfowindow != undefined) {
        openInfowindow.close();
    }

    openInfowindow = newInfowindow;
}

/*
 * função que adiciona um marcador ao mapa
 */

function placeMarker(location, markerText, markerIcon, markerTitle, centerHere){

    var infowindow = new google.maps.InfoWindow({
        content: markerText
    });

    var marker = new google.maps.Marker({
        position: location,
		map: map
    });

	if (markerIcon != null) {
		marker.setIcon(markerIcon);
	}

	if (markerTitle != null) {
		marker.setTitle(markerTitle);
	}

    mapMarkers.push(marker);
    mapHTMLS.push(markerText);

    if (centerHere == true) {
        map.setCenter(location);
        infowindow.open(map, marker);
        setInfowindow(infowindow);
    }

    google.maps.event.addListener(marker, 'click', function(){
        infowindow.open(map, marker);
        setInfowindow(infowindow);
    });
}
