// EMR JScript File

// initialize the string that holds web service feature data
var EMR_FEATURES_TEXT = '{}';
// initialize the object that holds web service feature data
var EMR_FEATURES = new Object();
var REPORT_FEATURES = new Object();

// initialize variables to hold active layer and resource values
var EMR_ACTIVE_LAYER_DIV_ID = '';
var EMR_ACTIVE_LAYER_ID = '';
var EMR_ACTIVE_LAYER_NAME = '';
var EMR_ACTIVE_RESOURCE_NAME = '';

// initialize length of innerHTML for TOC for dynamic regeneration
var EMR_TOC_LENGTH = 0;
// define delimiter used to separate feature names/values
var EMR_PARAM_DELIMITER = '|||';

// keep track of when the page loading notice is shown so we can clear it
var PAGE_LOADING_LAST_STARTED_TIME = new Date().getTime();
setInterval('clearPageLoadingNotice()', PAGE_LOADING_TIMEOUT);

// keep track of when the error message is shown so we can clear it
var ERROR_MESSAGE_LAST_SET_TIME = new Date().getTime();
setInterval('clearErrorDisplay()', ERROR_MESSAGE_TIMEOUT);

// declare the TOC refreshing state
var tocNodetreeNeedsRefreshing = true;
// declare the flag which indicates that the TOC is still being refreshed
var tocIsBeingRefreshed = false;

// flag for when to display the maptip for identification
var DISPLAY_IDENTIFICATION_LABEL = false;

// flag for tracking checking/unchecking exclusive layers
var EXCLUSIVE_THEMATIC_LAYERS_RESOLVED = false;

// keep track of whether request parameters need to be parsed
var REQUEST_PARAMETERS_NEED_PROCESSING = false;

var mapExtentN = 39;
var mapExtentS = 39;
var mapExtentE = -97;
var mapExtentW = -97;

var inputLatMax = [];
var inputLatMin = [];
var inputLongMax = [];
var inputLongMin = [];

/* BROWSER COMPATIBILITY */
var browserIsIE = (document.getElementsByTagName("body")[0].innerText != undefined) ? true : false;
function getNodeText(el) {
    return RTrim(browserIsIE ? el.innerText : el.textContent); // IE = innerText, firefox = textContent
}
function setNodeText(el, val) {
    if (browserIsIE) el.innerText = val; // IE
    else              el.textContent = val; // firefox
}
function getXMLText(xmlResponse) {
    // IE = 'string'[0].text, firefox = textContent
    return RTrim(browserIsIE ? xmlResponse.getElementsByTagName('string')[0].text : xmlResponse.documentElement.textContent);
}
/* --------------------- */

// turn opacity of an element off
function opacityOff(el) {
    el.style.filter = 'alpha(opacity=100)';
    el.style.opacity = '1.0';
}

// turn opacity of an element to 30%
function opacityOn(el) {
    el.style.filter = 'alpha(opacity=30)';
    el.style.opacity = '0.3';
}

// OVERRIDE OF MAP POINT CLICK
MapPoint = ESRI.ADF.MapTools.Point = function(mapid, mode, showLoading, cursor) {
    var map = $find(mapid);
    if (!map) { map = Pages[mapid]; }
    if (ESRI.ADF.UI.Map.isInstanceOfType(map)) {
        var onComplete = Function.createDelegate(map, function(geom) {
            showPageLoadingNotice();
            this.doCallback('EventArg=Point&coords=' + geom.toString(':') + '&' + mapid + '_mode=' + mode, this);
        });
        map.getGeometry(ESRI.ADF.Graphics.ShapeType.Point, onComplete, function() { map.__activeToolMode = null; }, null, null, cursor, true);
        map.__activeToolMode = mode;
    }
    else if (ESRI.ADF.UI.Page.isInstanceOfType(map)) {
        ESRI.ADF.PageTools.PageMapPoint(mapid, mode, showLoading, cursor);
    }
};

// shift layered elements on the map left/right/up/down as required to match the map dimensions
function shiftMapElements(moveRight, moveDown) {
    var panMapTools = $('zoomPanMapTools');
    var leftDim = Number(panMapTools.style.left.substr(0, panMapTools.style.left.indexOf('px')));
    panMapTools.style.left = (moveRight ? (leftDim + 250) : (leftDim - 250)) + 'px';

    var printMap = $('printMap');
    leftDim = Number(printMap.style.left.substr(0, printMap.style.left.indexOf('px')));
    printMap.style.left = (moveRight ? (leftDim + 250) : (leftDim - 250)) + 'px';
}

// send a callback to the server to update the list of report names when the report type is changed
function reportTypeChanged(el) {
    waitReport(true);
    $('ReportInputs').style.display = 'none';
    var reportTypeId = el.options[el.selectedIndex].id;
    if (reportTypeId) {
        var params = 'report_type_id=' + reportTypeId;
        processXMLCall('QueryServices.asmx/GetReportNames','getReportNames(xmlhttp.responseXML)','POST', params);
    } else {
	    $('Report_Name_Label').style.display = 'none';
        $('ReportNames').style.display = 'none';
        $('View_Report').style.display = 'none';
        waitReport(false);
    }
}

// handle the web service response to populate the list of report names
function getReportNames(xmlResponse) {
    $('ReportNames').innerHTML = getXMLText(xmlResponse);
	$('Report_Name_Label').style.display = 'block';
    $('ReportNames').style.display = 'block';
    $('View_Report').style.display = 'none';
    waitReport(false);
}

// send a callback to the server to update the list of parameters when the report name is changed
function reportChanged(el) {
    waitReport(true);
    var webServiceId = el.options[el.selectedIndex].value;
    var file = el.options[el.selectedIndex].id;
    if (file) {
        var params = 'web_service_id=' + webServiceId + '&file=' + file;
        processXMLCall('QueryServices.asmx/GenerateReportParams','generateReportParams(xmlhttp.responseXML)','POST', params);
    } else {
        $('ReportInputs').style.display = 'none';
        $('View_Report').style.display = 'none';
        waitReport(false);
    }
}

// handle the web service response to populate the list of report parameters
function generateReportParams(xmlResponse) {
    $('ReportInputs').innerHTML = getXMLText(xmlResponse);
	$('Report_Name_Label').style.display = 'block';
    $('ReportInputs').style.display = 'block';
    $('View_Report').style.display = 'block';
    waitReport(false);
}

// update the displayed parameter when the user changes the type of parameter to use for the report
function searchByChanged(el) {
    // clear out all parameter values to avoid submitting wrong values to report
    clearInputValue($('INPUT_1'));
    clearInputValue($('INPUT_2'));
    clearInputValue($('INPUT_3'));
    clearInputValue($('INPUT_4'));
    // get the parameter containers and show/hide them
    var reportId = $('select_report_name').value;
    var searchById = reportId + '_' + el.options[el.selectedIndex].id;
    var divs = el.parentNode.getElementsByTagName('div');
    for (var i=0; i<divs.length; i++) {
        // show this one and hide the others
        $(divs[i].id).style.display = (divs[i].id == searchById) ? 'block' : 'none';
    }
}

// show the execute button when the year value is changed
function yearChanged(el) {
    $('View_Report').style.display = 'block';
}

// show or hide the report execution loading message
function waitReport(show) {
    $('Wait_Getting_Info').style.display = (show ? 'block' : 'none');
}

// show or hide the report execution loading message
function waitReportResults() {
/*
	// expand the bottom panel if necessary and show the Results panel
    if (FloatingPanels[5].docked != false) {
	    if (webMapAppPanelBottomCollapsed) {
	        togglePanelDockBottom();
	    }
	    if (FloatingPanels[4].docked != false) {
    	    collapseFloatingPanel('Results');
	    }
	}
*/
    showQueryResultsPanel();
    var queryResults = $('queryResults').getElementsByTagName("div");
    for (var i=0; i<queryResults.length; i++) {
        var queryResult = queryResults[i];
        if (queryResult.getAttribute('isQueryResult') && queryResult.style.display != 'none') {
            toggleQueryResult(queryResult.id.substr(queryResult.id.lastIndexOf('_') + 1));
        }
    }
    var divId = new Date().getTime();
    $('queryResults').innerHTML += '<div id="' + divId + '" class="txt" isQueryResultWait="true">&nbsp;<img src="images/ajax-loader2.gif" /> ' + EMR_TEXT.t1007 + '</div>';
    setTimeout("timeoutQueryResult('" + divId + "')", QUERY_RESULT_TIMEOUT);
}

// show or hide the zoom loading message
function waitZoom(show, timeout) {
    $('Wait_Getting_Info2').style.display = (show ? 'block' : 'none');
    if (timeout)
        setTimeout('waitZoom(false)', timeout);
}

// first zoom to the report parameters, if possible, and then execute the report
function retrieveReportResults() {

	hideFloatingPanel('Parameters_Panel');
	waitReportResults();
    
    // select-and-zoom to the selected features if necessary
    zoomToQueryFeature();

	// call the web service proxy after a short delay to avoid async conflicts
	setTimeout('retrieveReportResultsHTML()', 15000);
}

// send a callback to the server to execute a report query
function retrieveReportResultsHTML(extraParams, reportId, reportFile) {
    var reportNameEl = $('select_report_name');

    // use the reportId that was either specified or automatically set
    reportId = reportId ? reportId : reportNameEl.options[reportNameEl.selectedIndex].value;
    
    // get the report file name
    reportFile = reportFile ? reportFile : reportNameEl.options[reportNameEl.selectedIndex].id;
    
    // build the parameter list
    var params = 'reportFile=' + reportFile + '&reportId=' + reportId;
    params += '&inputs=';
    
    // gather up the inputs and add to the parameter list
    params += getInputNameAndValue($('INPUT_1'), ':');
    params += getInputNameAndValue($('INPUT_2'), ':', EMR_PARAM_DELIMITER);
    params += getInputNameAndValue($('INPUT_3'), ':', EMR_PARAM_DELIMITER);
    params += getInputNameAndValue($('INPUT_4'), ':', EMR_PARAM_DELIMITER);
    
    // add any extra parameters that were specified
    if (extraParams)
        params += EMR_PARAM_DELIMITER + extraParams;

    // call the web service proxy
    processXMLCall('SelectReportResults.asmx/ExecuteWebService','viewReportResults(xmlhttp.responseXML)','POST', params);
}

/*
 * Build up a parameter based on the specified HTML element, a delimiter, and a separator
 * E.g., '&watershed_huc=01010101'
 */
function getInputNameAndValue(el, delim, separ) {
    var param = '';
    if (el) {
        delim = delim ? delim : '='; // default to =
        separ = separ ? separ : '';  // default to empty
        param = separ + el.name + delim + getInputValue(el);
    }
    return param;
}

// Get the value of a specified HTML element
function getInputValue(el) {
    var val = '';
    // get the value depending on select/textarea/input type
    if (el) {
        if (el.options) {
            val = el.options[el.selectedIndex].value;
        } else if (getNodeText(el)) {
            val = getNodeText(el);
        } else {
            val = el.value;
        }
    }
    return val;
}

// Get the name of a specified HTML element if it has a non-empty value
function getInputNameIfValue(el) {
    var val = '';
    // get the name
    if (el) {
        if (el.options) {
            if (el.options[el.selectedIndex].value != "") {
                val = el.name;
            }
        } else if (getNodeText(el)) {
            if (getNodeText(el) != "") {
                val = el.name;
            }
        } else if (el.value) {
            if (el.value != "") {
                val = el.name;
            }
        }
    }
    return val;
}

// clear out the value of the input field
function clearInputValue(el) {
    if (el) {
        if (el.options) {
            el.selectedIndex = 0;
        } else if (getNodeText(el)) {
            setNodeText(el, "");
        } else if (el.value) {
            el.value = "";
        }
    }
}

// filter the report results by sending another callback to the server to execute the report with extra params
function filterReportResults(extraParams, reportId) {
	collapseFloatingPanel('Query_Results_Panel');
	retrieveReportResultsHTML(extraParams, reportId);
}

