//*****************************************************************************
//
// USGS Vector Identify Query Tool
// Created By: Chris Rusanowski
// Modified By: Jennifer Ming for the BorderHealth
//Modified By:  Jennifer Ming for CEOS to get metadata
// Note: this is a modified version of the Selection Tool Created By: Jennifer Ming
// Prerequisites:
//    - USGS Scale Tool (USGS_Scale_Tool.js)
//    - USGS OGC Combined Layers (USGS_OGC.js)
//    - USGS OGC Layers (USGS_OGC_Layer.js or WMS_Catalog reference)
// Installation:
//   -Copy the getVectorIdentify.asp file into the main HTML viewer directory 
//     (IE: same directory mapframe.htm is in...)
//   -Copy USGS_Vector_Identify_Service.js into the javascript directory of the HTML Viewer
//   -Include the javascript/USGS_Vector_Identify_Service.js in MapFrame.htm 
//      <script type="text/javascript" language="JavaScript" src="javascript/USGS_Vector_Identify_Service.js"></script>
//   -Create the USGS_Vector_Identify_Loaded variable in MapFrame.htm
//      var USGS_Vector_Identify_Loaded=false;
//   -Add a button to the toolbar.php that calls parent.MapFrame.USGSVectorIdentifyTool().
//     (You can also replace the call to Identify or something like that with this tool...)
//     <span class="<?php echo $info_sel ?>"><a title="Displays the map feature attributes" href="toolbar.php?sec_select=2&button_sel=7" onClick='parent.MapFrame.modeName="Identify"; parent.MapFrame.USGSVectorIdentifyTool();'><img alt="Displays the map feature attributes" border=0 src=/website/ImageArchive/buttonarchive/info.gif></a></span>
//
//   -Add code below to aimsCustom.js (customMapTool) to the map tool functions...
//      if (toolMode == 1095) { 
//        getVectorIdentify(e);
//        return false; 
//      }
//
//*****************************************************************************
// useSelectionService determines if the toolbar should show this button or not.
var useVectorDrillDown = true;
// USGS_Select_Tools_Loaded determines if the tools are loaded or not.  Needs to be declared in Mapframe.htm or sometimes browsers don't catch it and call the layer creation functions
USGS_Vector_Identify_Loaded = true;
//Combined_Output_HTML is used to hold the data between requests, so that all can be displayed at the end...
Drill_Down_Combined_Output_HTML = '';
//Remaining_ID is used to track the ID's that have been queried, so we know when all have been retrieved
Drill_Down_Remaining_ID = '';
//Filter_BBox_String is used to store the query location between requests
Filter_BBox_String = '';
//Drill_Down_Data_CSV a string that holds a CSV text representation of the data from the query
Drill_Down_Data_CSV = '';
//Drill_Down_X and Drill_Down_Y hold the x and y location of the drill-down point
Drill_Down_X = '';
Drill_Down_Y = '';

//metadata layer
var metaLayer = "";

//*****************************************************************************
// Function USGSVectorIdentifyTool
// This function sets the current tool to the Drll-Down Query Tool
// Sets the toolMode to 1089
//*****************************************************************************
function USGSVectorIdentifyTool() {
  var isOk;
  var j; 
  if (hasLayer("measureBox")) {
    hideLayer("measureBox");
  }
  if (hasLayer("xBoxTop")) {        
    hideLayer("xBoxTop");
  }
  if (hasLayer("xBoxLeft")) {
    hideLayer("xBoxLeft");
  }
  if (hasLayer("xBoxRight")) {
    hideLayer("xBoxRight");
  }
  if (hasLayer("xBoxBottom")) {
     hideLayer("xBoxBottom");
  }
  panning=false;
  zooming=false;
  shapeSelectBuffer = false;
  toolMode = 1095;
  if (canQuery) {
  	if (isIE)	{
  		document.all.theTop.style.cursor = "crosshair";
  		theCursor = document.all.theTop.style.cursor;
  	}
  	modeBlurb = "USGS Identify Query";
  } else {
  	alert(msgList[46]);
  }
  showGeocode=false;
  if ( parent.TextFrame != null ) {
    parent.TextFrame.document.location = "http://" + hostName + appDir + "getVectorIdentify.asp?FIELDS=USER_WAIT";
  }
}

