// This file contains java/DWR specific code for updating the map.  This file must be referenced
// in ajax.jsp along with mapTools.js.


//add the elseif statements for the correct actions on clicking on submenu of drawing tool
//this statement made sure that the click on the submenu is not going to the map, which will 
//most likely bring up the loading image
var selecting = false;
var newSelectMinx;
var newSelectMiny;
var newSelectMaxx;
var newSelectMaxy;
var currLevel = 0;
var keyValue;
var layerID;

function refreshMap () {
    //var image = top.frames["map"].document.getElementById("theImage");
    //setOpacity(image,100);
    //fadeOut("theImage",100);
    showLayer("loadLayer");
    DWREngine.setOrdered(true);
    DWRMapAllBean.setMapWidth(top.getMapWidth());
    DWRMapAllBean.setMapHeight(top.getMapHeight());
    hideZoomBox();
    var reqMinX, reqMinY, reqMaxX, reqMaxY;
    var pixelX = (Math.abs(newMaxx)-Math.abs(newMinx)) / (mapWidth+orginOffsetX);
    var reqMinX = newMinx - pixelX * ( 0 - orginOffsetX);
    var reqMaxX = newMaxx + pixelX * ( 0 - orginOffsetX);
    var pixelY = (Math.abs(newMaxy) - Math.abs(newMiny)) / (mapHeight+orginOffsetY);
    var	reqMinY = newMiny - pixelY * (0 - orginOffsetY);
    var	reqMaxY = newMaxy + pixelY * (0 - orginOffsetY);
    if ( state == "CLEAR" || state == "INIT" ) {
        if ( state == "CLEAR" ) {
            var drawString = top.ajaxFrame.checkfordrawing();
            /*if ( drawString != null && drawString != "" ) {
                // Render vml drawing and place in session
                DWRRenderDrawingBean.setDrawingString(drawString);
                DWRMapAllBean.setDrawString(null, drawString);
                // Clear vml data from layer and drawing will be rendered as an acetate layer
                top.map.document.getElementById("theTop").innerHTML
                    = '<img name="pixel"  src="images/transparentpixel.gif" width=1 height=1>';
                zeroVariables();
            } else {
                DWRMapAllBean.setDrawString(null, "");
            }*/
        }

        DWRMapAllBean.setCommand(null, state);
        DWRMapAllBean.getMapUrl(setImage);
        DWRMapAllBean.getConfig(handleConfig);
        setToolImage('zoomin');
        top.ajaxFrame.setState("ZOOMIN");
    } else {
        if ( state == "ZOOMIN" || state == "ZOOMOUT" ) {
        	
            //DWRMapAllBean.setDrawString(null, "");
            DWRMapAllBean.setClickX(null, cx.toString());
            DWRMapAllBean.setClickY(null, cy.toString());
            DWRMapAllBean.setMinX(null, reqMinX.toString());
            DWRMapAllBean.setMinY(null, reqMinY.toString());
            DWRMapAllBean.setMaxX(null, reqMaxX.toString());
            DWRMapAllBean.setMaxY(null, reqMaxY.toString());
            DWRMapAllBean.setCommand(state);
            DWRMapAllBean.getMapUrl(setImage);
            DWRMapAllBean.getConfig(handleConfig);

            if ( state == "ZOOMIN" ) {
                setToolImage('zoomin');
                top.ajaxFrame.setState("ZOOMIN");
            }
           
        } else if ( state == "PAN" || state == "LASTEXTENT" ) {
            DWRMapAllBean.setMinX(null, newMinx.toString());
            DWRMapAllBean.setMinY(null, newMiny.toString());
            DWRMapAllBean.setMaxX(null, newMaxx.toString());
            DWRMapAllBean.setMaxY(null, newMaxy.toString());
            DWRMapAllBean.setCommand(state);
            DWRMapAllBean.getMapUrl(setImage);
            DWRMapAllBean.getConfig(handleConfig);

            if ( state == "LASTEXTENT" ) {
                setToolImage('zoomin');
                top.ajaxFrame.setState("ZOOMIN");
            //top.ajaxFrame.clearMeasuring('ZOOMIN');
            }
        } else if ( state == "ZOOMEXTENT" || state == "PANNE" || state == "PANSE" || state == "PANNW"
            || state == "PANSW" || state == "PANNORTH" || state == "PANSOUTH" || state == "PANEAST"
            || state == "PANWEST" || state == "MAPREFRESH" || state == "REFRESH" || state == "PRINT") {
            DWRMapAllBean.setCommand(state);
            DWRMapAllBean.getMapUrl(top.setImage);
            DWRMapAllBean.getConfig(handleConfig);
            setToolImage('zoomin');
            top.ajaxFrame.setState("ZOOMIN");
        } else if (state == "MEASURE"){
            DWRMapAllBean.setCommand(state);
            DWRMapAllBean.getMapUrl(top.setImage);
            DWRMapAllBean.getConfig(handleConfig);
            top.setMapCursor("cross");
            doArm();
        }
    }
}
/* check flash feature */
function checkFocusFeature () {
    DWRMapAllBean.getFocusImgFeature(flashFocusFeature);
}
/* transfer the call to mapFrame */
function flashFocusFeature ( data ) {
    if ( data != null ) {
        top.map.flashFocusFeature(data);
        DWRMapAllBean.setFocusFeature(null);
    }
}

