var xmlHttpCR;
var isIdentified = new Array();
var defaultRow = '#DEDEBE';
var highLightRow = "lightblue";
var curChildRow;
var theIdentifyParamForm;
var identify_http_request = false;
var resultDivs = new Array();
var footNotes = new Array();


function uncache(url){
var d = new Date();
var time = d.getTime();
return url + '&time='+time;
}

function captureMousePosition(e) {
    if (document.layers) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    } else if (document.all) {
        mouseX = window.event.x+document.body.scrollLeft;
        mouseY = window.event.y+document.body.scrollTop;
    } else if (document.getElementById) {
        mouseX = e.pageX;
        mouseY = e.pageY;
    }
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		do {
			curleft += obj.offsetLeft;
			curtop += obj.offsetTop;
		} while (obj = obj.offsetParent);
	}
	return [curleft,curtop];
}

function closeChildRecordsWindow() {
	var oldDiv = document.getElementById("childRecordsDiv");
	try {
	oldDiv.parentNode.removeChild(oldDiv);
	}catch (e) {}
		if (curChildRow != null) {
		curChildRow.style.backgroundColor = defaultRow;
	}
	curChildRow = null;
}
function showChildRecords(obj, value, tabletype) {
	var oldDiv = document.getElementById("childRecordsDiv");
	try {
	oldDiv.parentNode.removeChild(oldDiv);
	}catch (e) {}
	if (curChildRow != null) {
		curChildRow.style.backgroundColor = defaultRow;
	}
	curChildRow = obj.parentNode.parentNode;
	defaultRow = curChildRow.style.backgroundColor;
	curChildRow.style.backgroundColor = highLightRow;
	var pos = findPos(obj);
	var newDiv = document.createElement("div");
	newDiv.id = "childRecordsDiv";
	newDiv.style.background = "white";
	newDiv.className = "resulttext";
	newDiv.innerHTML = "Performing Queries...";
	document.getElementById("thebody").appendChild(newDiv);
	pos[0] = pos[0] + 150;
	newDiv.style.left = (pos[0]-250)+"px";
	newDiv.style.top = (pos[1] + 25) + "px";
	
	
try
    {    // Firefox, Opera 8.0+, Safari
    xmlHttpCR=new XMLHttpRequest();
    }
  catch (e)
    {    // Internet Explorer
    try
      {
      xmlHttpCR=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
       try
        {
        xmlHttpCR=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
        alert("Your browser does not support AJAX!");
        return;
        }
        }
        }

if (xmlHttpCR==null)
{
alert ("Browser does not support HTTP Request");
return;
}

var url="childrecords.jsp";
url=url+"?value="+value;
url=url+"&tabletype="+tabletype;



xmlHttpCR.onreadystatechange=populateChildRecords;
xmlHttpCR.open("GET",uncache(url),true);
xmlHttpCR.send(null);

}

function populateChildRecords()  {
  if (xmlHttpCR.readyState==4 || xmlHttpCR.readyState=="complete"){
    document.getElementById("childRecordsDiv").innerHTML=xmlHttpCR.responseText;
    sortables_init();
    curChildRow.style.backgroundColor = highLightRow;
  }
}

function toggleTab(bHide, title) {
	if (bHide) reAddTab(title);
	else removeTab(title);
}

function hideTab(title) {
	var tabs = document.getElementById("Results_Tabs").getElementsByTagName("ul")[0].getElementsByTagName("li");
	for (i=0; i<tabs.length;i++) {
			if (tabs[i].getElementsByTagName("a")[0].title == title) {
					
					tabs[i].style.display = "none";
					
			}
	}
}

function showTab(title) {
	var tabs = document.getElementById("Results_Tabs").getElementsByTagName("ul")[0].getElementsByTagName("li");
	for (i=0; i<tabs.length;i++) {
			if (tabs[i].getElementsByTagName("a")[0].title == title) {
					
					tabs[i].style.display = "block";
					
			}
	}
	
	
}

function showDetailTab(newTitle) {
	var tabList = document.getElementById("Results_Tabs").getElementsByTagName("ul")[0];
	var tabs = tabList.getElementsByTagName("li");
	tabs[tabs.length-1].getElementsByTagName("a")[0].innerHTML = newTitle;
	tabs[tabs.length-1].style.display="block";
}