//*****************************************************************************
// Function getVectorIdentify
// This function takes the coordinates from the map and starts the drill down tool
//*****************************************************************************
function getVectorIdentify(e) {
  Drill_Down_Combined_Output_HTML = '';
  Drill_Down_Remaining_ID = '';
  Drill_Down_Data_CSV = '<pre>';
  getMapXY(mouseX,mouseY);
  Drill_Down_X = mapX;
  Drill_Down_Y = mapY;
  searchTolerance = (xDistance/iWidth) * pixelTolerance;
  Drill_Down_Tolerance = searchTolerance;
  tempLeft = mapX-searchTolerance;
  tempTop = mapY-searchTolerance;
  tempRight = mapX+searchTolerance;
  tempBottom = mapY+searchTolerance;
  Drill_Through_Layers(tempLeft, tempBottom, tempRight, tempTop);
  return true;
}

//*****************************************************************************
// Function Call_QueryService
// This function Calls the queryservice using the parameters passed into it
// The BBox is always the current extent and the server to query is always
// the hostname so those do not need to be passed into this.
//*****************************************************************************
function Call_QueryService(Layer_Name, Layer_ID, Server_Address, Service_Name, Filter_BBox_String) {
  metaLayer = Layer_Name;

  var Query_URL_String = "http://" + hostName + "/xmlwebservices/";
  var BG_Color = parent.USGSBackgroundColor;
  if (Layer_ID.indexOf("|")> 0) {
    Query_URL_String += "getqueryrasterservice.aspx?";
    var Layer_ID_Array = Layer_ID.split("|");
    Layer_ID = Layer_ID_Array[1];
  } else {
    Query_URL_String += "getqueryservice.aspx?BGColor=" +  BG_Color.slice(1, BG_Color.length) +"&Background_Color=225,225,225&Transparent=true&Output_format=RESULTS";
  }
  Query_URL_String += "&Layer_ID=" + Layer_ID;
  Query_URL_String += "&BBOX_String=" + eLeft + "," + eTop + "," + eRight + "," + eBottom;
  Query_URL_String += "&Service_Name=" + Service_Name;
  Query_URL_String += "&Server_Address=" + Server_Address;
  Query_URL_String += "&filter_BBOX=" + Filter_BBox_String;
  Query_URL_String += "&RETURNURL=http://" + hostName + appDir + "getVectorIdentify.asp"; 
 //prompt ("", Query_URL_String);
  if ((useExternalWindow) || (!useTextFrame)) {
    window.open(Query_URL_String ,"Drill_Down_Query_Service","width=425,height=300,scrollbars=yes,resizable=yes");
  } else {	
    parent.TextFrame.document.location = Query_URL_String;
  }
}


//*****************************************************************************
// Function Drill_Through_Layers
// This is the function that makes the Drill-down a drill-down rather than just
// an identify, or select.  It cycles through all the visible layers with 
// Layer_ID's and calls the queryService for each.  The code is adapted from 
// the USGS_OGC.js VisibleLayerInfo() function.
//*****************************************************************************
function Drill_Through_Layers(tempLeft, tempBottom, tempRight, tempTop) {
  //Start with an Empty String
  var LayerInfoString = '<small>(Layers listed in order with bottom layer first, top layer last)</small><br />';
  //Get the Current Scale from USGS Scale Tool
  var CenterAdjust = Math.abs(eRight - eLeft);
  var CurrentMapScale = HaversineScale((eLeft + CenterAdjust), eBottom, (eLeft + CenterAdjust), eTop, mHeight, ScaleToolDPI);
  //Cycle through the Categories from the Category_Order array
	for (var i=Category_Order.length-1;i>=0;i--) {
    if (Category_Layer_Order[i].length>0) {
      //For each category, get the Layer_Order and Layer_Visibility and split into some temp arrays.
      TempArray = Category_Layer_Order[i].split(',');
	
      TempArray2 = Category_Layer_Visibility[i].split(',');
	
      //Cycle through the layers for this current category in Layer_Order
	    for (var j=TempArray.length-1;j>=0;j--) {
        //Only perform Drill-down for layers that are turned on...
        if (TempArray2[j].toLowerCase()=="true") {
		
          //Check the layer's scale factor and extent to see if we should display it
          //Only use the tempExtent (click on map...)
          if (Check_Layer_Extent_and_Scale(TempArray[j], tempLeft, tempBottom, tempRight, tempTop, CurrentMapScale)) {
            //Passes Extent/Scale check, so display the layer
            //Build the OGC WMS request string
			
            if (SRC_Layer_IDLayers[TempArray[j]].length>0) {
              if (Drill_Down_Remaining_ID.length>0) {
                Drill_Down_Remaining_ID = Drill_Down_Remaining_ID + ',' + TempArray[j];
              } else {
                Drill_Down_Remaining_ID = TempArray[j];
              }
            }
          }
        }
      }
    }
  }
  Filter_BBox_String = tempLeft + "," + tempTop + "," + tempRight + "," + tempBottom;
  Query_URL_String = "http://" + hostName + appDir + "getVectorIdentify.asp?FIELDS=QUERYING_SERVICE"; 
  if ((useExternalWindow) || (!useTextFrame)) {
    window.open(Query_URL_String ,"Drill_Down_Query_Service","width=425,height=300,scrollbars=yes,resizable=yes");
  } else {	
    parent.TextFrame.document.location = Query_URL_String;
  }
  return true;
}

