﻿//Handle prev and next entents on the map

//variable for resize map timer
var resizeTimer;

//variables for centering busy image
var busyWidth = 120;
var busyHeight = 24;

//variable for holding event points
var g_evt;

//variable to hold active map tool.  this will allow a single map click event
//to spawn different process based on the current active map tool
var g_sActiveTool = "";

//variables for handling the left panel
var g_sLeftPaneState = "OPEN";
var g_nLeftPaneWidth = 300;

//variable to flag when slider labels have been loaded
var g_bScalesLoaded = false;

function browserCheck() {
    //debugger;
    //there seems to be a bug in IE6 loading the maps correctly
    //however a simple alert box will get around the problem
    //check for the browser - if IE6 notify the user and go on
    var browser=navigator.appName;
    if (browser=="Microsoft Internet Explorer") {
        if (getMSIE_Version() == 6) {
            alert("Internet Explorer 6 is not fully supported.  However, most of the site should function properly.  If possible consider upgrading to IE7.");
        }
    } else {
        alert("Internet Explorer 7 & up are the only fully supported browsers.");
    }
}

// This function returns Internet Explorer's major version number,
// or 0 for others. It works by finding the "MSIE " string and
// extracting the version number following the space, up to the decimal
// point, ignoring the minor version number
function getMSIE_Version()
{
  var ua = window.navigator.userAgent
  var msie = ua.indexOf ( "MSIE " )

  if ( msie > 0 )      // If Internet Explorer, return version number
     return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
  else                 // If another browser, return 0
     return 0
}

//handle window resizing
function resizeMap() {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
        try {
            map.resize();
            map.reposition();
        } catch(err) {
            //do nothing at this point
            //debugger;
            var err1 = err;
        }
        //dojo.byId("bcMain").refresh();
        //var contentHeight = parseInt(dojo.byId("infoPanel").style.pixelHeight);
        //dojo.byId("acSearchResults").style.height = parseInt(dojo.byId("leftPane").style.pixelHeight) - contentHeight - 2;
    }, 800);
}

function toggleLeft() {
    var pane = dojo.byId("leftPane");
    if (g_sLeftPaneState == 'OPEN') {
        dojo.byId("leftPane").style.width = 0;
        dojo.byId("mainTabContainer").style.visibility = "hidden";
        dojo.byId("mainTabContainer").style.display = "none";
        dojo.byId("imgToggleLeft").src = "images/doubleright.png";

        //reset the left pane open/closed flag
        g_sLeftPaneState = 'CLOSED';
    } else {
        dojo.byId("leftPane").style.width = g_nLeftPaneWidth;
        dojo.byId("mainTabContainer").style.visibility = "visible";
        dojo.byId("mainTabContainer").style.display = "block";

        //reset the left pane open/closed flag
        g_sLeftPaneState = 'OPEN';
        dojo.byId("imgToggleLeft").src = "images/doubleleft.png";
    }

    //force container to resize
    dijit.byId("bcMain").layout();
    dijit.byId("bcMain").resize();   
    resizeMap();
}

function processMapClick(evt) {    
    //switch based on the current active map tool
    var activeMapTool = g_sActiveTool.toUpperCase();
    switch (activeMapTool) {
        case 'PARCELIDENTIFY':
            parcelIdentify(evt);
            break;
        case 'PICTUREVIEW':
            showPictureView(evt);
            break;
    }  
}

function extentHistoryChangeHandler() {
    dijit.byId("zoomprev").disabled = navToolbar.isFirstExtent();
    dijit.byId("zoomnext").disabled = navToolbar.isLastExtent();
}

//show the coordinates on the map
function showCoordinates(evt) {
    //get mapPoint from event
    var mp = evt.mapPoint;
    
    //display mouse coordinates in the coordInfo pane
    dojo.byId("coordInfo").innerHTML = " &copy; KGIS 2012  -  E" + Math.round(mp.x) + ", " + "N" + Math.round(mp.y);
}    

