﻿// DisplayMapIdentify.js

var identifyFilePath = "";
var identifyImageType = "png";

// Set up Identify tool
function MapIdentify(divid) {
    // Get the map and wait for the user to click on it.
    map = Maps[divid];
    MapPoint(map.controlName, "MapIdentify", false);
    map.divObject.onmousedown = MapIdClick;
}

// Event handler for Identify
function MapIdClick(e) {
    // The user has clicked on a location on the map.
    map.cursor = map.divObject.style.cursor;
	getXY(e);
	var box = calcElementPosition(map.containerDivId);
	zleft = mouseX - box.left;
	ztop = mouseY - box.top;

    // Open initial window
	// Note: Make sure 'newWindowName' stays the same as the 'windowName' in MapIdentify.cs
    var newWindowName = "identifyResultsWindow" + zleft + "_" + ztop;
    var pleaseWaitText = "Please wait while the identify results are being retrieved.  This may take a couple of minutes.";
    var newWindowHtml = "<div style=\"margin:0px 10px 0px 10px;\"><span style=\"font-family:Arial;font-size:12pt;\"><BR/><BR/>" + pleaseWaitText + "<BR/><BR/><img src=\"images/AjaxLoader.gif\">";
    if (!openIdentifyWindow("Identify Results", newWindowHtml, newWindowName))
    {
      // We couldn't open the new window (popup-blockers must be enabled) - so no reason to go on.
      return false;
    }
    window.status = pleaseWaitText;
    doHourglass();
	
	map.xMin=zleft;
	map.yMin=ztop;
	var div = document.getElementById("IdentifyLocation");
	if (div==null) {
	    addIdentifyLocation();
	}
	map.getTopLeftTile();
	
	
    var message = "ControlID=_map&ControlType=Map&EventArg=MapIdentify&Map1_mode=MapIdentify&minx=" + zleft + "&miny=" + ztop;
    var context = map.controlName;
    eval(map.identifyCallbackFunctionString);
	
    // Apparently we need to reset 'div' after the eval call
    div = document.getElementById("IdentifyLocation");
    // point is bottom center... 2 pixels up for shadow
    var cWidth = Math.floor(div.clientWidth / 2);
    var cHeight = div.clientHeight;
    if (cWidth==0) cWidth = 12;
    if (cHeight==0) cHeight = 29;
    var idLeft = zleft - parseInt(map.divObject.style.left) - cWidth;
    var idTop = ztop - parseInt(map.divObject.style.top) - cHeight + 2; // add two back for icon bottom
    window.setTimeout('moveLayer("IdentifyLocation", ' + idLeft + ', ' + idTop + '); showLayer("IdentifyLocation");', 0);
    map.mode = map.tempMode;
    map.actionType = map.tempAction;
    map.cursor = map.tempCursor;
    return false;
}

/* Opens a large window with the specified title and innerHTML. */
function openIdentifyWindow(title, innerHTML, newWindowName)
{
    var newWindow = window.open('',newWindowName,'height=700,width=1000,scrollbars=yes,resizable=yes,menubar=yes');
                
    if (newWindow == null)
    {
        alert("Cannot display new window. Check that popup blockers are disabled for this site.");
        
        // Just in case the alert doesn't work, also set the status bar text.
        window.status = "Cannot display new window. Check that popup blockers are disabled for this site.";
        
        return false;
    }
    else
    {
        // Note: Use write() instead of setting body.innerHTML.  Setting body.innerHTML doesn't render quotes correctly in Firefox.
        newWindow.document.write(innerHTML);
        
        // Make sure to set the title _after_ the write command; otherwise it'll be overwritten.
        newWindow.document.title = title;
        
        // Set the margin & padding to 0px.  This makes the header image go all the way to the edge of the screen as desired.
        newWindow.document.body.style.margin = "0px";
        newWindow.document.body.style.padding = "0px";
        
        newWindow.document.close();
        newWindow.focus();
        
        return true;
    }
}

// Adds the "IdentifyLocation" div to the page.
function addIdentifyLocation() {
    var content = '<div id="IdentifyLocation" style="position: absolute; left: 0px; top: 0px; visibility: hidden;">';
    if (isIE  && ieVersion < 7 && (identifyImageType.toLowerCase()=="png")) 
	    content += '<img src="' + identifyFilePath + 'images/Blank.gif" alt="" border="0"  hspace="0" vspace="0" style="filter:  progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'' + identifyFilePath + 'images/IdentifyMarker.png\');" />\n';
	else
	    content += '<img src="' + identifyFilePath + 'images/IdentifyMarker.png" alt="" border="0"  hspace="0" vspace="0" />\n';
    content += '</div>';
    map.overlayObject.insertAdjacentHTML("BeforeEnd", content);
}

