$(function () {
	Cesium.Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI5ODI4ZTYyZS1mMTg2LTQ5NGEtYjdiOS02ODg2NzVhNjc0MTAiLCJpZCI6MjkwNCwiaWF0IjoxNTM1MTA5OTAzfQ.kyDX_0ScvJBkYnvXI0DW5NfZbiaRL5ezwtAUhxYnk1Y';

	var imageryViewModels = [];
	imageryViewModels.push(new Cesium.ProviderViewModel({
		name: 'Sentinel-2',
		iconUrl: Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/sentinel-2.png'),
		tooltip: 'Sentinel-2 cloudless.',
		creationFunction: function () {
			return new Cesium.IonImageryProvider({ assetId: 3954 });
		}
	}));
	
	imageryViewModels.push(new Cesium.ProviderViewModel({
		name: 'Blue Marble',
		iconUrl: Cesium.buildModuleUrl('Widgets/Images/ImageryProviders/blueMarble.png'),
		tooltip: 'Blue Marble Next Generation July, 2004 imagery from NASA.',
		creationFunction: function () {
			return new Cesium.IonImageryProvider({ assetId: 3845	 });
		}
	}));

    var viewer = new Cesium.Viewer('cesiumContainer',
		{
			imageryProvider: new Cesium.IonImageryProvider({ assetId: 3954 }),
				
			terrainProvider : new Cesium.CesiumTerrainProvider({
					url: Cesium.IonResource.fromAssetId(1)
				}),
			scene3DOnly: false,
			shouldAnimate: true,
			animation: true,
			infoBox: true,
			baseLayerPicker: true,
			fullscreenButton: false,
			timeline: false,
			navigationHelpButton: false,
			navigationInstructionsInitiallyVisible: false,
			homeButton: false,
			selectionIndicator: true,
			geocoder: true,
			// imageryProviderViewModels: imageryViewModels
		});

		var imageryLayer = viewer.imageryLayers.addImageryProvider(
			new Cesium.IonImageryProvider({ assetId: 3954 })
		  );

		Cesium.ShadowMode.ENABLED
		
	// var layer = viewer.imageryLayers.addImageryProvider(
		// 	new Cesium.IonImageryProvider({ assetId: 3 })
		// );

		var imageryLayer = viewer.imageryLayers.addImageryProvider(
			new Cesium.IonImageryProvider({ assetId: 3954 })
		  );

	var tileset = viewer.scene.primitives.add(new Cesium.Cesium3DTileset({
		url: 'buildingTiles/Slod1/tileset.json',			
		show: true
	}));

	tileset.readyPromise.then(function (tileset){ 
		
		// set tileset height
       var height = 49;       
       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);

       return zoomAll(tileset);
	});
/*
	var terrainProvider = new Cesium.CesiumTerrainProvider({
        url: 'https://assets.agi.com/stk-terrain/v1/tilesets/world/tiles',
        requestWaterMask: true, // required for water effects
        requestVertexNormals: true // required for terrain lighting
    });
    viewer.terrainProvider = terrainProvider;
	*/
	viewer.scene.globe.enableLighting = true; // set lighting to true

	
	var zoomAll = function (tileset) {
		return new Promise(function (resolve, reject) {
			if (!tileset) { reject("Tileset is undifined"); }
			viewer.camera.viewBoundingSphere(tileset.boundingSphere, new Cesium.HeadingPitchRange(0, -0.5, 1500));
			viewer.camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
			resolve();
		});
	}

	// HTML overlay for showing feature name on mouseover
	var nameOverlay = document.createElement('div');
	viewer.container.appendChild(nameOverlay);
	nameOverlay.className = 'backdrop';
	nameOverlay.style.display = 'none';
	nameOverlay.style.position = 'absolute';
	nameOverlay.style.bottom = '0';
	nameOverlay.style.left = '0';
	nameOverlay.style['pointer-events'] = 'none';
	nameOverlay.style.padding = '4px';
	nameOverlay.style.backgroundColor = 'green';

	// Information about the currently selected feature
	var selected = {
		feature: undefined,
		originalColor: new Cesium.Color()
	};

	// Information about the currently highlighted feature
	var highlighted = {
		feature: undefined,
		originalColor: new Cesium.Color()
	};

	var selectedEntity = new Cesium.Entity();

	// Color a feature yellow on hover.
	viewer.screenSpaceEventHandler.setInputAction(function onMouseMove(movement) {
		// If a feature was previously highlighted, undo the highlight
		if (Cesium.defined(highlighted.feature)) {
			highlighted.feature.color = highlighted.originalColor;
			highlighted.feature = undefined;
		}

		// Pick a new feature
		var pickedFeature = viewer.scene.pick(movement.endPosition);
		if (!Cesium.defined(pickedFeature)) {
			nameOverlay.style.display = 'none';
			return;
		}

		// A feature was picked, so show it's overlay content
		nameOverlay.style.display = 'block';
		nameOverlay.style.bottom = viewer.canvas.clientHeight - movement.endPosition.y + 'px';
		nameOverlay.style.left = movement.endPosition.x + 'px';
		var name = pickedFeature.getProperty('name');
		if (!Cesium.defined(name)) {
			name = pickedFeature.getProperty('id');
		}
		nameOverlay.textContent = name;

		// Highlight the feature if it's not already selected.
		if (pickedFeature !== selected.feature) {
			highlighted.feature = pickedFeature;
			Cesium.Color.clone(pickedFeature.color, highlighted.originalColor);
			pickedFeature.color = Cesium.Color.AQUA;
		}
	}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);

	// Color a feature on selection and show metadata in the InfoBox.
var clickHandler = viewer.screenSpaceEventHandler.getInputAction(Cesium.ScreenSpaceEventType.LEFT_CLICK);
viewer.screenSpaceEventHandler.setInputAction(function onLeftClick(movement) {
    // If a feature was previously selected, undo the highlight
    if (Cesium.defined(selected.feature)) {
        selected.feature.color = selected.originalColor;
        selected.feature = undefined;
    }

    // Pick a new feature
    var pickedFeature = viewer.scene.pick(movement.position);
    if (!Cesium.defined(pickedFeature)) {
        clickHandler(movement);
        return;
    }

    // Select the feature if it's not already selected
    if (selected.feature === pickedFeature) {
        return;
    }
    selected.feature = pickedFeature;

    // Save the selected feature's original color
    if (pickedFeature === highlighted.feature) {
        Cesium.Color.clone(highlighted.originalColor, selected.originalColor);
        highlighted.feature = undefined;
    } else {
        Cesium.Color.clone(pickedFeature.color, selected.originalColor);
    }

    // Highlight newly selected feature
    pickedFeature.color = Cesium.Color.AQUA;

    // Set feature infobox description
    var featureName = pickedFeature.getProperty('name');
    selectedEntity.name = featureName;
    selectedEntity.description = 'Loading <div class="cesium-infoBox-loading"></div>';
    viewer.selectedEntity = selectedEntity;
    selectedEntity.description = '<table class="cesium-infoBox-defaultTable"><tbody>' +                                 
                                 '<tr><th>Bld function</th><td>' + pickedFeature.getProperty('Function') + '</td></tr>' +
								 '<tr><th>gmlID</th><td>' + pickedFeature.getProperty('gmlIDStr') + '</td></tr>' +
								 '<tr><th>gmlParentID</th><td>' + pickedFeature.getProperty('gmlParentIDStr') + '</td></tr>' +
								 '<tr><th>Dachgeschossausbau</th><td>' + pickedFeature.getProperty('dachgeschossausbau') + '</td></tr>' +
                                 '<tr><th>Lon</th><td>' + pickedFeature.getProperty('Longitude') + '</td></tr>' +
								 '<tr><th>Lat</th><td>' + pickedFeature.getProperty('Latitude') + '</td></tr>' +
								 '<tr><th>Geschossflaeche (sqm)</th><td>' + pickedFeature.getProperty('geschossflaeche') + '</td></tr>' +								 
								 '<tr><th>YearOfConstruction</th><td>' + pickedFeature.getProperty('YearOfConstruction') + '</td></tr>' +
								 '<tr><th>MeasuredHeight (m):</th><td>' + pickedFeature.getProperty('MeasuredHeight') + '</td></tr>' +
								 '<tr><th>HoeheFirst (m)</th><td>' + pickedFeature.getProperty('hoeheFirst') + '</td></tr>' +
								 '<tr><th>HoeheTrauf (m)</th><td>' + pickedFeature.getProperty('hoeheTrauf') + '</td></tr>' +
								 '<tr><th>Grundflaeche (sqm)</th><td>' + pickedFeature.getProperty('grundflaeche') + '</td></tr>' +
								 '<tr><th>StoreysAboveGround: </th><td>' + pickedFeature.getProperty('StoreysAboveGround') + '</td></tr>' +
								 '<tr><th>StoreysBelowGround: </th><td>' + pickedFeature.getProperty('StoreysBelowGround') + '</td></tr>' +
								 '<tr><th>Durchfahrtsstr.: </th><td>' + pickedFeature.getProperty('ThoroughfareName') + '</td></tr>' +
								 '<tr><th>Hausnummer.: </th><td>' + pickedFeature.getProperty('ThoroughfareNumber') + '</td></tr>' +
                                 '</tbody></table>';
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);

	var scene = viewer.scene;
	var longitude;
	var latitude;
	var fid;
	var featuretype;
	var gmlid;
	var selID = new Array();
	var cnt = 0;
	var lastPickedObject;

	var viewModel = {
		rightClickAction: 'properties',
		middleClickAction: 'hide'
	};

	Cesium.knockout.track(viewModel);

	var handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);

	
	handler.setInputAction(function (movement) {
			// makes camera go to a certain position given by the coordinates below
		
		var feature = viewer.scene.pick(movement.position);
			if (!Cesium.defined(feature)) {
				console.log("no feature defined")
				return;
			}	
		var propertyNames = feature.getPropertyNames();
		var lat = feature.getProperty("Latitude");
		var lon = feature.getProperty("Longitude");
		var tmp = feature.getProperty("YearOfConstruction");

		viewer.camera.flyTo({
			destination: Cesium.Cartesian3.fromDegrees(lon, lat, 900),
			maximumHeight: 1500.0,
			orientation: {
				heading: Cesium.Math.toRadians(0.0),
				pitch: Cesium.Math.toRadians(-90.0),
				roll: Cesium.Math.toRadians(45.0)
			},
			duration: 2
		});		}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
		


		handler.setInputAction(function (movement) {
			var feature = viewer.scene.pick(movement.position);
			if (!Cesium.defined(feature)) {
				return;
			}
			var action = viewModel.rightClickAction;
			action === 'properties'
			printProperties(movement, feature)
		}, Cesium.ScreenSpaceEventType.RIGHT_CLICK);


		function printProperties(movement, feature) {
			console.log('Properties:');
			var propertyNames = feature.getPropertyNames();
			var length = propertyNames.length;
			for (var i = 0; i < length; ++i) {
				var propertyName = propertyNames[i];
				if (propertyName == 'gmlIdALKISLageBezeichnung_1' ||
					propertyName == 'gmlIdALKISLageBezeichnung_2' ||
					propertyName == 'gmlIdALKISLageBezeichnung_3' ||
					propertyName == 'gmlIdALKISLageBezeichnung_4' ||
					propertyName == 'gmlIdALKISLageBezeichnung_5' ||
					propertyName == 'gmlIdALKISLageBezeichnung_6')
					console.log('  ' + propertyName + ': ' + 'zensiert');
				else
					console.log('  ' + propertyName + ': ' + feature.getProperty(propertyName));
			}

			// Evaluate feature description
			//console.log('Description : ' + tileset.style.meta.description.evaluate(scene.frameState, feature));
		}

		handler.setInputAction(function (movement) {
			var feature = viewer.scene.pick(movement.position);
			if (!Cesium.defined(feature)) {
				return;
			}

			var action = viewModel.middleClickAction;
			if (action === 'hide') {
				feature.show = false;
			}
		}, Cesium.ScreenSpaceEventType.MIDDLE_CLICK);
		

function showLegend() {
    $("#legend").css("display", "block");
}
function hideLegend() {
    $("#legend").css("display", "none");
}

// Legend - Colour Table
function emptyColourTable() {
    $(".inner").empty();
}

function setHeightTable() {
    $(".inner").append( "<table>" +
        "<tr><td class='outlined' bgcolor='red'>&nbsp;&nbsp;&nbsp;&nbsp;</td><td> >= 2015 </td></tr>" +
		"<tr><td class='outlined' bgcolor='#c85d00'></td><td> 2006 - 2014 </td></tr>" +
        "<tr><td class='outlined' bgcolor='#ffb400'></td><td> 1996 - 2005 </td></tr>" +
		"<tr><td class='outlined' bgcolor='yellow'></td><td> 1981 - 1995</td></tr>" +
        "<tr><td class='outlined' bgcolor='#00ff00'></td><td> 1966 - 1980 </td></tr>" +
        "<tr><td class='outlined' bgcolor='blue'></td><td> 1946 - 1965</td></tr>" +
        "<tr><td class='outlined' bgcolor='#4b0082'></td><td> 1918 - 1945</td></tr>" +
       	"<tr><td class='outlined' bgcolor='#f864dd'></td><td> 1800 - 1900 </td></tr>" +
        "<tr><td class='outlined' bgcolor='lightblue'></td><td> no YoC </td></tr>" +
    "</table>" );
}
	
	return Cesium.when(tileset.readyPromise).then(function (tileset) {
		tileset.style = new Cesium.Cesium3DTileStyle({

			color: {

				conditions: [
				
					

					['Number(${YearOfConstruction}) >= 2015', 'rgb(255,0,0)'],

					['Number(${YearOfConstruction}) >= 2005', 'rgb(200, 93 , 0)'],

					['Number(${YearOfConstruction}) >= 1995', 'rgb(255, 180, 0)'],

					['Number(${YearOfConstruction}) >= 1980', 'rgb(255,255,0)'],

					['Number(${YearOfConstruction}) >= 1965', 'rgb(0,255,0)'],

					['Number(${YearOfConstruction}) >= 1945', 'rgb(0,0,255)'],

					['Number(${YearOfConstruction}) >= 1918', 'rgb(75, 0, 130)'],

					['Number(${YearOfConstruction}) >= 1900', 'rgb(150, 248, 238)'],	
					
					['Number(${YearOfConstruction}) >= 1800', 'rgb(248, 100, 221)'],	
					
					['true', 'rgba(80,80,80,1)']

				]

			}			

		});
		showLegend();
		setHeightTable();
	});	

	/*
	return Cesium.when(tileset.readyPromise).then(function (tileset) {
		tileset.style = new Cesium.Cesium3DTileStyle({

			color: {

				conditions: [
				
					

					['Number(${MeasuredHeight}) >= 40', 'rgb(255,0,0)'],

					['Number(${MeasuredHeight}) >= 30.', 'rgb(255, 93 , 0)'],

					['Number(${MeasuredHeight}) >= 25', 'rgb(255, 180, 0)'],

					['Number(${MeasuredHeight}) >= 20', 'rgb(255,255,0)'],

					['Number(${MeasuredHeight}) >= 15', 'rgb(0,255,0)'],

					['Number(${MeasuredHeight}) >= 10', 'rgb(0,0,255)'],

					['Number(${MeasuredHeight}) >= 7.5', 'rgb(75, 0, 130)'],

					['Number(${MeasuredHeight}) >= 4', 'rgb(248, 100, 221)'],	
					
					['Number(${MeasuredHeight}) >= 0.1', 'rgb(248, 100, 221)'],	
					
					['true', 'color("lightblue")']

				]

			}

		});
	});	*/

});