var destiGeocoded;
var desti_lloc;
		
var geocoder = new google.maps.Geocoder();
var origen;

var travel_mode = google.maps.DirectionsTravelMode.WALKING;
var indicacions_mapa = 'mapa';
var waypts_info = [];
var markersArray = [];	
var map;

var div_mapa;
var div_popup;
var div_nom_lloc;
var div_address;

var request = {
    origin: origen,								
    destination: desti_lloc,
    travelMode: travel_mode
};
			
var rendererOptions = {  
    draggable: false,  
    suppressMarkers: true  
};		
			
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var directionsService = new google.maps.DirectionsService();						  

function geo(map_div, nom_popup, nom_lloc, nom_address) {

    div_mapa = map_div;
    div_popup = nom_popup;
    div_nom_lloc = nom_lloc;
    div_address = nom_address;
        
    if (geoPosition.init() !==null) {
        geoPosition.getCurrentPosition(initialize_location, error);        
    } else {
        msg.code = 1;
        error(msg);
    }					  
}

//Missatge d'error en cas que falli la geolocalització

function error(msg) {
    
    //alert(idiomes[llengua_activa]['geolocate_' + msg.code]);       
    alert(msg.message);    
    $.mobile.hidePageLoadingMsg();
    
}

function initialize_location(position) {		

    deleteOverlaysArribar();
    waypts_info.length = 0;
        
    origen = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    bounds.extend(origen);
    
    geocoder.geocode( {
        'latLng': origen
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
          
            waypts_info.push({
                nom_lloc: '<p>'+idiomes[llengua_activa]['lang_voste_aqui']+':</p><p>' + results[0].formatted_address + '</p>'
            });
            
            request.origin = origen;	
								
            request.destination = new google.maps.LatLng(coordenades_actives.latitude, coordenades_actives.longitude);
				
            deleteOverlaysArribar();
            
            draw_map_arribar();
            
            return calcDistanceArribar(origen, request.destination);   
                        
        } else {
            return false;
        }
    });
										
}
		  
function draw_directions_arribar(request) {	
			  
    directionsService.route(request, function(response, status) {
					
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(response);
            
            waypts_info.push({
                nom_lloc: '<p>'+ $('#'+div_nom_lloc+' h2').html() + '</p>' + '<p>' + $('#'+div_address).html() + '</p>'
            });
            
            inspectMarkersArribar();
        }
    });
				
}			

function draw_map_arribar() {
												
    myOptions = {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,  
        streetViewControl: false
    }
												
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    map = new google.maps.Map(document.getElementById(div_mapa), myOptions);
    directionsDisplay.setPanel(document.getElementById(div_mapa+'_ruta'));
    
    map.setOptions({
        styles: styles
    });
    
    directionsDisplay.setMap(map);
    
    google.maps.event.addListenerOnce(map, 'idle', function(){
        //Fer un resize del mapa un cop carregat per tal que la API reconegui les dimensions del contenidor. D'aquesta forma //s'evita que només mostri una part del mapa.
        
        //google.maps.event.trigger(map,'resize'); 
        
        $('#'+div_mapa).css('visibility','visible');
        
        $.mobile.hidePageLoadingMsg();    
        
    });	
        			
//createMarker(origen, 0, 'start');
			
}	
						
function set_directions_arribar() {
			
    directionsDisplay = new google.maps.DirectionsRenderer();    
			
}
						
function inspectMarkersArribar() {			
				
    createMarkerArribar(directionsDisplay.directions.routes[0].legs[0].start_location, 0, 16);
    
    if (div_mapa == 'map_canvas' || div_mapa == 'map_canvas_oferta') {
        
        createMarkerArribar(destiGeocoded, 1, 0);
        
    } else {
    
        createMarkerArribar(destiGeocoded, 1, 17);

    }
    
}
	
function createMarkerArribar(place, index, icon) {

    var image = icona_botiga[icon];
								
    var marker = new google.maps.Marker({
        map: map,
        position: place,
        icon: image
    });
				
    var info = waypts_info[index].nom_lloc;
    markersArray.push(marker);
			
    bounds.extend(place);
                        
    google.maps.event.addListener(marker, 'click', function() {				  			  			  
        
        $('#'+div_popup+'_text').empty();
        $('#'+div_popup+'_text').append(info);
        $('#'+div_popup+' a').attr('href', "javascript:infoBotiga(" + botiga_activa + ")")                
        $('#'+div_popup).popup('open');
        
    });
    				
}
			  
function deleteOverlaysArribar() {
    if (markersArray) {
        for (var i = 0; i < markersArray.length; i++) {
            markersArray[i].setMap(null);
        }
        markersArray.length = 0;
    }
}

//Calculem la distància entre els dos punts, si es més gran de x quilòmetres, el mode de transport
//serà en cotxe, en cas contrari, a peu.

function calcDistanceArribar(location1, location2) {
                    
    destiGeocoded = location2;
        
    if (distance(location1.lat(), location1.lng(), location2.lat(), location2.lng(), 'K') > 5) {

        request.travelMode = google.maps.DirectionsTravelMode.DRIVING;			  
        activaBotoMode('transport_en_cotxe');           
                
    } else {
                
        request.travelMode = google.maps.DirectionsTravelMode.WALKING;
        activaBotoMode('transport_a_peu');           
                
    }

    draw_directions_arribar(request);	
            
    return true;		
}