/* Com arribar a un lloc determinat des d'on som */

var destiGeocoded;
		
var geocoder = new google.maps.Geocoder();
		
var desti;		  
var origen;
	
var travel_mode = google.maps.DirectionsTravelMode.WALKING;
var indicacions_mapa = 'mapa';
var waypts_info = [];
var markersArray = [];	
var markersArrayParking = [];	
var map;
var bounds = new google.maps.LatLngBounds();

var com_arribar_activat = false;

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

var directionsService = new google.maps.DirectionsService();						  
		  
function geo_arribar() {
			  
    if (geoPosition.init() !==null) {
        geoPosition.getCurrentPosition(initialize, error);                
    } else {
        msg.code = 1;
        error(msg);           
    }		  					  
}

function initialize(position) {		
				
    //Eliminem l'estat actiu dels botons d'opcions
                
    $('.popup_opcions_mapa a').removeClass('ui-btn-active');

    deleteOverlays(markersArray);
    deleteOverlays(markersArrayParking);
    waypts_info.length = 0;
    com_arribar_activat = false;
    
    origen = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
    bounds.extend(origen);
			
    request.origin = origen;
    
    geocoder.geocode( {
        'latLng': origen
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            
            waypts_info.push({
                nom_lloc: '<p><strong>'+idiomes[llengua_activa]['lang_voste_aqui']+':</strong></p><p>' + results[0].formatted_address + '</p>'
            });	
    		
            draw_map_init();
			
            var input = document.getElementById('searchTextField');
            var autocomplete = new google.maps.places.Autocomplete(input);

            autocomplete.bindTo('bounds', map);

            google.maps.event.addListener(autocomplete, 'place_changed', function() {
			
                var place = autocomplete.getPlace();
			  			  
                request.destination = place.geometry.location;	
			  
                destiGeocoded = request.destination;
		                                        
                if (distance(origen.lat(), origen.lng(), destiGeocoded.lat(), destiGeocoded.lng(), 'K') > 5) {

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

                    activaBotoMode('transport_a_peu');           
                    request.travelMode = google.maps.DirectionsTravelMode.WALKING;						                                  
                    
                }
                                
                waypts_info.length = 1;
	  
                waypts_info.push({
                    nom_lloc: '<p><strong>' + place.name + '</strong></p><p>' + place.formatted_address + '</p>'
                });
                
                deleteOverlays(markersArray);
                deleteOverlays(markersArrayParking);
                
                draw_directions(request);
                
                com_arribar_activat = true;
                
            });
    
        } else {
            
            alert('Geocoding error');
            
        }

    });		
				
}
		  
function draw_directions(request) {	
			  
    directionsService.route(request, function(response, status) {
					
        if (status == google.maps.DirectionsStatus.OK) {									
            directionsDisplay.setDirections(response);
            inspectMarkers();
        }
    });
				
}	

function draw_map_init() {
												
    myOptions = {        
        zoom: 18,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: origen,
        styles: styles,
        panControl: false,
        streetViewControl: false,
        mapTypeControl: false
    }			
												
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    map = new google.maps.Map(document.getElementById("map_canvas_arribar"), myOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("map_canvas_arribar_ruta"));
				
    createMarker(origen, 0, 16);
    
    $.mobile.changePage('#pagina_com_arribar');
    
    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'); 
        
        $.mobile.hidePageLoadingMsg();    
        
    });	
    			
}				
						
function inspectMarkers() {			
				
    createMarker(origen, 0, 16);
    createMarker(destiGeocoded, 1, 19);
    				
}
	
function createMarker(place, index, icon) {

    var image = icona_botiga[icon];
    var zindex = google.maps.Marker.MAX_ZINDEX;

    if (index == 0) {
        
        zindex = google.maps.Marker.MAX_ZINDEX + 1;
        
    } 

    var marker = new google.maps.Marker({
        map: map,
        position: place,
        icon: image,
        zIndex: zindex
    });
				
    var info = waypts_info[index].nom_lloc;
    markersArray.push(marker);
    
    //Afegim el listener per al popup
    
    google.maps.event.addListener(marker, 'click', function() {				  			  			  

        $('#arribar_mapa_popup_aqui_text').empty();
        $('#arribar_mapa_popup_aqui_text').append("<p>" + info + "</p>");        
        $('#arribar_mapa_popup_aqui').popup('open');

    });        
    
}
			  
function deleteOverlays(markers) {
    if (markers) {
        for (var i = 0; i < markers.length; i++) {
            markers[i].setMap(null);
        }
        markers.length = 0;
        bounds.length = 0;
        bounds = new google.maps.LatLngBounds();
    }
}

/* Mapa de parkings */

function veureParkings() {
    
    deleteOverlays(markersArrayParking);
    directionsDisplay.setDirections({
        routes: []
    });
    
    $.getJSON((base_url+'SCC/ca/web_mobil/obteParkings'),function(data) {
        
        posicio_llocs = data;
        
    })
    .complete(function() { 
        
        $.each(posicio_llocs, function(key, val) {            
            
            createMarkerParking(val);
            
        });
        
        map.fitBounds(bounds);

    });
			  
}

/* Mapa de punts d'interès */