//*****************************************************************************
// Function getLayerInfo_Service
// This function parses the ServiceName= from the USGS_OGC_Layers URL
//*****************************************************************************
function getLayerInfo_Service(IDLayer){
  var pos = -1;

  pos = SRC_Layer_URL[IDLayer].indexOf("ServiceName=");
  if (pos!=-1) {
    startpos = pos + 12;
    endpos = SRC_Layer_URL[IDLayer].indexOf("&",startpos);
    if (endpos==-1) { endpos = SRC_Layer_URL[IDLayer].length; }
    return unescape(SRC_Layer_URL[IDLayer].substring(startpos,endpos));
  }  else {
  //the following line does not work for the layer http://ims.cr.usgs.gov/servlet/com.esri.wms.Esrimap/USGS_EDC_National_Atlas?SERVICE=WMS&VERSION=1.1.1&STYLES=&SRS=EPSG:4326
  //&FORMAT=image/png&BGCOLOR=0xFF0000&TRANSPARENT=true&LAYERS=ATLAS_STATES,ATLAS_STATES_075,ATLAS_STATES_150
	/*
	startpos = SRC_Layer_URL[IDLayer].lastIndexOf("/");
	endpos = SRC_Layer_URL[IDLayer].indexOf("?");
		
	if (startpos > endpos) {
		var tempString = SRC_Layer_URL[IDLayer].substring(0, startpos);
		//prompt("", tempString);
		startpos = tempString.lastIndexOf("/");
	}

	return unescape(SRC_Layer_URL[IDLayer].slice( startpos+1, endpos));
	*/
	
	pos = SRC_Layer_URL[IDLayer].indexOf("com.esri.wms.Esrimap/");

      	if (pos!=-1) {
      		startpos = pos + 21;
      		endpos = SRC_Layer_URL[IDLayer].indexOf("?",startpos);
      		if (endpos==-1) { endpos = SRC_Layer_URL[IDLayer].length; }
		//prompt("", SRC_Layer_URL[IDLayer].substring(startpos,endpos));
      		return unescape(SRC_Layer_URL[IDLayer].substring(startpos,endpos))
			
      	}  else {
		return "";
        }
  }
  
}

//*****************************************************************************
// Function getLayerInfo_Server
// This function parses the Server from the USGS_OGC_Layers URL
//*****************************************************************************
function getLayerInfo_Server(IDLayer){
  var pos = -1;
  pos = SRC_Layer_URL[IDLayer].indexOf("http://");
  if (pos!=-1) {
    startpos = pos + 7;
    endpos = SRC_Layer_URL[IDLayer].indexOf("/",startpos);
    if (endpos==-1) { endpos = SRC_Layer_URL[IDLayer].length; }
    return unescape(SRC_Layer_URL[IDLayer].substring(startpos,endpos));
  }  else {
    return "";
  }
}

