//Définition des variables globales
var map;
var bulle;


window.onload = function(){
    
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(success);
    } else {
      error('Geo Location is not supported');
    }

    function success(position){
        var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
        
        var options = {
            center: coords,
            zoom: 15,
            mapTypeId: google.maps.MapTypeId.HYBRID,
        };

        // Instanciation de la carte google
        var map = new google.maps.Map(document.getElementById("mapSection"), options); 
        // Options d'affichage de la carte
        var GeoMarker = new GeolocationMarker(map);
        GeoMarker.setCircleOptions({fillColor: '#808080'});
        google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
            map.setCenter(this.getPosition());
            map.fitBounds(this.getBounds());
        });
        google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
            alert('There was an error obtaining your position. Message: ' + e.message);
        });

        jQuery(function() {
        var waypoints = [
            {"Geometry":{"Latitude":49.188779,"Longitude":-0.363831}},
            {"Geometry":{"Latitude":49.188113,"Longitude":-0.362346}},
            {"Geometry":{"Latitude":49.188022,"Longitude":-0.359942}},
            {"Geometry":{"Latitude":49.186143,"Longitude":-0.360012}},
            {"Geometry":{"Latitude":49.185304,"Longitude":-0.360049}},
            {"Geometry":{"Latitude":49.184103,"Longitude":-0.359476}},
            {"Geometry":{"Latitude":49.183366,"Longitude":-0.360820}},
            {"Geometry":{"Latitude":49.185112,"Longitude":-0.363832}},
            {"Geometry":{"Latitude":49.186483,"Longitude":-0.366125}},
            {"Geometry":{"Latitude":49.187937,"Longitude":-0.366348}},
            {"Geometry":{"Latitude":49.188779,"Longitude":-0.363831}}
        ];

        var waypointsDeauville = [
        //CID -> Planches -> Bains pompéiens -> villa les Abeilles -> Place Morny -> Gare -> Hippodrome -> Normandy -> Casino -> Villa le Cercle
            {"Geometry":{"Latitude":49.359727,"Longitude":0.067075}}, // 1 CID de Deauville
            {"Geometry":{"Latitude":49.3614668,"Longitude":0.0655532}}, // 3 Les planches
            {"Geometry":{"Latitude":49.358346,"Longitude":0.062491}}, // 2 Les bains
            {"Geometry":{"Latitude":49.3617951,"Longitude":0.0729261}}, // 4 Villa les abeilles
            {"Geometry":{"Latitude":49.3596202,"Longitude":0.0753127}}, //Place Morny
            {"Geometry":{"Latitude":49.3600366,"Longitude":0.0820439}},//Gare
            {"Geometry":{"Latitude":49.3533769,"Longitude":0.0769361}},//Hippodrome
            {"Geometry":{"Latitude":49.359951,"Longitude":0.0692634}},//Normandy
            {"Geometry":{"Latitude":49.3590715,"Longitude":0.0679263}}, // 5 Casino
            {"Geometry":{"Latitude":49.358482,"Longitude":0.0679821}} // 6 Villa le cercle
        ];

        var routes = [waypointsDeauville];

        //Initialisation des variables de google
        //Un google.maps.DirectionsRenderer par parcours
        var directionsDisplay1 = new window.google.maps.DirectionsRenderer({suppressMarkers: true});
        var directionsDisplay2 = new window.google.maps.DirectionsRenderer({suppressMarkers: true});
        var directionsService = new window.google.maps.DirectionsService();

        //Tableau de Display pour chaque parcours
        var tabDisplay = [directionsDisplay1, directionsDisplay2];


        //Lancer l'affichage pour tout les parcours
        for(var i = 0; i < routes.length; i++){
            
            loadMap(map, tabDisplay[i]);
            fitBounds(map, routes[i]);

            if (routes[i].length > 1){
                calcRoute(directionsService, tabDisplay[i], routes[i]);
                //map.setCenter(new google.maps.LatLng(49.359727, 0.067075));
            }
        }
        
        });//jQuery(function() 

        var titres = [
            "CID de Deauville",
            "Les planches",
            "Les bains pompéiens",
            "Villa les abeilles",
            "Place Morny",
            "Gare",
            "Hippodrome de la Touques",
            "Hôtel Barrière Le Normandy",
            "Casion Barrière",
            "Villa le Cercle"
        ];

        var descriptions = [
            "<p>Notre point de départ d'une journée typiquement deauvillaise des années 1920</p>", //CID de Deauville
            "<p>Promenade de Deauville par excellence</p>", //Planches
            "<p>Les thermes du Pompéi normands</p>", //Bains
            "<p>Un des nombreux lieux de villégiature de l'espace deauvillais</p>", //Villa les abeilles
            "<p>Symbole du Deauville créé de toutes pièces</p>",//Place Morny
            "<p>Point phare de la liaison avec la capitale</p>",//Gare
            "<p>Lieu de hobbies</p>",//Hippodrome
            "<p>Précurseur des palaces deauvillais</p>",//Normandy
            "<p>Etablissement glamour des jeux de hasard</p>",//Casion
            "<p>Point de rassemblement des passionnés de sport</p>"//Villa le cercle
        ];

        //instancier la map
        function loadMap(map, directionsDisplay){
            var myOptions = {
                zoom: 13,
                mapTypeId: window.google.maps.MapTypeId.HYBRID,
                center: {lat: 49.359727, lng: 0.067075},
                //styles : retirer les labels de Google
                styles:[{"featureType":"poi","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"poi","elementType":"labels.text.stroke","stylers":[{"visibility":"off"}]}]
            };
            map.setOptions(myOptions);
            //map.setCenter(new google.maps.LatLng(49.359727, 0.067075));
            directionsDisplay.setMap(map);
        }//loadMap

        //Creer le tableau de waypoints
        function fitBounds(map, stops) {
            var bounds = new window.google.maps.LatLngBounds();

            jQuery.each(stops, function (key, val) {
                var myLatlng = new window.google.maps.LatLng(val.Geometry.Latitude, val.Geometry.Longitude);
                bounds.extend(myLatlng);
            });
            map.fitBounds(bounds);
        }//fitBounds


        //Afficher la route sur la map
        function calcRoute(directionsService, directionsDisplay, stops) {
            var batches = [];
            var itemsPerBatch = 10;
            var itemsCounter = 0;
            var wayptsExist = stops.length > 0;

            //Tant qu'il y a encore des waypoints dans le tableau
            while (wayptsExist) {
                var subBatch = [];
                var subitemsCounter = 0;

                for (var j = itemsCounter; j < stops.length; j++) {
                    subitemsCounter++;
                    subBatch.push({
                        location: new window.google.maps.LatLng(stops[j].Geometry.Latitude, stops[j].Geometry.Longitude),
                        stopover: true
                    });
                    if (subitemsCounter == itemsPerBatch){
                        break;
                    }
                }

                itemsCounter += subitemsCounter;
                batches.push(subBatch);
                wayptsExist = itemsCounter < stops.length;
                itemsCounter--;
            }

            var combinedResults;
            var unsortedResults = [{}];
            var directionsResultsReturned = 0;

            for (var k = 0; k < batches.length; k++) {
                var lastIndex = batches[k].length - 1;
                var start = batches[k][0].location;
                var end = batches[k][lastIndex].location;
                
                var waypts = [];
                waypts = batches[k];
                waypts.splice(0, 1);
                waypts.splice(waypts.length - 1, 1);

                var request = {
                    origin: start,
                    destination: end,
                    waypoints: waypts,
                    travelMode: window.google.maps.TravelMode.WALKING
                };

                (function (kk) {
                    directionsService.route(request, function (result, status) {
                        if (status == window.google.maps.DirectionsStatus.OK) {
                            var unsortedResult = { order: kk, result: result };
                            unsortedResults.push(unsortedResult);

                            directionsResultsReturned++;

                            if (directionsResultsReturned == batches.length){
                                unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
                                var count = 0;
                                for (var key in unsortedResults) {
                                    if (unsortedResults[key].result != null) {
                                        if (unsortedResults.hasOwnProperty(key)) {
                                            if (count == 0)
                                                combinedResults = unsortedResults[key].result;
                                            else {
                                                combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
                                                combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);

                                                combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
                                                combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
                                            }
                                            count++;
                                        }
                                    }
                                }

                                directionsDisplay.setDirections(combinedResults);
                                //Creer les markers et rajouter les informations dans les infobulles
                                var legs = combinedResults.routes[0].legs;
                                for (var i=0; i < legs.length;i++){
                                  //Si c'est un point visible : on fait ca
                                  var markerletter = "A".charCodeAt(0);
                                  markerletter += i;
                                  markerletter = String.fromCharCode(markerletter);
                                  createMarker(directionsDisplay.getMap(),legs[i].start_location,titres[i],descriptions[i],markerletter);
                                  //Sinon on passe
                                }
                                //On teste a nouveau si c'est un point visible
                                var i=legs.length;
                                var markerletter = "A".charCodeAt(0);
                                markerletter += i;
                                markerletter = String.fromCharCode(markerletter);
                                createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,titres[i],descriptions[i],markerletter);
                            }
                        }
                    });
                })(k);//function(kk)
            }//for de calcRoute
        }//calcRoute

        function updateStops(newStops) {
            stops = newStops;
        }//updateStops

        //Charger un contenu XML
        function loadXML(url) {
            var xmlhttp = new XMLHttpRequest();
            xmlhttp.open("GET", url, false);
            xmlhttp.send();
            var doc = xmlhttp.responseXML;
            removeBlankNodes(doc.documentElement);
            return doc;
        }//loadXML

        //Supprime les "blank nodes" d'un document
        function removeBlankNodes(node) {
            for (var n = 0; n < node.childNodes.length; n++) {
                var child = node.childNodes[n];
                if (child.nodeType === 8 ||
                (child.nodeType === 3 && !/\S/.test(child.nodeValue))
                ) {
                    node.removeChild(child);
                    n--;
                } else if(child.nodeType === 1) {
                    removeBlankNodes(child);
                }
            }
        }//removeBlankNodes

        var infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50)});

        var icons = new Array();
        icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
              // This marker is 20 pixels wide by 34 pixels tall.
              new google.maps.Size(20, 34),
              // The origin for this image is 0,0.
              new google.maps.Point(0,0),
              // The anchor for this image is at 9,34.
              new google.maps.Point(9, 34));

        function getMarkerImage(iconStr) {
           if ((typeof(iconStr)=="undefined") || (iconStr==null)) { 
              iconStr = "red"; 
           }

           if (!icons[iconStr]) {
              icons[iconStr] = new google.maps.MarkerImage("http://www.google.com/mapfiles/marker"+ iconStr +".png",
              // This marker is 20 pixels wide by 34 pixels tall.
              new google.maps.Size(20, 34),
              // The origin for this image is 0,0.
              new google.maps.Point(0,0),
              // The anchor for this image is at 9,34.
              new google.maps.Point(9, 34));
           } 

           return icons[iconStr];
        }


        function createMarker(map, latlng, label, html, color) {
            //console.log("createMarker("+latlng+","+label+","+html+","+color+")");
            var contentString = '<b>'+label+'</b><br>'+html;

            var marker = new google.maps.Marker({
                position: latlng,
                map: map,
                icon: getMarkerImage(color),
                title: label,
                zIndex: Math.round(latlng.lat()*-100000)<<5
            });

            marker.myname = label;

            google.maps.event.addListener(marker, 'click', function() {
                infowindow.setContent(contentString); 
                infowindow.open(map,marker);
            });

            return marker;
        }




    }//sucess
}//window.onload