function mapInfoInteres() {
    
    deleteOverlays(markersArrayParking);
    directionsDisplay.setDirections({
        routes: []
    });
    
    $.getJSON((base_url+'SCC/ca/web_mobil/getInfoInteresMap'),function(data) {
        
        posicio_llocs = data;
        
    })
    .complete(function() { 
        
        $.each(posicio_llocs, function(key, val) {            
            
            createMarkerInfo(val);
            
        });
        
        map.fitBounds(bounds);

    });
			  
}

//Com arribar a un POI en concret, seleccionat des de la pàgina d'informació d'interès

function arribarLlocInteres(id) {
    
    deleteOverlays(markersArrayParking);
    directionsDisplay.setDirections({
        routes: []
    });
    
    $.getJSON((base_url+'SCC/ca/web_mobil/getInfoInteresId/'+id),function(data) {
        
        posicio_llocs = data;
        
    })
    .complete(function() { 
        
        $.each(posicio_llocs, function(key, val) {            
            
            createMarkerInfo(val);
            arribarLloc(1);
                        
        });
        map.fitBounds(bounds);
        $.mobile.changePage('#pagina_com_arribar');
        
    });
    
    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'); 
        
        $.mobile.hidePageLoadingMsg();    
        
    });	
			  
}


function createMarkerParking(place) {
        
    var posicio_actual;
     
    var place_location = new google.maps.LatLng(place.parking_lat, place.parking_lang);
    
    var image = icona_botiga[18];
    
    if (place.parking_promocio == 1) {
        
        image = icona_botiga[25];
        
    }
        
    var marker = new google.maps.Marker({
        map: map,
        position: place_location,
        icon: image
    });
    
    bounds.extend(place_location);
    
    markersArrayParking.push(marker);
    
    posicio_actual = markersArrayParking.length;
    
    //Afegim el listener per al popup
    
    google.maps.event.addListener(marker, 'click', function() {				  			  			  

        $('#arribar_mapa_popup_text').empty();
        $('#arribar_mapa_popup_text').append("<p><strong>" + place.nom_parking + "</strong></p><p>" + place.direccio_parking + '</p><p><strong>' + place.parking_message + '</strong></p>');        
        $('#arribar_mapa_popup #boto_telefon').attr('href', "tel:"+place.parking_telefon);        
        $('#arribar_mapa_popup #boto_arribar').attr('href', "javascript:arribarLloc("+posicio_actual+")");
        $('#arribar_mapa_popup').popup('open');

    });
    
}

/* Creem els marcadors d'info */

function createMarkerInfo(place) {
    
    var posicio_actual;
     
    var place_location = new google.maps.LatLng(place.latitude, place.longitude);
    
    var marker = new google.maps.Marker({
        map: map,
        position: place_location,
        icon: icona_botiga[place.tipus_info_servei]
    });
    
    bounds.extend(place_location);
    
    markersArrayParking.push(marker);
    
    posicio_actual = markersArrayParking.length;
    
    //Afegim el listener per al popup
    
    google.maps.event.addListener(marker, 'click', function() {				  			  			  

        $('#arribar_mapa_popup_text').empty();
        $('#arribar_mapa_popup_text').append("<p><strong>" + place.nom_ca + "</strong></p><p>" + place.adreca + '</p>');        
        $('#arribar_mapa_popup #boto_telefon').attr('href', "tel:"+place.telefon);
        $('#arribar_mapa_popup #boto_arribar').attr('href', "javascript:arribarLloc("+posicio_actual+")");        
        $('#arribar_mapa_popup').popup('open');

    });
    
}

function arribarLloc(end) {	

    request = {
        origin: markersArray[0].getPosition(),
        destination: markersArrayParking[end-1].getPosition(),
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);
            $('#arribar_mapa_popup').popup('close');
        }
    });
}

//Opcions modes de transport

var mapa_actiu = "arribar";

function executaModeTransportArribar() {
    
    directionsService.route(request, function(result, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            directionsDisplay.setDirections(result);               
        }
    });
    
    $('#' + $.mobile.activePage.attr('id') + ' .popup_opcions_mapa').popup('close');
        
}

function aPeuArribar() {
    
    request.travelMode = google.maps.DirectionsTravelMode.WALKING;
    executaModeTransportArribar();
    activaBotoMode('transport_a_peu');        
    
}

function enCotxeArribar() {
    
    request.travelMode = google.maps.DirectionsTravelMode.DRIVING;
    executaModeTransportArribar();
    activaBotoMode('transport_en_cotxe');    
        
}

function enTPublicArribar() {
    
    request.travelMode = google.maps.DirectionsTravelMode.TRANSIT;
    executaModeTransportArribar();
    activaBotoMode('transport_public');        
        
}

function veureRutaArribar() {
    
    if ($('#map_canvas_arribar').css('display') == 'block') {
     
        $('#map_canvas_arribar').hide();
        $('#map_canvas_arribar_ruta').show();
             
    } else {
        
        $('#map_canvas_arribar').show();
        $('#map_canvas_arribar_ruta').hide();
        
        bounds.extend(origen);
        map.fitBounds(bounds);
                        
    }
    
    $('#' + $.mobile.activePage.attr('id') + ' .popup_opcions_mapa').popup('close');
}