function setTab(tabName) {
    //first make sure the left panel is open
    if (g_sLeftPaneState.toUpperCase() == "CLOSED")
        toggleLeft;
        
    dijit.byId('mainTabContainer').selectChild(dijit.byId(tabName));
}

function showBusy() {
    //debugger;
    var x = document.getElementById('busyIndicator');
    var w = parseInt(dojo.byId("centerPanel").style.pixelWidth);  //had to use the centerPanel for width - mappane width was missing????
    var h = parseInt(dojo.byId("mapPane").style.pixelHeight);

    //calculate the position for the image
    var topPos = ((h / 2) - (Math.floor(busyHeight / 2))).toString() + "px";
    var leftPos = ((w / 2) - (Math.floor(busyWidth / 2))).toString() + "px";
    
    x.style.left = leftPos;
    x.style.top = topPos;
    x.style.visibility = "visible";
    x.style.display = "block";
}

function hideBusy() {
    var x = document.getElementById('busyIndicator');
    x.style.visibility = "hidden";
    x.style.display = "none";
}

function showBusyDetails() {
    var x = document.getElementById('imgBusySearchingDetails');
    if ((x != null) && (typeof(x)!='undefined')) {
        x.style.visibility = "visible";
        x.style.display = "block";
    }
}

function hideBusyDetails() {
    var x = document.getElementById('imgBusySearchingDetails');
    if ((x != null) && (typeof(x)!='undefined')) {
        x.style.visibility = "hidden";
        x.style.display = "none";
    }
}

function showBusyResults() {
    var x = document.getElementById('imgBusySearchingResults');
    if ((x != null) && (typeof(x)!='undefined')) {
        x.style.visibility = "visible";
        x.style.display = "block";
    }
}

function hideBusyResults() {
    var x = document.getElementById('imgBusySearchingResults');
    if ((x != null) && (typeof(x)!='undefined')) {
        x.style.visibility = "hidden";
        x.style.display = "none";
    }
}

function clearDetails() {
    //get the details pane and show the data
    var detailsPane = dojo.byId("cpDetails");
    detailsPane.innerHTML = "";    
}

function getLayerID(mapLayerName) {
    var layerID = -1;
    
    for(var j = 0; j < map.layerIds.length; j++) {
        var layer = map.getLayer(map.layerIds[j]);
        if (layer.id == mapLayerName) {
            layerID = j;
            j = map.layerIds.length;
        }
    }
    return layerID;        
}

function getLayerIDFromMapDoc(mapLayerName, layerNameInMapDoc) {
    var layerID = -1;
    for(var j = 0; j <= map.layerIds.length - 1; j++) {
        var layer = map.getLayer(map.layerIds[j]);
        if (layer.id == mapLayerName) {
            var mapDocLayers = layer.layerInfos;
            for (var n = 0; n <= mapDocLayers.length - 1; n++) {
                if (mapDocLayers[n].name.toUpperCase() == layerNameInMapDoc.toUpperCase()) {
                    layerID = n;
                    n = mapDocLayers.length;
                }
            }
            j = map.layerIds.length;
        }
    }
    return layerID;        
}

function launchAdvancedMap() {
    var xMin = map.extent.xmin;
    var yMin = map.extent.ymin;
    var xMax = map.extent.xmax;
    var yMax = map.extent.ymax;
    var sCoords = xMin.toString() + ":" + yMin.toString() + ":" + xMax.toString() + ":" + yMax.toString();
    
    //var params = {"value":'"' + sCoords + '"'}
    var params = (gTheme + "area=" + sCoords);
    dojo.xhrGet(
    {
        url: "./wsSearches.asmx/GetEncryptedValue",
        handleAs: "json",
        contentType: "application/json; charset=utf-8",
        content: params,
        load: launchMap,
        error: function(error,args){
            console.warn("error!",error);
        }
    });            
}