/* tool tips */
function setToolTips () {
    DWRMapAllBean.initializeToolTips();
    parent.status = "Getting Tooltips...";
    DWRMapAllBean.getToolTipMapID(setTTMapID);
    DWRMapAllBean.getToolTipCount(setTTCount);
    DWRMapAllBean.getToolTipDisplayHTML(setTTDivText);
    DWRMapAllBean.getToolTipMapHTML(setTTMapText);
    DWRMapAllBean.cleanupToolTips(writeTT);
}

function setTTMapID ( data ) {
    ttMapID = data;
}

function setTTCount ( data ) {
    ttCount = data;
}

function setTTMapText ( data ) {
    ttMapText = data;
}

function setTTDivText ( data ) {
    ttDivText = data;
}

function writeTT () {
    writeTT();
    parent.status = "Tooltips retrieved";
}

function extendedMouseDown ( e ){
	
}

function setMapFull () {
    if ( isMapFull ) {
        top.window.frames["outerFrame"].cols = "280,*";
        top.map.setSizeButtonImg("images/FrameArea5.gif")
        isMapFull = false;
    } else {
        top.window.frames["outerFrame"].cols = "0,*";
        top.map.setSizeButtonImg("images/FrameArea0.gif")
        isMapFull = true;
    }

    top.resetMapSize();
}

function extendedSetState ( newstate ){
	
}
// check for mouseup
function extendedMouseUp ( e ) {
    getImageXY ( e );
    getMapXY(mouseX,mouseY);
    
    //alert("state: " + state+ "  ,  mouseX:" +mouseX+ " ,mouseY:"+mouseY+"  ,mapX:"+mapX+" ,mapY:"+mapY );
    if ( state == "IDENTIFYBYPOLY" ) {
    	//alert("state: " + state+ "  ,  newMinx:" +newMinx+ " ,newMiny:"+newMiny+"  ,newMaxx:"+newMaxx+" ,newMaxy:"+newMaxy );
    	showLayer("loadLayer");
    	DWREngine.setOrdered(true);
    	DWRPointFunctionBean.setMinX(newMinx);
    	DWRPointFunctionBean.setMinY(newMiny);
    	DWRPointFunctionBean.setMaxX(newMaxx);
    	DWRPointFunctionBean.setMaxY(newMaxy);
    	DWRPointFunctionBean.setPointSelectParcelLayer(false);
    	DWRPointFunctionBean.setIdentifyByPoly(true);
    	DWRPointFunctionBean.identifyAnyFeatureByPolygon(generateIdentifyReport);
    	
    	DWRPointFunctionBean.getHighlightedFeatureParams(highlightFeatures);
    	
    }
    if ( state == "IDENTIFY" ) {
        showLayer("loadLayer");
        DWREngine.setOrdered(true);
        DWRPointFunctionBean.setPointSelectParcelLayer(false);
        DWRPointFunctionBean.setIdentifyByPoly(false);
    	DWRPointFunctionBean.setClickX(mapX);
        DWRPointFunctionBean.setClickY(mapY);
        DWRPointFunctionBean.identifyAnyFeature(generateIdentifyReport);
      
        
    }else if( state == "POINTFUNCTION"){
    	//alert("state is POINTFUNCTION mapX and mapY --> " + mapX + " , " + mapY);
    	showLayer("loadLayer");
    	DWREngine.setOrdered(true);
    	DWRPointFunctionBean.setPointSelectParcelLayer(true);
    	DWRPointFunctionBean.setIdentifyByPoly(false);
    	DWRPointFunctionBean.setClickX(mapX);
        DWRPointFunctionBean.setClickY(mapY);
        DWRPointFunctionBean.identifyParcelFeature(generateIdentifyReport);
		
		DWRPointFunctionBean.getHighlightedFeatureParams(highlightFeatures);
		
    }
}
function generateIdentifyReport( switchdata ){
        hideLayer("loadLayer");
	switch(switchdata)
	{
		case "GENERATEREPORT":
		  DWREngine.setOrdered(true);
		  DWRPointFunctionBean.getReportArray(displayResults);
		  
		   hideLayer("loadLayer");
		  break;
		
		case "PARCEL":
			DWREngine.setOrdered(true);
			DWRPointFunctionBean.getReportArray(displayResults);
			
		   hideLayer("loadLayer");
			break;  
		case "ACTIVELAYERNOTTAXPARCEL":
			alert("Tax Parcel layer is not Active. Please activate Tax Parcel layer.");
			break;
		case "NOTVISIBLE":
		   alert("Layer is not Visible. Please turn ON the layer.");
		  break;
		case "NOTINSCALE":
		   alert("Layer is not Visible due to Map Scale. Please zoom in.");
		  break;
		case "NOTFOUNDFEATURES":
		   alert("No Features could be located. Please select again.");
		  break;
		default:
		  alert("end of switch");
	}
}


