﻿// Dojo Requirements
dojo.require("esri.map");
dojo.require("esri.tasks.query");
dojo.require("esri.toolbars.navigation");
dojo.require("dijit.form.Button");
dojo.require("dijit.Toolbar");
dojo.require("dijit.Dialog");
dojo.require("dijit.Menu");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");

function queryViewsheds(layerID) {
    console.log(layerID);

    // Clear the quick zoom menu
    //dijit.byId('quickZoomMenu').destroyDescendants(false);

    /* if (layerID == null) {
        dijit.byId('quickZoomMenu').addChild(new dijit.MenuItem({
            label: 'No viewpoints are available for this alternative.'
        }));
    }
	if (layerID == "-1") {
        dijit.byId('quickZoomMenu').addChild(new dijit.MenuItem({
            label: '6b 3D Renderings Coming in 2011'
        }));	
	} */

    var queryTask, query;
    //build query task
    queryTask = new esri.tasks.QueryTask(baseUrl + 'Dynamic/MapServer/' + layerID);

    //build query filter
    query = new esri.tasks.Query();
    query.returnGeometry = true;
    query.outFields = ["IMAGE_NO", "ALTERNATIV", "VIEWPOINT", "ALT_IMAGE_" ];
    query.where = "IMAGE_NO <> ''"; // hack to return all rows

	map.infoWindow.setTitle( "3D Visualization" );
    map.infoWindow.resize(480,390);

    //Can listen for onComplete event to process results or can use the callback option in the queryTask.execute method.
    dojo.connect(queryTask, "onComplete", function (featureSet) {
        // Declarations
        var graphic, i, j, k,
            symbol = new esri.symbol.SimpleFillSymbol(
                esri.symbol.SimpleFillSymbol.STYLE_SOLID,           // Fill style
                new esri.symbol.SimpleLineSymbol(
                    esri.symbol.SimpleLineSymbol.STYLE_DASH,        // Line style
                    new dojo.Color([255, 255, 255, 0]), 1              // Line color and width
                ),
                new dojo.Color([234, 189, 0, 0.10])                    // Fill color
            ),
            numOfFeatures = featureSet.features.length;

        //QueryTask returns a featureSet.  Loop through features in the featureSet and add them to the map.

        //WARNING WARNING ... BREAKS ON DUPLICATE VIEWSHEDS ... POSSIBLE INF. LOOP
        j = numOfFeatures;
        i = 0;
        k = 0;

        imagesWE = new Array("1", "3", "4", "5", "5B", "6B", "7", "9", "10");

        while (j > 0) {
            //Get the current feature from the featureSet.
            //Feature is a graphic
            if (i == featureSet.features.length) { i = 0; k++; }

            graphic = featureSet.features[i];

            if (imagesWE[k] == null) break;

            /*
            alert('J: ' + j );
            alert(graphic.attributes['IMAGE_NO'] + ' images: ' + imagesWE[k]);
            }*/

            if (graphic.attributes['IMAGE_NO'] == imagesWE[k]) {
                graphic.setSymbol(symbol);
                //graphic.setInfoTemplate(infoTemplate);

                /*vshedShapeExtents.add(graphic.geometry.getExtent().expand(1.9),
                { id: graphic.attributes['VIEWPOINT'] }); */

                //Add graphic to the counties graphics layer.
                graphicsLayer.add(graphic);

                // Change the quick zoom menu
                /*dijit.byId('quickZoomMenu').addChild(new dijit.MenuItem({
                    label: graphic.attributes['VIEWPOINT'],
                    onClick: function (evt) {
                        var idx = dijit.byId('quickZoomMenu').getIndexOfChild(this);
                        map.setExtent(graphicsLayer.graphics[idx].geometry.getExtent().expand(1.9));
                        //map.setExtent(vshedShapeExtents.get(label));
                    }
                })); */

                j--;  // match made
                k++;
                i = 0;
            }
            else
                i++;
        }

        map.addLayer(graphicsLayer);

        //listen for when map.graphics onMouseOut event is fired and then clear the highlight graphic
        //and hide the info window
        /*        dojo.connect(map.graphics, "onMouseOut", function(evt) {
        //map.graphics.clear();
        //map.infoWindow.hide();
        }); */

        map.infoWindow.setContent(dijit.byId('tabs').domNode);

        dojo.connect(map.graphics, "onClick", activateViewshed);
        dojo.connect(map.graphics, "onMouseOut", clearViewshed);
    });
    
    queryTask.execute(query);
}