// handle the web service response to populate 
function viewReportResults(xmlResponse) {
	// reset the features text
	EMR_FEATURES_TEXT = '';
    var resultId = new Date().getTime();
    // format the query results pane
    var queryResultsPanel = $('queryResults');
    var queryResults = queryResultsPanel.getElementsByTagName("div");
    // get the last waiting div, which will contain the wait message
    for (var i=queryResults.length-1; i>=0; i--) {
        if (queryResults[i].getAttribute('isQueryResultWait') && queryResults[i].getAttribute('isQueryResultWait') == 'true') {
            queryResultsPanel.removeChild(queryResults[i]);
            break;
        }
    }
    var headerDiv = "<div id='queryresult_toggle_" + resultId + "' class='queryresult' style='background-color:#EDEDED; height:20px' ";
    headerDiv += "onmouseover='showQueryResultRemove(\"" + resultId + "\")' onmouseout='hideQueryResultRemove(\"" + resultId + "\")'>";
    headerDiv += "<img id='queryresult_img_" + resultId + "' src='images/minus.gif' onclick='toggleQueryResult(\"" + resultId + "\")' style='cursor: pointer'/>Query Result &nbsp; <span id='queryresult_remove_" + resultId + "'><a href='javascript:void(0);' onclick='clearQueryResult(\"" + resultId + "\");'>Remove</a></span>";
    headerDiv += "</div>";
	// get the data
	var result = getXMLText(xmlResponse);
	if (result.indexOf('/') == -1)
		result = '&nbsp;There are no results to display.';
    queryResultsPanel.innerHTML += headerDiv + "<div style='border-color:#EDEDED; border-width:2px; border-style:solid' isQueryResult='true' id='" + "queryresult_" + resultId + "'>" + result + "</div>";
	/*
	// expand the bottom panel if necessary and show the Results panel
	if (FloatingPanels[5].docked != false) {
	    if (webMapAppPanelBottomCollapsed) {
	        togglePanelDockBottom();
	    }
	    if (FloatingPanels[4].docked != false) {
    	    collapseFloatingPanel('Results');
	    }
	}
	// make sure the panel is expanded
	expandFloatingPanel('Query_Results_Panel');
    */
    
    // take the results and select & zoom on map
	if (EMR_FEATURES_TEXT != '') {
	    // capture the JSON text as an object
	    EMR_FEATURES = eval('(' + EMR_FEATURES_TEXT + ')');
	    if (EMR_FEATURES.layer_id) {
	        EMR_FEATURES_LAYER_ID = EMR_FEATURES.layer_id;
	        // set the active layer
            processActiveLayer(EMR_FEATURES.layer_id);
            // do the rest of the processing after a short pause
//            showPageLoadingNotice();
            setTimeout('mapQueryResults()', 3000);
        }
    }
    waitReport(false);
}

function toggleQueryResult(resultId) {
    var img = $('queryresult_img_' + resultId);
    var result = $('queryresult_' + resultId);
    if (result.style.display == 'none') {
        img.src = "images/minus.gif";
        result.style.display = 'block';
    } else {
        img.src = "images/plus.gif";
        result.style.display = 'none';
    }
}

function clearQueryResult(resultId) {
    var queryResults = $('queryResults');
    var toggle = $('queryresult_toggle_' + resultId);
    var result = $('queryresult_' + resultId);
    queryResults.removeChild(toggle);
    if (result)
        queryResults.removeChild(result);
}

function showQueryResultRemove(resultId) {
    $('queryresult_remove_' + resultId).style.visibility = 'visible';
}

function hideQueryResultRemove(resultId) {
    $('queryresult_remove_' + resultId).style.visibility = 'hidden';
}

function mapQueryResults() {
    showPageLoadingNotice();
    // add on the active layer name
    EMR_FEATURES.layer_name = EMR_ACTIVE_LAYER_NAME;
    // show the layer results from the query
    var numFeatures = EMR_FEATURES.features.length ? EMR_FEATURES.features.length : 0;
    showFeaturesFoundInLayer(numFeatures, EMR_FEATURES.layer_name, false);
    // process the ids
    var featureIds = "";
    for (var i=0; i<EMR_FEATURES.features.length; i++) {
        featureIds += "'" + EMR_FEATURES.features[i].value + "'";
        if (i < (EMR_FEATURES.features.length - 1)) featureIds += ",";
    }
    var context = map.controlName;
    var message = 'SelectAndZoomToIDs';
    message += '&layerId=' + EMR_FEATURES.layer_id;
    message += '&IDs=' + featureIds;
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}


function featureTypeChanged(el) {
    var featureSelect = $('select_feature_type');
    var featureType = featureSelect.options[featureSelect.selectedIndex].value;
    clearZoomError();
	switch(featureType) {
		case 'latlong':
			$('Lat_Long_Label').style.display = 'block';
			$('Lat_Long').style.display = 'block';
			$('State2_Label').style.display = 'none';
			$('State2').style.display = 'none';
			$('select_state2').selectedIndex = $('select_state2')[0];
			$('County_Label').style.display = 'none';
			$('County').style.display = 'none';
			$('Watershed_Label').style.display = 'none';
			$('Watershed').style.display = 'none';
			$('Zipcode_Label').style.display = 'none';
			$('Zipcode2').style.display = 'none';
			$('LayerSelect_Label').style.display = 'none';
			$('LayerSelected').style.display = 'none';
			$('EntityIds_Label').style.display = 'none';
			$('EntityIds_Text').style.display = 'none';
			$('ZoomToFeatureButton').value = 'Zoom to Location';
			$('ZoomToFeature').style.display = 'block';
            if ($('lat').value == '' || $('lng').value == '') {
                $('lng').value = (parseFloat(mapExtentW) + parseFloat(mapExtentE)) / 2;
                $('lat').value = (parseFloat(mapExtentN) + parseFloat(mapExtentS)) / 2;
            }
			break;
		case 'state':
			$('Lat_Long_Label').style.display = 'none';
			$('Lat_Long').style.display = 'none';
			$('State2_Label').style.display = 'block';
			$('State2').style.display = 'block';
			$('select_state2').selectedIndex = $('select_state2')[0];
			$('County_Label').style.display = 'none';
			$('County').style.display = 'none';
			$('Watershed_Label').style.display = 'none';
			$('Watershed').style.display = 'none';
			$('Zipcode_Label').style.display = 'none';
			$('Zipcode2').style.display = 'none';
			$('LayerSelect_Label').style.display = 'none';
			$('LayerSelected').style.display = 'none';
			$('EntityIds_Label').style.display = 'none';
			$('EntityIds_Text').style.display = 'none';
			$('ZoomToFeatureButton').value = 'Zoom to State';
			$('ZoomToFeature').style.display = 'none';
			break;
		case 'county':
			$('Lat_Long_Label').style.display = 'none';
			$('Lat_Long').style.display = 'none';
			$('State2_Label').style.display = 'block';
			$('State2').style.display = 'block';
			$('select_state2').selectedIndex = $('select_state2')[0];
			$('County_Label').style.display = 'none';
			$('County').style.display = 'none';
			$('Watershed_Label').style.display = 'none';
			$('Watershed').style.display = 'none';
			$('Zipcode_Label').style.display = 'none';
			$('Zipcode2').style.display = 'none';
			$('LayerSelect_Label').style.display = 'none';
			$('LayerSelected').style.display = 'none';
			$('EntityIds_Label').style.display = 'none';
			$('EntityIds_Text').style.display = 'none';
			$('ZoomToFeatureButton').value = 'Zoom to County';
			$('ZoomToFeature').style.display = 'none';
			break;
		case 'watershed':
			$('Lat_Long_Label').style.display = 'none';
			$('Lat_Long').style.display = 'none';
			$('State2_Label').style.display = 'block';
			$('State2').style.display = 'block';
			$('select_state2').selectedIndex = $('select_state2')[0];
			$('Watershed_Label').style.display = 'none';
			$('Watershed').style.display = 'none';
			$('County_Label').style.display = 'none';
			$('County').style.display = 'none';
			$('Zipcode_Label').style.display = 'none';
			$('Zipcode2').style.display = 'none';
			$('LayerSelect_Label').style.display = 'none';
			$('LayerSelected').style.display = 'none';
			$('EntityIds_Label').style.display = 'none';
			$('EntityIds_Text').style.display = 'none';
			$('ZoomToFeatureButton').value = 'Zoom to Watershed';
			$('ZoomToFeature').style.display = 'none';
			break;
		case 'zipcode':
			$('Lat_Long_Label').style.display = 'none';
			$('Lat_Long').style.display = 'none';
			$('State2_Label').style.display = 'none';
			$('State2').style.display = 'none';
			$('select_state2').selectedIndex = $('select_state2')[0];
			$('County_Label').style.display = 'none';
			$('County').style.display = 'none';
			$('Watershed_Label').style.display = 'none';
			$('Watershed').style.display = 'none';
			$('Zipcode_Label').style.display = 'block';
			$('Zipcode2').style.display = 'block';
			$('LayerSelect_Label').style.display = 'none';
			$('LayerSelected').style.display = 'none';
			$('EntityIds_Label').style.display = 'none';
			$('EntityIds_Text').style.display = 'none';
			$('ZoomToFeatureButton').value = 'Zoom to Zipcode';
			$('ZoomToFeature').style.display = 'block';
			break;
        case 'entityIds':
            $('Lat_Long_Label').style.display = 'none';
            $('Lat_Long').style.display = 'none';
            $('State2_Label').style.display = 'none';
            $('State2').style.display = 'none';
            $('select_state2').selectedIndex = $('select_state2')[0];
            $('County_Label').style.display = 'none';
            $('County').style.display = 'none';
            $('Watershed_Label').style.display = 'none';
            $('Watershed').style.display = 'none';
            $('Zipcode_Label').style.display = 'none';
            $('Zipcode2').style.display = 'none';
            setNodeText($('LayerSelect_Label'), "Select a " + EMR_ENTITY_IDS_RESOURCE_NAME + " layer:");
            $('LayerSelect_Label').style.display = 'block';
            $('LayerSelected').style.display = 'block';
            $('EntityIds_Label').style.display = 'none';
            $('EntityIds_Text').style.display = 'none';
            $('ZoomToFeatureButton').value = 'Zoom to Entity IDs';
            $('ZoomToFeature').style.display = 'none';
            showAvailableLayers();
            break;
        default:
            $('Lat_Long_Label').style.display = 'none';
            $('Lat_Long').style.display = 'none';
            $('State2_Label').style.display = 'none';
            $('State2').style.display = 'none';
            $('select_state2').selectedIndex = $('select_state2')[0];
            $('County_Label').style.display = 'none';
            $('County').style.display = 'none';
            $('Watershed_Label').style.display = 'none';
            $('Watershed').style.display = 'none';
            $('Zipcode_Label').style.display = 'none';
            $('Zipcode2').style.display = 'none';
            $('LayerSelect_Label').style.display = 'none';
            $('LayerSelected').style.display = 'none';
            $('EntityIds_Label').style.display = 'none';
            $('EntityIds_Text').style.display = 'none';
            $('ZoomToFeature').style.display = 'none';
            break;
    }
}

function state2Changed(el) {
    var featureType = $('select_feature_type').options[$('select_feature_type').selectedIndex].value;
    state2ChangedExec();
}

function state2ChangedExec() {
    var featureSelect = $('select_feature_type');
    var featureType = featureSelect.options[featureSelect.selectedIndex].value;
    if (featureSelect.selectedIndex > 0) {
        if (featureType == 'county') {
    		retrieveCounties();
        } else if (featureType == 'watershed') {
    		retrieveWatersheds();
        } else {
            $('ZoomToFeature').style.display = 'block';
        }
    }
}

function countyChanged(el) {
    $('ZoomToFeature').style.display = 'block';
}

function watershedChanged(el) {
    $('ZoomToFeature').style.display = 'block';
}

// send a callback to the server to update the list of counties for a state
function retrieveCounties() {
    waitZoom(true);
    var params = 'state=' + $('select_state2').options[$('select_state2').selectedIndex].id;
    processXMLCall('QueryServices.asmx/GetStateCounties','viewCounties(xmlhttp.responseXML)','POST', params);
}