function openPanelByName(divName){
			
            //var panelElement = $(divName);
            var panelElement = top.busFrame.document.getElementById(divName);
            
            if (panelElement != null){
                panelElement.onclick();
            }
        } 

function displayResults(reportData) {
        //var resultArea = top.busFrame.document.getElementById("panelContent_IDENTIFY");
        var resultArea = top.busFrame.tabIframeIdentify.document.getElementById("panelContent_IDENTIFY");
		var innerdefaultHTMLTable = "<div style='overflow:visible;'> <table style='font-family:Arial,Helvetica,sans-serif;font-size:10px;border:thin;border-color:rgb(150,150,150);border-style:solid;padding:0;border-collapse:collapse;' width='100%'>";
		var innerStart = "", innerHTMLTable = "", innerEnd = "", innerHTML = "";
                var innerStartIndex = -1;
		for (i=0; i<reportData.length; i++ )
		{
                    
			for (j=0; j < reportData[i].length ; j++)
			{
				if (reportData[i][j] == "#SHAPE#" || reportData[i][j] == "[Geometry]" || reportData[i][j] == "Object Id"){
					//do nothing
                                    innerStartIndex = j;
                                    innerStart = "<TD style='border:thin;border-color:rgb(150,150,150);border-style:solid;padding:0;' align='center'></TD>" ;
                                    //innerHTMLTable = innerHTMLTable + "<TD style='border:thin;border-color:rgb(150,150,150);border-style:solid;padding:0;' align='center'></TD>" ;
				}
				else
				{
                                    if (j == innerStartIndex ){
                                        innerEnd = "<TD style='border:thin;border-color:rgb(150,150,150);border-style:solid;padding:0;' align='center'>" + reportData[i][j] + "</TD>" ;
                                    } else {
                                        innerHTML = innerHTML + "<TD style='border:thin;border-color:rgb(150,150,150);border-style:solid;padding:0;' align='center'>" + reportData[i][j] + "</TD>" ;					
                                    }
                                } 
				
			}

                        innerHTMLTable = innerHTMLTable + "<TR>"+innerStart + innerEnd + innerHTML + "</TR>";
                        innerStart = "";
                        innerEnd = "";
                        innerHTML = "";
		}
                
		innerHTMLTable = innerdefaultHTMLTable+innerHTMLTable + "</TABLE></DIV>";
		
		resultArea.innerHTML = innerHTMLTable;
                 //debugger;
                var parcelIdsObj = top.busFrame.tabIframeIdentify.document.getElementById("clickEvent");
                if (parcelIdsObj != null){
                    if (parcelIdsObj.value != null){
                        top.busFrame.tabIframeIdentify.showTaxParcelInfo("http://www.nccde.org/parcelview/parcelinfo.asp?parcel="+parcelIdsObj.value);
                    } else {
                        if (parcelIdsObj.attributes != null){
                            if (parcelIdsObj.attributes["value"].nodeValue != null){
                                top.busFrame.tabIframeIdentify.showTaxParcelInfo("http://www.nccde.org/parcelview/parcelinfo.asp?parcel="+parcelIdsObj.attributes["value"].nodeValue);
                            }
                        }
                    }
                }
}

	
// IY
function highlightFeatures(dataHashMap){
	//alert(DWRUtil.toDescriptiveString(dataHashMap, 1));	
	var featureLayerId = dataHashMap["LAYERID"];
	var featureIds = dataHashMap["FEATUREIDS"];
	var featureIdsFieldName = dataHashMap["FID_FIELD_NAME"]
	//alert("featureLayerId: " + featureLayerId + "  , featureIds: " + featureIds + " , featureIdsFieldName: " + featureIdsFieldName);
	zoomToFeatureFids(featureLayerId,featureIds,featureIdsFieldName);
}

