﻿// This is the JavaScript for setting up the Measure Tool and ID tool
var arcgisWebApp;
//May need next line
var isIE = (Sys.Browser.agent == Sys.Browser.InternetExplorer);

//Javascript timeout
var maximumLapseTime = 600;

function sleep(milliSeconds) {
    startTime = new Date().getTime(); // get the current time
    while (new Date().getTime() < startTime + milliSeconds); // hog cpu
}


function startUp() {

        //Allows updating of Map controls from non ADF async postback i.e. Updatepanel
        Sys.WebForms.PageRequestManager.getInstance().add_pageLoading(AsyncResponseHandler);        

        arcgisWebApp.MapId = "Map1";
        arcgisWebApp.map = $find(arcgisWebApp.MapId);
        map = arcgisWebApp.map;  //$find("Map1");
		
		//Allows the Linn county tax page to work right
		winRef = window.open('http://www.co.linn.or.us/propertywebquery/ExternalLogin.aspx', 'test', 'height=10,width=10,menubar=no')
        if (winRef == null || typeof (winRef) == "undefined")
            alert("Please allow popup windows for this site")
        else {
            sleep(3000)
            //setTimeout("closemap()",5000)
            winRef.close()
        }
        
        
        // because the toolbar is listed before the map control,
        //  make sure toolbar will be listening to changes in map extent
        // Putting the toolbar into a floating panel renamed it to FloatingPanel1_Toolbar1
        var toolbar = $find("FloatingPanel1_Toolbar1"); //$find("Toolbar1");
		if (map != null && toolbar!=null)
		{
		    map.remove_extentChanged(toolbar._toolbarExtentChangedHandler); // just in case it is already present
			map.add_extentChanged(toolbar._toolbarExtentChangedHandler);
			toolbar.add_onToolSelected(OnToolSelectHandler);
			//window.setTimeout("resetMapHistory();", 1500);
		}
		
	    // hide identify window when extent changes, especially when back or forward are clicked
		map.add_extentChanging(function() {if (arcgisIdentifyTool!=null) closeIdentifyPanel();} ); // for start of continuous panning or zoom animation
		map.add_extentChanged(function() {if (arcgisIdentifyTool!=null) closeIdentifyPanel();} );  // extent changes that do not trigger ExentChanging

        var ov = $find("OverviewMap1");
		if (ov!=null) {
            toggleOverviewMap();
        }

        //add handlers to respond to the expand and collapse events of the TOC panel
        $find("cpbPanel").add_expandComplete(expandHandler);
        $find("cpbPanel").add_collapseComplete(collapseHandler);

        //add handlers for mouseover and mouseout on the map for the maptips
        map.add_mouseMove(handleMouseMove);
        map.add_mouseOut(handleMouseOut);

        //add handler for page resizeing
        $addHandler(window, "resize", pageResizeHandler);
        //run the pageresize handler to make sure the map and toc are the correct size on initial load
        pageResizeHandler()
        //recenter the map after the map initially resizes
        var initialExtent = new ESRI.ADF.Geometries.Envelope(map._extent._xmin, map._extent._ymin, map._extent._xmax, map._extent._ymax);
        map.zoomToBox(initialExtent, false)
    }

    // Called whenever a response to a partial postback is processed on the client
    function AsyncResponseHandler(sender, args) {
        var dataItems = args.get_dataItems();
        if (dataItems['__Page'] != null)
            ESRI.ADF.System.processCallbackResult(dataItems['__Page']);
    }

    // Called whenever the browser window is resized to handle resizing the map and toc
    function pageResizeHandler() {
        newMapHeight = document.documentElement.clientHeight - 167
        newTOCHeight = document.documentElement.clientHeight - 422
        if (newMapHeight < 430) {
            newMapHeight = 430;
            newTOCHeight = 175;
        }
        var mapPanel = $get("Map_Panel");
        var tocPanel = $get("Toc_Panel")
        mapPanel.style.height = newMapHeight + "px"
        tocPanel.style.height = newTOCHeight + "px"
    }
//Functions to handle the expanding and collapsing of the TOC panel
function expandHandler(sender, args) {
    //CallServer("Expanded");
    map.refresh();
}

function collapseHandler(sender, args) {
    //CallServer("Collapsed");
    map.refresh();
}

//Required to allow callback from javascript
function ReceiveServerData(rValue) {

}

//Functions for maptips
var idTimer;
var PageX;
var PageY;


function handleMouseOut(sender, args) {
    clearTimeout(idTimer);
}

