/*
COPYRIGHT 1995-2003 ESRI

TRADE SECRETS: ESRI PROPRIETARY AND CONFIDENTIAL
Unpublished material - all rights reserved under the 
Copyright Laws of the United States.

For additional information, contact:
Environmental Systems Research Institute, Inc.
Attn: Contracts Dept
380 New York Street
Redlands, California, USA 92373


email: contracts@esri.com
*/


// set path for loading banner image
loadBannerPath = "images";
var displayLoading = false;
var sendDelay = 100;
var currentEventArg = "";

activeControl = "Map1";
var esriCurrentResponseCount = 0;
var esriLastResponseCount = -1;
var postBackInterval = null;

var clientPostbackEventArgs = new Array();
// add additional control non-tool event args, if necessary
clientPostbackEventArgs[0] = "resize";
clientPostbackEventArgs[1] = "scrollwheelzoom";
clientPostbackEventArgs[2] = "dragimage";
clientPostbackEventArgs[3] = "drawtile";
clientPostbackEventArgs[4] = "getextent";
clientPostbackEventArgs[5] = "newextent";
clientPostbackEventArgs[6] = "dragrectangle";
clientPostbackEventArgs[7] = "changelevel";
clientPostbackEventArgs[8] = "point";
clientPostbackEventArgs[9] = "line";
clientPostbackEventArgs[10] = "polyline";
clientPostbackEventArgs[11] = "polygon";
clientPostbackEventArgs[12] = "circle";
clientPostbackEventArgs[13] = "oval";


function postBack(control, eventArg, responseFunction) {
	//eventArg = eventArg.toLowerCase();
	currentEventArg = eventArg;	
	var map2 = Maps[control];
	var ov2 = Overviews[control];
	var page2 = Pages[control];
	var toolbar2 = Toolbars[control];
	var toc2 = Tocs[control];
	var forcePostBack  = false;
	activeControl = control;
	var mode = "";
	var f;
	if (map2!=null) {
		// map request
		f = map2.document.forms[docFormID];
		f.minx.value = map2.xMin;
		f.miny.value = map2.yMin;
		f.maxx.value = map2.xMax;
		f.maxy.value = map2.yMax;
		f.coords.value = map2.coords;
		var postbackEvents = map2.forcePostBackEvent.split(",");
		for (var h=0;h<clientPostbackEventArgs.length;h++)
		{	// Check if eventArg is a PostBack event arg.
			if (eventArg.toLowerCase()==clientPostbackEventArgs[h])
			{	//check postback event
				for (var i=0;i<postbackEvents.length;i++)
				{	// Check if Postback is for Map Mode.
					if (map2.mode==postbackEvents[i])
						forcePostBack = true;
				}
			}
		}
		f.elements[control + "_mode"].value = map2.mode;
		mode = map2.mode;
		map2.mode = map2.tempMode;
		map2.actionType = map2.tempAction;
		map2.cursor = map2.tempCursor;
		if (map2.callBackFunctionString!=null) callBackFunctionString = map2.callBackFunctionString;
	} else if (page2!=null) {
		// page request
		f = page2.document.forms[docFormID];
		f.minx.value = page2.xMin;
		f.miny.value = page2.yMin;
		f.maxx.value = page2.xMax;
		f.maxy.value = page2.yMax;
		f.coords.value = page2.coords;
		var supportpostbackEvents = page2.toolsSupportingClientPostBack.split(",");
		for (var j=0;j<clientPostbackEventArgs.length;j++)
		{	// Check if eventArg is a PostBack event arg.
			if (eventArg.toLowerCase()==clientPostbackEventArgs[j])
			{	//check postback event
				for (var k=0;k<supportpostbackEvents.length;k++)
				{	// Check if Postback is for Page Mode.
					if (page2.mode==supportpostbackEvents[k])
						forcePostBack = true;
				}
			}
		}
		f.elements[control + "_mode"].value = page2.mode;
		mode = page2.mode;
		page2.mode = page2.tempMode;
		page2.actionType = page2.tempAction;
		page2.cursor = page2.tempCursor;
		if (page2.callBackFunctionString!=null) callBackFunctionString = page2.callBackFunctionString;
	} else if (ov2!=null) {
		// overview request
		f = ov2.document.forms[docFormID];
		f.centerx.value = ov2.centerX;
		f.centery.value = ov2.centerY;
        if (eventArg==ov2.forcePostBackEvent)
            forcePostBack = true;
		if (ov2.callBackFunctionString!=null) callBackFunctionString = ov2.callBackFunctionString;
	}  else if (toolbar2!=null) {
		f = toolbar2.document.forms[docFormID];
		//find out if item supports client postback
		// ToDo: set up for forced postback
//		if (toolbar2.enableClientPostBack &&
//			(isForcePostBackTool(eventArg, toolbar2.buttonsSupportingClientPostBack)
//		  || eventArg == "resize" || eventArg == "drawtile") )
//			forcePostBack = true;
		if ((toolbar2.items[currentEventArg]!=null) && (toolbar2.items[currentEventArg].selectAutoPostBack))
			forcePostBack = true;
		if (toolbar2.callBackFunctionString!=null) callBackFunctionString = toolbar2.callBackFunctionString;
	} 	else if (toc2 !=null) {
		f = toc2.document.forms[docFormID];
		//enableClientPostBack = toc2.enableClientPostBack;
		if (toc2.callBackFunctionString!=null) callBackFunctionString = toc2.callBackFunctionString;
	} else {
		alert(control + " is not available or does not exist.");
		return false;
	}
	if (f.elements["PostBackMode"]!=null) f.PostBackMode.value = f.elements[control+"_mode"].value;
	//alert("forcePostBack=" + forcePostBack);
	if (forcePostBack) {
		__doPostBack(control, eventArg);
	} else {
		// send to ClientPostBack
		var querystring = createClientPostBackQueryString(control, eventArg);
		clientPostBack(querystring);
	}
	
	map2=null;
	page2=null;
	ov2=null;
	toolbar2=null;
	toc2=null;
}

