﻿// JScript File
function DataQuery(map, sensorTypeSelector) {
	var view = map.GetMapView();
	this.locationCSV = view.TopLeftLatLong.Latitude + ','
                + view.TopLeftLatLong.Longitude + ';'
                + view.TopLeftLatLong.Latitude + ','
                + view.BottomRightLatLong.Longitude + ';'
                + view.BottomRightLatLong.Latitude + ','
                + view.BottomRightLatLong.Longitude + ';' 
                + view.BottomRightLatLong.Latitude + ','
                + view.TopLeftLatLong.Longitude;
    this.zoomLevel = map.GetZoomLevel();
    var i = sensorTypeSelector.selectedIndex;
    this.sensorType = sensorTypeSelector.options[i].value;
    this.sensorTypeName = sensorTypeSelector.options[i].text;
}

function Tiles() {
}

Tiles.prototype.getLatest = function(query) {
	
}

Tiles.prototype.getLatestCustomed = function(query, contourMapSettings) {
}

var graphAndTileHandler = {
	lastTileLayer: null
	, lastTimeSetting: null
	, lastQuery: null
	, tileLayerHidden: false
	, map: null
	, imageLayer: null
	, lastImage: null
	, init: function(map) {
		graphAndTileHandler.map = map;
        graphAndTileHandler.imageLayer = ImageLayer(graphAndTileHandler.map);
    }
    , showGraphPanel: function(tilesGraph) {
		// show thumbnail and legend
		var x = new Array();
		x.push('<div class="panel_subtitle" onclick="javascript:graphTx.toggleContourMapPanel();graphAndTileHandler.toggleTileLayer();">');
		x.push('Contour Map ');
		x.push('<span style="vertical-align:middle;"><img id="contourMapPanelImg" src="image/collapse.jpg" /></span>');
		x.push('</div>');
		x.push('<div id="contourMapPanel">');
		x.push('<span onclick="javascript:document.get">');
		x.push(graphAndTileHandler.lastQuery.sensorTypeName);
		if (graphAndTileHandler.lastTimeSetting != null) {
  		    x.push('<br />');
		    x.push(dateToMyString(graphAndTileHandler.lastTimeSetting.currentTime));
		    x.push(' ~ <br />')
		    x.push(dateToMyString(new Date(graphAndTileHandler.lastTimeSetting.currentTime.getTime()
		        + graphAndTileHandler.lastTimeSetting.resolution * 1000)));
		} else {
		    x.push(' (latest)');
  		    x.push('<br />');		    
		}
		x.push('</span>');
		x.push('<img src="');
		// if graph
		if (tilesGraph.TopLeftLatLon) {
		    var width = 200;
		    var height = tilesGraph.Height * 200 / tilesGraph.Width;
		    if (height > 200) {
		        height = 200;
		        width = tilesGraph.Width * 200 / tilesGraph.Height;
		    }
		    x.push(tilesGraph.GraphURL);
		    x.push('" width=' + width + ' height=');
		    x.push(height);
		// if tile
		} else {
		    x.push(tilesGraph.GraphThumbnailURL);
		    x.push('"');
		}
		x.push(' /><br />');
	    x.push(tilesGraph.GraphLegendHtml);
	    x.push('</div>');
		var el = document.getElementById('graphtx_graph');
		el.innerHTML = x.join('');
		el.style.display = 'block';
        el = null;
    }
    
    , showTiles: function(tilesGraph) {
		// show graph on map
		if (tilesGraph.TopLeftLatLon) {
            var graphSource = window.location.href.substring(0, window.location.href.lastIndexOf('/')) + '/' + tilesGraph.GraphURL;
            if (graphAndTileHandler.lastImage) {
                graphAndTileHandler.imageLayer.deleteImage(graphAndTileHandler.lastImage);
                //graphAndTileHandler.imageLayer.deleteImages();
                graphAndTileHandler.lastImage = null;
            }
            graphAndTileHandler.lastImage = graphAndTileHandler.imageLayer.addImage(
                new Image(graphSource, tilesGraph.Width, tilesGraph.Height
                , new VELatLong(tilesGraph.TopLeftLatLon.Lat, tilesGraph.TopLeftLatLon.Lon, 0, VEAltitudeMode.Default)
                , new VELatLong(tilesGraph.BottomRightLatLon.Lat, tilesGraph.BottomRightLatLon.Lon, 0, VEAltitudeMode.Default)
                ));
            graphAndTileHandler.imageLayer.reload();
		// show tiles on map
		} else {
            var tileSource = window.location.href.substring(0, window.location.href.lastIndexOf('/')) + '/' + tilesGraph.URL;
            var tileSourceSpec = new VETileSourceSpecification(tileSource, tileSource);
            //tileSourceSpec.MaxZoom = 18;
            //tileSourceSpec.MinZoom = 1;
            tileSourceSpec.ID = tileSource;
            tileSourceSpec.TileSource = tileSource;
            tileSourceSpec.Opacity = 0.7;
            tileSourceSpec.ZIndex = 101;

            // delete graph on map
            if (graphAndTileHandler.lastTileLayer) {
                graphAndTileHandler.map.DeleteTileLayer(graphAndTileHandler.lastTileLayer);
                graphAndTileHandler.lastTileLayer = null;
            }
            graphAndTileHandler.map.AddTileLayer(tileSourceSpec, true);
            graphAndTileHandler.lastTileLayer = tileSource;

            graphAndTileHandler.tileLayerHidden = true;
        }
    }    

	, tilesGraphGetLatestDone: function(tilesGraph) {
		document.getElementById('getMap').disabled = false;
        graphAndTileHandler.showGraphPanel(tilesGraph);
        graphAndTileHandler.showTiles(tilesGraph);		
        graphAndTileHandler.highLightContourMapStations(tilesGraph.StationsLatLon);
        if (TimePanel.isTimerOn)
            TimePanel.nextDone();        
	}
	
	, highLightContourMapStations : function(stationsLatLon){
	    var latLonLen = stationsLatLon.length;
	    var sensorLocation;
	    var pin;
	    for(var i=0;i<latLonLen;i++){
            sensorLocation = new VELatLong(stationsLatLon[i].Location.Lat, stationsLatLon[i].Location.Lon);
            pin = new VEShape(VEShapeType.Pushpin, sensorLocation);
            pin.SetCustomIcon('image/station.jpg');
            sensorLayer.AddShape(pin);	        
	    }
	    for(var i=0;i<arrSensorsExFrmContourMapLoc.length; i++)
	    {
	        sensorLocation = arrSensorsExFrmContourMapLoc[i].split(':');
	        pin = new VEShape(VEShapeType.Pushpin, new VELatLong(sensorLocation[0],sensorLocation[1]));        
	        pin.SetCustomIcon('');
	        sensorLayer.AddShape(pin);
	        //sensorLayer.DeleteShape(pin);
	        //pin.HideIcon();
	    }
	}
	   
    , showTileLayer: function() {
        if (graphAndTileHandler.lastTileLayer)
            graphAndTileHandler.map.ShowTileLayer(graphAndTileHandler.lastTileLayer);
        if (graphAndTileHandler.lastImage)
            ImageLayer.show();
        graphAndTileHandler.tileLayerHidden = false;
    }

    , hideTileLayer: function() {
            if (graphAndTileHandler.lastTileLayer)
                graphAndTileHandler.map.HideTileLayer(graphAndTileHandler.lastTileLayer);
            if (graphAndTileHandler.lastImage)
                ImageLayer.hide();
            graphAndTileHandler.tileLayerHidden = true;
    }
    , toggleTileLayer: function() {
        if (graphAndTileHandler.tileLayerHidden) {
            graphAndTileHandler.showTileLayer();
        } else {
            graphAndTileHandler.hideTileLayer();
        }
    }

	, tilesGraphGetLatestTimeout: function() {
        // delete graph panel
		var el = document.getElementById('graphtx_graph');
		el.innerHTML = '';
		el.style.display = 'none';

        // delete graph on map
        if (graphAndTileHandler.lastTileLayer) {
            graphAndTileHandler.map.DeleteTileLayer(graphAndTileHandler.lastTileLayer);
            graphAndTileHandler.lastTileLayer = null;
        }
        if (graphAndTileHandler.lastImage) {
            graphAndTileHandler.imageLayer.deleteImage(graphAndTileHandler.lastImage);
            //graphAndTileHandler.imageLayer.deleteImages();
            graphAndTileHandler.lastImage = null;
        }

		document.getElementById('getMap').disabled = false;
		//alert('Get map time out');
		var el = document.getElementById('graphtx_graph');
		el.innerHTML = 'Error: not enough data points';
		el.style.display = 'block';

        if (TimePanel.isTimerOn)
            TimePanel.nextDone();        
	}

	, getContourMap: function(contourSettings, colorMapSettings, timeSetting) {

		var query = new DataQuery(graphAndTileHandler.map, document.getElementById('sensorType'));
		graphAndTileHandler.lastQuery = query;
		if (timeSetting != null && timeSetting.inUse)
		    graphAndTileHandler.lastTimeSetting = timeSetting;
		else 
		    graphAndTileHandler.lastTimeSetting = null;
        var tiles = new Tiles();
        document.getElementById('getMap').disabled = true;

		// hide thumbnail and legend
		/*
		var el = document.getElementById('graphtx_graph');
		el.style.display = 'none';
        el.innerHTML = '';
        el = null;
        */
        var index = contourSettings.outputType;
        var outputTypes = [GraphManagerService, TileManagerService];
        var outputHandler = [graphAndTileHandler.tilesGraphGetLatestDone, graphAndTileHandler.tilesGraphGetLatestDone];
        var timeoutHandler = [graphAndTileHandler.tilesGraphGetLatestTimeout, graphAndTileHandler.tilesGraphGetLatestTimeout];
        var passCode = GetPassCode();
        var userName = GetUserName();

        // not customized
        if (!graphTx.customed) {
            if (timeSetting == null || !timeSetting.inUse) {
                //outputTypes[index].HelloWorld(outputHandler[index], timeoutHandler[index]);
                if (passCode.length > 0)
	                outputTypes[index].GetLatestWithAuthentication(
                        userName
                        , passCode
	                    , query.locationCSV
	                    , query.sensorType
	                    , query.zoomLevel
	                    , arrSensorsExFrmContourMap
	                    , outputHandler[index]
	                    , timeoutHandler[index]);
	            else
	                outputTypes[index].GetLatest(
	                    query.locationCSV
	                    , query.sensorType
	                    , query.zoomLevel
	                    , arrSensorsExFrmContourMap
	                    , outputHandler[index]
	                    , timeoutHandler[index]);            
	        } else {
                if (passCode.length > 0)
	            outputTypes[index].GetByTimeWithAuthentication(
                    userName
                    , passCode
                    , query.locationCSV
	                , query.sensorType
	                , query.zoomLevel
	                , timeSetting.currentTime.toLocaleString()
	                , new Date(timeSetting.currentTime.getTime() + timeSetting.resolution * 1000).toLocaleString()
	                , arrSensorsExFrmContourMap
	                , outputHandler[index]
	                , timeoutHandler[index]);
	            else
	            outputTypes[index].GetByTime(
	                query.locationCSV
	                , query.sensorType
	                , query.zoomLevel
	                , timeSetting.currentTime.toLocaleString()
	                , new Date(timeSetting.currentTime.getTime() + timeSetting.resolution * 1000).toLocaleString()
	                , arrSensorsExFrmContourMap
	                , outputHandler[index]
	                , timeoutHandler[index]);
	        }
        // customized
	    } else {
            if (timeSetting == null || !timeSetting.inUse) {
                if (passCode.length > 0)
                outputTypes[index].GetLatestCustomedWithAuthentication(
                    userName
                    , passCode
                    , query.locationCSV
	                , query.sensorType
	                , query.zoomLevel
	                , colorMapSettings.min
	                , colorMapSettings.max
	                , colorMapSettings.resolution
	                , colorMapSettings.colorMapIndex
	                , colorMapSettings.isContinuous
	                , contourSettings.interpoMethod
	                , arrSensorsExFrmContourMap	                
	                , outputHandler[index]
	                , timeoutHandler[index]);
                else
                outputTypes[index].GetLatestCustomed(
	                query.locationCSV
	                , query.sensorType
	                , query.zoomLevel
	                , colorMapSettings.min
	                , colorMapSettings.max
	                , colorMapSettings.resolution
	                , colorMapSettings.colorMapIndex
	                , colorMapSettings.isContinuous
	                , contourSettings.interpoMethod
	                , arrSensorsExFrmContourMap	                
	                , outputHandler[index]
	                , timeoutHandler[index]);
		    } else {
		        /*
		        document.getElementById('debugMsg').innerHTML =
		            query.locationCSV + ','
		            + query.sensorType + ','
		            + query.zoomLevel + ','
		            + timeSetting.currentTime + ','
		            + new Date(timeSetting.currentTime.getTime() + timeSetting.resolution * 1000) + ','
		            + colorMapSettings.minValue + ','
		            + colorMapSettings.maxValue + ','
		            + colorMapSettings.resolution + ','
		            + colorMapSettings.colorMapId + ','
		            + colorMapSettings.isContinuous;
		        */
                if (passCode.length > 0)
                outputTypes[index].GetByTimeCustomedWithAuthentication(
                    userName
                    , passCode
                    , query.locationCSV
	                , query.sensorType
	                , query.zoomLevel
	                , timeSetting.currentTime.toLocaleString()
	                , new Date(timeSetting.currentTime.getTime() + timeSetting.resolution * 1000).toLocaleString()
	                , colorMapSettings.min
	                , colorMapSettings.max
	                , colorMapSettings.resolution
	                , colorMapSettings.colorMapIndex
	                , colorMapSettings.isContinuous
	                , contourSettings.interpoMethod
	                , arrSensorsExFrmContourMap	                
	                , outputHandler[index]
	                , timeoutHandler[index]);
                else
                outputTypes[index].GetByTimeCustomed(
	                query.locationCSV
	                , query.sensorType
	                , query.zoomLevel
	                , timeSetting.currentTime.toLocaleString()
	                , new Date(timeSetting.currentTime.getTime() + timeSetting.resolution * 1000).toLocaleString()
	                , colorMapSettings.min
	                , colorMapSettings.max
	                , colorMapSettings.resolution
	                , colorMapSettings.colorMapIndex
	                , colorMapSettings.isContinuous
	                , contourSettings.interpoMethod
	                , arrSensorsExFrmContourMap	                
	                , outputHandler[index]
	                , timeoutHandler[index]);
		    }
	    }
	}
}