function zoomToFeatureFids(featureLayerId,featureIds,featureIdsFieldName){
	showLayer("loadLayer");
	//alert("Zoom to FIDs");
	//showLayer("loadLayer");
	
	//TODO: Get from Server side as function param
	var keyColName = featureIdsFieldName; 
	//alert(featureID+" " +keyColName);
	DWREngine.setOrdered(true);
	//alert(" after DWREngine.setOrdered(true) ");
    
    //alert(" after showLayer('loadLayer') ");
    // zoom to the selected feature
    DWRMapAllBean.setLayerId( featureLayerId );
    
    var whereString = keyColName+ " in ("+ featureIds + ") ";
    DWRMapAllBean.setWhereClause( null, whereString)
    
    DWRMapAllBean.setCommand("ZOOMTOFIDS");
    
    
	if (state == "POINTFUNCTION")
	{
		//	Setting TaxLayerId Selected boolean to true.
		//	Need to confirm from server if the tax parcel(s) was/were really selected somehow.
		//	TaxParcelSelected boolean value was set from DWRPointFunctionBean's identifyParcelFeature() method
			DWRBufferBean.setTaxParcelHighlighted(); //Assuming everything is OK till now.
	}
	
	DWRMapAllBean.getMapUrl( setImage );
    DWRMapAllBean.getConfig( handleConfig );
	
}

function mapIt(layerId, ObjectId){
	
	//alert(" mapIt at AppMapTools.js with layerId and Objectid " + layerId + " and " + ObjectId);
	
	var featureID = ObjectId;
//TODO: Get from Server side as function param
	var keyColName = "OBJECTID" 
	DWREngine.setOrdered(true);
    showLayer("loadLayer");
    DWRMapAllBean.setLayerId( layerId );
    var whereString = keyColName+ " in ("+featureID + ") ";
    DWRMapAllBean.setWhereClause( null, whereString)
    DWRMapAllBean.setCommand( "ZOOMTOSINGLEFID" );
    DWRMapAllBean.getMapUrl( top.map.setImage );
    DWRMapAllBean.getConfig( top.ajaxFrame.handleConfig );
}
//IY END

function setKeyValue ( data ) {
    keyValue = data;
}

function setLayerID ( data ) {
    layerID = data;

    if ( layerID != null ) {
        popupAWindow("attributeReport.jsp?keyValue=" + keyValue + "&layerID=" + layerID);
    }

    hideLayer("loadLayer");
}

function extendedMouseMove ( e ){
}

function showHelp () {
    window.open("help/Help_Main.html");
}

function mailComments () {
    parent.location.href = 'mailto:INFORM_Comments@mail.dot.state.de.us?Subject=NPDES%20Feedback';
}
// ajax function to generate legend image
function generateLegend(lminx, lminy, lmaxx, lmaxy){
    DWRMapAllBean.genLegendSymbol(getLegendWidth(), getLegendHeight(), lminx, lminy, lmaxx, lmaxy, setLegend);
}

function setLegend(data){
    if (data != null){
        top.busFrame.$("imgLegend").src = data;
    }
}
//get legend width based on client side generic buz frame size
function getLegendWidth(){
    var theWidth;
    // Window dimensions:
    if (window.innerWidth) {
        theWidth=top.busFrame.window.innerWidth;
    } else if (document.documentElement && document.documentElement.clientWidth) {
        theWidth=top.busFrame.document.documentElement.clientWidth;
    } else if (document.body) {
        theWidth=top.busFrame.document.body.clientWidth;
    }
    return theWidth;
}
//get legend height based on client side generic buz frame size
function getLegendHeight(){
    var theHeight;
    if (window.innerHeight) {
        theHeight=top.busFrame.innerHeight - 80;
    } else if (document.documentElement && document.documentElement.clientHeight) {
        theHeight=top.busFrame.document.documentElement.clientHeight - 80;
    } else if (document.body) {
        theHeight=top.busFrame.document.body.clientHeight - 80;
    }
    return theHeight;
}


function openBufferPanel(){
        //alert("openBufferPanel");
        // Change Tool Panel Content's src to bufferPage.jsp
        top.busFrame.$("tabIframeTool").src = "bufferPage.html";
        // Dynamically open Buffer Page
        openPanelByName("divToolPanel");

}

function openPrintPanel(){
        // Change Tool Panel Content's src to bufferPage.jsp
        top.busFrame.$("tabIframeTool").src = "printSetup.jsp";
        // Dynamically open Buffer Page
        openPanelByName("divToolPanel");
}