// aimsIdentify.js
/*
*  JavaScript template file for ArcIMS HTML Viewer
*       dependent on aimsXML.js, ArcIMSparam.js, aimsCommon.js, aimsMap.js, and aimsLayers.js
*       To be interactive, dependent also on aimsDHTML.js, aimsClick.js, and aimsNavigation.js
*    functions: 
*       identify(e) {
*       hyperLink(e) {
*       writeGetFeatures(west1,south1,east1,north1) {
*       writeIdentifyXML(theLayer,theLayerType,theFields,leftX,bottomY,rightX,topY,hasLimit) {
*       Unique_Reply(theReply) {
*       replaceComma(inText) {
*       parseHyperLink(theReply) {
*       HyperLink_attributes(theReply) {
*       checkSelected() {
*       checkHyperLinkLayer(layerIndex) {
*/

aimsIdentifyPresent=true;

// hyperlink variables
var currentHyperLinkLayer="";
var currentHyperLinkField="";
var hyperlinkWindowWidth=700;
var hyperlinkWindowHeight=390;

// variable for search tolerance... dynamically set in app
var searchTolerance=0.01;
// starting record position for returned records
var queryStartRecord=0;

if (imsQueryURL=="") {
    imsQueryURL= imsURL + "&CustomService=Query";
}
var canQuery=true;
var newSelectCount=0;
var selectPoints = new Array();
var numrecs = 0;

/*
***************************************************************************************

Identify functions 

***************************************************************************************
*/

// identify feature

function identify(e,theLayer) {
    ActiveLayer=LayerID[theLayer];
    ActiveLayerType=LayerType[theLayer];
    ActiveLayerIndex=theLayer;
    setLayerFields(theLayer);

    highlightedOne="";
    var theX = mouseX;
    var theY = mouseY;
    getMapXY(theX,theY);
    searchTolerance = (xDistance/iWidth) * pixelTolerance;
    var tempWest = mapX - searchTolerance;
    var tempNorth = mapY + searchTolerance;
    var tempEast = mapX + searchTolerance;
    var tempSouth = mapY - searchTolerance;
    var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
    showRetrieveData();
    sendToServer(imsQueryURL,theString,7);
}

// hyperlink from feature
function hyperLink(e) {
   // added next line 5/2002 because changing active layer without reclicking
   // hyperlink button did reset hyperlinklayer
    var isOk = checkHyperLinkLayer(ActiveLayerIndex)
    if (!isOk) {
        currentHyperLinkLayer="";
        currentHyperLinkField="";
      }
    if (currentHyperLinkLayer!="") {
        highlightedOne="";
        var theX = mouseX;
        var theY = mouseY;
        getMapXY(theX,theY);
        searchTolerance = (xDistance/iWidth) * pixelTolerance;
        var tempWest = mapX - searchTolerance;
        var tempNorth = mapY + searchTolerance;
        var tempEast = mapX + searchTolerance;
        var tempSouth = mapY - searchTolerance;
        var tempSwap = swapSelectFields;
        //swapSelectFields=false;
        swapSelectFields=true;
        var tempSelect = selectFields;
        selectFields = LayerIDField[ActiveLayerIndex] + " " + LayerShapeField[ActiveLayerIndex] + " " + currentHyperLinkField;
        var theString = writeGetFeatures(tempWest,tempSouth,tempEast,tempNorth);
        selectFields = tempSelect;
        swapSelectFields=tempSwap;
        showRetrieveData();
        sendToServer(imsQueryURL,theString,hyperlinkXMLMode);
    } else {
        alert("This layer does not have any HyperLinks.");
    }
}

// write out XML request to identify features
function writeGetFeatures(west1,south1,east1,north1) {
    if (swapSelectFields) {
        selectFields=selFieldList[ActiveLayerIndex];    
     }
    var useString = writeIdentifyXML(ActiveLayer,ActiveLayerType,selectFields,west1,south1,east1,north1,maxFeaturesReturned,useLimitExtent);
    hightlightedOne="";
    return useString;
}

