     Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiJkNjcyOWZhYi0xZmQ0LTQyYmMtYjQ0MS1hY2YxYzcxYWFmMWEiLCJpZCI6MTEwNzEsImlhdCI6MTYzMDk5MzEyNX0.fcsH4S5hE0ye9s-2cOFMyObiHlhu9vqjWdlYfGkv5gU';



    //////////////////////////////////////////////////////////////////////////
    // Creating the Viewer
    //////////////////////////////////////////////////////////////////////////

     var viewer = new Cesium.Viewer('cesiumContainer', {
         scene3DOnly: true,
         selectionIndicator: false,
		 timeline: false,
		 animation: false,
		 shadow: false,
		 // // Set default basemap
           imageryProvider : new Cesium.ArcGisMapServerImageryProvider({
    url : 'https://services.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer',
	enablePickFeatures: false
    }),
		 baseLayerPicker: true
		 
     });
     viewer.clock.shouldAnimate = false;
	 viewer.scene.globe.enableLighting = false;
     viewer.clock.startTime = Cesium.JulianDate.fromIso8601("2019-09-20T16:00:00Z");
     viewer.clock.stopTime = Cesium.JulianDate.fromIso8601("2019-09-20T16:20:00Z");
     viewer.clock.currentTime = Cesium.JulianDate.fromIso8601("2019-09-20T16:00:00Z");
	 document.getElementById("heatdemandlegend").style.display = "none"; //defining legends hidden by default
	 document.getElementById("pvpotentialLegend").style.display = "none"; //defining legends hidden by default
	 
    //////////////////////////////////////////////////////////////////////////
    // Configuring the camera
    //////////////////////////////////////////////////////////////////////////
    // // Create an initial camera view
     var initialPosition = Cesium.Cartesian3.fromDegrees(9.116678, 48.822745, 2000);
     var initialOrientation = new Cesium.HeadingPitchRoll.fromDegrees(235, -23, 360);
     var homeCameraView = {
         destination : initialPosition,
         orientation : {
            heading : initialOrientation.heading,
            pitch : initialOrientation.pitch,
            roll : initialOrientation.roll
         }
      };
    // // Set the initial view
     viewer.scene.camera.setView(homeCameraView);
		// set home button to initial view 
	 
	 viewer.homeButton.viewModel.command.beforeExecute.addEventListener(function (e) {
        e.cancel = true;
         viewer.scene.camera.flyTo(homeCameraView);
     });
	 viewer.camera.changed.addEventListener(function() {

  var deg = Math.round( Cesium.Math.toDegrees(viewer.camera.heading))
  console.log('Heading:', deg)

  var deg = Math.round( Cesium.Math.toDegrees(viewer.camera.pitch))
  console.log('Pitch:', deg)
  
  var deg = Math.round( Cesium.Math.toDegrees(viewer.camera.roll))
  console.log('Roll:', deg)
});
    //////////////////////////////////////////////////////////////////////////
    // Load 3D Tileset
    //////////////////////////////////////////////////////////////////////////
    var gerlingenbldgsld = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url: './Source/Data/Bldg/tileset.json'}));
	var gerlingenroof = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({url: './Source/Data/Roof/tileset.json'}));
	gerlingenroof.readyPromise.then(function(tileset) {
                 height = 0.02;
                 viewer.scene.primitives.add(tileset);
                 var cartographic = Cesium.Cartographic.fromCartesian(tileset.boundingSphere.center);
                 var surface = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, 0.0);
                 var offset = Cesium.Cartesian3.fromRadians(cartographic.longitude, cartographic.latitude, height);
                 var translation = Cesium.Cartesian3.subtract(offset, surface, new Cesium.Cartesian3());
                 tileset.modelMatrix = Cesium.Matrix4.fromTranslation(translation);
					console.log(error);
             });
			gerlingenbldgsld.show=true;
			gerlingenroof.show =false;


    //////////////////////////////////////////////////////////////////////////
    // Style 3D Tileset
    //////////////////////////////////////////////////////////////////////////
	
	var defaultstyle = new Cesium.Cesium3DTileStyle({
         color : "color('WHITE')",
		  show: true
     });
	 
	 var pvpotentialstyle = new Cesium.Cesium3DTileStyle({
         color : {
            conditions : [
					["(${AvgPV} === 0)", "color('#FFFFFF')"],
					["(${AvgPV} > 0)  && (${AvgPV} < 5)", "color('#fc4f00')"],
					["(${AvgPV} >= 5)  && (${AvgPV} < 10)", "color('#f27600')"],
                    ["(${AvgPV} >= 10) && (${AvgPV} < 15)", "color('#e29700')"],
                    ["(${AvgPV} >= 15) && (${AvgPV} < 20)", "color('#cab500')"],
                    ["(${AvgPV} >= 20) && (${AvgPV} < 25)", "color('#aad000')"],
					["(${AvgPV} >= 25) && (${AvgPV} < 30)", "color('#7de800')"],
                    ["(${AvgPV} >= 30)", "color('#00ff00')"]
			 ]
         },
		 show: true
     });
	 
	 var colorstyle1 = document.getElementById('3dbuildings');	 
	 var colorstyle2 = document.getElementById('heatdemand');
	 var colorstyle3 = document.getElementById('pvpotential');
     function set3DColorStyle() {
        if (colorstyle1.checked) {
			gerlingenbldgsld.show=true;
			gerlingenroof.show =false;
			viewer.dataSources.removeAll();
             gerlingenbldgsld.style = defaultstyle;
			 document.getElementById("heatdemandlegend").style.display = "none";
			 document.getElementById("pvpotentialLegend").style.display = "none";
			  } 
		else if (colorstyle2.checked) {
			gerlingenbldgsld.show=true;
			gerlingenroof.show =false;
			var promise = Cesium.GeoJsonDataSource.load(
    './Source/Data/Gerlingen_Grid5050_heat.json'
  );
		promise
    .then(function (dataSource1) {
      viewer.dataSources.add(dataSource1);

      //Get the array of entities
      var entities = dataSource1.entities.values;

      var colorHash = {};
      for (var i = 0; i < entities.length; i++) {
        //For each entity, create a random color based on the state name.
        //Some states have multiple entities, so we store the color in a
        //hash so that we use the same color for the entire state.
        var entity = entities[i];
        var name = entity.name;
        var color = colorHash[name];
		var grdcode = entity.properties.Avg_Sp_Ht;
        if (!color) { if (grdcode == 0) {
                        color = Cesium.Color.fromCssColorString('#FFFFFF8C');
                        } 
						else if (grdcode < 25) {
                        color = Cesium.Color.fromCssColorString('#61B9498C');
                        }
						else if (grdcode < 50) {
                        color = Cesium.Color.fromCssColorString('#A4C7118C');
                        }
						else if (grdcode < 75) {
                        color = Cesium.Color.fromCssColorString('#B2D5318C');
                        }
						else if (grdcode < 100) {
                        color = Cesium.Color.fromCssColorString('#D1E0238C');
                        }else if (grdcode < 125) {
                        color = Cesium.Color.fromCssColorString('#F6EC008C');
                        }else if (grdcode < 150) {
                        color = Cesium.Color.fromCssColorString('#FECE028C');
                        }else if (grdcode < 200) {
                        color = Cesium.Color.fromCssColorString('#F9A7178C');
                        }else if (grdcode < 250) {
                        color = Cesium.Color.fromCssColorString('#F56D1F8C');
                        }
					
					else {
                        color = Cesium.Color.fromCssColorString('#F22E228C');
                        }
        }

        //Set the polygon material to our random color.
        entity.polygon.material = color;
        //Remove the outlines.
        entity.polygon.outline = true;

        //Extrude the polygon based on the state's population.  Each entity
        //stores the properties for the GeoJSON feature it was created from
        //Since the population is a huge number, we divide by 50.
        entity.polygon.extrudedHeight =
         grdcode ;
      }
    })
	 
    
			 document.getElementById("heatdemandlegend").style.display = "block";
			 document.getElementById("pvpotentialLegend").style.display = "none";
		}
		else if (colorstyle3.checked) {
			gerlingenbldgsld.show=true;
			gerlingenroof.show =true;
			viewer.dataSources.removeAll();
			gerlingenbldgsld.style = defaultstyle;
             gerlingenroof.style = pvpotentialstyle;
			 document.getElementById("heatdemandlegend").style.display = "none";
			 document.getElementById("pvpotentialLegend").style.display = "block";
		      }
        }
	 
	 colorstyle1.addEventListener('change', set3DColorStyle);
     colorstyle2.addEventListener('change', set3DColorStyle);
	 colorstyle3.addEventListener('change', set3DColorStyle);
	