function handleMouseMove(sender, args) {
    var cboLayer = $get("cboMaptipLayers");
    if (cboLayer.value == "None") {
        return;
    }

    clearTimeout(idTimer);
    var popupDiv = $get("Popup");
    popupDiv.innerHTML = "";


    PageX = args.clientX + document.documentElement.scrollLeft;
    PageY = args.clientY + document.documentElement.scrollTop;

    var x = args.coordinate.coordinates[0];
    var y = args.coordinate.coordinates[1];
    idTimer = setTimeout("MapTip(" + x + ", " + y + ")", 500);
}

function MapTip(x, y) {
    var cboLayer = $get("cboMaptipLayers");
    if (cboLayer.value != "None") {
        PageMethods.MapTip(x, y, cboLayer.value, OnMaptipSucess, OnFail)
    }
}


function OnMaptipSucess(result, userContext, methodName) {
    var popupDiv = document.getElementById("Popup"); //$get("Popup");
    popupDiv.innerHTML = result;
    popupDiv.style.left = PageX + "px";
    popupDiv.style.top = (PageY + 10) + "px";
}

function OnFail(result, userContext, methodName) {
    alert("A problem has occured please restart your browser and try again")
}


    
//Function to open and close the overview map
function toggleOverviewMap() {
    var ovm = $find("OverviewMap1");
    var toolbarobj = $find("FloatingPanel1_Toolbar1"); //$find("Toolbar1");
    var toolbar = (toolbarobj != null) ? Toolbars["FloatingPanel1_Toolbar1"] : null; //? Toolbars[toolbarobj._uniqueID] : null;
	var imageTag = "FloatingPanel1_Toolbar1OverviewMapToggleImage";
    var toolbarItemName = "OverviewMapToggle"; 
    var showImage = "images/show-overview-map.png"; 
    var hideImage = "images/hide-overview-map.png";	
    var img = document.images[imageTag];
    if (ovm) {
        if(ovm.isVisible()) {
            ovm.hide();
            if (toolbar!=null) { 
                toolbar.items[toolbarItemName].selectedImage = showImage;
                toolbar.items[toolbarItemName].defaultImage = showImage;
                toolbar.items[toolbarItemName].hoverImage = showImage; 
                img.alt = "Show OverviewMap";
                img.title = "Show OverviewMap";
                switchImageSourceAndAlphaBlend(img,toolbar.items[toolbarItemName].defaultImage);  
            }   
        } else {
            ovm.show();
            if (toolbar!=null) {   
                toolbar.items[toolbarItemName].selectedImage = hideImage;
                toolbar.items[toolbarItemName].defaultImage = hideImage;
                toolbar.items[toolbarItemName].hoverImage = hideImage;  
                img.alt = "Hide OverviewMap";
                img.title = "Hide OverviewMap";
                switchImageSourceAndAlphaBlend(img,toolbar.items[toolbarItemName].defaultImage); 
            }
        } 
    }  
}

function GetElementRectangle(element) {
    var rect = null;
    if (isIE) 
        rect = element.getBoundingClientRect(); 
    else {
        var bounds = Sys.UI.DomElement.getBounds(element); 
        rect = {"left":bounds.x, "top":bounds.y, "right":bounds.x+bounds.width, "bottom":bounds.y+bounds.height};
    }
    return rect;   
}

function OnToolSelectHandler(sender, args) {
    if (args.name) {
        var mode = args.name;
        arcgisWebApp.currentMode = mode;
        if (mode!="Measure" && arcgisWebApp.lastMode=="Measure") closeMeasureToolbarTool();
        if (mode!="MapIdentify" && arcgisWebApp.lastMode=="MapIdentify") {
            if (arcgisIdentifyTool!=null) closeIdentifyPanel();
        } 
        arcgisWebApp.lastMode = mode;
    }
}

MyApp = function() {

    this.MapId = "Map1";
	this.map = null; 
	this.currentMode = "Pan";
	this.lastMode = "Pan";
}


arcgisWebApp = new MyApp();

function doPrint() {
    CallServer("GetVisibleLayers");
	PageMethods.GetPrintString(OnPrintStringSucess, OnPrintStringFail);
}

function OnPrintStringSucess(result, userContext, methodName) {
	if (result == "False") {
	alert("Please select an address before trying to print");
	}
	else {
		window.open(result, 'PrintWin');
	}
}

function OnPrintStringFail(result, userContext, methodName) {
	alert("A problem has occured please restart your browser and try again")
}