function writeIdentifyXML(theLayer,theLayerType,theFields,leftX,bottomY,rightX,topY,hasLimit) {
    var theString = '<?xml version="1.0" encoding="UTF-8"?><ARCXML VERSION="1.1">\n<REQUEST>\n<GET_FEATURES outputmode="xml" envelope="false" geometry="false">\n';
    theString += '<LAYER id="' + theLayer + '" />';
    theString += '<SPATIALQUERY subfields="' + theFields + '">';
    theString += '<SPATIALFILTER relation="area_intersection" >';
    theString += '<ENVELOPE maxy="' + topY + '" maxx="' + rightX + '" miny="' + bottomY + '" minx="' + leftX + '" />';
    theString += '</SPATIALFILTER>';
    theString += '</SPATIALQUERY>';
    if (hasLimit) {
        // keep this within the limitExtent
        theString += '<SPATIALFILTER relation="area_intersection">\n';
        theString += '<ENVELOPE maxx="' + limitRight + '" maxy="' + limitTop + '" minx="' + limitLeft + '" miny="' + limitBottom + '" />\n';
        theString += '</SPATIALFILTER>\n';
    }
    theString += '</GET_FEATURES>';
    theString += '</REQUEST>';
    theString += '</ARCXML>';

    return theString;
}