// Note: This was copied from the ESRI code, in order to add the capability of opening the identify results in a new window.
function processCallbackResultNew(response, context) {
    esriLastResponseCount = esriCurrentResponseCount;
    esriCurrentResponseCount++;
    // Debug stuff to be removed, or at least commented out
    if (checkForFormElement(document, 0, "MapDebugBox")) document.forms[0].MapDebugBox.value += "PostBack Response: " + response + "\n";
	var controlName = "";    
	var contextArray = new Array();
	var map2 = null;
	var page2 = null;
	if (context!=null) {
	    contextArray = context.split(",");
	    if (contextArray.length>0)
	        controlName = contextArray[0];
	}
    if (response==null || response.length==0)
    {
        // check for end of map dragimage
       if (Maps[controlName]!=null && contextArray.length>1 && contextArray[1]=="DragImage") {
            //
            validResponse = true;
            map2 = Maps[controlName];
            window.setTimeout("Maps['" + controlName + "'].updateMapDiv2();", map2.mapDiv2UpdateDelay);
       } // check for end of page dragimage
       else if (Pages[controlName]!=null && contextArray.length>1 && contextArray[1]=="DragImage") {
            //
            validResponse = true;
            page2 = Pages[controlName];
            window.setTimeout("Pages['" + controlName + "'].createDivs();", Page2.pageDiv2UpdateDelay);
       } 
       else
        return;
    }
    
    commonCallbackFree = true;
	var ov2 = null;
	var pairs = response.split("^^^");
	var actions;
	var o;
	var action;
    var controlType = "";
	var controlID = "";
	var responseItem = "";
	var validResponse = false;
	for (var i=0;i<pairs.length;i++)
	{
		actions = pairs[i].split(":::");
		responseItem = pairs[i];
		if (responseItem==null || responseItem.length==0) 
		    continue;
		controlType = actions[0].toLowerCase();
		controlID = actions[1];
		action = actions[2].toLowerCase();
		switch (controlType) {
		    case "map":
		        map2 = Maps[controlID];
                if (action=="changelevel") {
		            validResponse = true;
		            var minCol = (actions[13]==null) ? 0 : actions[13];
		            var minRow = (actions[14]==null) ? 0 : actions[14];  
					var resourceLimits = (actions[15]==null) ? "" : actions[15];
					var resourceMapping = (actions[16]==null) ? "": actions[16];
		            window.setTimeout("Maps['" + controlID + "'].setUpLevelGrid(" + actions[3] + "," + actions[4] + "," + actions[5] + "," + actions[6] + "," + actions[7] + "," + actions[8] + "," + actions[9] + "," + actions[10] + "," + actions[11] + "," + actions[12] + "," + minCol + "," + minRow + ", '" + resourceLimits + "', '" + resourceMapping + "');", 1);
		        } 
		        else if (action=="shiftgrid") {
		            validResponse = true;
		            window.setTimeout("Maps['" + controlID + "'].shiftGrid(" + actions[3] + "," + actions[4] + "," + actions[5] + "," + actions[6]  + ");", 1);
		        }
		        else if (action=="gettiles") {
		            validResponse = true;
		            window.setTimeout("Maps['" + controlID + "'].updateView(true);", 1);
		        }
		        else if (action=="cleargrid") {
		            validResponse = true;
					var resourceLimits2 = (actions[4]==null) ? "" : actions[4];
		            if (actions.length>3)
		                 window.setTimeout("Maps['" + controlID + "'].clearLevelGrid('" + actions[3] + "','" + resourceLimits2 + "');", 1);
		            else   
		                window.setTimeout("Maps['" + controlID + "'].clearLevelGrid(null,'" + resourceLimits2 + "');", 1);
		        }
		        else if (action=="tileserverurl") {
		            validResponse = true;
		            if (actions[3].toLowerCase()=="null") actions[3] = "";
		            map2.tileServerUrl = actions[3];
		        }
		        else if (action=="serverextentupdated") {
		            validResponse = true;
		            if (map2.overviewId!="") {
		                var ov_id = map2.overviewId;
                        ov2 = Overviews[ov_id];
                        if (ov2!=null) window.setTimeout("Overviews['" + ov_id + "'].getAOIBox();", 1);
                        ov2 = null;
                    }
		        }
		        map2.divObject.style.cursor = map2.cursor;  
	            map2=null;
		        break;
		    case "page":
		        page2 = Pages[controlID];
            if (action=="changeExtent") {
		            validResponse = true;
		        } 
		        else if (action=="shiftgrid") {
		            validResponse = true;
		        }
		        else if (action=="serverextentupdated") {
		            validResponse = true;
		        }
		        else if (action=="updateimage") {
		            validResponse = true;
		            if (actions[3].toLowerCase()=="null") actions[3] = "";
		            updateImage(actions[3]);
		        }
		        page2.divObject.style.cursor = page2.cursor;
	            page2=null;
		        break;
		    case "overviewmap":
		        ov2 = Overviews[controlID];
		        if (action=="aoiextent") {
		            validResponse = true;
                    window.setTimeout("Overviews['" + controlID + "'].parseUpdateString('" + responseItem + "');",0);
                }
	            ov2=null;
		        break;
		        
		    case "maptips":
		        maptipString = escape(responseItem);
		        validResponse = true;		        
   	            window.setTimeout("MapTipCollections['" + controlID + "'].addMapTips('" + maptipString + "');", 1000);
		        break;
		        
		    case "taskresults":
	            if (action=="content")
	            {
	                if ((actions.length==6 && esriTaskResultsCancelledJobs[actions[4]]==null) || actions.length==4)
	                {
	                    validResponse = true;
		                o = document.getElementById(controlID);
		                if (o != null) o.outerHTML = actions[3];
		            }
		            else if (actions.length==6)
		            {
		                // remove node if the job was cancelled
		                validResponse=true;
                        window.setTimeout("TreeViewPlusObjects['" + controlID + "'].clearNode('" + actions[5] + "');",0);
                        return; // ignore the map.Refresh stuff.
		            }
		        }
		        if (action=="showcallout")
		        {
		            validResponse = true;
		            showCallout(actions[3],actions[4],actions[5],actions[6]);
		        }
		        break;
		        
		    case "task":
		        break;
		    case "magnifier":
		        mag2 = FloatingPanels[controlID];
		        mag3 = esriMagnifiers[controlID];
		        map2 = Maps[mag3.mapBuddyId];
		        if (action=="mapimage") 
		        {
		            validResponse = true;
                	var imgObj = document.getElementById(actions[3]);
                	if (imgObj!=null) 
                	{
                		imgObj.src = actions[4];
                		imgObj.style.visibility = "visible";
                		if (actions.length>5) 
                		{
                    		if (mag2!=null) mag2.extentString = actions[5];
                    		var magcoord0 = map2.setDecimalDelimiter(Math.round(map2.setDecimalDelimiter(actions[5],esriJavaScriptDecimalDelimiter)* 1000)/1000);
                    		var magcoord1 = map2.setDecimalDelimiter(Math.round(map2.setDecimalDelimiter(actions[6],esriJavaScriptDecimalDelimiter)* 1000)/1000);
                    		var magcoord2 = map2.setDecimalDelimiter(Math.round(map2.setDecimalDelimiter(actions[7],esriJavaScriptDecimalDelimiter)* 1000)/1000);
                    		var magcoord3 = map2.setDecimalDelimiter(Math.round(map2.setDecimalDelimiter(actions[8],esriJavaScriptDecimalDelimiter)* 1000)/1000);
                			extString = "Extent: " + magcoord0 + ", " + magcoord1 + ", " + magcoord2 + ", " + magcoord3;
                			imgObj.alt = extString;
                			imgObj.title = extString;
                		}
                	}
                	if (mag3!=null) {
                        if (mag3.magnifierAOI!=null)
                            mag3.magnifierAOI.style.visibility = "hidden";
                        if (mag3.magnifierCrosshair!=null)
                            mag3.magnifierCrosshair.style.visibility = "hidden";
                    }
		        }
		        break;
		    case "measure":
		        validResponse = true;
		        if (actions[2]=="addpoint" || actions[2]=="coordinates") {
		            if (m_measureDisplay!=null) {
			            var md = document.getElementById(m_measureDisplay);
			            if (md!=null) md.innerHTML = actions[3];
			        }
		        }
		        break;
		    default:
		        break;
		}
		if (!validResponse)
		{
            if (action=="content") {
		        // content...response: ///:::elementId:::content:::html_content ....///=any character as place holder to split triple colons
	            validResponse = true;
		        o = document.getElementById(actions[1]);
		        if (o != null)
		        {
                    o.outerHTML=actions[3];
		        }
	        }
	        else if (action=="newwindow") {
		        // Open up a new window to display the content.
		        // To parse the actions:
		        //      actions[0] == title
		        //      actions[1] == window name (unique identifier) - Must be string with no spaces.
		        //      actions[2] == "newwindow"
		        //      actions[3] == HTML content of new window
	            validResponse = true;
                
                openIdentifyWindow(actions[0], actions[3], actions[1]);
                window.status = "Identify results retrieved."
                undoHourglass();
	        }
            else if (action=="innercontent") {
		        // content...response: ///:::elementId:::content:::html_content ....///=any character as place holder to split triple colons
	            validResponse = true;
		        o = document.getElementById(actions[1]);
		        if (o != null)
		        {
                    o.innerHTML=actions[3];
		        }
	        }
	        else if (action=="image")
	        {
	            validResponse = true;
		        o = document.images[actions[1]];
		        if (o != null)
		        {
		            o.src = actions[3];
		        }
		        else alert (actions[1] + " was null");
	        } 		
	        else if (action=="javascript") {
	            // javascript... response: ///:::///:::javascript:::javascript_content ... ///=any character as place holder to split triple colons
	            validResponse = true;
		        eval(actions[3]);
	        }
	        else if(response.length>0)
	        {
	            alert(response + "\nContext: " + context);
	        }
		}
		if (validResponse)
		{
		    lastResponseReceivedTime=new Date();
		    validResponse=false;
		}
	}
}