//*****************************************************************************
// Function Display_Identify_Data
// This function opens a new window that will show all the data results in a 
// CSV format that can be cut and pasted into other applications.
//*****************************************************************************
function Display_Identify_Data() {
  Drill_Down_Data_CSV += '</pre>';
  Create_Pop_Up_Window("Query data results", "", Drill_Down_Data_CSV, "Drill_Down_Data_Service", "toolbar=yes,width=900,height=900,scrollbars=yes,resizable=yes", true);
} 
//*****************************************************************************
// Function get_Data_Rows
// This function parses the response from the server and adds it to the 
// the Combined_HTML
//*****************************************************************************
function get_Identify_Data_Rows(FIELDCOUNT, FIELDS_Array, Value_Array, ENVELOPES, JavaScriptLocation, FIELDS) {
  var lastDotPos = -1;
  var entityPos = -1;
  var entityVal = "";
  var metaVal = "";
  Drill_Down_Combined_Output_HTML += "<table border=1 cellpadding=2 cellspacing=2>";
  //Drill_Down_Data_CSV += "\n";
  if (FIELDS!="") { 
    Drill_Down_Combined_Output_HTML += "<thead><tr>";
    //Drill_Down_Combined_Output_HTML += "<td>Goto</td>";
    Drill_Down_Data_CSV += '<TABLE BORDER="1" CELLPADDING="2" >';
    Drill_Down_Data_CSV += "<tr>";
    Drill_Down_Combined_Output_HTML += "<td>Metadata";
    Drill_Down_Data_CSV += "<td>Metadata";
    for (var i=0; i<= FIELDCOUNT ; i++) {
      //get the position of ENTITY_ID
      entityVal = FIELDS_Array[i].toUpperCase();
      if(entityVal .indexOf("TITY_ID") > -1){  //for Entity_ID or TITY_ID           
	entityPos = i;
      }
      lastDotPos = (FIELDS_Array[i]).lastIndexOf(".");
      Drill_Down_Combined_Output_HTML += "<td><center>" +(FIELDS_Array[i]).slice(lastDotPos + 1, (FIELDS_Array[i]).length) + "</center></td>";
      //if (i!=0) {
        Drill_Down_Data_CSV += "<td><center>" + (FIELDS_Array[i]).slice(lastDotPos + 1, (FIELDS_Array[i]).length)+ "</center></td>";
      //} else {
        //Drill_Down_Data_CSV +='"<blockquote><iframe width="100%"src="' + FIELDS_Array[i];
        //Drill_Down_Data_CSV +=  FIELDS_Array[i];
      //}
    }
//    Drill_Down_Data_CSV += 'Drill_Down_X,Drill_Down_Y,Drill_Down_Tolerance';
    //Drill_Down_Data_CSV += "\n";
    Drill_Down_Data_CSV += "</td>";            
    Drill_Down_Combined_Output_HTML += "</td>";      
    Drill_Down_Data_CSV += "</tr>";
    Drill_Down_Combined_Output_HTML += "</tr></thead>";
    for (var j=0; j < Value_Array[0].length; j++) {
      Drill_Down_Combined_Output_HTML += "<tr>";
      Drill_Down_Data_CSV += "<tr>";
      
      if (entityPos >-1){
        //The following is the URL to get metadata for ceos layers
	metaVal = getCSEQVal (metaLayer); 
	if (metaVal != ""){
		metaURL = "http://edcsns17.cr.usgs.gov/cgi-bin/EarthExplorer/phtml/results/display_full.phtml?fgdc=Y&cseq=" + metaVal  + "&entity_id=" + Value_Array[entityPos][j]      
		Drill_Down_Combined_Output_HTML += "<td><a href=\"" + metaURL + "\">Entity_ID: " + Value_Array[entityPos][j] + "</A>";       
		Drill_Down_Data_CSV += "<td><a href=\"" + metaURL + "\"> Entity_ID: " + Value_Array[entityPos][j] + "</A>";        

	}else{
		Drill_Down_Combined_Output_HTML += "<td>";      
		Drill_Down_Data_CSV += "<td>";    	
	}
	//metaURL = "http://edcsns17.cr.usgs.gov/cgi-bin/EarthExplorer/phtml/results/display_full.phtml?fgdc=Y&cseq=2411&entity_id=7030045000330951";   

      }else{
 	Drill_Down_Combined_Output_HTML += "<td>";      
	Drill_Down_Data_CSV += "<td>";            
      }
      /*
      if (ENVELOPES[j].length>0) {
        Drill_Down_Combined_Output_HTML += "<td><a href=\"javascript:void(0);\" onclick=\"" + JavaScriptLocation + ".zoomToEnvelope(" + ENVELOPES[j] + ");\">Goto</a></td>";
      } else {
        Drill_Down_Combined_Output_HTML += "<td>N/A</td>";
      }
      */
      for (var i=0; i <= FIELDCOUNT; i++) {
	
        Drill_Down_Combined_Output_HTML += "<td><center>" + Value_Array[i][j] + "</center></td>";
        //if (i!=0) {
          //Drill_Down_Data_CSV += "," + Value_Array[i][j] + "</iframe></blockquote>";
          Drill_Down_Data_CSV += "<td><center>" + Value_Array[i][j] + "</center></td>";

        //} else {
          //Drill_Down_Data_CSV += Value_Array[i][j];
        //}
      }	 
//      Drill_Down_Data_CSV += "," + Drill_Down_X + "," + Drill_Down_Y + "," + Drill_Down_Tolerance;
      Drill_Down_Data_CSV += "</td>";      
      Drill_Down_Combined_Output_HTML += "</td>";        
      Drill_Down_Data_CSV += "</tr>"; 
      Drill_Down_Combined_Output_HTML += "</tr>";  
      Drill_Down_Data_CSV += "\n";
    }
    Drill_Down_Data_CSV += "\n\n";
  } else {
    Drill_Down_Combined_Output_HTML += "<thead><tr>";
    Drill_Down_Combined_Output_HTML += "<td>No Data returned.</td>";
    Drill_Down_Data_CSV += "\n";
    Drill_Down_Data_CSV += "No Data returned.";
    Drill_Down_Data_CSV += "</tr>";
    Drill_Down_Combined_Output_HTML += "</tr></thead>";  
  }
  Drill_Down_Data_CSV += "\n";
  Drill_Down_Data_CSV += "</table>";
  Drill_Down_Combined_Output_HTML += "</table>";
}

