
// global vars   
var ImgNav = null;
var latitude = 0;
var longitude = 0;
var defaultmarker = null;
var pict_activeTool = "pict_pan";
var tb_pictometry = document.getElementById("pict_toolbar");

function pictometryInit() {
    // Instantiate the constructor parameters object.   
    // UserId - The required Pictometry User Identification code.   
    // ServerProxy - The fully qualified URL for the required local proxy server.
    var params = { UserId: "1052", ServerProxy: "ImageNavigatorProxy.ashx" };
    //var params = { UserId: "jkiley@cityofrockhill.com", ServerProxy: "ImageNavigatorProxy.ashx" };

    // Instantiate the new ImageNavigator passing in the id   
    // of previously defined DIV element and parameters.   
    ImgNav = new Pol.VI.ImageNavigator("ImageViewer", params);

    // Call the Init method.   
    ImgNav.Init();

    // Attach to the onclick event.
    ImgNav.AttachEvent('onclick', OnClick);

    // Attach to the onviewchange event.
    ImgNav.AttachEvent('onviewchange', OnViewChange);

    // Attach to the onedgedetect event.
    ImgNav.AttachEvent('onedgedetect', OnEdgeDetect);

    // Attach to the navigate fail event.
    ImgNav.AttachEvent("onnavigatefail", OnNavigateFail);

    // Attach to the resize event.
    //ImgNav.AttachEvent("onresize", OnResize);

    // Attach to the edge detect event.
    ImgNav.AttachEvent("onedgedetect", OnEdgeDetect);

    // Attach to the onstartmeasurement event. (Optional)   
    ImgNav.AttachEvent('onstartmeasurement', OnStartMeasurement);

    // Attach to the onendmeasurement event. (Required)   
    ImgNav.AttachEvent('onendmeasurement', OnEndMeasurement);

    // Enable Auto Navigation.
    ImgNav.SetAutoNavigate(true);

    document.getElementById("ImageViewer").style.height = "1px";
}

function pictometryResize(e) {
    //alert("resize");
    var div_width = parseInt(document.getElementById("divPictometry").style.width.replace('px', ''));
    var div_height = parseInt(document.getElementById("divPictometry").style.height.replace('px', ''));

    document.getElementById("ImageViewer").style.height = div_height - 48 + 'px';
    document.getElementById("ImageViewer").style.width = div_width + 'px';

    ImgNav.SetViewerSize(div_width, div_height - 48);
}

function setOneX() {
    var div_width = 400;
    var div_height = 400;

    document.getElementById("divPictometry").style.width = div_width + 'px';
    document.getElementById("divPictometry").style.height = div_height + 'px';

    document.getElementById("ImageViewer").style.height = div_height - 48 + 'px';
    document.getElementById("ImageViewer").style.width = div_width + 'px';

//    document.getElementById("tbl_pict_tb").width = div_width + 'px';
//    document.getElementById("pict_toolbar").style.width = div_width + 'px';

    ImgNav.SetViewerSize(div_width, div_height - 48);
}

function setTwoX() {
    var div_width = 800;
    var div_height = 800;

    document.getElementById("divPictometry").style.width = div_width + 'px';
    document.getElementById("divPictometry").style.height = div_height + 'px';

    document.getElementById("ImageViewer").style.height = div_height - 48 + 'px';
    document.getElementById("ImageViewer").style.width = div_width + 'px';

//    document.getElementById("tbl_pict_tb").width = div_width + 'px';
//    document.getElementById("pict_toolbar").style.width = div_width + 'px';

    ImgNav.SetViewerSize(div_width, div_height - 48);
}

function showPictometry() {
    try {
        dojo.byId("divPictometry").className = "myshow";
        document.getElementById("ImageViewer").className = "myshow";
        document.getElementById("ImageViewer").style.height = "352px";
        bringToFront("divPictometry");
    }
    catch (err) {
        errorWin(err.description, "showPictometry");
    }
}

function hidePictometry() {
    try {
        dojo.byId("divPictometry").className = "myhide";
        document.getElementById("ImageViewer").className = "myhide";
        document.getElementById("ImageViewer").style.height = "1px";
        clearPictometryGraphic();
        clearMeasurements();
        navToolbar.activate(esri.toolbars.Navigation.PAN);
        makeIconActive(document.getElementById("pan"));
        map.enablePan();
        activeTool = document.getElementById("pan").id;
    }
    catch (err) {
        errorWin(err.description, "hidePictometry");
    }
}