function showAllResults(tableId,tableTitle,divId) {
	alert(divId);
	buildStringFromForm("search");
}

function buildStringFromForm(formid) {
	var theform = document.getElementById(formid);
	var params = theform.getElementsByTagName("input");
	for (i=0;i<params.length;i++) {
		alert(params[i].name + "="+params[i].value + "("+i+")");
	}
}

function toggleMapLayer(layerId, checked){
	var ww = getWindow();
	ww.toggleLayerByName(layerId,checked);
}

function initializeCheckboxes(tableDiv, layerId) {
	initializeSelectCheckboxes(tableDiv, layerId);
	initializeLayerToggleSelectboxes();
}

function initializeSelectCheckboxes(tableDiv, layerId) {
	var nextCheckboxId;
	var nextObjectId;
	
	var layers = getSelectedRecordsByLayer(layerId);

	for (var i =0;i<layers.length;i++) {
		try {
			document.getElementById("selectBox|"+layers[i]+"|"+layerId).checked = "true";
			} catch (e) {}
		

	}
}

function initializeLayerToggleSelectboxes() {
	var nextCheckboxId;
	var nextLayerId;
		var checkboxes = document.getElementsByName("toggleLayerCheckBox");
		var originalLength = checkboxes.length;
	for (var i =0;i<checkboxes.length;i++) {
		nextCheckboxId = checkboxes[i].id.split("|");
		nextLayerId = nextCheckboxId[1];
		if (isMapLayerVisible(nextLayerId)) {
			checkboxes[i].checked = "true";
		}
		checkboxes[i].name= "intializedLayerCheckbox";
		if (checkboxes.length < originalLength) i--;
	}
	
}

  function addTableToFootNote(tabId,tableName, rowCount) {
  	if (rowCount != null && rowCount != "0" && rowCount != "-1" && rowCount != "" && rowCount != "null") return true;
  	try {
  	document.getElementById(tabId+"FootNote").style.visibility = "visible";
  	var list = 	document.getElementById(tabId+"FootNoteList");
  	var note = document.createElement("li");
  	note.innerHTML = tableName;
  	list.appendChild(note);
  	footNotes.push(note);
  	} catch (e) {}
  	return false;
  }
   
   function getTableHTML(str) {
   var index1 = str.indexOf("</tableinfo>") + 12;
   var index2 = str.length -1;
   return str.substring(index1,index2);
   }
   
   function getTagValue(tag,str) {
   	var index1 = str.indexOf("<"+tag);
   	if (index1 == -1) return "";
   	index1 = index1 + tag.length + 2;
   	var index2 = str.indexOf("</"+tag);
   	return str.substring(index1,index2);
   }
   
      function performNextSearch(tableInfo) {
	   var nextTable = getTagValue("nexttable",tableInfo);
	   var tabIndex = getTagValue("tabindex",tableInfo);
	   //alert(nextTable);
	  // alert(tableInfo);
	   if (nextTable != null && nextTable != "null" && nextTable != "") {
			var paramString = getParamString(theIdentifyParamForm);
			makeRequest('identifyCallBack.jsp', paramString, nextTable, tabIndex);
	   }
	   else {
	   	isIdentified[tabIndex] = true;
	   }
   }
   
      function processTableResult() {
      if (identify_http_request.readyState == 4) {
         if (identify_http_request.status == 200) {
         
            //alert(identify_http_request.responseText);
            var result = identify_http_request.responseText;
            var tableInfo = getTagValue("tableinfo",result);    
            var tabId = getTagValue("tabid",tableInfo);
            var tableId = getTagValue("tableid",tableInfo);
            var tableName = getTagValue("tablename",tableInfo);
            var rowCount = getTagValue("rowcount",tableInfo);
            var hasResults = addTableToFootNote(tabId,tableName,rowCount);
            var selectBox = getTagValue("selectbox",tableInfo);
            var layerId = getTagValue("layerid",tableInfo);
   			if (selectBox == "null") selectBox = "";
   			var zoomTo = getTagValue("zoomto",tableInfo);
   			if (zoomTo == "null") zoomTo = "";
   					try {
            document.getElementById(tabId+"Params").innerHTML = getSearchParamString() + zoomTo + selectBox;
					} catch (e) {}
            var tabTableId = tabId+"."+tableId+"ResultDiv";
          //  alert(tabId+"."+tableId+"ResultDiv");
          if (hasResults) {
	            var tableHTML = getTableHTML(result);
	            
	           try{
	              document.getElementById(tabTableId).innerHTML = tableHTML;
	              resultDivs.push(tabTableId);
	              sortables_initByDocument(document.getElementById(tabTableId));
	             
	         
	              initializeCheckboxes(document.getElementById(tabTableId), layerId);
	             
	            }
	            catch(exception){ 
	            }
	             
            }
            try {
            //AO added callback to AII.aspx so user can be notified if no records returned 09/2009
            identifyComplete(rowCount);
            }
            catch (exception)
            {}
            performNextSearch(tableInfo);
            	
         } else {
            alert('There was a problem with the request:' + identify_http_request.status);
         }
      }
      
   }
   
   
   function makeRequest(url, parameters, currentTable, tabIndex) {
      identify_http_request = false;
      if (window.XMLHttpRequest) { // Mozilla, Safari,...
         identify_http_request = new XMLHttpRequest();
         if (identify_http_request.overrideMimeType) {
            identify_http_request.overrideMimeType('text/html');
         }
      } else if (window.ActiveXObject) { // IE
         try {
            identify_http_request = new ActiveXObject("Msxml2.XMLHTTP");
         } catch (e) {
            try {
               identify_http_request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
         }
      }
      if (!identify_http_request) {
         alert('Cannot create XMLHTTP instance');
         return false;
      }
      parameters += "&currentTable="+currentTable;
      parameters += "&tabIndex="+tabIndex;
     
      identify_http_request.onreadystatechange = processTableResult;
      identify_http_request.open('get', url + parameters, true);
      identify_http_request.send(null); 
   }
   
   function getParamString(form) {

  var paramString = "?";
  var inputs = form.getElementsByTagName("input");
  
  for (i=0; i<inputs.length; i++) {
        if (inputs[i].type == "text" || inputs[i].type == "hidden") {
           paramString += inputs[i].name + "=" + 
                   inputs[i].value + "&";
        }
        if (inputs[i].type == "checkbox") {
           if (inputs[i].checked) {
              paramString += inputs[i].name + "=" + 
                   inputs[i].value + "&";
           } else {
              paramString += inputs[i].name + "=&";
           }
        }
        if (inputs[i].type == "radio") {
           if (inputs[i].checked) {
              paramString += inputs[i].name + "=" + 
                   inputs[i].value + "&";
           }
     }  
  }
  
  var selects = form.getElementsByTagName("select");
  for (i=0; i<selects.length;i++) {
 
  	paramString += selects[i].name + "=" + 
                   selects[i].value + "&";
  }
  

return paramString;
}

function identifyCallBack(form, tabIndex) {
  var paramString = getParamString(form);
	theIdentifyParamForm = form;
  makeRequest('identifyCallBack.jsp', paramString, "null",tabIndex);
}

function detailIdentifyCallBack(table, tabIndex) {
  var paramString = getParamString(theIdentifyParamForm);
	
  makeRequest('identifyCallBack.jsp', paramString, table ,tabIndex);
}

function detailIdentify(tableId, tableTitle) {
	
	document.getElementById("isDetail").value = "true";
	document.getElementById("detailTable").value = tableId;
	showDetailTab(tableTitle + " Results");
	document.getElementById("detail.detailResultDiv").innerHTML = "";
	//document.getElementById("detailTabResults").innerHTML = "<img src=\"/blmMap/images/callbackActivityIndicator.gif\" alt=\"loading query\"/>Performing Query...";
	detailIdentifyCallBack(tableId, "detail");
	 document.getElementById('Results_Tabs').firstChild.tabber.tabShow(getLastTabIndex());
	 document.getElementById("isDetail").value = "false";
}

   function featureIdentify(objectId, layerId, mapService, featureLabel) {
  identifyByFeature(objectId, layerId, mapService, featureLabel);
}

function clearCachedDivs() {

	for (var i = 0; i < resultDivs.length; i++) {
		try {
		document.getElementById(resultDivs[i]).innerHTML = "";
		} catch (e) {}
	}
	resultsDivs = new Array();
	
	for (var ii = 0; ii < footNotes.length; ii++) {
		footNotes[ii].parentNode.parentNode.parentNode.style.visibility = "hidden";
		footNotes[ii].parentNode.removeChild(footNotes[ii]);
	}
	footNotes = new Array();
}