function clientPostBack(querystring) {
	
	var argument = querystring;
	var context = activeControl + "," + currentEventArg;
	eval(callBackFunctionString);
    // Debug stuff to be removed, or at least commented out
    if (checkForFormElement(document, 0, "MapDebugBox")) document.forms[0].MapDebugBox.value += "PostBack Request: " + querystring + "\n";
}

function delayedClientPostBack(argument, context, callbackString) {
    if (commonCallbackFree) {
        eval(callBackString);
// Debug stuff to be removed, or at least commented out
if (checkForFormElement(document, 0, "MapDebugBox")) document.forms[0].MapDebugBox.value += "PostBack Request: " + querystring + "\n";
        window.clearInterval(postBackInterval);
        commonCallbackFree = false;
    }

}

function postBackError(argument, context) {
	alert("An unhandled exception has occurred:\n" + argument);
}


function processCallbackResult(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 resourceLimits = (actions[4]==null) ? "" : actions[4];
		            if (actions.length>3)
		                 window.setTimeout("Maps['" + controlID + "'].clearLevelGrid('" + actions[3] + "','" + resourceLimits + "');", 1);
		            else   
		                window.setTimeout("Maps['" + controlID + "'].clearLevelGrid(null,'" + resourceLimits + "');", 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=="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;
		}
	}
}

function createClientPostBackQueryString(control, eventArg) {
	var s = "ControlID=" + control;
	s += "&EventArg=" + eventArg;
	var map2 = map;
	var ov2 = ov;
	var page2 = page;
	var map2 = Maps[control];
	var ov2 = Overviews[control];
	var page2 = Pages[control];
	var toolbar2 = Toolbars[control];
	var toc2 = Tocs[control];
	var f;
	if (map2!=null) {
	  f = map2.document.forms[docFormID];
		s += "&ControlType=Map&PageID=" + map2.pageID;
	} else if (ov2!=null) {
	  f = ov2.document.forms[docFormID];
		s += "&ControlType=OverviewMap&PageID=" + ov2.pageID;
	} else if (page2!=null) {
	  f = page2.document.forms[docFormID];
		s += "&ControlType=PageLayout&PageID=" + page2.pageID;
		s += "&dataframeIndex=" + page2.dataframeIndex;
	} else if (toolbar2!=null) {
	  f = toolbar2.document.forms[docFormID];
		s += "&ControlType=Toolbar&PageID=" + toolbar2.pageID;
	} else if (toc2!=null) {
	  f = toc2.document.forms[docFormID];
		s += "&ControlType=Toc&PageID=" + toc2.pageID;
	}
	
	if (f != null)
	{
	  var fieldList = f.elements["ESRIWebADFHiddenFields"].value;
	  var fields = fieldList.split(',');
	  var value;
	  for (var i= 0; i < fields.length; ++i)
	  {
	    if (f.elements[fields[i]] !=null)
	    {
	      value = f.elements[fields[i]].value;
	      if (value != null)
	        s += "&" + fields[i] + "=" + value;
	    }
	  }
	}
	
	map2=null;
	page2=null;
	ov2=null;
	toolbar2=null;
	toc2=null;
	//alert(s);
	return s;
}

// checks if tool is available for client postback
function isForcePostBackTool(tool,toolstring) {
	//alert("tool: " + tool + "\ntoolstring: " + toolstring);
	var hasIt = false;
	if (toolstring!=null && toolstring!="") {
		var toollist = toolstring.split(",");
		for (var i=0;i<toollist.length;i++) {
			if (toollist[i]==tool) {
				hasIt = true;
				break;
			}
		}
	}
	return hasIt;
}

function tocAutoLayerVisibility(e, tocID) {
	var o;
	if (isNav && e != null)
		o = e.target;
	else
    o = window.event.srcElement;
  if (o.tagName == 'INPUT' && o.type == 'checkbox' && o.name != null && o.name.indexOf('CheckBox') > -1)
	{
	    //alert(o.state);
        o.state = o.checked;
        var req = "EventArg=Toc&" + o.value + "&state=" + o.checked; 
        eval('CallServer_' + tocID + '(req,"");');
	}
}

function resizeContentsFunction(win){
    
	if (win.contentsObject!=null) {
		if (win.contentsObject.resize!=null) //map, overviewmap, pagelayout
			win.contentsObject.resize(win.width, win.height); 
	}
}

function checkForClientPostbackEventArgs(eventArg) {
	//retValue = false;
	for (var i=0;i<clientPostbackEventArgs.length;i++) {
		if (eventArg.toLowerCase().indexOf(clientPostbackEventArgs[i].toLowerCase())!=-1) return true;
	}
	return false;
}