var VizControllers = {
    'Icon': {vizTypeTitle:1, vizType:1
            , sensorTypeTitle:1, sensorType:1
            , interpoMethodTitle:0, interpoMethod:0
            , outputTypeTitle:0, outputType:0
            , colorMapConfTitle:0, colorMapConfPanel:0
            , getMap:1
            , graphtx_list:0, graphtx_graph:0}
    
    , 'Rectangle': {vizTypeTitle:1, vizType:1
            , sensorTypeTitle:1, sensorType:1
            , interpoMethodTitle:0, interpoMethod:0
            , outputTypeTitle:0, outputType:0
            , colorMapConfTitle:1, colorMapConfPanel:0
            , getMap:1
            , graphtx_list:0, graphtx_graph:0}

    , 'Contour Map': {vizTypeTitle:1, vizType:1
            , sensorTypeTitle:1, sensorType:1
            , interpoMethodTitle:1, interpoMethod:1
            , outputTypeTitle:1, outputType:1
            , colorMapConfTitle:1, colorMapConfPanel:0
            , getMap:1
            , graphtx_list:1, graphtx_graph:1}
}


var graphTx = {
    vizTypes: null
    , contourSettings: {interpoMethod: 'Contouring.ContourByKriging', outputType: 0}
    , timeSetting: null
    , customed: false
    , init: function(vizTypes, sensorTypes, vizChangeHandler, timeSetting, onColorMapChange) {
        graphTx.vizTypes = vizTypes;

        var selector;
		// init viz type selector
		var selector = document.getElementById('vizType');
		for (var i in vizTypes) {
            var temp = null;
            if (!window.addEventListener)
                temp = selector.length;
		    selector.add(new Option(
		        vizTypes[i]
		        , vizTypes[i]
		        , false
		        , false), temp);
		}

		if (selector.options[2]) {
			selector.options[2].defaultSelected = true;
			selector.options[2].selected = true;
		}

		selector.onchange = function() {
		    var el = document.getElementById('vizType');
		    var newVizType = el.options[el.selectedIndex].value;
		    for (var i in VizControllers[newVizType]) {
		        el = document.getElementById(i);
		        if (VizControllers[newVizType][i])
		            el.style.display = 'block';
		        else 
		            el.style.display = 'none';
		    }
		    //alert(newVizType);
		    //vizChangeHandler(newVizType);
		}

        // init parameter selectors
        selector = document.getElementById('interpoMethod');
        selector.onchange = function() {
            graphTx.contourSettings.interpoMethod = this.options[this.selectedIndex].value;
        }

        selector = document.getElementById('outputType');
        selector.onchange = function() {
            graphTx.contourSettings.outputType = this.options[this.selectedIndex].value;
        }
		
		// init sensor type selector
		graphTx.updateSensorTypes(sensorTypes);
		
		// init get map button
		document.getElementById('getMap').onclick = function() {
            var el = document.getElementById('vizType');
	        var newVizType = el.options[el.selectedIndex].value;
	        
	        // get colorMapSettings
	        var colorMapSettings = null;
    	    if (document.getElementById('colorMapConfPanel').style.display == 'block') {
    		    el = document.getElementById('isContinuous');
    	        var isContinuous = el.options[el.selectedIndex].value == 1 ?
    	            true : false;
        	    
    	        el = document.getElementById('colorMap');
    	        var colorMapId = el.options[el.selectedIndex].value;
        	    
                el = document.getElementById('minValue');
                var minValue = parseFloat(el.value);
                el = document.getElementById('maxValue');    	    
                var maxValue = parseFloat(el.value);
                el = document.getElementById('resolution');
                var resolution = parseFloat(el.value);
	            colorMapSettings = new ColorMapSetting(isContinuous, colorMapId, minValue, maxValue, resolution, true);
	            graphTx.onColorMapChange(colorMapSettings);
    		}
	        
    		var el = document.getElementById('sensorType');
    		var sensorTypes = el.options[el.selectedIndex].value;
            vizChangeHandler(newVizType, sensorTypes);
	        switch (newVizType) {
	            case graphTx.vizTypes.contour:
	                graphAndTileHandler.getContourMap(graphTx.contourSettings, colorMapSettings, graphTx.timeSetting);
	                break;
	            default:
		            break;
	        }
        }
        graphTx.timeSetting = timeSetting;
        graphTx.onColorMapChange = onColorMapChange;
    }
    
    , updateSensorTypes: function(sensorTypes) {
		// init sensor type selector
		var selector = document.getElementById('sensorType');
		selector.options.length = 0;
		for (var i in sensorTypes) {
		    if (sensorTypes[i].dataType == 'scalar' && sensorTypes[i].inView) {
		        var temp = null;
		        if (!window.addEventListener)
		            temp = selector.length;
			    selector.add(new Option(
			        sensorTypes[i].name
				    , sensorTypes[i].id
				    , false
				    , false), temp);
            }
		}

		if (selector.options[0]) {
			selector.options[0].defaultSelected = true;
			selector.options[0].selected = true;
		}
    }
    
    , getContourMap: function(colorMapSettings, timeSetting) {
        graphAndTileHandler.getContourMap(this.contourSettings, colorMapSettings, timeSetting);
    }
    
    , toggleColorMapConfPanel: function () {
        var el = document.getElementById('colorMapConfPanel');
        var img = document.getElementById('colorMapConfPanelImg'); 
        var text = document.getElementById('colorMapConfPanelTxt');
        var button = document.getElementById('getMap');         
        if (el.style.display == 'none') {
            el.style.display = 'block';
            img.src = 'image/collapse.jpg';
            button.value = 'Get Customized Visualization';
            text.innerHTML = '(customed)';
            graphTx.customed = true;
        } else {
            el.style.display = 'none';
            img.src = 'image/expand.jpg';
            button.value = 'Get Visualization';
            text.innerHTML = '(default)';
            graphTx.customed = false;
        } 
    }
    
    , toggleContourMapPanel: function() {
        var el = document.getElementById('contourMapPanel');
        var img = document.getElementById('contourMapPanelImg');
        if (el.style.display == 'none') {
            el.style.display = 'block';
            img.src = 'image/collapse.jpg';
        } else {
            el.style.display = 'none';
            img.src = 'image/expand.jpg';
        }
    }
    , open: function() {
        document.getElementById('graphTx_panel').style.display = 'block';
    }

    , close: function() {
        document.getElementById('graphTx_panel').style.display = 'none';
    }

    /*
    , addOnColorMapChangeListener: function(func){
        if (!this.onColorMapChange || this.onColorMapChange == null) {
            this.onColorMapChange = func;
        } else {
            var old = this.onColorMapChange;
            this.onColorMapChange = function(isContinuous, colorMapId, minValue, maxValue, resolution) {
                old(isContinuous, colorMapId, minValue, maxValue, resolution);
                func(isContinuous, colorMapId, minValue, maxValue, resolution);
            }
        }
    }
    */
}
 