function activateViewshed(evt) {
    var
		vue = evt.graphic.attributes["img"],
		a1 = evt.graphic.attributes["alternative"],
		a2 = evt.graphic.attributes["altimg"],

		link = 'AJAX/AlternativesImageHandler.ashx?a1='+ a1 +'&a2=' + a2 + '&vue=' + vue,

		ptC= map.extent,

		iwpX = evt.screenPoint.x,
		iwpY = evt.screenPoint.y,

		panX = 0,
		panY = 0,

		ptExtent = new esri.geometry.Point,
		ptOrig = new  esri.geometry.Point,

		anchor = map.getInfoWindowAnchor(evt.screenPoint);

	    if( a1 == "4") {
		    map.infoWindow.resize(480,350);
	    }
	    else {
		    map.infoWindow.resize(480,390);
	    }

		map.infoWindow.attr('style', 'scroll:none');

		if (true) { //dijit.byId('tabs') == null) {
		    xhrArgs = {
		        url: "AJAX/AlternativesImageHandler.ashx",
		        handleAs: "text",
		        content: {
		            a1: a1,
		            a2: a2,
                    vue: vue
		        },
		        load: function (responseObject) {
		            map.infoWindow.setContent(responseObject);
		        }
		    };

            dojo.xhrGet(xhrArgs);
        }
        else {
            dijit.byId('tabs').attr('href', link);
        }

	if(iwpX < 480 && (anchor == "upperleft" || anchor == "lowerleft" ) ) {
		panX = 480 - iwpX + 20;
	}

	if(iwpY < 350 && (anchor == "upperleft" || anchor == "upperright") ) {
		panY = 400 - iwpY + 80;
	}

	if(iwpX + 500 > map.width && (anchor == "upperright" || anchor == "lowerright" ) ) {
		panX = map.width - iwpX - 480 - 20;
	}

	if(iwpY + 500 > map.height && (anchor == "lowerleft" || anchor == "lowerright" ) ) {
		panY = map.height - iwpY - 400 - 60;
	}

	ptExtent.x = panX;
	ptExtent.y = panY;

	ptOrig.x = 0;
	ptOrig.y = 0;	
	
	map.infoWindow.show(evt.screenPoint , anchor  );
	map.setExtent(ptC.offset(-(map.toMap(ptExtent).x - map.toMap(ptOrig).x), -(map.toMap(ptExtent).y - map.toMap(ptOrig).y)));
}

function clearViewshed(evt) {
	map.graphics.clear();
}

function highlightViewshed(evt) {
    var highlightSymbol = new esri.symbol.SimpleFillSymbol(
            esri.symbol.SimpleFillSymbol.STYLE_SOLID,
            new esri.symbol.SimpleLineSymbol(esri.symbol.SimpleLineSymbol.STYLE_SOLID, new dojo.Color([0,126,161]), 3),
            new dojo.Color([230,230,230,0.35])
        ),
        highlightGraphic = new esri.Graphic(evt.graphic.geometry,highlightSymbol);
       
    map.graphics.clear();  //use the maps graphics layer as the highlight layer

	if(evt.graphic.attributes['ALT_IMAGE_1'] != null)
		highlightGraphic.setAttributes({img: evt.graphic.attributes['IMAGE_NO'], alternative: evt.graphic.attributes['ALTERNATIV'], altimg: evt.graphic.attributes['ALT_IMAGE_'] });
	else
	    highlightGraphic.setAttributes({ img: evt.graphic.attributes['IMAGE_NO'], alternative: evt.graphic.attributes['ALTERNATIV'], altimg: "NONE" });

    map.graphics.add(highlightGraphic);
}

function doShowNoBuildAlternative(linkObj) {
    if (linkObj != null) {
        linkObj.className = 'ahover';
    }

    dojo.byId('nbuildindic').innerHTML = "Now Showing No Build Alternative";
    dijit.byId('DiagramButton').attr('style', 'display: none;');
}

function showAlternative(linkObj, altID) {
    var link = 'AJAX/AlternativesHandler.ashx?f=desc&a='+altID,
        descrDialog = dijit.byId('alternativeDescriptionDialog'),
        xhrArgs;

    if (altID == 1) {
        doShowNoBuildAlternative();
    }
    else {
        dojo.byId('nbuildindic').innerHTML = "";
        dijit.byId('DiagramButton').attr('style', 'display: inline;');
    }

    // turn on all layers
    ptrsEnabled = new Array(true, true, true);
    showML = 0;
    dijit.byId('transpSelectionBtn').setChecked(true);
    dijit.byId('vshedsBtn').setChecked(true);

    dojo.query('.ahover').removeClass('ahover');

    // Show the alternative description
    descrDialog.draggable = false;

    if (linkObj != null) {
        linkObj.className = 'ahover';
        descrDialog.attr('title', linkObj.innerHTML);
        descrDialog.attr('href', link);
        descrDialog.attr('width', '300px');
        descrDialog.show();
    }

    xhrArgs = {
        url: "AJAX/AlternativesHandler.ashx",
        handleAs: "json",
        preventCache: true,
        content: {
            a: altID,
            f: 'layerlist'
        },
        load: function (responseObject, ioArgs) {
            var i, j;

            if (responseObject.layers != null) {
                masterLayerList = responseObject.layers;

                ptrs = responseObject.PointerList;
                currAlternative = altID;

                for (i = 0, j = 0; i < ptrs.length; i++) {
                    if (ptrs[i] == -1) {
                        ptrsEnabled[i] = false;
                        j++;
                    }
                }

                if (isDiagramming == false) {
                    //dynamicLayer.setVisibleLayers(responseObject.layers);
                    showLayers();
                }

                console.log(j);

                dojo.style('vsheds', 'display',                 (ptrs[0] != -1) ? '' : 'none');
                dojo.style('transpSelection', 'display',        (ptrs[1] != -1) ? '' : 'none');
                dojo.style('managedLaneSelection', 'display',   (ptrs[2] != -1) ? '' : 'none');
            }
            else
                dynamicLayer.setDefaultVisibleLayers();

            // Cleanup graphics
            if (map.graphics != null && graphicsLayer != null) {
                map.removeLayer(graphicsLayer);
                map.graphics.clear();
                graphicsLayer.clear();

                // Get new graphics
                dojo.connect(graphicsLayer, "onMouseOver", highlightViewshed);

                currViewshedIndex = responseObject.viewshed;
                //dojo.byId('Idic').innerHTML = responseObject.viewshed;
            }

            queryViewsheds(responseObject.viewshed);

            map.infoWindow.hide();
        },
        error: function (error) {
            alert("An unexpected error occurred: " + error);
        }
    }

    // Make the request
    dojo.xhrGet(xhrArgs);

    getManagedLaneSQLStrings(altID);
}
