(function($, Drupal) {
  Drupal.behaviors.qd30mini = {
    attach: function(context, settings) {


        Cesium.BingMapsApi.defaultKey = 'mqrOOSbN2SMpDuWhHx0W~HVi_IW2A0UwRAV1xLIZuTQ~AnSezO-xLZ4_s1rf8ydB6Wf0aRdKtw_znPffJQ9qKbntyOPWFvitPVAvxT0v6dib';

        var viewer = new Cesium.Viewer('boutique-map-cesium', {
            animation: false,
            homeButton: false,
            vrButton: false,
            infoBox: false,
            geocoder: false,
            sceneModePicker: false,
            selectionIndicator: true,
            timeline: false,
            navigationHelpButton: false,
            navigationInstructionsInitiallyVisible: false,
            scene3DOnly: false,
            shadows: true,
            terrainShadows: true,
            // imageryProvider : new Cesium.createOpenStreetMapImageryProvider({
            // url : 'https://stamen-tiles.a.ssl.fastly.net/toner-background/'
            // url : 'http://tile.stamen.com/toner/',
            // alpha : 0.5
            // brightness : 1.0,
            // contrast : 1.0,
            // hue : 3.0,
            // saturation : 3.0,
            //     url : 'http://tile.stamen.com/watercolor/',
            // 'https://b.tile.openstreetmap.org'
            // }),
            baseLayerPicker: false
        });

        var camera = viewer.camera;
        var scene = viewer.scene;
        var ellipsoid = scene.globe.ellipsoid;
        var canvas = viewer.canvas;
        var layers = viewer.scene.imageryLayers;
        var globe = viewer.scene.globe;

        globe.imageryLayers.removeAll();
        globe.baseColor = Cesium.Color.fromCssColorString('#f3f3f3');

        var tonerLayer = layers.addImageryProvider(Cesium.createOpenStreetMapImageryProvider({
            url : 'http://tile.stamen.com/toner/'
        }));
        tonerLayer.alpha = 0.2;

        var terrainProvider = new Cesium.CesiumTerrainProvider({
            url : '//assets.agi.com/stk-terrain/world',
            requestVertexNormals: true
        });


        var dataSource = Cesium.GeoJsonDataSource.load('/sites/quartierdix30/files/geojson/quartier_en.json').then(function(data)  {
            viewer.dataSources.add(data);
            var entities = data.entities.values;
            var billboards = new Cesium.BillboardCollection();
            for (var i = 0; i < entities.length; i++) {
                var entity = entities[i];
                entity.polygon.outline = true;
                entity.polygon.outlineWidth = 1.2;
                entity.polygon.outlineColor = Cesium.Color.BLACK;

                if (entity.properties.hasOwnProperty('level')) {
                    entity.polygon.extrudedHeight = 0.5 * (entity.properties.level * 10);
                }

                if (entity.properties.hasOwnProperty("colour")) {
                    if (entity.properties.hasOwnProperty("event")) {
                        entity.polygon.material = new Cesium.StripeMaterialProperty({
                            evenColor : Cesium.Color.fromCssColorString(entity.properties.colour),
                            oddColor : Cesium.Color.BLACK,
                            repeat : 10
                        });
                    } else {
                        entity.polygon.material = Cesium.Color.fromCssColorString(entity.properties.colour);
                    }
                }

                if (entity.properties.hasOwnProperty("description")) {
                    entity.description = '<div>' + entity.properties.description
                        + '</div>';
                }
            }
        });

        function gotoQD30() {
            var pos = Cesium.Ellipsoid.WGS84.cartesianToCartographic(new Cesium.Cartesian3(
                1278149.1996018, -4297423.8092246,
                4522591.15943));
            pos.latitude = Cesium.Math.toDegrees(pos.latitude);
            pos.longitude = Cesium.Math.toDegrees(pos.longitude);

            viewer.camera.flyTo({
                destination : Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, pos.height),
                orientation : {
                    heading : 5.51747,
                    pitch : -1.419427,
                    roll : 6.2675
                },
                duration: 0.5
            });
        }

        function colourReset() {
            for (var j = 0; j < viewer.dataSources.get(0).entities.values.length; j++) {
                var entity = viewer.dataSources.get(0).entities.values[j];
                if (entity.properties.hasOwnProperty('colour')) {
                    entity.polygon.material = new Cesium.Color.fromCssColorString(entity.properties.colour);
                }
            }
        }

        function selectStore(entity, data) {
            var pCoords = entity.polygon.hierarchy.getValue(viewer.clock.currentTime);
            var avgPoint = pCoords.positions.length > 1 ? Math.round(pCoords.positions.length / 2) : 0;
            var topPoint = 0;

            for (var xy = 0; xy < pCoords.positions.length - 1; xy++) {
                if (pCoords.positions[xy+1].x > pCoords.positions[xy].x) {
                    topPoint = xy;
                }
            }

            var pos = Cesium.Ellipsoid.WGS84.cartesianToCartographic(pCoords.positions[avgPoint]);
            pos.latitude = Cesium.Math.toDegrees(pos.latitude);
            pos.longitude = Cesium.Math.toDegrees(pos.longitude);

            viewer.camera.flyTo({
                destination : Cesium.Cartesian3.fromDegrees(pos.longitude +0.0008, pos.latitude -0.0012, 300),
                // destination : Cesium.Cartesian3.fromDegrees(pos.longitude, pos.latitude, 300),
                orientation : {
                    heading : 5.982409,
                    pitch : -1.075697,
                    roll : 6.281078
                },
                duration: 1
            });

            for (var j = 0; j < data.entities.values.length; j++) {
                if (entity.id == data.entities.values[j].id) {
                    for (z = 0; z < viewer.entities.values.length; z++) {
                        if (viewer.entities.values[z].name == 'selectionOutline') {
                            viewer.entities.remove(viewer.entities.values[z]);
                        }
                    }
                    viewer.entities.add({
                        name : 'selectionOutline',
                        polyline : {
                            positions : pCoords.positions,
                            width : 20,

                            material : new Cesium.PolylineGlowMaterialProperty({
                                glowPower : 0.9,
                                color : Cesium.Color.fromCssColorString('#008B8B'),
                                extrudedHeight : entity.polygon.extrudedHeight + 20
                            })
                        }
                    });
                }
            }
            colourReset();
            entity.polygon.material = Cesium.Color.fromCssColorString('#000000');
            viewer.selectedEntity = entity;
        }

        function gotoBoutique(title, data) {
            var choice = title.trim();
            var found = false;
            if (choice == 'Quartier Dix 30') {
                gotoQD30();
            } else {
                var length = data.entities.values.length;
                for (var i = 0; i < length; i++) {
                    var entity = data.entities.values[i];
                    if (entity.properties.name != undefined) {
                        if (entity.properties.name.toLowerCase() == choice.toLowerCase()) {
                            found = true;
                            if (entity.polygon.hierarchy._value.positions.length > 1) {
                                selectStore(entity, data);
                            } else {
                                gotoQD30();
                            }
                        }
                    }
                }
            }
            if (!found) gotoQD30();
        }

        window.onload = function() {

            var data = viewer.dataSources.get(0);

            gotoBoutique(settings.boutique_title, data);

            // var frame = viewer.infoBox.frame;
            // var cssLink = frame.contentDocument.createElement('link');
            // cssLink.href = Cesium.buildModuleUrl('../../../../css/qd30minimap.css');
            // cssLink.rel = 'stylesheet';
            // cssLink.type = 'text/css';
            // frame.contentDocument.head.appendChild(cssLink);

            clickHandler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
            clickHandler.setInputAction(function(movement) {
                var pickedObject = scene.pick(movement.position);
                if (Cesium.defined(pickedObject)) {
                    for (var i = 0; i < data.entities.values.length; i++)  {
                        var entity = data.entities.values[i];
                        if (entity.properties.name != undefined) {
                            if (entity.properties.name.toLowerCase().trim() == pickedObject.id.properties.name.toLowerCase().trim()) {
                                gotoBoutique(pickedObject.id.properties.name, data);

                            }
                        }
                    }
                }
            }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
        }

    }}})(jQuery, Drupal);