function displayPictometry(evt) {
    if (activeTool == "pictometry") {
        clearPictometryGraphic();
        var point = evt.mapPoint;
        var symbol = new esri.symbol.PictureMarkerSymbol();
        symbol.height = 36;
        symbol.width = 36;
        symbol.url = "images/picNorth.png";
        var infoTemplate = new esri.InfoTemplate();
        infoTemplate.title = "Pictometry";
        var graphic = new esri.Graphic(point, symbol);
        graphic.setInfoTemplate(infoTemplate);
        map.graphics.add(graphic);
        if (refScale_baseMap == 4326) {
            showMap(point.x, point.y);
        }
        else {
            var outSR = new esri.SpatialReference({ wkid: 4326 });
            geometryService.project([graphic], outSR, function(features) {
                pt = features[0].geometry;
                showMap(pt.x, pt.y);
            });
        }
    }
}

function setViewGraphic(fle) {
    try {
        var graphics = map.graphics.graphics;
        var graphic;
        var j = 1;
        for (var i = 0, il = graphics.length; i < il; i++) {
            graphic = graphics[i];
            var title = graphic.getTitle();
            if (title == "Pictometry") {
                var symbol = new esri.symbol.PictureMarkerSymbol();
                symbol.height = 36;
                symbol.width = 36;
                symbol.url = "images/" + fle + ".png";
                graphic.setSymbol(symbol);
            }
        }
    }
    catch (err) {
        errorWin(err.description, "setViewGraphic");
    }
}

function clearPictometryGraphic() {
    try {
        var graphics = map.graphics.graphics;
        var graphic;
        var j = 1;
        for (var i = 0, il = graphics.length; i < il; i++) {
            graphic = graphics[i];
            var title = graphic.getTitle();
            if (title == "Pictometry") {
                map.graphics.remove(graphic);
            }
        }
    }
    catch (err) {
        errorWin(err.description, "clearPictometryGraphics");
    }
}

// On Start Measurement handler. (Optional)   
function OnStartMeasurement(evt) {
    //alert("Start Measurement");   
}

// On End Measurement handler. (Required)   
function OnEndMeasurement(evt) {
    // Call the Image Navigator Measure method with callback.   
    ImgNav.Measure(MeasurementCB);
}

function MeasurementCB(resp) {
    var mesg;

    // Status of 0 indicates a good measurement.
    if (resp.status == 0) {
        // The tool field indicates the type of measurement.
        switch (resp.tool) {
            case Pol.VI.ImageTools.Distance:
                mesg = resp.value + " " + resp.unit;
                break;

            case Pol.VI.ImageTools.Height:
                mesg = resp.value + " " + resp.unit;
                break;

            case Pol.VI.ImageTools.Location:
                mesg = resp.latitude + ", " + resp.longitude + " " + resp.unit;
                showMap(resp.longitude, resp.latitude);
                resetPictometryMarker(resp.longitude, resp.latitude);
                pict_makeIconActive(document.getElementById("pict_pan"));
                ImgNav.SetImageTool(Pol.VI.ImageTools.NoTool);
                document.getElementById("picImage").src = "images/picNavigation_north.png";
                return;

            case Pol.VI.ImageTools.Area:
                mesg = resp.value + " " + resp.unit;
                break;

            case Pol.VI.ImageTools.Elevation:
                //
                // When a change in elevation measurement is taken, the distance (run) field contains the
                // linear distance from start to end. This can be used with the change in elevation
                // value (rise) to compute a slope (rise/run).
                //
                if (resp.distance > 0.0) {
                    var slope = Math.atan(resp.value / resp.distance) * (180 / Math.PI);

                    mesg = "Rise: " + resp.value + " " + resp.unit +
						   	   " Run: " + resp.distance +
							   " Slope: " + slope.toFixed(2) + " Degrees";
                }
                else {
                    mesg = resp.value + " " + resp.unit;
                }
                break;

            case Pol.VI.ImageTools.Bearing:
                mesg = resp.value + " " + resp.unit;
                break;

            case Pol.VI.ImageTools.Pitch:
                mesg = "Roof Area: " + resp.area.value + " " + resp.area.unit;
                mesg += "\nEave Height: " + resp.eave.value + " " + resp.eave.unit;
                mesg += "\nPeak Height: " + resp.peak.value + " " + resp.peak.unit;
                mesg += "\nRoof Angle: " + resp.angle.value + " " + resp.angle.unit;
                mesg += "\nRoof Pitch: " + resp.pitch.value;
                break;

            default:
                mesg = "Unknown measurment type.";
                break;
        }
    }
    else {
        mesg = "Bad Measurement";
    }

    // Display the measurement.
    alert(mesg);
}

function resetPictometryMarker(lon,lat) {
    clearPictometryGraphic();
    var point = new esri.geometry.Point(lon, lat, new esri.SpatialReference({ wkid: 4326 }))
    var symbol = new esri.symbol.PictureMarkerSymbol();
    symbol.height = 36;
    symbol.width = 36;
    symbol.url = "images/picNorth.png";
    var infoTemplate = new esri.InfoTemplate();
    infoTemplate.title = "Pictometry";
    var graphic = new esri.Graphic(point, symbol);
//    if (refScale_baseMap == 4326) {
//        
//    }
//    else {
//        var outSR = new esri.SpatialReference({ wkid: parseInt(refScale_baseMap)});
//        geometryService.project([graphic], outSR, function(features) {
//            pt = features[0].geometry;
//            showMap(pt.x, pt.y);
//        });
//    }
    graphic.setInfoTemplate(infoTemplate);
    map.graphics.add(graphic);
}