//*****************************************************************************
// Function getCSEQVal: get the values of CSEQ for CEOS layers
//*****************************************************************************
function getCSEQVal (layerName) {
	var CSEQVal = "";
	
	switch (layerName)
	{
		case "Landsat 1-3 MSS": 
			CSEQVal=934;
		break;
		
		case "Landsat 4-5 MSS": 
			CSEQVal=934;
		break;

		case "Landsat 4-5 TM 12/31/99": 
			CSEQVal=937;
		break;
		
		case "LGSOWG Landsat 4-5 MSS": 
			CSEQVal=934;
		break;

		case "USGS SPOT": 
			CSEQVal=1691;
		break;
		
		case "USGS Declassified":           
			CSEQVal=1051;
		break;

		case "Landsat ETM+ 12/31/03":                    
			CSEQVal=931;
		break;
		
		case "USGS EO1 ALI 10/31/04": 
			CSEQVal=1852;
		break;		

		case "USGS EO1 Hyperion": 
			CSEQVal=1854;
		break;
		
		case "USGS Landsat Orthorectified ETM+ Pan": 
			CSEQVal=2732;
		break;
		
		case "USGS Landsat Orthorectified ETM+ XS":      
			CSEQVal=2731;
		break;
		
		case "USGS Landsat Orthorectified TM": 
			CSEQVal=2733;
		break;		
		
		case "NHAP Black and White": 
			CSEQVal=1712;
		break;
		
		case "NHAP Color": 
			CSEQVal=1712;
		break;

		case "Declass II High Resolution":    
			CSEQVal=2071;
		break;

		case "Declass II Medium Resolution":  
			CSEQVal=2071;
		break;
		
		case "Space Imaging IKONOS": 
			CSEQVal=2572;
		break;
		
		case "DigitalGlobe Quickbird": 
			CSEQVal=2572;
		break;		
		
		default: CSEQVal = "";
		break;
	}
	
	return CSEQVal;
}