// handle the web service response to populate the list of counties for a state
function viewCounties(xmlResponse) {
    $('County').innerHTML = getXMLText(xmlResponse);
	$('County_Label').style.display = 'block';
	$('County').style.display = 'block';
	$('ZoomToFeature').style.display = 'none';
    waitZoom(false);
}

// send a callback to the server to update the list of counties for a state
function retrieveWatersheds() {
    waitZoom(true);
    var params = 'state=' + $('select_state2').options[$('select_state2').selectedIndex].id;
    processXMLCall('QueryServices.asmx/GetStateWatersheds','viewWatersheds(xmlhttp.responseXML)','POST', params);
}

// handle the web service response to populate the list of counties for a state
function viewWatersheds(xmlResponse) {
    $('Watershed').innerHTML = getXMLText(xmlResponse);
	$('Watershed_Label').style.display = 'block';
	$('Watershed').style.display = 'block';
	$('ZoomToFeature').style.display = 'none';
    waitZoom(false);
}

function zoomToFeature() {
    // NOTE: a delay is added to selection of the required layer because scale dependencies mean a layer
    //       may not be clickable if we're not zoomed in yet.
    
    var featureSelect = $('select_feature_type');
    var featureType = featureSelect.options[featureSelect.selectedIndex].value;
    var context = map.controlName;
    var message = "";

	switch(featureType) {
		case 'latlong':
            message = 'ZoomToXY';
		    var lat = $('lat').value;
		    var lng = $('lng').value;
		    if (!lat.match(reLatLng) || !lng.match(reLatLng)) {
		        showZoomError(EMR_ERRORS.e1014);
		        return;
		    }
		    message += "&y=" + lat + "&x="+ lng;
			break;
		case 'state':
            message = 'ZoomToState';
		    var stateCode = $('select_state2').options[$('select_state2').selectedIndex].value;
            if (!stateCode.match(reStatecode)) {
                showZoomError(EMR_ERRORS.e1016);
                return;
            }
		    message += "&state='" + stateCode + "'";
            setTimeout("processActiveLayer('10000')", 5000);
			break;
		case 'county':
            message = 'ZoomToCounty';
		    var stateCode = $('select_state2').options[$('select_state2').selectedIndex].id;
		    message += "&state='" + stateCode + "'";
		    var countyCode = $('select_county').options[$('select_county').selectedIndex].value;
            if (!countyCode.match(reCountycode)) {
                showZoomError(EMR_ERRORS.e1015);
                return;
            }
		    message += "&county='" + countyCode + "'";
            setTimeout("processActiveLayer('10001')", 5000);
			break;
		case 'watershed':
            message = 'ZoomToWatershed';
		    var watershedHUC = $('select_watershed').options[$('select_watershed').selectedIndex].value;
		    if (!watershedHUC.match(reWatershedHUC8)) {
		        showZoomError(EMR_ERRORS.e1001);
		        return;
		    }
		    message += "&watershed='" + watershedHUC + "'";
            setTimeout("processActiveLayer('30008')", 5000);
			break;
		case 'zipcode':
            message = 'ZoomToZipcode';
		    var zipcode = $('zip').value;
		    if (!zipcode.match(reZipcode)) {
		        showZoomError(EMR_ERRORS.e1002);
		        return;
		    }
		    message += "&zipcode='" + zipcode + "'";
            setTimeout("processActiveLayer('10002')", 5000);
			break;
		case 'entityIds':
            message = 'SelectAndZoomToIDs';
            var selectedLayer = $('select_entity_id_layer');
		    message += "&layerId=" + selectedLayer.options[selectedLayer.selectedIndex].value;
		    message += "&IDs=";
		    var ids = $('entityIds').value;
		    // we don't know what the user used for a delimiter, so try , and ; and <space>
		    var idArray = ids.split(',');
		    if (idArray.length == 1)
		        idArray = idArray[0].split(';');
		    if (idArray.length == 1)
		        idArray = idArray[0].split(' ');
		    for (var i=0; i<idArray.length; i++) {
		        var id = idArray[i];
		        id = id.replace(' ','');
		        id = id.replace(',','');
		        id = id.replace(';','');
		        if (id != '') {
    		        message += "'" + id + "'" + ',';
		        }
		    }
		    if (message.substring(message.length - 1) == ',')
		        message = message.substring(0, message.length - 1);
			break;
    }
    clearZoomError();
    waitZoom(true, 5000);
//    showPageLoadingNotice();
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

// select and zoom to the specified features
function zoomToQueryFeature() {
    showPageLoadingNotice();
    var reportNameEl = $('select_report_name');
    var reportId = reportNameEl.options[reportNameEl.selectedIndex].value;
    var context = map.controlName;
    var command;
    var params = '&';

    // add the report id
    params += 'reportId=' + reportId;
    
    // gather up the inputs and add to the parameter list
    params += "&featureIds=";
    params += getInputValue($('INPUT_1')) + ",";
    params += getInputValue($('INPUT_2')) + ",";
    params += getInputValue($('INPUT_3')) + ",";
    params += getInputValue($('INPUT_4'));

    params += "&paramNames=";
    params += getInputNameIfValue($('INPUT_1')) + ",";
    params += getInputNameIfValue($('INPUT_2')) + ",";
    params += getInputNameIfValue($('INPUT_3')) + ",";
    params += getInputNameIfValue($('INPUT_4'));
    
    // zoom to the specified features
    command = 'SelectQueryFeatures';
    executeStandardCallback(command + params);

    // get the layers for this report and let the callback handle the processing
    command = 'GetReportLayerID';
    setTimeout('executeStandardCallback("' + command + params + '")', 10000);
}

function executeStandardCallback(message) {
    showPageLoadingNotice();
    var context = map.controlName;
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

// format and show the help box
function showHelp() {
	if (!readCookie('EMR_help')) {
	    $('shader').style.left = "0px";
	    $('shader').style.top = "0px";
	    $('shader').style.width = getWinWidth() + "px";
	    $('shader').style.height = getWinHeight() + "px";
	    $('shader').style.display = '';
	    $('help').style.left = ((getWinWidth()/2) - 350) + "px";
	    $('help').style.top = ((getWinHeight()/2) - 275) + "px";
	    $('help').style.display = '';
	    toggleSelectElementsVisibility(false);
	    if ($('CLOSE_HELP')) $('CLOSE_HELP').focus();
	}
}

// hide the help box - uses cookies to store the user preference to hide it for n days
function hideHelp() {
	toggleSelectElementsVisibility(true);
	$('shader').style.display = 'none';
	$('help').style.display = 'none';
	if ($('hideHelpCheck').checked) {
	    createCookie('EMR_help', 'Hide EMR Help', 7);
	}
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name,"",-1);
}

function processRequestParameters() {
    var context = map.controlName;
    var message = '';
    var errorMessage = getRequestParameter('ErrorMessage');
    if (errorMessage)
    	showCallbackError(errorMessage);
    var bbox = getRequestParameter('ZoomToBoundingBox');
    if (bbox) {
        message = 'ZoomToBoundingBox';
        message += '&bbox=' + bbox;
        message = createClientPostBackQueryString(context, message);
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var latlng = getRequestParameter('ZoomToPoint');
    if (!latlng)
        latlng = getRequestParameter('ZoomToLatLong');
    if (!latlng)
        latlng = getRequestParameter('ZoomToLongLat');
    if (latlng) {
        message = 'ZoomToXY';
        var lng = latlng.substring(0, latlng.indexOf(','));
        var lat = latlng.substring(latlng.indexOf(',') + 1, latlng.length);
        if (lat.indexOf('-') == 0 && lng.indexOf('-') == -1) {
        	// swap lat/long
        	var swapLL = lng;
        	lng = lat;
        	lat = swapLL;
        }
        message += '&y=' + lat + '&x=' + lng;
        message = createClientPostBackQueryString(context, message);
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var state = getRequestParameter('ZoomToState');
    if (state) {
        message = 'ZoomToState';
        message += '&state=' + state;
        message = createClientPostBackQueryString(context, message);
        processActiveLayer('10000');
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var zipcode = getRequestParameter('ZoomToZip');
    if (!zipcode) zipcode = getRequestParameter('ZoomToZIP');
    if (!zipcode) zipcode = getRequestParameter('ZoomToZipcode');
    if (zipcode) {
        message = 'ZoomToZipcode';
        message += '&zipcode=' + zipcode;
        message = createClientPostBackQueryString(context, message);
		setTimeout("processActiveLayer('10002')", 5000);
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var watershed = getRequestParameter('ZoomToWatershed');
    if (watershed) {
        message = 'ZoomToWatershed';
        message += '&watershed=' + watershed;
        message = createClientPostBackQueryString(context, message);
        processActiveLayer('30008');
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var county = getRequestParameter('ZoomToCounty');
    if (county) {
        message = 'ZoomToCounty';
        if (county.indexOf('.') > 0) {
            message += '&state=' + county.substring(0, county.indexOf('.'));
            message += '&county=' + county.substring(county.indexOf('.') + 1, county.length);
        } else if (county.indexOf("'") > -1) {
            message += '&state=' + county.substring(1, 3);
            message += '&county=' + county.substring(3, 6);
        } else {
            message += '&state=' + county.substring(0, 2);
            message += '&county=' + county.substring(2);
        }
		setTimeout("processActiveLayer('10001')", 5000);
        message = createClientPostBackQueryString(context, message);
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var selectAndZoomToIds = getRequestParameter('SelectAndZoomToIDs');
    if (selectAndZoomToIds) {
        message = 'SelectAndZoomToIDs';
        var layerId = selectAndZoomToIds.substring(0, selectAndZoomToIds.indexOf('*'));
        message += '&layerId=' + layerId;
        var ids = selectAndZoomToIds.substring(selectAndZoomToIds.indexOf('*') + 1, selectAndZoomToIds.length);
        message += '&IDs=' + ids;
        message = createClientPostBackQueryString(context, message);
        if (layerId.indexOf(',') < 0) {
			setTimeout("processActiveLayer('" + layerId + "')", 5000);
        }
        WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    }
    var ws = getRequestParameter('WebService');
    if (ws) {
//        var el = $('select_report_type');
//        el.options.selectedIndex = 1;
//        reportTypeChanged(el);
        retrieveReportResultsHTML();
    }
    if (bbox || state || zipcode || watershed || county || selectAndZoomToIds || ws) {
        showPageLoadingNotice();
    } else {
        hidePageLoadingNotice();
    }
}

function processActiveLayer(layerId) {
//    showPageLoadingNotice();
    var params = 'layer_id=' + layerId;
    processXMLCall('QueryServices.asmx/GetResourceAndLayerNames','updateActiveLayer(xmlhttp.responseXML)','POST', params);
    
    // show thematic legends more clearly
    if (layerId >= 80010 && layerId <= 80100) {
        var tocDiv = $('Toc_Panel_Toc1');
        tocDiv.scrollTop = tocDiv.scrollHeight;
    }
}

function updateActiveLayer(xmlResponse) {
//    showPageLoadingNotice();
    var text = getXMLText(xmlResponse);
    var resourceName = text.substring(0, text.indexOf(':::'));
    var layerName = text.substring(text.indexOf(':::') + 3, text.length);
    EMR_ACTIVE_LAYER_NAME = layerName;
    EMR_ACTIVE_RESOURCE_NAME = resourceName;
    setActiveLayer(resourceName, layerName);
}

function setActiveLayer(resourceName, layerName) {
    showPageLoadingNotice();
    var tocDiv = $('Toc1');
    var tables = tocDiv.getElementsByTagName('table');
    for (var i=0;i<tables.length;i++)
    {
        var id = tables[i].parentNode.id;
        var tds = tables[i].getElementsByTagName('td');

        // activate the layer by clicking its radio button
        // note: if this layer has no symbology, its name will be at index 3
        if ((tds.length == 5 && (RTrim(getNodeText(tds[4])) == layerName))
            || (tds.length == 4 && (RTrim(getNodeText(tds[3])) == layerName))) {
            var rdo = $(id + '_RDO');
            if (rdo) {
                rdo.checked; // ???
                rdo.click();
            }
            // turn on the layer by clicking its checkbox
            var layerCheckbox = $(id + '_CheckBox');
            if (layerCheckbox && !layerCheckbox.checked) {
                if (layerCheckbox.isExclusiveThematic) {
                    // turn off all other thematic layers
                    /*
                    var inputs = tocDiv.getElementsByTagName('input');
                    for (var j=0;j<inputs.length;j++)
                    {
                        if (inputs[j] && inputs[j].isExclusiveThematic && inputs[j].checked) {
                            inputs[j].click();
                        }
                    }
                    */
                }
                layerCheckbox.click();
            }
            // also turn on the resource by clicking its checkbox
            if (tables[i].parentNode.parentNode.parentNode) {
                var resourceCheckbox = $(tables[i].parentNode.parentNode.parentNode.id + '_CheckBox');
                if (resourceCheckbox && !resourceCheckbox.checked)
                    resourceCheckbox.click();
            }
        }
    }
    hidePageLoadingNotice();
}

function processTOCLayers(expandTOC) {
    var tocDiv = $('Toc1');

    // if the TOC is currently being refreshed,
    // or it has not changed since the last time we refreshed it,
    // skip this iteration
    if (tocIsBeingRefreshed) {
        return;
//    } else if (EMR_TOC_LENGTH == tocDiv.innerHTML.length) {
//        setTimeout('processTOCLayers()', timeoutTOCRefresh);
//        return;
    } else {
        tocIsBeingRefreshed = true;
    }

    var tables = tocDiv.getElementsByTagName('table');
    var resourceName = '';
    var layerName = '';
    var layerNum = -1;

    showTOCLoadingNotice();

    for (var i=0;i<tables.length;i++)
    {
        var rows = tables[i].rows;
        tables[i].className = 'lnk';
        var divId = tables[i].parentNode.id;
        for (var j=0;j<rows.length;j++)
        {
            var divs = rows[j].getElementsByTagName('div');
            if (divs.length == 0) {
                // it's a resource, so add a href and get its name
                layerNum = -1;
                resourceName = RTrim(getNodeText(rows[j].cells[2]));
//                if (rows[j].cells[2].innerHTML.indexOf('href') < 0 && rows[j].cells[2].innerHTML.indexOf('input') < 0)
//                    rows[j].cells[2].innerHTML = "<a href='javascript: void(0)'>" + getNodeText(rows[j].cells[2]) + "</a>";
                // turn off the toggle command
                rows[j].cells[2].onmousedown = '';
                rows[j].cells[2].style.cursor = 'auto';
            } else if (divs.length == 2) {
                // it's a layer, so add a radio button and href
                layerNum++;
                var layerIsLast = (i == tables.length - 2);
                // first remove the radio button
                divs[1].innerHTML = "";
//                 and is visible
//                 && tables[i+2].innerHTML.indexOf('checkbox') > 0
                // add a radio button only if this layer has no child layers
                if (tables[i+2]) {
                    var divsSub = tables[i+2].getElementsByTagName('div');
                    if (divsSub.length < 6) {
                        if (divs[1].innerHTML.indexOf('input') < 0 && layersCanBeActivated(resourceName))
                            divs[1].innerHTML = "<input type='radio' id='" + divId + "_RDO' value='" + divId + "' name='ACTIVE_LAYER_RDO' title='Make this layer Active' onclick='activeLayerChanged(this, \"" + resourceName + "\", \"" + (rows[j].cells[4] ? getNodeText(rows[j].cells[4]) : getNodeText(rows[j].cells[3])) + "\", \"" + layerNum + "\");' />";
                    }
                } else if (layerIsLast) {
                    if (divs[1].innerHTML.indexOf('input') < 0 && layersCanBeActivated(resourceName))
                        divs[1].innerHTML = "<input type='radio' id='" + divId + "_RDO' value='" + divId + "' name='ACTIVE_LAYER_RDO' title='Make this layer Active' onclick='activeLayerChanged(this, \"" + resourceName + "\", \"" + (rows[j].cells[4] ? getNodeText(rows[j].cells[4]) : getNodeText(rows[j].cells[3])) + "\", \"" + layerNum + "\");' />";
                }
                // then add the href
                if (rows[j].cells[4] && rows[j].cells[4].innerHTML.indexOf('href') < 0 && getNodeText(rows[j].cells[4]) != '') {
                    layerName = getNodeText(rows[j].cells[4]);
                    // break the name into multiple lines if it's long
                    cleanUpText(rows[j].cells[4], 14);
                    // add the hyperlink
                    rows[j].cells[4].onclick = "";
                    rows[j].cells[4].innerHTML = "<a href='javascript:getLayerMetadata(\""+RTrim(layerName)+"\")' onclick='javascript:void(0)'>" + rows[j].cells[4].innerHTML + "</a>";
                    // turn off the toggle command
                    rows[j].cells[4].onmousedown = '';
                } else if (rows[j].cells[3].innerHTML.indexOf('href') < 0 && getNodeText(rows[j].cells[3]) != '') {
                    layerName = getNodeText(rows[j].cells[3]);
                    rows[j].cells[3].onclick = "";
                    rows[j].cells[3].innerHTML = "<a href='javascript:getLayerMetadata(\""+RTrim(layerName)+"\")' onclick='javascript:void(0)'>" + rows[j].cells[3].innerHTML + "</a>";
                    // turn off the toggle command
                    rows[j].cells[3].onmousedown = '';
                }
                /* SDK: THIS IS NOT WORKING, CAME FROM display_treeviewplus.js
                // then add the cascading to the resource
                if (rows[j].cells[3] && rows[j].cells[3].innerHTML.indexOf('heckbox') > 0) {
                    rows[j].cells[3].onclick = "showTOCLoadingNotice(1000); setTimeout('cascadeSelectedLayer(\"" + divId + "\")', 750); ";
                }
                */
                // if this is a graphic layer, set a flag for later use
                /*
                if (RTrim(resourceName) == EMR_GRAPHIC_RESOURCE_NAME) {
                    if (rows[j].cells[3].innerHTML.indexOf('isExclusiveGraphic') < 0) {
                        var chkGraphicLayerSelector = $(divId + '_CheckBox');
                        chkGraphicLayerSelector.isExclusiveGraphic = true;
                    }
                }
                */
                // if this is a graphic layer, insert its symbology
                if (RTrim(resourceName) == EMR_GRAPHIC_RESOURCE_NAME) {
                    if (rows[j].cells[4] == undefined) {
                        if (rows[j].cells[3] && rows[j].cells[3].innerHTML.indexOf('src') < 0) {
                            // add the symbology below
                            var symbolImg = getNodeText(rows[j].cells[3]).indexOf('Surface') > -1 ? EMR_GRAPHIC_LAYER_SYMBOL_SURFACE_WATER : EMR_GRAPHIC_LAYER_SYMBOL_GROUND_WATER;
                            rows[j].cells[3].innerHTML += '<br/><img src="images/' + symbolImg + '" />';
                            rows[j].cells[1].innerHTML += '<img src="images/blank.gif" width="0" height="14"/>';
                            rows[j].cells[2].innerHTML += '<br/><img src="images/blank.gif" width="0" height="14"/>';
                        }
                    }
                }
                // if this is a thematic layer and not a point layer, set a flag for later use
                if (RTrim(resourceName) == EMR_THEMATIC_RESOURCE_NAME) {
                    var thematicLayerNameCell = rows[j].cells[4];
                    if (thematicLayerNameCell && getNodeText(thematicLayerNameCell)) {
                        if (getNodeText(thematicLayerNameCell).indexOf('Point') < 0 && getNodeText(thematicLayerNameCell).indexOf('point') < 0) {
                            var thematicCheckbox = rows[j].cells[3].innerHTML;
                            if (thematicCheckbox.indexOf('isExclusiveThematic') < 0) {
                                var chkThematicLayerSelector = $(divId + '_CheckBox');
                                if (chkThematicLayerSelector) {
                                    chkThematicLayerSelector.isExclusiveThematic = true;
/*
                                    if (browserIsIE) {
                                        var rdoHTML = chkThematicLayerSelector.outerHTML;
                                        rdoHTML = rdoHTML.replace('="checkbox"', '=checkbox');
                                        rdoHTML = rdoHTML.replace('=checkbox', '=radio name=thematicMapsLayer_Radio');
                                        chkThematicLayerSelector.outerHTML = rdoHTML;
                                    }
*/
                                }
                            }
                        }
                    }
                }
            } else if ((divs.length == 4) && (rows[j].cells[6])) {
                if (rows[j].cells[6].innerHTML.indexOf('img') < 0) {
                    // it's a layer, so add a radio button and href
                    layerNum++;
                    layerName = getNodeText(rows[j].cells[6]);
                    if (divs[1].innerHTML.indexOf('input') < 0 && layersCanBeActivated(resourceName))
                        divs[1].innerHTML = "<input type='radio' id='" + divId + "_RDO' value='" + divId + "' name='ACTIVE_LAYER_RDO' title='Make this layer Active' onclick='activeLayerChanged(this, \"" + resourceName + "\", \"" + getNodeText(rows[j].cells[6]) + "\", \"" + layerNum + "\");' />";
                    if (rows[j].cells[6].innerHTML.indexOf('href') < 0 && getNodeText(rows[j].cells[6]) != '') {
                        rows[j].cells[6].onclick = "";
                        rows[j].cells[6].innerHTML = "<a href='javascript:getLayerMetadata(\""+RTrim(layerName)+"\")' onclick='javascript:void(0)'>" + getNodeText(rows[j].cells[6]) + "</a>";
                    }
                }
            }
        }
    }
    
    // now that everything's done, re-select the lost selection
    if (EMR_ACTIVE_LAYER_DIV_ID) {
        var rdo = $(EMR_ACTIVE_LAYER_DIV_ID + '_RDO');
        if (rdo) {
            rdo.checked = true;
            rdo.click();
        }
    }

    // finally, collapse nodes if necessary
    if (tocNodetreeNeedsRefreshing) {
        var divs = tocDiv.getElementsByTagName('div');
        for (var k=0;k<divs.length;k++)
        {
            // collapse any unchecked nodes that are layer nodes
            if (divs[k].id.indexOf('childrenContainer') < 0) {
                var checkBox = $(divs[k].id + '_CheckBox');
                var childContainerDiv = $(divs[k].id + '_childrenContainer');
                var textCell = $(divs[k].id + '_textCell');
                if (childContainerDiv != null) {
                    if ((checkBox == null || !checkBox.checked) && childContainerDiv.style.display != 'none') {
                        // close the node, it is unchecked but still visible
                        // AGS 9.3 SP1
                        $find('Toc1')._toggleNodeState(divs[k].id,false);
                        //TreeViewPlusObjects['Toc_Panel_Toc1'].toggleNodeState(divs[k].id);
                    } else if (checkBox != null && checkBox.checked && childContainerDiv.style.display == 'none') {
                        // open the node, it is checked but still not visible - do the node toggle at 0.5 second intervals to avoid skips
                        //setTimeout("TreeViewPlusObjects['Toc_Panel_Toc1'].toggleNodeState('" + divs[k].id + "')", k*500);
                    }
                }
            }
        }
        tocNodetreeNeedsRefreshing = false;
    }
    
    // expand the TOC Panel if necessary
    /*
    if (expandTOC) {
        expandFloatingPanel("Toc_Panel");
        resetEMRFloatingPanels("OverviewMap_Panel");
    }
    */
    // repeat the TOC layer refreshing process every n seconds
    tocIsBeingRefreshed = false;
//    EMR_TOC_LENGTH = tocDiv.innerHTML.length;
//    setTimeout('processTOCLayers()', timeoutTOCRefresh);
    hideTOCLoadingNotice();
    
    if (REQUEST_PARAMETERS_NEED_PROCESSING) {
		setTimeout('processRequestParameters()', 1000);
		REQUEST_PARAMETERS_NEED_PROCESSING = false;
	}
}

function toggleTOCNode(nodeID, isChecked) {
    container = $(nodeID+'_childrenContainer');
    if (container) {
        if (isChecked == 'True' && container.style.display == 'none') {
            // AGS 9.3 SP1
            $find('Toc_Panel_Toc1')._toggleNodeState(nodeID,true);
            //TreeViewPlusObjects['Toc_Panel_Toc1'].toggleNodeState(nodeID);
        } else if (isChecked == 'False' && container.style.display != 'none') {
            // AGS 9.3 SP1
            $find('Toc_Panel_Toc1')._toggleNodeState(nodeID,false);
            //TreeViewPlusObjects['Toc_Panel_Toc1'].toggleNodeState(nodeID);
        }
    }
}

function activeLayerChanged(el, resourceName, layerName, layerId) {
    var activeDiv = $('ACTIVE_LAYER')
    activeDiv.innerHTML = "<b> " + EMR_ACTIVE_LAYER_LABEL + " " + layerName + " </b>";
    activeDiv.style.display = 'block';
    if (el)
        EMR_ACTIVE_LAYER_DIV_ID = el.value;
    
    var context = map.controlName;
    var message = 'SetActiveLayer';
    message += '&SelectedLayer=' + RTrim(layerName) + '&SelectedResource=' + RTrim(resourceName) + '&SelectedLayerIndex=' + layerId;
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function RTrim(input) {
    var trimmed = input;
    if (input != undefined) { // firefox
        var re = /((\s*\S+)*)\s*/;
        trimmed = input.replace(re, "$1");
    }
	return trimmed;
}

function showZoomError(err) {
    $('Validation_zoomToFeature').innerHTML = err + '<br/><br/>';
}

function clearZoomError() {
    $('Validation_zoomToFeature').innerHTML = '';
}

function zoomToStateCode(stateCode) {
    showPageLoadingNotice();
    var context = map.controlName;
    var message = 'ZoomToState';
    message += "&state='" + stateCode + "'";
    message = createClientPostBackQueryString(context, message);
    processActiveLayer('10000');
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function zoomToWatershedHUC(watershedHUC) {
    showPageLoadingNotice();
    var context = map.controlName;
    var message = 'ZoomToWatershed';
    message += "&watershed='" + watershedHUC + "'";
    message = createClientPostBackQueryString(context, message);
    processActiveLayer('30008');
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function showPageLoadingNotice(timeout) {
    var loading = $('PAGE_LOADING');
    if (loading) {
        loading.style.top = (getWinHeight()/2 - 80) + 'px';
        loading.style.left = (getWinWidth()/2 - 120) + 'px';
        loading.style.display = 'block';
        if (timeout && timeout > 0) {
            setTimeout('hidePageLoadingNotice()', timeout);
        } else {
            PAGE_LOADING_LAST_STARTED_TIME = new Date().getTime();
        }
    }
}

function hidePageLoadingNotice() {
    $('PAGE_LOADING').style.display = 'none';
    map.divObject.style.cursor = map.cursor;
}

function showTOCLoadingNotice(timeout) {
    var loading = $('TOC_LOADING');
    if (loading) {
        loading.style.top = (getWinHeight()/2 - 80) + 'px';
        loading.style.left = (getWinWidth()/2 - 121) + 'px';
        loading.style.display = 'block';
        if (timeout) {
            setTimeout('hideTOCLoadingNotice()', timeout);
        }
    }
}

function hideTOCLoadingNotice() {
    $('TOC_LOADING').style.display = 'none';
}

function showAndIdentifyLayerFeatures(identifyFeaturesFileName, hasKML) {
	REPORT_FEATURES = eval('(' + EMR_FEATURES_TEXT + ')');
    var numFeatures = EMR_FEATURES.features.length ? EMR_FEATURES.features.length : 0;
    for (var i=0; i<EMR_GRAPHIC_LAYER_NAMES.length; i++) {
        if (EMR_GRAPHIC_LAYER_NAMES[i] == EMR_FEATURES.layer_name) {
            // it's a USGS layer, so cut the total features found by 2, USGS stations are over-reported by 100%
            if (numFeatures % 2 == 0) numFeatures *= 0.5;
            break;
        }
    }
    // change the mouse cursor back to a pointer if necessary
    if (map.divObject.style.cursor == "wait") map.divObject.style.cursor = "pointer";
    // show the identification results
    showFeaturesFoundInLayer(numFeatures, EMR_FEATURES.layer_name, true);
    identifyFeatures(identifyFeaturesFileName, hasKML);
	hidePageLoadingNotice();
}

function showAndIdentifyAllFeatures(identifyFeaturesFileName, layerNames) {
/*
	// expand the bottom panel if necessary and show the Results panel
	if (FloatingPanels[4].docked != false) {
	    if (webMapAppPanelBottomCollapsed) {
	        togglePanelDockBottom();
	    }
	    if (FloatingPanels[5].docked != false) {
    	    collapseFloatingPanel('Query_Results_Panel');
	    }
	}
	expandFloatingPanel('Results');
*/
    showFloatingPanel('ID_Results');
    expandFloatingPanel('ID_Results');
    $('taskResults').innerHTML = '<img src="images/ajax-loader2.gif" /> ' + EMR_TEXT.t1008;
	$('taskResultsReports').innerHTML = '';
    var params = 'identifyFeaturesFileName=' + identifyFeaturesFileName;
    params += '&layerNames=' + layerNames;
    // call the web service proxy
    processXMLCall('SelectReportResults.asmx/IdentifyAllFeatures','viewIdentifiedFeatures(xmlhttp.responseXML)','POST', params);
}

function zoomToIdentifiedFeature(layerName, featureId, rowId, labelText, layerId) {
    showPageLoadingNotice();
    collapseFloatingPanel('ID_Results');
    // highlight the row in the id results
    var highlightColor = '#FFFFCC';
    if (rowId) {
        var idTrs = $('taskResults').getElementsByTagName('tr');
        for (var i=0; i<idTrs.length; i++) {
            if (idTrs[i].style.backgroundColor.toUpperCase() == highlightColor)
                idTrs[i].style.backgroundColor = '';
        }
        $(rowId).style.backgroundColor = highlightColor;
        setFeatureLabel(layerName, labelText);
    }
    // do the callback
    var context = map.controlName;
    var message = 'SelectAndZoomToIdentifiedFeature';
    message += '&layerName=' + layerName;
    message += "&ID='" + featureId + "'";
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    // prepare the feature for report execution
    EMR_FEATURES_TEXT = "{'layer_name': '" + layerName.replace('\'','`') + "', 'layer_id': '" + layerId + "', 'features': [{'value': '" + featureId.replace('|',',') + "'}]}";
    EMR_FEATURES = eval('(' + EMR_FEATURES_TEXT + ')');
    setTimeout('retrieveLayerReports("' + layerId + '")', 5000);
}

function setFeatureLabel(layerName, labelText) {
    hideLayer('IDENTIFICATION_LABEL');
    var identificationLabel = $("IDENTIFICATION_LABEL");
    var labelLength = layerName.length > labelText.length ? layerName.length : labelText.length;
    identificationLabel.innerHTML = layerName + '<br/>' + labelText;
    identificationLabel.innerHTML += '<div class="lnk-black" id="IdentificationLabelMenu" style="visibility:hidden;"><a href="javascript:void(0);" onclick="hideLayer(\'IDENTIFICATION_LABEL\');">Remove</a>';
    identificationLabel.style.top = (getWinHeight()/2) + 'px';
    identificationLabel.style.left = (getWinWidth()/2) + 'px';
    // mark the identification label for displaying when the map extent gets changed
    DISPLAY_IDENTIFICATION_LABEL = true;
}

function showFeaturesFoundInLayer(numFeatures, layerName, showReports) {
    var msg = "<b>Found " + numFeatures + " ";
    msg += numFeatures == 1 ? "feature" : "features";
    msg += " in layer " + layerName + "</b>"
    showFeatureText(msg);
    setTimeout('showFeatureText("")', 10000);
    if (numFeatures > 0 && showReports) {
        // wait for a delay before getting the layer's reports, to let the identify finish executing
        setTimeout('retrieveLayerReports()', 5000);
    }
}

function retrieveLayerReports(layerId) {
    var params = 'layer_id=' + (layerId ? layerId : EMR_FEATURES.layer_id);
    processXMLCall('QueryServices.asmx/GetLayerReports','showLayerReports(xmlhttp.responseXML)','POST', params);
}

function showLayerReports(xmlResponse) {
    var htmlText = getXMLText(xmlResponse);
    if (htmlText != '') {
    	$('taskResultsReports').innerHTML = htmlText;
/*
        var layerReports = $('LAYER_REPORTS');
        layerReports.innerHTML = htmlText;
        layerReports.style.top = (getWinHeight()/2 - 100) + 'px';
        layerReports.style.left = (getWinWidth()/2 - 180) + 'px';
        layerReports.style.display = 'block';
*/
    }
}

function executeReport(reportId, inputs) {
    // hide the reports box, show the waiting note, hide any previous query results
    collapseFloatingPanel('ID_Results');
    showQueryResultsPanel();
    waitReportResults();
	
    // build the parameter list
    var params = 'reportId=' + reportId;
    params += '&inputs=';
    if (inputs) {
        params += inputs;
    } else {
        for (var i=0; i<REPORT_FEATURES.features.length; i++) {
            params += REPORT_FEATURES.field_name + ':' + REPORT_FEATURES.features[i].value;
            if (i != (REPORT_FEATURES.features.length - 1))
                params += EMR_PARAM_DELIMITER;
        }
    }
    // call the web service proxy
    processXMLCall('SelectReportResults.asmx/ExecuteWebService','viewReportResults(xmlhttp.responseXML)','POST', params);
}

function identifyFeatures(identifyFeaturesFileName, hasKML) {
/*
	// expand the bottom panel if necessary and show the Results panel
	if (FloatingPanels[4].docked != false) {
	    if (webMapAppPanelBottomCollapsed) {
	        togglePanelDockBottom();
	    }
	    if (FloatingPanels[5].docked != false) {
    	    collapseFloatingPanel('Query_Results_Panel');
	    }
	}
*/
	showIDResultsPanel();
    $('taskResults').innerHTML = '<img src="images/ajax-loader2.gif" /> ' + EMR_TEXT.t1009;
	$('taskResultsReports').innerHTML = '';
    var params = 'identifyFeaturesFileName=' + identifyFeaturesFileName;
    params += '&layerName=' + (EMR_FEATURES.layer_name ? EMR_FEATURES.layer_name : EMR_ACTIVE_LAYER_NAME);
    params += '&hasKML=' + hasKML;
    // call the web service proxy after a delay to avoid conflicts
    setTimeout('doIdentifyFeatures("' + params + '")', 6000);
}

function doIdentifyFeatures(params) {
    processXMLCall('SelectReportResults.asmx/IdentifyFeatures','viewIdentifiedFeatures(xmlhttp.responseXML)','POST', params);
}

function viewIdentifiedFeatures(xmlResponse) {
    $('taskResults').innerHTML = getXMLText(xmlResponse);
    hidePageLoadingNotice();
}

function cascadeSelectedLayer(id) {
    // cascade checkboxes only if this is a layer
    var div = $(id);
    var checkBox = $(id + '_CheckBox');
    // if neither the layer DIV nor its checkbox were found, bail out
    if (!div || !checkBox)
        return;
    if (div.parentNode.id.indexOf('_childrenContainer') > -1) {
        var topResourceDiv = div.parentNode.parentNode;
        var topResourceCheckbox = $(topResourceDiv.id + '_CheckBox');
        if (checkBox.checked) {
            // make sure the parent node of this checkbox is checked; if not, check it
            if (!topResourceCheckbox.checked) {
                $(topResourceDiv.id + '_CheckBox').click();
            }
        } else {
            // if this is the last child node to be checked, uncheck its parent
            var layerInputs = topResourceDiv.getElementsByTagName('input');
            var hasChecked = false;
            for (var i=0; i<layerInputs.length; i++) {
                if (layerInputs[i].type == 'checkbox') {
                    // if this checkbox is checked and it's not the currently selected one and it's not the top resource one
                    if (layerInputs[i].checked && layerInputs[i].id.indexOf(id) < 0 && layerInputs[i].id.indexOf(topResourceDiv.id) < 0) {
                        hasChecked = true;
                        break;
                    }
                }
            }
            // @todo
//            if (!hasChecked && topResourceCheckbox.checked)
                // turn off the top resource checkbox
//                topResourceCheckbox.click();
        }
    } else {
        // if this is a top-level resource checkbox and it's still collapsed, expand it
        // @todo
    }
    
    // if this layer was an exclusive thematic, turn off all other exclusive layers
    if (checkBox.isExclusiveThematic && !EXCLUSIVE_THEMATIC_LAYERS_RESOLVED) {
        EXCLUSIVE_THEMATIC_LAYERS_RESOLVED = true;
        var exclusiveThematicLayerChks = topResourceDiv.getElementsByTagName('input');
        for (var i=0; i < exclusiveThematicLayerChks.length; i++) {
            if (exclusiveThematicLayerChks[i].id.indexOf(id) < 0) {
                if (exclusiveThematicLayerChks[i].isExclusiveThematic && exclusiveThematicLayerChks[i].checked) {
                    exclusiveThematicLayerChks[i].click();
                }
            }
        }
        // give the cascading layer selection time to reset all exclusive thematic layers before resetting this flag
        setTimeout('EXCLUSIVE_THEMATIC_LAYERS_RESOLVED = false;', 1000);
    }

    // if this layer was an exclusive graphic, turn off all other exclusive layers
    /*
    if (checkBox.isExclusiveGraphic) {
        var exclusiveGraphicLayerChks = topResourceDiv.getElementsByTagName('input');
        for (var i=0; i < exclusiveGraphicLayerChks.length; i++) {
            if (exclusiveGraphicLayerChks[i].id.indexOf(id) < 0) {
                if (exclusiveGraphicLayerChks[i].isExclusiveGraphic && exclusiveGraphicLayerChks[i].checked) {
                    exclusiveGraphicLayerChks[i].click();
                }
            }
        }
    }
    */
}

// send a callback to the server to generate an image file based on the map canvas
function generateMapImage() {
//    showPageLoadingNotice();
    $('DOWNLOAD_IMAGE_LINK').style.display = 'none';
    $('DOWNLOAD_IMAGE_WAIT').style.display = 'block';
    showImageDownloadNotice();
    var context = map.controlName;
    var message = 'GenerateMapImage';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

// using the unique ID of an image file on the server, render a link to it
function getMapImage(id) {
    var params = 'id=' + id;
    $('DOWNLOAD_IMAGE_LINK').style.display = 'block';
    $('DOWNLOAD_IMAGE_WAIT').style.display = 'none';
    var url = EMR_URL + "/GetMapImage.aspx?" + params;
    $('DOWNLOAD_IMAGE_LINK').innerHTML = "<b><img border='0' src='images/down_arrow.jpg' /> &nbsp; <a onclick='hideImageDownloadNotice();' href='" + url + "'>Download Map Image</a><br/><br/><a href='javascript:void(0);' onclick='hideImageDownloadNotice()'>Cancel</a></b>";
    hidePageLoadingNotice();
}

// turn on or off all SELECT html elements so that an overlaid DIV displays properly
function toggleSelectElementsVisibility(show) {
	var selects = document.getElementsByTagName('select');
	for (var i=0; i<selects.length; i++) {
	    selects[i].style.display = show ? '' : 'none';
	}
}

// prompt the user to reload the app before doing so
function reloadPage() {
    if (confirm(EMR_TEXT.t1001)) {
        document.location.reload();
    }
}

// send a callback to the server to revert to the previous map extent
function revertToOldMapExtent() {
    showPageLoadingNotice();
    var context = map.controlName;
    var message = 'LoadOldMapExtent';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function zoomToFullExtent() {
    showPageLoadingNotice();
    var context = map.controlName;
    var message = 'LoadFullExtent';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

// send a callback to the server to clear all selected features
function clearAllSelections() {
    showPageLoadingNotice();
    var context = map.controlName;
    var message = 'ClearAllSelections';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

// update the message shown for the feature selection
function showFeatureText(html) {
    var featureTextDiv = $('FEATURE_TEXT')
    featureTextDiv.innerHTML = html ? html : '';
    featureTextDiv.style.display = html ? 'block' : 'none';
}

// display the image download box
function showImageDownloadNotice() {
    var download = $('DOWNLOAD_IMAGE');
    download.style.top = (getWinHeight()/2 - 50) + 'px';
    download.style.left = (getWinWidth()/2 - 110) + 'px';
    download.style.display = 'block';
}

// hide the image download box
function hideImageDownloadNotice() {
    $('DOWNLOAD_IMAGE_LINK').style.display = 'none';
    $('DOWNLOAD_IMAGE_WAIT').style.display = 'block';
    $('DOWNLOAD_IMAGE_LINK').innerHTML = "";
    $('DOWNLOAD_IMAGE').style.display = 'none';
}

// display the image print box
function showImagePrintNotice() {
    var print = $('PRINT_IMAGE');
    print.style.top = (getWinHeight()/2 - 50) + 'px';
    print.style.left = (getWinWidth()/2 - 110) + 'px';
    print.style.display = 'block';
}

// hide the image print box
function hideImagePrintNotice() {
    $('PRINT_IMAGE_LINK').style.display = 'none';
    $('PRINT_IMAGE_WAIT').style.display = 'block';
    $('PRINT_IMAGE_LINK').innerHTML = "";
    $('PRINT_IMAGE').style.display = 'none';
}

// clear any errors displayed in the error message box
function clearErrorDisplay() {
    var now = new Date().getTime();
    if (now > (ERROR_MESSAGE_LAST_SET_TIME + ERROR_MESSAGE_TIMEOUT)) {
        setNodeText($('ERROR_DISPLAY'), "");
    }
}

// send a callback to the server to display the available layers for the fixed resource
function showAvailableLayers() {
    waitZoom(true);
    var params = 'resource_name=' + EMR_ENTITY_IDS_RESOURCE_NAME;
    processXMLCall('QueryServices.asmx/GetLayersList','showLayers(xmlhttp.responseXML)','POST', params);
}

// handle the web service response to populate available layers
function showLayers(xmlResponse) {
    var htmlText = getXMLText(xmlResponse);
    if (htmlText != '') {
        $('LayerSelected').innerHTML = htmlText;
    }
    waitZoom(false);
}

function selectedLayerChanged(el) {
    var selectedLayer = $('select_entity_id_layer');
    var selectedLayerId = selectedLayer.options[selectedLayer.selectedIndex].value;
    if (selectedLayerId != '')
        processActiveLayer(selectedLayerId);
	$('EntityIds_Label').style.display = 'block';
	$('EntityIds_Text').style.display = 'block';
	$('ZoomToFeatureButton').value = 'Zoom to Entity IDs';
	$('ZoomToFeature').style.display = 'block';
}

function layerIsEmptyGraphic(divID) {
    var layerName = getNodeText($(divID + '_textCell'));
    layerName = RTrim(layerName);
    for (var i=0; i<EMR_GRAPHIC_LAYER_NAMES.length; i++) {
        if (EMR_GRAPHIC_LAYER_NAMES[i] == layerName) {
            // it's a graphic layer, so save for later and return true
            $('graphics_layer_name').value = layerName;
            return true;
        }
    }
    return false;
}

function promptGraphicLayerZoomSelection(divID) {
    $('Validation_zoomToGraphicsLayer').innerHTML = '';
    var rdo = $(divID + '_RDO');
    if (rdo) {
        rdo.click();
    }
    EMR_ACTIVE_LAYER_DIV_ID = divID;
    $('zoomscale_n').value = mapExtentN;
    $('zoomscale_s').value = mapExtentS;
    $('zoomscale_e').value = mapExtentE;
    $('zoomscale_w').value = mapExtentW;
    $('zoomscale_lat').value = (parseFloat(mapExtentS) + parseFloat(mapExtentN)) / 2;
    $('zoomscale_lng').value = (parseFloat(mapExtentE) + parseFloat(mapExtentW)) / 2;
    
    if ((mapExtentN - mapExtentS) < EMR_GRAPHIC_LAYER_MAX_SCALE_DEGREE_MEASURE
        && (mapExtentE - mapExtentW) < EMR_GRAPHIC_LAYER_MAX_SCALE_DEGREE_MEASURE)
	{
        setTimeout('zoomAndActivateGraphicsLayer(true);', 500);
    } else {
        showFloatingPanel('ScaleZoom_Panel');
    }
}

function cancelGraphicsLayerZoom() {
    var chk = $(EMR_ACTIVE_LAYER_DIV_ID + '_CheckBox');
    if (chk) {
        chk.click();
    }
    hideFloatingPanel('ScaleZoom_Panel');
}

function zoomAndActivateGraphicsLayer(useLatLong) {
    var context = map.controlName;
    var message = 'ZoomToGraphicsLayer';
    var validationEl = $('Validation_zoomToGraphicsLayer');
    
    if (useLatLong || $('scalezoom_latlng_rdo').checked) {
        var n = $('zoomscale_n').value;
        if (!n.match(reLatLng)) {
            validationEl.innerHTML = EMR_ERRORS.e1007;
            return;
        }
        message += '&n=' + n;
        var s = $('zoomscale_s').value;
        if (!s.match(reLatLng)) {
            validationEl.innerHTML = EMR_ERRORS.e1007;
            return;
        }
        message += '&s=' + s;
        var e = $('zoomscale_e').value;
        if (!e.match(reLatLng)) {
            validationEl.innerHTML = EMR_ERRORS.e1007;
            return;
        }
        message += '&e=' + e;
        var w = $('zoomscale_w').value;
        if (!w.match(reLatLng)) {
            validationEl.innerHTML = EMR_ERRORS.e1007;
            return;
        }
        message += '&w=' + w;
    }
    else if ($('scalezoom_zip_rdo').checked) {
        var zipcode = $('zoomscale_zip').value;
        if (!zipcode.match(reZipcode)) {
            validationEl.innerHTML = EMR_ERRORS.e1002;
            return;
        }
        message += '&zipcode=' + zipcode;
		setTimeout("processActiveLayer('10002')", 10000);
    }
    else if ($('scalezoom_huc_rdo').checked) {
        var huc = $('zoomscale_huc').value;
        if (!huc.match(reWatershedHUC8)) {
            validationEl.innerHTML = EMR_ERRORS.e1001;
            return;
        }
        message += '&huc=' + huc;
    }
    else if ($('scalezoom_latlngrad_rdo').checked) {
        var lat = $('zoomscale_lat').value;
        var lng = $('zoomscale_lng').value;
        var rad = $('zoomscale_rad').options[$('zoomscale_rad').selectedIndex].value;
        if (!lat.match(reLatLng)) {
            validationEl.innerHTML = EMR_ERRORS.e1007;
            return;
        }
        if (!lng.match(reLatLng)) {
            validationEl.innerHTML = EMR_ERRORS.e1007;
            return;
        }
        if (!rad.match(reDouble)) {
            validationEl.innerHTML = EMR_ERRORS.e1011;
            return;
        }
        message += '&lat=' + lat;
        message += '&lng=' + lng;
        message += '&rad=' + rad;
    }
    hideFloatingPanel('ScaleZoom_Panel');
    showPageLoadingNotice();
    // make the callback
    message += '&graphics_resource_name=' + EMR_GRAPHIC_RESOURCE_NAME;
    message += '&graphics_layer_name=' + $('graphics_layer_name').value;
    message += '&report_id=' + EMR_GRAPHIC_LAYER_REPORT_ID;
    message += '&report_file=' + EMR_GRAPHIC_LAYER_REPORT_FILE;
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function clearGraphicsLayer(divID) {
    // turn off the layer in the TOC
    $(divID + '_CheckBox').checked = false;
    // get the layer name
    var layerName = getNodeText($(divID + '_textCell'));
    layerName = RTrim(layerName);
    // make the callback
    var context = map.controlName;
    var message = 'ClearGraphicsLayer';
    message += '&graphics_resource_name=' + EMR_GRAPHIC_RESOURCE_NAME;
    message += '&graphics_layer_name=' + layerName;
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    // clear the graphics layer results
//    $('queryResults').innerHTML = '';
}

function showCallbackError(message, skipMsgPrefix) {
	setNodeText($('ERROR_DISPLAY'), (!skipMsgPrefix ? "There was a problem with your request: " : "") + message);
    ERROR_MESSAGE_LAST_SET_TIME = new Date().getTime();
    // clear the map loading message if necessary
    hidePageLoadingNotice();
    map.divObject.style.cursor = map.cursor;
}

function refreshMap() {
    showPageLoadingNotice();
    // make the callback
    var context = map.controlName;
    var message = 'RefreshMap';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function refreshTOC() {
    showTOCLoadingNotice();
    tocNodetreeNeedsRefreshing = true;
    // make the callback
    var context = map.controlName;
    var message = 'RefreshTOC';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function cleanUpText(tableCell, maxLength) {
    var nameText = RTrim(getNodeText(tableCell));
//    if (nameText.length > maxLength && nameText.indexOf(' ',maxLength) > -1)
//        alert(nameText);
//        tableCell.innerHTML = nameText.substring(0, nameText.indexOf(' ',maxLength)) + '<BR/>' + nameText.substring(nameText.indexOf(' ',maxLength)+1, nameText.length);
}

// update the watershed list based on state selection
function watershedParamStateChanged(el, inputId) {
    var params = 'state=' + $('WATERSHED_PARAM_STATE_SELECTOR').options[$('WATERSHED_PARAM_STATE_SELECTOR').selectedIndex].id;
    processXMLCall('QueryServices.asmx/GetStateWatershedsOptionsOnly','viewReportWatersheds(xmlhttp.responseXML, "' + inputId + '")','POST', params);
}

// handle the web service response to populate the list of counties for a state
function viewReportWatersheds(xmlResponse, inputId) {
    var select = $(inputId);
    // IE bug hack: add TWO empty options on the front, then set the outerHTML to itself
    if (browserIsIE)
        select.innerHTML = "<options><option> -- </option><option> -- </option>" + getXMLText(xmlResponse) + "</options>";
    else
        select.innerHTML = "<options><option> -- </option>" + getXMLText(xmlResponse) + "</options>";
    select.outerHTML = select.outerHTML;
}

function toggleMapCoordinates() {
    var visibility = (webMapAppCoordNorth.style.display == 'none') ? 'block' : 'none';
    webMapAppCoordNorth.style.display = visibility;
    webMapAppCoordSouth.style.display = visibility;
    webMapAppCoordEast.style.display = visibility;
    webMapAppCoordWest.style.display = visibility;
}

function RefreshMapCoordinates() {
    // make the callback
    var context = map.controlName;
    var message = 'RefreshMapCoordinates';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function promptVisibleLayersSelection() {
    $('FEATURE_SELECTION_LAYER').style.display = 'none';
    $('FEATURE_SELECTION_WAIT').style.display = 'block';
    showFloatingPanel('VisibleLayerSelection_Panel');
    // make the callback
    var context = map.controlName;
    var message = 'ShowVisibleLayersSelection';
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function showVisibleLayersSelection(options) {
    var select = $("FEATURE_SELECTION_LAYER");
    // IE bug hack: add TWO empty options on the front, then set the outerHTML to itself
    if (browserIsIE)
        select.innerHTML = "<options><option> -- </option><option> -- </option>" + options + "</options>";
    else
        select.innerHTML = "<options><option> -- </option>" + options + "</options>";
    select.outerHTML = select.outerHTML;
    $('FEATURE_SELECTION_LAYER').style.display = 'block';
    $('FEATURE_SELECTION_WAIT').style.display = 'none';
    try {
        $('SelectLayerOK').focus();
    } catch(err) {
        // do nothing
    }
    // reset the TOC in case there is no radio button on the desired layer
    processTOCLayers();
}

function selectLayerForFeatureSelection() {
    var select = $("FEATURE_SELECTION_LAYER");
    var layerID = select.options[select.selectedIndex].id;
    processActiveLayer(layerID);
    hideFloatingPanel('VisibleLayerSelection_Panel');
}

function MapIt(layerId, featureId) {
    showTOCLoadingNotice();
    var context = map.controlName;
    var message = 'SelectAndZoomToID';
    message += '&layerId=' + layerId;
    message += "&id='" + featureId + "'";
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
    // prepare the feature for report execution
    EMR_FEATURES_TEXT = "{'layer_name': '', 'layer_id': '" + layerId + "', 'features': [{'value': '" + featureId.replace('|',',') + "'}]}";
    EMR_FEATURES = eval('(' + EMR_FEATURES_TEXT + ')');
    setTimeout('retrieveLayerReports("' + layerId + '")', 5000);
}

function loadGMap(kmlFilePath) {
	var lng = (parseFloat(mapExtentW) + parseFloat(mapExtentE)) / 2;
	var lat = (parseFloat(mapExtentN) + parseFloat(mapExtentS)) / 2;
    window.open("gmap.aspx?lat=" + lat + "&lng=" + lng + "&kml=" + kmlFilePath, "", "top=50, left=50, height=500, width=600, menubar=no, status=no, titlebar=no, toolbar=no", "");
}

function loadVEMap(rssFilePath) {
    window.open("VEMap.html?RSS=" + rssFilePath, "", "top=50, left=50, height=500, width=600, menubar=no, status=no, titlebar=no, toolbar=no", "");
}

function getLayerMetadata(layerName) {
    var params = 'resource_name=&layer_name=' + layerName;
    processXMLCall('QueryServices.asmx/GetLayerMetadata','showLayerMetadata(xmlhttp.responseXML)','POST', params);
    $('LAYER_METADATA_LOADING').style.display = '';
    $('LAYER_METADATA').style.display = 'none';
    $('LAYER_METADATA').innerHTML = '';
    showFloatingPanel('LayerMetadata_Panel');
    expandFloatingPanel('LayerMetadata_Panel');
}

function showLayerMetadata(xmlResponse) {
    var htmlText = getXMLText(xmlResponse);
    if (htmlText == '') {
        htmlText = EMR_ERRORS.e1009;
    }
    $('LAYER_METADATA_LOADING').style.display = 'none';
    $('LAYER_METADATA').style.display = '';
    $('LAYER_METADATA').innerHTML = htmlText;
}

function setLayerOutOfScale(layerName) {
    var tocDiv = $('Toc1');
    var tables = tocDiv.getElementsByTagName('table');
    for (var i=0;i<tables.length;i++)
    {
        var id = tables[i].parentNode.id;
        var tds = tables[i].getElementsByTagName('td');

        if ((tds.length == 5 && (RTrim(getNodeText(tds[4])) == layerName))
            || (tds.length == 4 && (RTrim(getNodeText(tds[3])) == layerName))) {

            var layerCheckbox = $(id + '_CheckBox');
            if (layerCheckbox && layerCheckbox.checked) {
                layerCheckbox.checked = false;
            }
            break;
        }
    }
    showCallbackError(EMR_ERRORS.e1008 + layerName + EMR_ERRORS.e1010, true);
}

function promptMapPrint() {
    showFloatingPanel('PrintMap_Panel');
    $('PrintMapOK').focus();
}

function generateMapPrintImage() {
    hideFloatingPanel('PrintMap_Panel');
    showImagePrintNotice();
    $('PRINT_IMAGE_LINK').style.display = 'none';
    $('PRINT_IMAGE_WAIT').style.display = 'block';
//    showPageLoadingNotice();
    var context = map.controlName;
    var title = $('PRINT_MAP_TITLE').value;
    var message = 'GenerateMapPrintImage&title=' + escape(title);
    message = createClientPostBackQueryString(context, message);
    WebForm_DoCallback('__Page', message, processCallbackResult, context, postBackError, true);
}

function printMapImage(title, id) {
    $('PRINT_IMAGE_LINK').style.display = 'block';
    $('PRINT_IMAGE_WAIT').style.display = 'none';
    var url = "PrintMap.aspx?title=" + title + "&id=" + id;
    $('PRINT_IMAGE_LINK').innerHTML = " &nbsp; &nbsp; <b><img border='0' src='images/print-small.gif' /> &nbsp; <a onclick='hideImagePrintNotice();' href='" + url + "' target='_blank'>Print Map Image</a> &nbsp;  &nbsp; <br/><br/><a href='javascript:void(0);' onclick='hideImagePrintNotice()'>Cancel</a></b>";
    hidePageLoadingNotice();
    showImagePrintNotice();
}

// clear the page loading notice if it's been displayed for n seconds
function clearPageLoadingNotice() {
    var now = new Date().getTime();
    var loading = $('PAGE_LOADING');
    if (loading.style.display == 'block') {
        if (now > (PAGE_LOADING_LAST_STARTED_TIME + PAGE_LOADING_TIMEOUT)) {
            showCallbackError(EMR_ERRORS.e1012, true);
 			map.divObject.style.cursor = map.cursor;
       }
    }
}

function showMapPoint(x, y, lng, lat) {
    // add the identify icon to the map canvas
	if (!$('IdentifyLocation')) {
        addIdentifyLocation();
        $('IdentifyLocation').style.textAlign = "center";
    }
    if (!$('IdentifyLocationCoords'))
    	$('IdentifyLocation').innerHTML += '<div class="lnk-black" id="IdentifyLocationCoords"></div><div class="lnk-black" id="IdentifyLocationMenu" style="visibility:hidden;"><a href="javascript:void(0);" onclick="hideLayer(\'IdentifyLocation\');">Remove</a>';
	$('IdentifyLocationCoords').innerHTML = '<nobr>' + lng + ', ' + lat + '</nobr>';
	var xoffset = lng < -100 ? 69 : 65;
	var yoffset = 23;
	window.setTimeout('moveLayer("IdentifyLocation", ' + (x-xoffset) + ', ' + (y-yoffset) + '); showLayer("IdentifyLocation");', 0);
    hidePageLoadingNotice();
	map.divObject.style.cursor = map.cursor;
}

function displayIdentificationLabel() {
    if (DISPLAY_IDENTIFICATION_LABEL) {
        DISPLAY_IDENTIFICATION_LABEL = false;
        setTimeout("showLayer('IDENTIFICATION_LABEL')", 3000);
    } else {
        hideLayer('IDENTIFICATION_LABEL');
    }
}

function timeoutQueryResult(id) {
    var queryResult = $(id);
    if (queryResult) {
        queryResult.id = "queryresult_toggle_" + id;
        queryResult.className = "queryresult";
        queryResult.style.backgroundColor = "#EDEDED";
        queryResult.style.height = "20px";
        queryResult.onmouseover = "showQueryResultRemove('" + id + "')";
        queryResult.onmouseout = "hideQueryResultRemove('" + id + "')";
        queryResult.innerHTML = "<img src='images/blank.gif' width=20px height=15px />" + EMR_ERRORS.e1013 + " &nbsp; <span id='queryresult_remove_" + id + "'><a href='javascript:void(0);' onclick='clearQueryResult(\"" + id + "\");'>Remove</a></span>";
    }
}

function setCoordinateValue(id, name) {
    var input = $(id);
    if (input) {
        if (name.toUpperCase().indexOf('LAT') > -1) {
            if (name.toUpperCase().indexOf('MAX') > -1) {
                input.value = mapExtentN;
                inputLatMax = [id, name];
            } else if (name.toUpperCase().indexOf('MIN') > -1) {
                input.value = mapExtentS;
                inputLatMin = [id, name];
            }
        } else if (name.toUpperCase().indexOf('LONG') > -1) {
            if (name.toUpperCase().indexOf('MAX') > -1) {
                input.value = mapExtentE;
                inputLongMax = [id, name];
            } else if (name.toUpperCase().indexOf('MIN') > -1) {
                input.value = mapExtentW;
                inputLongMin = [id, name];
            }
        }
    }
}

function setMapExtentCoordinates(n, s, e, w) {
    mapExtentN = n;
    mapExtentS = s;
    mapExtentE = e;
    mapExtentW = w;
    if (inputLatMax.length == 2)
        setCoordinateValue(inputLatMax[0], inputLatMax[1]);
    if (inputLatMin.length == 2)
        setCoordinateValue(inputLatMin[0], inputLatMin[1]);
    if (inputLongMax.length == 2)
        setCoordinateValue(inputLongMax[0], inputLongMax[1]);
    if (inputLongMin.length == 2)
        setCoordinateValue(inputLongMin[0], inputLongMin[1]);
}

function layersCanBeActivated(resourceName) {
    return EMR_RESOURCE_NAMES_EXCLUDE_ACTIVATING_LAYERS.indexOf(resourceName) < 0;
}

function showIDResultsPanel()
{
    showFloatingPanel('ID_Results');
    expandFloatingPanel('ID_Results');
}

function showIDResultsPanel()
{
    showFloatingPanel('ID_Results');
    expandFloatingPanel('ID_Results');
}

function showQueryResultsPanel()
{
    showFloatingPanel('Query_Results_Panel');
    expandFloatingPanel('Query_Results_Panel');
}

function showQueryBuilderPanel()
{
    showFloatingPanel('Parameters_Panel');
    expandFloatingPanel('Parameters_Panel');
}





/* ******* */
/* ADAPTED FROM COMPILED ESRI LIBRARY FOR postBackError() */
/* ******* */

function postBackError(argument, context) {
    showCallbackError(argument);
}


/* ******* */
/* ADAPTED FROM COMPILED ESRI LIBRARY FOR showLapseAlert() */
/* ******* */

function showLapseAlert() {
    showCallbackError('Session has timed out from extended inactivity. A new session must be started to use this application by closing this browser and reopening.');
}


/* ******* */
/* ADAPTED FROM COMPILED ESRI LIBRARY FOR maximumLapseTime */
/* ******* */

maximumLapseTime = 120; // Change this value to session timeout in minutes



/* ******* */
/* ADAPTED FROM COMPILED ESRI LIBRARY FOR ToolbarMouseDown() */
/* ******* */

function ToolbarMouseDown(toolbarName, toolbarItemName, buttonType, e)
{
    if (buttonType != "DropDownBox" && !isLeftButton(e))
        return;
    var f = document.forms[docFormID];
    var imageTag = toolbarName + toolbarItemName + "Image";
    var cell = toolbarName + toolbarItemName;
    var toolbar = Toolbars[toolbarName];
    var toolbarComp = $find(toolbarName);
    if (toolbar === null || toolbarComp===null) return;
    if (toolbar.items[toolbarItemName].disabled) { return; }

    // SDK: show loading notice for identify and select tools
    /*
    if (toolbarItemName == 'MapIdentify' || toolbarItemName == 'PointSelect') {
        $('Map1').onclick = showPageLoadingNotice;
    } else {
        $('Map1').onclick = doNothing;
    }
    */
    if (toolbarItemName == 'RectangleSelect') {
        $('Map1').onmouseup = showPageLoadingNotice;
    } else {
        $('Map1').onmouseup = doNothing;
    }
    if (toolbarItemName == 'RubberBandSelect') {
        $('Map1').ondblclick = showPageLoadingNotice;
    } else {
        $('Map1').ondblclick = doNothing;
    }

    if (buttonType == "Tool") {
        //change toolbar's selected tool
        f.elements[toolbar.currentToolField].value = toolbarItemName;
        //clientAction for each buddy control
        var clientAction =  toolbar.items[toolbarItemName].clientAction;
        if (clientAction != null) {
            var clientActions = "";
            if (!toolbar.items[toolbarItemName].isClientActionCustom) {
                var buddies = toolbar.buddyControls;
                if (buddies != null) {
                    for (var i = 0; i < buddies.length; i++)
                    {
                        var modeField = f.elements[buddies[i] + "_mode"];
                        if (modeField != null)
                            modeField.value = toolbarItemName;
                        var cursor = toolbar.items[toolbarItemName].cursor;
                        if (cursor != null)
                            clientActions = clientActions + clientAction + " ( '" + buddies[i] + "' , '" + toolbarItemName + "', " + toolbar.items[toolbarItemName].showLoading + ",'" + cursor + "'); ";
                        else
                            clientActions = clientActions + clientAction + " ( '" + buddies[i] + "' , '" + toolbarItemName + "', " + toolbar.items[toolbarItemName].showLoading + "); ";
                    }
                }
            }
            else
            {
                clientActions = clientAction;
            }
            //fire onSelect handler if set... fires before clientActions
            var tbObject = $find(toolbarName);
            if (tbObject!=null) {
                var handler = tbObject.get_events().getHandler('onToolSelected');
                if(handler) 
                    handler(tbObject,{"name": toolbarItemName, "tool": toolbar.items[toolbarItemName]});
            }
            if (toolbar.items[toolbarItemName].preExecFunction != null)
                clientActions += toolbar.items[toolbarItemName].preExecFunction;
    
            var clientActionFunction = new Function(clientActions);
            clientActionFunction.call(null);
            //select this tool and unselect others
            Toolbars[toolbarName].selectTool();
            Toolbars[toolbarName].refreshGroup();
        }
        // SDK: prompt the user to choose an active layer for this tool
//        if (toolbarItemName == 'PointSelect' || toolbarItemName == 'RubberBandSelect' || toolbarItemName == 'RectangleSelect')
//            promptVisibleLayersSelection();
//        if (toolbarItemName != 'Measure')
//            closeMeasureToolbarTool();
    }
    else if (buttonType == "Command")
    {
        if (toolbar.items[toolbarItemName].preExecFunction != null)
            eval(toolbar.items[toolbarItemName].preExecFunction);

        // SDK: commands need to show the wait message
        /*
        if (toolbarItemName != 'Magnifier' && toolbarItemName != 'Print' && toolbarItemName != 'OverviewMapToggle')
            showPageLoadingNotice(3000);
*/
        //if (toolbar.items[toolbarItemName].showLoading) showLoading();
        document.body.style.cursor = "wait";
        //reset toolbar images: IE does not refresh toolbar properly if this is not done.
        Toolbars[toolbarName].refreshCommands();
        Toolbars[toolbarName].selectTool();
        var toolbarComp = $find(toolbarName);
        //set selected style and image
        var cellElement = document.getElementById(cell);
        cellElement.style.cssText = toolbar.selectedStyle;
        if (toolbar.toolbarStyle != "TextOnly")
        {
            var img = document.images[imageTag];
            switchImageSourceAndAlphaBlend(img,toolbar.items[toolbarItemName].selectedImage);
        }
        cellElement.focus(); // Allow pending onchange event to fire
        var clientAction =  toolbar.items[toolbarItemName].clientAction;
        if (clientAction != null && clientAction.length>0) {
            esriClientActionFunction = clientAction;
            window.setTimeout("eval(esriClientActionFunction);", 0);
        }
        else {
            var arg = 'eventArg='+toolbarItemName+'&ControlID='+toolbarName+'&ControlType=Toolbar&PageID='+toolbar.pageID;
            toolbarComp.doCallback(arg,toolbarComp);
        }

        document.body.style.cursor = "default";
    }
    else if (buttonType == "DropDownBox")
    {
        var selectDropDown = toolbarName + toolbarItemName + "DropDownBox";
        var selectValueField = toolbarName + toolbarItemName + "Value";
        //f.elements[selectValueField].value = f.elements[selectDropDown].value;
        var arg = 'eventArg='+toolbarItemName+'&ControlID='+toolbarName+'&ControlType=Toolbar&PageID='+toolbar.pageID+'&'+selectValueField+'='+f.elements[selectDropDown].value;
        toolbarComp.doCallback(arg,toolbarComp);
    }
}
// empty function for when user clicks on map without a tool selected
function doNothing() {}




/* ******* */
/* ADAPTED FROM COMPILED ESRI LIBRARY FOR floating panel functions */
/* ******* */
/*
toggleFloatingPanelState = function(fpID, fireServerSideExpandEvent, fireServerSideCollapseEvent)
{
    var obj = $find(fpID);
    if(obj)
        obj.toggleState(fireServerSideExpandEvent, fireServerSideCollapseEvent);
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
showFloatingPanel = function(fpID, doCallback, argument)
{
    var obj = $find(fpID);
    if(obj)
        obj.show(doCallback, argument);
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
toggleFloatingPanelVisibility = function(fpID, doCallback, argument)
{
    var obj = $find(fpID);
    if(obj)
        obj.toggleVisibility(doCallback, argument);
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
hideFloatingPanelFrame = function(fpID)
{
    var obj = $find(fpID);
    if(obj)
        obj.hideFrame();
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
showFloatingPanelFrame = function(fpID)
{ 
    var obj = $find(fpID);
    if(obj)
        obj.showFrame();
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
expandFloatingPanel = function(fpID)
{
    var obj = $find(fpID);
    if(obj)
        obj.expand();
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
collapseFloatingPanel = function(fpID)
{
    var obj = $find(fpID);
    if(obj)
        obj.collapse();
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
dockFloatingPanel = function(fpID)
{
    var obj = $find(fpID);
    if(obj)
        obj.dock();
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
undockFloatingPanel = function(fpID)
{
    var obj = $find(fpID);
    if(obj)
        obj.undock();
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
hideFloatingPanel = function(fpID, doCallback, argument)
{
    var obj = $find(fpID);
    if(obj)
        obj.hide(doCallback, argument);
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
    // SDK 29-DEC-2008: prevent measure toolbar from re-appearing
    if (fpID.indexOf('MeasureToolbar') > -1)
        closeMeasureToolbarTool();
};
showFloatingPanel = function(fpID, doCallback, argument)
{
    var obj = $find(fpID);
    if(obj)
        obj.show(doCallback, argument);
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
toggleFloatingPanelDockState = function(fpID)
{
    var obj = $find(fpID);
    if(obj)
        obj.toggleDockState();
    // SDK 03-AUG-2007
    var fp = $(fpID);
    fp.style.left = 100 + Math.round(100*Math.random()) + "px";
    fp.style.top = 100 + Math.round(100*Math.random()) + "px";
    // SDK 10-MAR-2007
    resetEMRFloatingPanels(fpID);
};
*/

/* ******* */
/* ADAPTED FROM COMPILED ESRI LIBRARY FOR treeview plus functions */
/* ******* */

ESRI.ADF.UI.TreeViewPlus.prototype._nodeChecked = function (nodeID)
{
    // SDK 28-Mar-2007: trigger the turning on/off of resource checkbox
    setTimeout('cascadeSelectedLayer("' + nodeID + '")', 750);

    var argument='nodeID=' + nodeID + '&';
    var checkBox=document.getElementById(nodeID + '_CheckBox');
    if (checkBox===null) {return;}
    if (checkBox.checked===false)
    {
        argument+='EventArg=checked&Value=false';
        checkBox.value=false;

        // SDK 30-Apr-2007: turn off the layer if the user just clicked on a graphics layer
        if (layerIsEmptyGraphic(nodeID)) {
            clearGraphicsLayer(nodeID);
            return false;
        }

    }
    else
    {
        argument+='EventArg=checked&Value=true';
        checkBox.value=true;

        // SDK 30-Apr-2007: do extra stuff if the user just turned on a graphics layer
        if (layerIsEmptyGraphic(nodeID)) {
            promptGraphicLayerZoomSelection(nodeID);
            return false;
        }

    }
    this._raiseEvent('nodeChecked', {"nodeID": nodeID, "checked":checkBox.checked});
    var context = null;
    eval(this._callbackFunctionString);
}

function togglePanelBarShadingLeft(over) {
	$('ToggleCell').style.backgroundColor = over ? "Gray" : "White";
}