function setMeasureDistance() {
    ImgNav.SetImageTool(Pol.VI.ImageTools.Distance);
}

function setMeasureHeight() {
    ImgNav.SetImageTool(Pol.VI.ImageTools.Height);
}

function setLocation() {
    ImgNav.SetImageTool(Pol.VI.ImageTools.Location);
}

function setNoTool() {
    ImgNav.SetImageTool(Pol.VI.ImageTools.NoTool);
}

function clearMeasurements() {
    ImgNav.ClearMeasurement();
    ImgNav.SetImageTool(Pol.VI.ImageTools.NoTool);
}

function SearchCallback(resp) {
    // A 0 status indicates the search succeeded.   
    if (resp.status == 0) {
        // Find the first available oblique image.   
        var view = ImgNav.FindFirstOblique();

        // Set the view.   
        ImgNav.SetView(view.level, view.type, view.orientation);
    }
    else {
        alert("Search Failed: " + resp.reason);
    }
}

function showMap(x, y) {
    // Location coordinates.
    latitude = y;
    longitude = x;

    if (defaultmarker != null) { ImgNav.RemoveOverlay(defaultmarker) }

    // Perform a Search.
    ImgNav.Search(latitude, longitude, SearchCallback);

    // Create a default marker.
    defaultmarker = new Pol.VI.Marker(new Pol.VI.LatLng(latitude, longitude));

    // Attach a callback for click events.
    //ImgNav.AttachEvent('onclick', OnMarkerClick, defaultmarker);

    // Add marker to the overlay manager.
    ImgNav.AddOverlay(defaultmarker);

    // Render it.
    ImgNav.RenderOverlay();

    document.getElementById("picImage").src = "images/picNavigation_north.png";
}

function OnClick(evt) {
    //alert("Mouse: " + evt.mouse.x + ',' + evt.mouse.y + " Image: " + evt.image.x + ',' + evt.image.y);
    //ImgNav.SetCenter(evt.image.x,evt.image.y);
}

function zoomIn(evt) {
    ImgNav.SetScale(ImgNav.GetScale() * 1.5);
}

function zoomOut(evt) {
    ImgNav.SetScale(ImgNav.GetScale() * 0.5);
}

function setNorth(evt) {
    ImgNav.SetOrientation("N");
    document.getElementById("picImage").src = "images/picNavigation_north.png";
    setViewGraphic("picNorth");
}

function setSouth(evt) {
    ImgNav.SetOrientation("S");
    document.getElementById("picImage").src = "images/picNavigation_south.png";
    setViewGraphic("picSouth");
}

function setEast(evt) {
    ImgNav.SetOrientation("E");
    document.getElementById("picImage").src = "images/picNavigation_east.png";
    setViewGraphic("picEast");
}

function setWest(evt) {
    ImgNav.SetOrientation("W");
    document.getElementById("picImage").src = "images/picNavigation_west.png";
    setViewGraphic("picWest");
}

function OnViewChange(evt) {
    //alert("Level: " + evt.view.level + " Type: " + evt.view.type + " Orientation: " + evt.view.orientation + " Scale: " + evt.scale);
}

function OnEdgeDetect(evt) {
    alert("Status: " + evt.status + " Reason: " + evt.reason);
}

function OnNavigateFail(evt) {
    alert("Navigation Failed: " + evt.reason);
}

function OnEdgeDetect(evt) {
    ImgNav.Navigate();
}

function toggleWindow() {
    var ele = document.getElementById("ImageViewer");

    if (ele.style.display == "block") {
        ele.style.display = "none";
    }
    else {
        ele.style.display = "block";
    }
}

function pict_makeIconActive(elm) {
    try {
        if (activeTool.length > 0) {
            var className = pict_activeTool + "IconActive";
            var repClassName = pict_activeTool + "Icon";
            var btnNode = dojo.byId('' + pict_activeTool);
            dojo.removeClass(btnNode.firstChild, className);
            dojo.addClass(btnNode.firstChild, repClassName);
        }

        if (tb_pictometry != null) {
            tb_pictometry.deactivate();
        }

        var className = elm.id + "Icon";
        var repClassName = elm.id + "IconActive";
        var btnNode = dojo.byId('' + elm.id);
        dojo.removeClass(btnNode.firstChild, className);
        dojo.addClass(btnNode.firstChild, repClassName);
        pict_activeTool = elm.id;

        var node = dojo.byId(elm.id);
        node.blur();
    }
    catch (err) {
        errorWin(err.description, "pict_makeIconActive");
    }
}