// INTERNAL WEBSITES - MY KGIS LITE
//
//function launchMap(results) {
//  params = results;
//            if (g_sLaunchApp == "KnoxNetWhere")
//            { 
//            //var coords = dojo.fromJson(results);
//                var sURL = KnoxNetWhere_LaunchPage + "?maptheme=" + results; 
//                    window.open(sURL);
//            } else if (g_sLaunchApp == "MPCCaseAgenda"){
//            //MPCCaseAgenda_LaunchPage
//            //var coords = dojo.fromJson(results);
//                var sURL = MPCCaseAgenda_LaunchPage + "?maptheme=" + results; 
//                    window.open(sURL);
//            }
//}

// PUBLIC WEBSITES - KGIS LITE
//
//added by jeb for MPC Cases
function launchMap(results) {
    //var coords = dojo.fromJson(results);
    var sURL = MPCCases_LaunchPage + "?coords=" + results;            
    window.open(sURL);
}

function updateScaleBar(a, b, c, d) {
    //debugger;
    //alert("zoomEnd " + d.toString());
    dojo.byId("scaleBarImage").src = "images/Scalebars/" + d.toString() + ".png"
}

function setSliderLabels() {  
    var layer = map.getLayer(scaleBase);
    var t = ""
    var labels = [];
    var lods = layer.tileInfo.lods;
    for (var i=0, il=lods.length; i<il; i++) {
        if ((lods[i].scale / 12) > 5000) {
            t = lods[i].scale / 12 / 5280;
            labels[i] = t + "m"
        } else {
            t = lods[i].scale / 12;
            labels[i] = t + "ft"
        }
    }

    esriConfig.defaults.map.sliderLabel = {
        tick: 3,
        labels: labels,
        style: "width: 2em; font-family: Verdana; font-size: 85%; color: #000; padding-left: 2px;"
    };        
}

function removeMe(obj) {
    var ctl = dijit.byId(obj);
    ctl.destroyRecursive();
}

function printMap() {
    var title = document.getElementById('txtPrintTitle').value;
    var subTitle = document.getElementById('txtPrintSubtitle').value;
    var notes = document.getElementById('txtPrintNotes').value;
    var env = new esri.geometry.Extent(map.Extent);
    var centerPnt = new esri.geometry.Point(env.getCenter);
    var scale, level;
    
    //determine if we have a cache map or dynamic map
    if (map.getLevel() < 0) {
        //pure dynamic map
        level = -1
        alert("dynamic maps are not supported at this time.");
    } else {
        
//        var tileInfo = portlandParcels.tileInfo;
//        var scales = "";
//        for (var j=0, jl=tileInfo.lods.length; j<jl; j++) {
//          var level = tileInfo.lods[j].level;
//          var scale = tileInfo.lods[j].scale;
//          var resolution = tileInfo.lods[j].resolution;
        var myMap = map;
        var mapLevel = map.getLevel();
        //var myLayer = map.getLayer(mapLevel);
        var myLods = map.tileInfo.height();
        var mapScale = map.tileInfo.lod[mapLevel].scale()
    }
        
       
    
    var mapScale = getMapScale();
    
    
    
    g_activeTheme;
    printPageURL;
}

function getMapScale() {
    //determine if we have a tiled map service to get a level from
    var haveTiledMap = false;
    
    //find the incoming theme
    for (i=0, lCount=themes.length; i<lCount; i++) {
        var thisTheme = themes[i];
        if (thisTheme.themeID == g_activeTheme) {
            //found the correct theme now show the layers
            var myLayers = thisTheme.mapsOn.split(",");
            for (n=0; n < myLayers.length; n++) {
                var layer = map.getLayer(dojo.trim(myLayers[n]));

                if (layer.mapType == 'tiled') haveTiledMap = true;
            }
        }
    }

    //if we have a tiled map - get the current map level
    if (haveTiledMap) {
        var mapLevel = map.getLevel();
        
        var mapScale = tileInfo.lods[mapLevel].scale()
    
    } else {
        return -1;
    }
}

