var directionDisplay;
var directionsService = new google.maps.DirectionsService();
var map;

function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer();
    var centro = new google.maps.LatLng(40.977189, 0.290255);
    var myOptions = {
        zoom:12,
        mapTypeId: google.maps.MapTypeId.HYBRID,
        center: centro
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));
    
    datoscontacto = $('#pie').html();

    masia = addInfoWindow(datoscontacto,40.977189, 0.290255);

}

function addInfoWindow(texto,lat,lng){

    var marker = new Array(1);

    marker[0] = new google.maps.InfoWindow({
        content: texto
    });

    marker[1] = new google.maps.Marker({
        position: new google.maps.LatLng(lat, lng),
        map: map
    });
    google.maps.event.addListener(marker[1], 'click', function() {
        marker[0].open(map,marker[1]);
    });

    return marker;

}

function calcRoute() {
    var start = $("#desde").val();
    var end = "40.977189, 0.290255";
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            $('#directionsPanel').hide('slow',function(){
                $('#directionsPanel').show('slow');
            });
            directionsDisplay.setDirections(response);
        }else{
            if(start==''){
                alert("Introduzca un punto de origen");
            }else{
                alert("Se ha producido un error");
            }
        }
    });
}

$(document).ready(function(){

    url = window.location.pathname;
    if(url.indexOf("llegar")!=-1){
        initialize();
        $('#calcular').click(function(){
            calcRoute();
        });
    }
});
  
