﻿Type.registerNamespace("KC");

KC.Pictometry = function() {
    this._controlId = "ImgCtrl";
    this._floatingPanelId = "Pictometry1_PictometryFloatingPanel";
    this._geometryServiceUrl = "http://localhost/ArcGIS/rest/services/Geometry/GeometryServer";
    this._licenseText = null;
    this._warehouse = "http://it-apictometry/KENTNIW/Kent County Warehouse";
    this._obliqueIcon = "obliqueIcon";
    this._onOblique = Function.createDelegate(this, function(geom) {
        var argument = geom.get_x() + "," + geom.get_y();
        this.doCallback(argument, this);
    });
}

KC.Pictometry.prototype = {
    startOblique: function() {
        this.getViewer().unload();
        this.getMap();
        this._map.getGeometry(ESRI.ADF.Graphics.ShapeType.Point, this._onOblique, null, 'black', 'gray', 'crosshair', true);
    },

    doCallback: function(argument, context) {
        var a = argument.split(',');
        var pointX = eval(a[0]);
        var pointY = eval(a[1]);
        this.AddGraphic(pointX, pointY);
        this.ObliqueLocation(pointX, pointY);
    },

    getViewer: function() {
        return $get(this._controlId);
    },

    getWarehouse: function() {
        return this._warehouse;
    },

    setWarehouse: function(url) {
        this._warehouse = url;
    },

    getFloatingPanelId: function() {
        return this._floatingPanelId;
    },

    setFloatingPanelId: function(id) {
        this._floatingPanelId = id;
    },

    setGeometryServiceUrl: function(url) {
        this._geometryServiceUrl = url;
    },

    getLicense: function() {
        return this.getViewer().UserLicense;
    },

    setLicense: function(text) {
        this._licenseText = text;
        this.getViewer().UserLicense = this._licenseText;
    },

    getMap: function() {
        this._map = $find("Map1");
        return this._map;
    },

    AddGraphic: function(pointX, pointY, drawLine) {
        if (drawLine == null) drawLine = false;
        this.RemoveGraphic();

        this.getMap();
        var newPt = new ESRI.ADF.Geometries.Point(pointX, pointY);
        if (drawLine && (this._oldPt != null)) {
            var linePoints = new ESRI.ADF.Geometries.CoordinateCollection();
            linePoints.add(this._oldPt);
            linePoints.add(newPt);
            var newLine = new ESRI.ADF.Geometries.Polyline(linePoints, this._map.get_spatialReference());
            this.lineCallout = $create(ESRI.ADF.Graphics.GraphicFeature,
			{ "id": "line" + this._oldPt.toString() + newPt.toString(), "geometry": newLine, "symbol": new ESRI.ADF.Graphics.LineSymbol("blue", 2) });
            //            this.lineCallout.get_symbol().set_imageFormat("png32");
            //            this._map.addGraphic(this.lineCallout);

            var graphicFeatureGroupID = "pictometryNavigation";
            var graphicFeatureGroup = $find(graphicFeatureGroupID);

            if (!graphicFeatureGroup) {
                var defaultSymbol = new ESRI.ADF.Graphics.FillSymbol('white', 'blue', 2, 'default');
                defaultSymbol.set_opacity(0.5);

                var highlightSymbol = new ESRI.ADF.Graphics.FillSymbol('yellow', 'green', 4, 'pointer');
                highlightSymbol.set_opacity(0.5);

                var graphicFeatureGroup = $create(ESRI.ADF.Graphics.GraphicFeatureGroup,
				{ "id": graphicFeatureGroupID, "symbol": defaultSymbol, "highlightSymbol": highlightSymbol });

                this._map.addGraphic(graphicFeatureGroup);
            }
            graphicFeatureGroup.add(this.lineCallout);
        }
        this.obliqueCallout = $create(ESRI.ADF.Graphics.GraphicFeature,
			{ "id": this._obliqueIcon, "geometry": newPt, "symbol": new ESRI.ADF.Graphics.MarkerSymbol("images/PictCrosshair.png", 5, 5) });

        this.obliqueCallout.get_symbol().set_imageFormat("png32");
        this._map.addGraphic(this.obliqueCallout);
        this._oldPt = newPt;
    },

    Close: function() {
        this.RemoveGraphic();
        hideFloatingPanel(this._floatingPanelId);
    },

    HideMeasureBarFrame: function() {
        border.Show("MeasureBarFrameExpand");
        border.Show("PictMeasureBarExpand");
        border.Hide("MeasureBarFrame");
    },

    HideNavigateFrame: function() {
        border.Show("NavigateFrameExpand");
        border.Show("PictNavigateExpand");
        border.Hide("NavigateFrame");
    },

    HideStatusFrame: function() {
        border.Show("StatusFrameExpand");
        border.Hide("StatusFrameCollapse");
        border.Hide("StatusFrame");
        border.Hide("pictStatus");
    },

    HideToolBarFrame: function() {
        border.Show("PictToolBarExpand");
        border.Show("ToolBarFrameExpand");
        border.Hide("ToolBarFrame");
        border.Hide("ZoomLevelFrame");
    },

    Initialize: function(latDegrees, lonDegrees, showPanel) {
        this.getViewer().unload();
        var RetVal = this.getViewer().SearchAndLoadDeg(this.getWarehouse(), latDegrees, lonDegrees);
        if (RetVal != 0) {
            $get("pictStatus").innerText = "No image available";
            if (showPanel != null)
                if (showPanel) hideFloatingPanel(this._floatingPanelId);
        }
        else window.setTimeout("pictViewer.HideStatusFrame();", 2500);
        this.getViewer().ViewCrosshair();
        this.getViewer().AutoUpdateImageList = true;
        this.SetTool(KC.Pictometry.ToolType.Pan);
        this.ShowToolBarFrame();
        this.ShowMeasureBarFrame();
        this.ShowStatusFrame();
        this.ResetZoomLevel();
    },

    LoadImage: function(latRadians, lonRadians) {
        this.getViewer().unload();
        var RetVal = this.getViewer().SearchAndLoad(this.getWarehouse(), latRadians, lonRadians);
        switch (RetVal) {
            case 0:
                this.getViewer().ViewCrosshair();
                break;
            case -2147220986:
                alert("Pictometry license could not be validated: \n" + this.getLicense());
                break;
            case -2147467259:
                alert("The latitude of " + latRadians + " and longitude of " + lonRadians
                    + " radians does not contain imagery in the " + this.getWarehouse() + " warehouse. ");
                break;
            default:
                alert("Pictometry image could not be loaded: \n" + RetVal);
        }
    },

    Maximize: function() {
        var button = $get("PictMaximize")
        var floatingPanel = $get(this._floatingPanelId);
        if (button.alt == "Maximize") {
            floatingPanel.style.width = "100%";
            floatingPanel.style.left = "8px";
            floatingPanel.style.top = "8px";
            button.alt = "Restore";
            button.src = "images/expand_left2.GIF";
        } else {
            floatingPanel.style.width = "50%";
            floatingPanel.style.left = "20px";
            floatingPanel.style.top = "100px";
            button.alt = "Maximize";
            button.src = "images/expand_right2.GIF";
        }
    },

    MoveAdjacent: function(cardinal) {
        var fileName = this.getViewer().GetFileName();
        var i = 1;
        do {
            var factor = this.MoveTo(cardinal, factor);
            i++;
            if (i > 8) break
            else factor = factor * 2;
        } while (fileName == this.getViewer().GetFileName())
    },

    MoveGraphic: function(latDegrees, lonDegrees, drawLine, shiftPan, zoomFactor) {
        if (shiftPan) showFloatingPanel(this._floatingPanelId);
        var fromWkid = 4326; // WGS84
        var toWkid = 2253; // NAD_1983_StatePlane_Michigan_South_FIPS_2113_Feet_Intl
        this.Project(lonDegrees, latDegrees, fromWkid, toWkid, function(features) {
            pt = features[0].geometry;
            pictViewer.ZoomTo(pt.x, pt.y, drawLine, shiftPan, zoomFactor);
        }, "ZoomTo");
    },

    MoveTo: function(cardinal, factor) {
        var moved = 0;
        var a = this.getViewer().GetViewPolygon().split(', ');
        if (a.length < 8) return;
        var upperLeftY = eval(a[0]);
        var upperLeftX = eval(a[1]);
        var upperRightY = eval(a[2]);
        var upperRightX = eval(a[3]);
        var lowerLeftY = eval(a[4]);
        var lowerLeftX = eval(a[5]);
        var lowerRightY = eval(a[6]);
        var lowerRightX = eval(a[7]);
        var top = (upperLeftY + upperRightY) / 2;
        var bottom = (lowerLeftY + lowerRightY) / 2;
        var left = (upperLeftX + lowerLeftX) / 2;
        var right = (upperRightX + lowerRightX) / 2;
        var centerY = (top + bottom) / 2;
        var centerX = (left + right) / 2;
        var newCenterY = centerY;
        var newCenterX = centerX;
        var height = top - bottom;
        var width = 4 * (right - left);
        if (factor != null) {
            height = factor;
            width = factor;
        } else {
            height = .00002;
            width = .00004;
        }
        switch (cardinal) {
            case "N":
                newCenterY = centerY + height;
                moved = height;
                break;
            case "S":
                newCenterY = centerY - height;
                moved = height;
                break;
            case "E":
                newCenterX = centerX + width;
                moved = width;
                break;
            case "W":
                newCenterX = centerX - width;
                moved = width;
                break;
            case "NW":
                newCenterY = centerY + height;
                newCenterX = centerX - width;
                moved = width;
                break;
            case "NE":
                newCenterY = centerY + height;
                newCenterX = centerX + width;
                moved = width;
                break;
            case "SW":
                newCenterY = centerY - height;
                newCenterX = centerX - width;
                moved = width;
                break;
            case "SE":
                newCenterY = centerY - height;
                newCenterX = centerX + width;
                moved = width;
                break;
        }
        var zoom = this.getViewer().ZoomFactor;
        this.LoadImage(newCenterY, newCenterX);
        if (zoom < 1)
            this.getViewer().ZoomFactor = zoom;
        else
            this.getViewer().ZoomFactor = .9;

        return moved;
    },

    NavigateViewNext: function(wrap) {
        this.getViewer().NavigateViewNext(wrap);
        this.SetZoom(.25);
    },

    NavigateViewPrev: function(wrap) {
        this.getViewer().NavigateViewPrev(wrap);
        this.SetZoom(.25);
    },

    Navigate: function(cardinal) {
        if (cardinal == 'O') {
            this.HideMeasureBarFrame();
        } else {
            this.getViewer().DisplayCompass = -1;
            $get("MeasureBarFrame").style.right = "96px";
            $get("PictMeasureBar").style.right = "96px";
            this.ShowMeasureBarFrame();
        }
        this.getViewer().NavigateViewFrom(cardinal);
    },

    ObliqueLocation: function(pointX, pointY) {
        var fromWkid = 2253; // NAD_1983_StatePlane_Michigan_South_FIPS_2113_Feet_Intl
        var toWkid = 4326; // WGS84
        this.Project(pointX, pointY, fromWkid, toWkid, function(features) {
            pt = features[0].geometry;
            pictViewer.Initialize(pt.y, pt.x);
        }, "Initialize");

        showFloatingPanel(this._floatingPanelId);
        expandFloatingPanel(this._floatingPanelId);
    },

    PanTo: function(pointX, pointY, offset, zoomFactor) {
        if (zoomFactor == null) zoomFactor = 0.5;
        var m = $find("Map1");
        var maxExtent = m.get_layers().get_extent();
        var width = m.get_extent().get_width() * zoomFactor;
        var height = m.get_extent().get_height() * zoomFactor;
        var box;
        if (offset) {
            // if (width < 20000) width = 20000;
            box = new ESRI.ADF.Geometries.Envelope(pointX - (width * .60), pointY - height, pointX + (width * .40), pointY + height);
        }
        else
            box = new ESRI.ADF.Geometries.Envelope(pointX - width, pointY - height, pointX + width, pointY + height);
        m.zoomToBox(box);
    },

    Print: function() {
        var floatingPanel = $get(this._floatingPanelId);
        floatingPanel.style.width = "900px";
        floatingPanel.style.left = "0px";
        floatingPanel.style.top = "0px";
        window.print();
    },

    Project: function(pointX, pointY, fromWkid, toWkid, callback, context) {
        // dojo does not seem to work in IE8
        try {
            //concept taken from http://resources.esri.com/help/9.3/arcgisserver/apis/javascript/arcgis/help/jssamples_start.htm#jssamples/util_project.html page.
            dojo.require("esri.map");
            var gsvc = new esri.tasks.GeometryService(this._geometryServiceUrl);
            var point = new esri.geometry.Point(pointX, pointY, new esri.SpatialReference({ wkid: fromWkid }))
            var symbol = new esri.symbol.SimpleMarkerSymbol();
            var graphic = new esri.Graphic(point, symbol);
            var outSR = new esri.SpatialReference({ wkid: toWkid });
            gsvc.project([graphic], outSR, callback, function(error) {
                alert(error.message);
            });
        }
        catch (ex) {
            // this method is dependant on a CoordinateControl1 custom control be included on the page to work
            var cc = $find('CoordinateControl1');
            if (cc != null) {
                var projCoords = cc.projectCoords(pointX, pointY, fromWkid, toWkid, context);
                if (projCoords != null) {
                    pictViewer.ZoomTo(eval(projCoords[0]), eval(projCoords[1]), false, true, 0.5);
                }
            }
        }
    },

    RemoveGraphic: function() {
        var oCallout = $find(this._obliqueIcon);
        if (oCallout != null) {
            this.getMap();
            this._map.removeGraphic(oCallout);
            oCallout.dispose();
            oCallout = null;
        }
    },

    ResetZoomLevel: function() {
        var inactive = "images/slider_inactive.gif";
        var active = "images/slider_active.gif";
        $get("ZoomFull").src = inactive;
        $get("ZoomFar").src = inactive;
        $get("ZoomActual").src = inactive;
        $get("ZoomClose").src = inactive;
        $get("ZoomCloser").src = inactive;
        var num = this.getViewer().ZoomFactor;
        switch (true) {
            case num < .001:
                $get("ZoomActual").src = active;
                break;
            case num < .3:
                $get("ZoomFull").src = active;
                break;
            case num >= .3 && num < .8:
                $get("ZoomFar").src = active;
                break;
            case num >= .8 && num < 1.6:
                $get("ZoomActual").src = active;
                break;
            case num >= 1.6 && num < 3.7:
                $get("ZoomClose").src = active;
                break;
            case num >= 3.7:
                $get("ZoomCloser").src = active;
                break;
        }
    },

    SetTool: function(id) {
        var oldToolId = this.getViewer().Tool;
        var bSuccess = false;

        switch (id) {
            case KC.Pictometry.ToolType.Pan:
            case KC.Pictometry.ToolType.Zoom:
                this.HideStatusFrame();
                break;
            default:
                this.ShowStatusFrame();
        }

        try {
            this.getViewer().Tool = id;
            bSuccess = true;
        }
        catch (objError) {
            var strResult = "Tool could not be set to " + id + " ERROR: ";
            strResult += objError + "\n";
            strResult += "error code: " + (objError.number & 0xFFFF).toString() + "\n\nDescription:\n";
            strResult += objError.description;
            alert(strResult);
        }

        if (!bSuccess) {
            try {
                // indicates "no tool"
                this.getViewer().Tool = 0;
            }
            catch (objError2) {
                alert('Tool could not be reset to nothing. ' + objError2);
            }
        }
    },

    SetZoom: function(factor) {
        this.getViewer().ZoomFactor = factor;
        this.ResetZoomLevel();
    },

    ShowMeasureBarFrame: function() {
        border.Hide("MeasureBarFrameExpand");
        border.Hide("PictMeasureBarExpand");
        border.Show("MeasureBarFrame");
    },

    ShowNavigateFrame: function() {
        border.Hide("NavigateFrameExpand");
        border.Hide("PictNavigateExpand");
        border.Show("NavigateFrame");
    },

    ShowStatusFrame: function() {
        border.Hide("StatusFrameExpand");
        border.Show("StatusFrameCollapse");
        border.Show("StatusFrame");
        border.Show("pictStatus");
    },

    ShowToolBarFrame: function() {
        border.Hide("PictToolBarExpand");
        border.Hide("ToolBarFrameExpand");
        border.Show("ToolBarFrame");
        border.Show("ZoomLevelFrame");
    },

    Zoom: function(delta) {
        if (((delta < 0) && (this.getViewer().ZoomFactor > Math.abs(delta) * 2))
        || ((delta > 0) && (this.getViewer().ZoomFactor < 5))) {
            this.getViewer().ZoomFactor = this.getViewer().ZoomFactor + delta;
        } else {
            if (delta < 0) {
                this.getViewer().ZoomFactor = 0.15;
            } else {
                this.getViewer().ZoomFactor = 5.5;
            }
        }
        this.ResetZoomLevel();
    },

    ZoomIn: function() {
        this.getViewer().ZoomIn();
        this.ResetZoomLevel();
    },

    ZoomOut: function() {
        this.getViewer().ZoomOut();
        this.ResetZoomLevel();
    },

    ZoomTo: function(pointX, pointY, drawLine, shiftPan, zoomFactor) {
        pictViewer.AddGraphic(pointX, pointY, drawLine);
        pictViewer.PanTo(pointX, pointY, shiftPan, zoomFactor);
    },

    dispose: function() {
        alert('KC.Pictometry disposed ' + this.getWarehouse());
    }
}
KC.Pictometry.registerClass('KC.Pictometry', null, Sys.IDisposable);

KC.Pictometry.ToolType = function() { };
KC.Pictometry.ToolType.prototype = {
    NoTool: 0,
    Location: 1,
    Distance: 2,
    Bearing: 3,
    Area: 4,
    Height: 5,
    Zoom: 6,
    Elevation: 7,
    Navigation: 8, // Walking Man
    Extraction: 9, // Image Extraction
    Pan: 10
}
KC.Pictometry.ToolType.registerEnum("KC.Pictometry.ToolType");

var pictViewer = new KC.Pictometry();

// Notify ScriptManager that this is the end of the script.
if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();