function HyperLink_attributes(theReply) {
    setLayerFields(ActiveLayerIndex);
    var theError = getXMLErrorMessage(theReply);
    var fList="";
    var lpos1 = 1;
    var lpos2 = 1;
    var epos = 1;
    var spos = 1;
    var morePoints=true;
    var moreFeatures=true;
    var featureCount = justGetFeatureCount(theReply);
    var pos = 0;
    var startpos = 0;
    var endpos = xmlEndPos;
    var stillMore = false
    pos = theReply.indexOf('hasmore="true"',endpos);
    if (pos!=-1) stillMore = true;
    pos=0;
    var tempCount = 0;
    var selectedData="";
    var inData="";
    var xStr="";
    var yStr="";
    var eNorth="";
    var eSouth="";
    var eWest="";
    var eEast="";
    var jasetemp = "";
    var fCount = featureCount;
    selectCount = 0;
    jascount = 0;
    var tempString="";
    jasestring = new Array();
    
    var Win2 = parent.TextFrame;
    var theFrame = "parent.MapFrame";
    if (featureCount > 0){
        newSelectCount += 1;
        if (showSelectedData) {
            var searchStr = currentHyperLinkField + "=";
            var pos1 = theReply.indexOf(searchStr,1);
            var startpos1 = pos1 + searchStr.length + 1;
            var endpos1 =theReply.indexOf(dQuote,startpos1);
            var inData1 = theReply.substring(startpos1,endpos1);
            var Win1 = window.open("","QueryWindow","width=" + hyperlinkWindowWidth + ",height=" + hyperlinkWindowHeight + ",scrollbars=yes,resizable=yes");
            Win1.document.open();
            Win1.document.writeln('<html><head><title>Select Results</title></head>');
            Win1.document.writeln('<body bgcolor="' + textFrameBackColor + '" text="Black" link="Blue" vlink="Gray" LEFTMARGIN=0 onload="window.focus()">');
            
            Win1.document.writeln('<center><img src="' + inData1 + '"<br>');
            
            Win1.document.writeln('<center><FONT FACE="Arial" SIZE="-1"><b>' + LayerName[ActiveLayerIndex] + '</b>');
        
            Win1.document.writeln('<table border="1" cellspacing="0" cellpadding="2" nowrap bgcolor="' + tableBackColor + '">');
        }
        endpos = 1;

            inData = parseRecordString(theReply, endpos);

            endpos = xmlEndPos;

            selectedData = clearLeadingSpace(inData);
            
            epos = theReply.indexOf("</FEATURE",endpos);
            if (showSelectedData) {
                var fName1 = getFieldNames(selectedData);
                var fValue1 = getFieldValues(selectedData);         
            
                selectPoints[selectCount] = getIdValue(fName1, fValue1);
                if (selectCount==0) {
                    //Win1.document.write('<tr><th><FONT FACE="Arial" SIZE="-2">Record</FONT></a></th>');
                    Win1.document.write('<tr>');
                    for (var f=0;f<fName1.length;f++) {
                        if (fName1[f].toUpperCase()=="#SHAPE#") continue;
                        else if (fName1[f].toUpperCase()=="#ID#") continue;
                        else if (fName1[f].toUpperCase()=="URL") continue;
                        var f2 = -1;
                        if (useFieldAlias) {
                            for (var f3=0;f3<AliasFieldName.length;f3++) {
                                if (AliasFieldName[f3]==fName1[f]) f2 = f3;
                            }
                        }
                        if (f2!=-1) {
                            Win1.document.write('<th><FONT FACE="Arial" SIZE="-2">' + AliasFieldAlias[f2] + '</FONT></a></th>');
                        } else {
                            Win1.document.write('<th><FONT FACE="Arial" SIZE="-2">' + fName1[f] + '</FONT></a></th>');
                          }
                    }
                    
                    Win1.document.writeln('</tr>');
                }
    
    
                
                for (var f=0;f<fName1.length;f++) { //--------------------------------- 
                    // Jason modification to hide the last two fields from being displayed SHAPE and ID and the NMTYPSH for the roads fields
                    if (fName1[f].toUpperCase()=="#SHAPE#") continue;
                    else if (fName1[f].toUpperCase()=="#ID#") continue;
                    else if (fName1[f].toUpperCase()=="URL") continue;

                 // Table elements
                    Win1.document.write('<TD nowrap>');
                    var isHyper=false;
    
                    var s2 = -1;
                    
                    for (var s1=0;s1<LayerFields.length;s1++) {
                        if (fName1[f]==LayerFields[s1]) s2=s1;
                    }
                    if (LayerFieldType[s2]=="91") {
                        if (isNaN(fValue1[f])) {
                            var theDate = fValue1[f];
                        } else {
                            //var theDate = new Date(parseInt(fValue1[f]));
                            var theDateObj = new Date(parseFloat(fValue1[f]));
                            var theDate = theDateObj.toGMTString();
                        }
                        Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + theDate + '</FONT>');
                        theDate=null;
                                } 
                        else {
                        Win1.document.write('<FONT FACE="Arial" SIZE="-2">' + fValue1[f] + '</FONT>');
                    }
                    if (isHyper) Win1.document.write('</a>');
                    Win1.document.writeln('</td>');
                } // ---------------------------------------------------------------------------
                Win1.document.writeln('</tr>');
                fName1 = null;
                fValue1 = null;
                // end of the table display
            }
            selectCount += 1;
                    
//      }
        if (showSelectedData) {
            Win1.document.writeln('</table>');
            Win1.document.writeln('</font></center></body></html>');
            Win1.document.close();
            
// write something to the textframe as well - nf
            Win2 = parent.TextFrame;
            Win2.document.open();
            Win2.document.writeln('<html><head>');
            Win2.document.writeln(' <title>Select Results</title>');
            Win2.document.writeln('</head>');
            Win2.document.writeln('<body BGCOLOR="white" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
            Win2.document.writeln('<center><FONT FACE="Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
            Win2.document.writeln('</FONT>');
            Win2.document.writeln('</body></html>');
            Win2.document.close();

            
        }
    
        
            
    } else {


    
        Win2 = parent.TextFrame;
        Win2.document.open();
    
        Win2.document.writeln('<html><head>');
        Win2.document.writeln(' <title>Select Results</title>');
        Win2.document.writeln('</head>');
        Win2.document.writeln('<body BGCOLOR="white" TEXT="Black" LEFTMARGIN=0 TOPMARGIN=0>');
        Win2.document.writeln('<center><FONT FACE="Arial"><B>' + LayerName[ActiveLayerIndex] +'</B></font><FONT FACE="Arial" size="-2">');
    
                Win2.document.writeln('<br>No features found. Please try again.</center>');
    
        if (debugOn>0) {
            Win2.document.writeln('<p>Returned ArcXML Response:<br>');
            Win2.document.writeln(untag(theReply));
        } else {
            if (theError!="") {
                Win2.document.writeln('<p>Server returned:<br>');
                Win2.document.writeln(theError);
            }
        }
        Win2.document.writeln('</FONT>');
        Win2.document.writeln('</body></html>');
        Win2.document.close();
    }
    if ((toolMode==4) || (toolMode==9))  selectCount=0;
    Win2=null;
    hideRetrieveData();
    
}