var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");  
    
function updateLayers(tblLayers, map, hdnLegendTreeXmlCID, legendUpdateDummyImgCID)
{
	var colLayers;
	var currentLayer;
	var currentLayerGroup;
	
	var newRow;
	var newCell;
	var currentRow;
	var currentCell;
		
	var isInRoot = false;
	
	var i;
	var parentIndex;
	
	var sChecked = "";
	var refreshMap = false;
	
	map.setObjectLinkTarget("_self");
	
	if(tblLayers != null && map)
	{
	    map.setAutoRefresh(false);
    	
	    while(tblLayers.rows.length > 0)
	    {
		    tblLayers.deleteRow();
	    }
	   
    	
	    tblLayers.border = 0;
	    tblLayers.cellPadding=1;

	    // Assign collection to layers variable
	    var colLayers = map.getMapLayersEx();    
	    // Use size() to step through collection 
	    var size = colLayers.size() - 1;
	    
	    var hdnLegendTreeXml = $get(hdnLegendTreeXmlCID);
	    xmlDoc.async = "false";
		xmlDoc.onreadystatechange = verify;
		xmlDoc.loadXML(HtmlDecode(hdnLegendTreeXml.value));
		rootEl = xmlDoc.documentElement;
	    
	    for(var i = size; i >= 0; i--)  
	    {
		    isInRoot = false;
		    // Get each item in collection...
		    currentLayer = colLayers.item(i);
		    currentLayerGroup = currentLayer.getMapLayerGroup();
		        		
		    if(currentLayerGroup != null)
		    {
			    if(!doesItemExist(tblLayers, currentLayerGroup.getName()) && currentLayerGroup.ShowInLegend)
			    {
				    //We have to check if we are at the correct zoom to display the group
				    if(isGroupVisibleOnControl(map, currentLayerGroup))
				    {
						lyrGrpEl = rootEl.selectSingleNode("lyrgrp[@id='" + currentLayerGroup.getName() + "']");
						if(lyrGrpEl != null)
						{
							var groupVisibility = "0";
							if(currentLayerGroup.getVisibility())
								groupVisibility = "1";

							if(lyrGrpEl.getAttribute("iv") != groupVisibility)
							{
								refreshMap = true;
								if(lyrGrpEl.getAttribute("iv") == "1")
								{
									sChecked = "checked";
									currentLayerGroup.setVisibility(true);
								}
								else
								{
									sChecked = "";
									currentLayerGroup.setVisibility(false);
								}
							}
							else
							{
								if(currentLayerGroup.getVisibility())
									sChecked = "checked";
								else
									sChecked = "";
							}
						}
						else
						{					
							if(currentLayerGroup.getVisibility())
								sChecked = "checked";
							else
								sChecked = "";
						}
					    newRow = tblLayers.insertRow();
					    newCell = newRow.insertCell(0);
					    newCell.width = "35px";
					    newCell.align = "left";
					    newCell.vAlign = "top";
					    newCell.noWrap = true;
					    newCell.innerHTML = "<image src='images/bkmfolderopen.gif' border=0 class=map_layer_img /><input type=checkbox " + sChecked + " value='" + currentLayerGroup.getName() + "' class=map_layer_checkbox onclick='UpdateMapLayers(this, document.all." + map.id + ", 1, \"" + hdnLegendTreeXmlCID + "\", \"" + legendUpdateDummyImgCID + "\")'>";
					    newCell = newRow.insertCell(1);
					    newCell.innerText = currentLayerGroup.getLegendLabel();
					    newCell.setAttribute("data", currentLayerGroup.getName());
					    newCell.className = "map_layer_item";
				    }
			    }
		    }
		    else
		    {
			    isInRoot = true;
		    }
    		
		    if(currentLayer.ShowInLegend)
		    {
			    if (isLayerVisibleOnControl(map,currentLayer)) 
			    {
					if(!isInRoot)
					{
						if(!currentLayer.getMapLayerGroup().ShowInLegend)
							continue;
					}
					
					lyrEl = rootEl.selectSingleNode(".//lyr[@id='" + currentLayer.getName() + "']");
					if(lyrEl != null)
					{
						var lyrVisibility = "0";
						if(currentLayer.getVisibility())
							lyrVisibility = "1";

						if(lyrEl.getAttribute("iv") != lyrVisibility)
						{
							refreshMap = true;
							if(lyrEl.getAttribute("iv") == "1")
							{
								sChecked = "checked";
								currentLayer.setVisibility(true);
							}
							else
							{
								sChecked = "";
								currentLayer.setVisibility(false);
							}
						}
						else
						{
							if(currentLayer.getVisibility())
								sChecked = "checked";
							else
								sChecked = "";
						}
					}
					else
					{					
						if(currentLayer.getVisibility())
							sChecked = "checked";
						else
							sChecked = "";
					}
					
				   
					    if(isInRoot)
						    newRow = tblLayers.insertRow();
					    else
					    {
						    parentIndex = getParentIndex(tblLayers, currentLayer.getMapLayerGroup().getName());
						    newRow = tblLayers.insertRow(parentIndex);
    						
						    if(currentLayerGroup.getVisibility())
						    {
							    newRow.disabled = false;
							}
						    else
							    newRow.disabled = true;
					    }
    					
					    newCell = newRow.insertCell(0);
					    newCell.width = "35px";
					    newCell.vAlign = "top";
					    newCell.align = "left";
					    newCell.noWrap = true;
					    if(isInRoot)
						    newCell.innerHTML = "<image src='images/bkmfolderopen.gif' border=0 class=map_layer_img /><input type=checkbox " + sChecked + " value='" + currentLayer.getName() + "' class=map_layer_checkbox onclick='UpdateMapLayers(this, document.all." + map.id + ", 0, \"" + hdnLegendTreeXmlCID + "\", \"" + legendUpdateDummyImgCID + "\")'>";
					    else
						    newCell.innerHTML = "&nbsp;";
    					
					    newCell = newRow.insertCell(1);
					    
					    if(isInRoot)
						    newCell.innerText = currentLayer.getLegendLabel();
					    else
					    {
						    newCell.innerHTML = "<input type=checkbox " + sChecked + " value='" + currentLayer.getName() + "' class=map_layer_checkbox onclick='UpdateMapLayers(this, document.all." + map.id + ", 0, \"" + hdnLegendTreeXmlCID + "\", \"" + legendUpdateDummyImgCID + "\")'>" + currentLayer.getLegendLabel();
						    if(sChecked != "")
						    {
						        newCell.innerHTML = newCell.innerHTML + "<div id=subLyr" + i + ">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<img src='/seitel_client/MapControl_client/MapLegend/" + currentLayer.getLegendLabel() + ".gif' border=0 onerror='imgOnError(\"subLyr" + i + "\");'/></div>";
						        
						        var tmpParentIndex = getParentIndex2(tblLayers, currentLayer.getMapLayerGroup().getName());
						        var tmpParentRow = tblLayers.rows(tmpParentIndex);
					            tmpParentRow.cells(1).innerHTML = currentLayer.getMapLayerGroup().getLegendLabel() + "<div id=mainLyr" + i + "><img src='/seitel_client/MapControl_client/MapLegend/" + currentLayer.getMapLayerGroup().getLegendLabel() + ".gif' border=0 onerror='imgOnError(\"mainLyr" + i + "\");'/></div>";
					            tmpParentRow.cells(1).style.paddingTop = "4px";
						    }
					    }
					    newCell.setAttribute("data", currentLayer.getName());
					    if(currentLayer.getMapLayerGroup())
					        newCell.setAttribute("prnt", currentLayer.getMapLayerGroup().getName());
					    newCell.className = "map_layer_item";
				   
			    }
		    }
	    }
    	
	    map.setAutoRefresh(true);
	    if(refreshMap)
			map.refresh();
    }
}


function imgOnError(lyrID)
{
    var lyr = eval("document.all." + lyrID);
    lyr.style.display = "none";
    lyr.style.visibility = "hidden";
}

function UpdateMapLayers(chkBox, map, flag, hdnLegendTreeXmlCID, legendUpdateDummyImgCID)
{
	var layer;
	var layerGrp;
	var hdnLegendTreeXml = $get(hdnLegendTreeXmlCID);
	var legendUpdateDummyImg = $get(legendUpdateDummyImgCID);
	xmlDoc.async = "false";
	xmlDoc.onreadystatechange = verify;
	xmlDoc.loadXML(HtmlDecode(hdnLegendTreeXml.value));
	//window.prompt("test",xmlDoc.xml);
	rootEl = xmlDoc.documentElement;
	if(flag == 1)
	{
		layerGrp = map.getMapLayerGroup(chkBox.value);
		if(layerGrp != null)
		{
			lyrGrpEl = rootEl.selectSingleNode("lyrgrp[@id='" + layerGrp.getName() + "']");
			if(lyrGrpEl != null)
			{
			    if(chkBox.checked)
				    lyrGrpEl.setAttribute("iv", "1");
			    else
				    lyrGrpEl.setAttribute("iv", "0");
			}
		}
		saveLayerState = true;
		var finalXml = xmlDoc.xml.replace(new RegExp('\n|\r','g'), '');
	    hdnLegendTreeXml.value = HtmlEncode(finalXml);
		map.setAutoRefresh(true);
		layerGrp.setVisibility(chkBox.checked);
	}
	else
	{
		layer = map.getMapLayer(chkBox.value);
		if(layer != null)
		{
			lyrEl = rootEl.selectSingleNode(".//lyr[@id='" + layer.getName() + "']");
			if(lyrEl != null)
			{
			    if(chkBox.checked)
				    lyrEl.setAttribute("iv", "1");
			    else
				    lyrEl.setAttribute("iv", "0");
		    }
		}
		saveLayerState = true;
		var finalXml = xmlDoc.xml.replace(new RegExp('\n|\r','g'), '');
	    hdnLegendTreeXml.value = HtmlEncode(finalXml);
		layer.setVisibility(chkBox.checked);
		map.refresh();
	}
	
	
	
	//legendUpdateDummyImg.click();
}

function verify()
{
  // 0 Object is not initialized
  // 1 Loading object is loading data
  // 2 Loaded object has loaded data
  // 3 Data from object can be worked with
  // 4 Object completely initialized
  if (xmlDoc.readyState != 4)
  {
	return false;
  }
}


function getParentIndex(tbl, parentName)
{
	var i;
	var currentRow;
	var currentCell;
	var currentData;
	var len = tbl.rows.length - 1;
	
	for(i = len; i >= 0 ; i--)
	{
		currentRow = tbl.rows[i];
		currentCell = currentRow.cells(1);
		if(currentCell)
			currentData = currentCell.getAttribute("prnt");
		if(currentData == parentName)
			return i + 1;
	}
	return -1;
}


function getParentIndex2(tbl, parentName)
{
	var i;
	var currentRow;
	var currentCell;
	var currentData;
	
	for(i = 0; i < tbl.rows.length; i++)
	{
		currentRow = tbl.rows[i];
		currentCell = currentRow.cells(1);
		if(currentCell)
			currentData = currentCell.getAttribute("data");
		if(currentData == parentName)
			return i;
	}
	return -1;
}



function doesItemExist(tbl,data)
{
	var i;
	var currentRow;
	var currentCell;
	var currentData;
	
	for(i = 0; i < tbl.rows.length; i++)
	{
		currentRow = tbl.rows[i];
		currentCell = currentRow.cells(1);
		if(currentCell)
			currentData = currentCell.getAttribute("data");
		if(currentData == data)
			return true;
	}
	return false;
}

			
			/*
	Purpose:	This function lets us know if a map layer should be present on the layer control at the current zoom.
	Arguments:	oLayer->The layer object to check
	Returns:	boolean, indicating if the layer should be drawn on the control
	Remarks:	We cannot use the method isVisible (from MGMapLayer) because if the map layer
			is invisible by default, it will never be shown in the layercontrol.

*/
function isLayerVisibleOnControl(theMap, oLayer)
{
	var dMinDisplayRange;
	var dMaxDisplayRange;
	var dMapScale;
	
	var i

	//retrieve the map scale
	dMapScale = theMap.getScale();
	
	//retrieve the display ranges of the map layer
	var mapStyles = (theMap.getMapLayer(oLayer.Name)).getMapLayerStyles();
	
	//loop through all the styles and check map scale is within any of the min and max display ranges
	//for the layer.  We have to check them all because the ranges may not be continuous, so we cannot
	//simplay grab the smallest and largest ones
	for(i = 0; i < mapStyles.size(); i++) 
	{
		dMaxDisplayRange = mapStyles.item(i).getMaxDisplayRange();
		dMinDisplayRange = mapStyles.item(i).getMinDisplayRange();
		
		//check if map layer should be visible
		if ((dMaxDisplayRange >= dMapScale) && (dMinDisplayRange <= dMapScale)) 
		{
			return true;
		}
	}
	return false;
	
}

/*
	Purpose:	To check if one layer in a group is visible at the current scale we are at.  This
			tells us the the group should be displayed on the layercontrol.
	Arguements:	oGroup -> the group to check
	Returns:	boolean, indicating if the group should be added the the layercontrol
*/
function isGroupVisibleOnControl(map, oGroup)
{
	var oLayers;
	
	oLayers = oGroup.getMapLayers();
	for(var iloop=0;iloop<oLayers.Count;iloop++)
	{
		if(isLayerVisibleOnControl(map, oLayers.item(iloop)))
			return true;
	}
	return false;		
}


		
function generateOrder(map, maxOrderLines, rootPath)
{
	var oCount = 0;
	var sel = map.getSelection();
	
	if(sel != null)
		oCount = sel.getNumObjects();
	
	if(oCount > 0)
	{
		if(oCount > maxOrderLines)
		{
			alert("The maximum number of lines that may be ordered at a time is " + maxOrderLines + ".\n\nPlease reduce the number of lines selected and try again.\n\nNumber of selected lines: " + oCount);
			return false;
		}
	}
	else
	{
		alert("Please select at least one line to order.");
		return false;
	}
	
	var selData = "";
	var i;
	var layerName;
	var entKey;
	var mapObjCol = sel.getMapObjects(null);
	for(i = 0; i < oCount; i++)
	{
		entKey = mapObjCol.item(i).getKey();
		if(selData == "")
			selData = selData + "'" + entKey + "'";
		else
			selData = selData + ",'" + entKey + "'";
	}
	
	window.location.href = rootPath + "/OrderSelectedSeismicLines.aspx?MapLines=" + selData;
	
	return false;
}

function generateQI(map, maxQILines, mapID, isCached, mapGUID, qiMaxScale)
{
	var lat = map.getLat();
	var lon = map.getLon();
	var scale = map.getScale();
	var selData = "";
	var oCount = 0;
	var i;
	var layerName;
	var entKey;
	var sel = map.getSelection();
	var mapHtmlObj = document.all(mapID);
	
	if(sel != null)
		oCount = sel.getNumObjects();
	
	if(oCount > 0)
	{
	    if(scale > qiMaxScale)
	    {
	        var maxScaleFormatted = "1:" + qiMaxScale;
	        alert("The maximum scale when generating QI is " + maxScaleFormatted + ". \n\nPlease adjust the current map scale.\n\nThe scale indicator is located on the right side of the map control status bar.");
	        return;
	    }
		if(oCount > maxQILines)
		{
			alert("The maximum number of lines that may be generated for QI at a time is " + maxQILines + ".\n\nPlease reduce the number of lines selected and try again.\n\nNumber of selected lines: " + oCount);
		}
		else
		{
			var mapObjCol = sel.getMapObjects(null);
			for(i = 0; i < oCount; i++)
			{
				entKey = mapObjCol.item(i).getKey();
				if(selData == "")
					selData = selData + "'" + entKey + "'";
				else
					selData = selData + ",'" + entKey + "'";
			}
			//alert(map.getWidth(map.getUnits()));
			//alert(mapHtmlObj.style.width + " - " + mapHtmlObj.style.height);
			var w = map.getWidth(map.getUnits());
			var h = map.getHeight(map.getUnits());
			var dt = new Date();
	        var dummy;
            //Use date and time as a url parameter so the page returned is not cached
            dummy = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds() + "" + dt.getMilliseconds();
			openWindow("qiWin" + dummy,"GenerateQI.aspx?MapLines=" + selData + "&Lat=" + lat + "&Long=" + lon + "&Scale=" + scale + "&height=" + h + "&width=" + w + "&ic=" + isCached + "&mid=" + mapGUID,790,580,false,false,false,true,false,true,true);
		}
	}
	else
	{
		alert("Please select at least one line to generate QI.");
	}
}



function generateReport(mapID, reportID, selCtrlID, mapName)
{
	var map = eval("document.all." + mapID);
	var selCtrl = eval("document.all." + selCtrlID);
	var selData = selCtrl.value;
	var oCount;
	var sel = map.getSelection();
	var arrValidIDs = new Array();
	var i;
	var j = 0;
	var k = 0;

	if(sel != null)
		oCount = sel.getNumObjects();
	
	//selData = "'" + selData.replace(/\|/g, "','") + "'";
	var mapObjCol = sel.getMapObjects(null);
	for(i = 0; i < oCount; i++)
	{
		entKey = mapObjCol.item(i).getKey();
		var currLayerName = mapObjCol.item(i).getMapLayer().getName().toLowerCase();
		var objLayerGroup = mapObjCol.item(i).getMapLayer().getMapLayerGroup();
		var currLayerGroup = "";
		if(objLayerGroup != null)
		    currLayerGroup = objLayerGroup.getName().toLowerCase();
        var arrMapNames;
        var isValidLayer = false;
        
        arrMapNames = mapName.split(",");
	    
	    for(k = 0; k < arrMapNames.length; k++)
	    {
	        //alert("mapname " + k + ": " + arrMapNames[k] + "\n\ncurrlayername: " + currLayerName + "\n\ncurrgroup: " + currLayerGroup);
	        if(currLayerName.indexOf(arrMapNames[k].toLowerCase()) >= 0 || currLayerGroup.indexOf(arrMapNames[k].toLowerCase()) >= 0)
	        {
	            isValidLayer = true;
	            break;
	        }
	    }
	    
		if(isValidLayer)
		{
			arrValidIDs[j] = entKey;
			j++;
		}
	}
	selData = "'" + arrValidIDs.join("','") + "'";
	
	//Added on Feb 23, 2007 - Seems like 1700 is the max chars that could be passed to a report via url parameter.
	//It causes js script error on paging of the report.  
	//Future remedy will us CrossPagePostBack to expose the selected lines in the page's property.
	if(selData.length > 1700){
	    var tmpS =selData.substring(0,1700);
	    var iLast=tmpS.lastIndexOf(",");
	    tmpS = tmpS.substring(0,iLast);
	    selData = tmpS;
	    
	}
	//openWindow("reportsWin","ReportViewer.aspx?MapLines=" + selData + "&ID=" + reportID,790,580,false,false,false,true,false,true,true);
	var dt = new Date();
	var unique;
    //Use date and time as a url parameter so the page returned is not cached
    unique = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds() + "" + dt.getMilliseconds();
	openWindow("reportsWin" + unique,"ReportViewer.aspx?ID=" + reportID + "&MapLines=" + selData + "&",790,580,false,false,false,true,false,true,true);
			//Check for max selected lines
			//if(selData.length < maxReportLines)
			//	openWindow("reportsWin","ReportViewer.aspx?MapLines=" + selData + "&ID=" + reportID,790,580,false,false,false,true,false,true,true);
}


function updateReports(mapID, selID, reportIDs, mapNames, hdnRptIDs, mapSelDummyImgID)
{
	var map = eval("document.all." + mapID);
	var selCtrl = eval("document.all." + selID);
	var hdnRptCtrl = eval("document.all." + hdnRptIDs);
	var mapSelDummyImgCtrl = document.getElementById(mapSelDummyImgID);
	
	var arrReportID = reportIDs.split("|");
	var arrMapName = mapNames.split("|");
	var oCount = 0;
	var i;
	var j;
	var k;
	var layerName;
	var entKey;
	var sel = map.getSelection();
	var selData = "";
	//alert(arrReportID.length);
	//return;
	if(sel != null)
		oCount = sel.getNumObjects();
	
	if(hdnRptCtrl)
	{	
		hdnRptCtrl.value = "";
		
		if(oCount > 0)
		{
			var mapObjCol = sel.getMapObjects(null);
			for(j = 0; j < arrMapName.length; j++)
			{
				var isDeleted = true;
				var arrTmp = arrMapName[j].split(",");
				
				for(i = 0; i < oCount; i++)
				{
					entKey = mapObjCol.item(i).getKey();
					var currLayerName = mapObjCol.item(i).getMapLayer().getName().toLowerCase();
					var objLayerGroup = mapObjCol.item(i).getMapLayer().getMapLayerGroup();
					var currLayerGroup = "";
					if(objLayerGroup != null)
						currLayerGroup = objLayerGroup.getName().toLowerCase();

					//alert("map name: " + arrMapName[j] + "\n\nlayer group name: " + currLayerGroup + "\n\nlayer name: " + currLayerName + "\n\nindexof layer: " + currLayerName.indexOf(arrTmp[k].toLowerCase()) + "\n\nindexof group: " + currLayerGroup.indexOf(arrTmp[k].toLowerCase()));
					for(k = 0; k < arrTmp.length; k++)
					{
						if(currLayerName.indexOf(arrTmp[k].toLowerCase()) == 0 || currLayerGroup.indexOf(arrTmp[k].toLowerCase()) == 0)
						{
							isDeleted = false;
							continue;
						}
					}
					
					if(!isDeleted)
						continue;
				}
				if(!isDeleted)
				{
					if(hdnRptCtrl.value == "")
						hdnRptCtrl.value = arrReportID[j];
					else
						hdnRptCtrl.value = hdnRptCtrl.value + "|" + arrReportID[j];
				}
			}
		}
	}
}

function refreshPanels(mapID, selID, reportIDs, mapNames, hdnRptIDs, mapSelDummyImgID, mainTabCID)
{
	var mainTab = $find(mainTabCID);
	var mapSelDummyImgCtrl = $get(mapSelDummyImgID);
	var map = $get(mapID);
	
	var sel = map.getSelection();
	
	if(sel != null)
	{
	    /*
		if(sel.getNumObjects() > 0)
			mainTab.set_activeTabIndex(0);
	    */
    }
	updateReports(mapID, selID, reportIDs, mapNames, hdnRptIDs, mapSelDummyImgID);
	//updateAreaData(mapID, selID, mapNames, mapSelDummyImgID);
    mapSelDummyImgCtrl.click();
}



function isInRange(mapExtent, mapObjExtent)
{
    var mapTopL;
    var mapBottomL;
    var mapTopR;

    var mapObjTopL;
    var mapObjBottomR;
    var mapObjBottomL;
    var mapObjTopR;
    
    mapTopLX = mapExtent.MinX;
    mapTopLY = mapExtent.MinY;
    
    mapTopRX = mapExtent.MaxX;
    mapTopRY = mapExtent.MinY;
    mapBottomLX = mapExtent.MinX;
    mapBottomLY = mapExtent.MaxY;
    
    mapObjTopLX = mapObjExtent.MinLon;
    mapObjTopLY = mapObjExtent.MinLat;
    mapObjBottomRX = mapObjExtent.MaxLon;
    mapObjBottomRY = mapObjExtent.MaxLat;
    
    mapObjTopRX = mapObjExtent.MaxLon;
    mapObjTopRY = mapObjExtent.MinLat;
    mapObjBottomLX = mapObjExtent.MinLon;
    mapObjBottomLY = mapObjExtent.MaxLat;
    
    if( ((mapObjTopLX >= mapTopLX && mapObjTopLX <= mapTopRX) && (mapObjTopLY >= mapTopLY && mapObjTopLY <= mapBottomLY)) || ((mapObjTopRX >= mapTopLX && mapObjTopRX <= mapTopRX) && (mapObjTopRY >= mapTopLY && mapObjTopRY <= mapBottomLY)) || ((mapObjBottomLX >= mapTopLX && mapObjBottomLX <= mapTopRX) && (mapObjBottomLY >= mapTopLY && mapObjBottomLY <= mapBottomLY)) || ((mapObjBottomRX >= mapTopLX && mapObjBottomRX <= mapTopRX) && (mapObjBottomRY >= mapTopLY && mapObjBottomRY <= mapBottomLY)) )
        return true;
    else
        return false;
    
}

function confirmDefaultView()
{
	return confirm("You are about to set the current map location as your home view.\n\nDo you want to proceed?\n");	
}

function SelBkm(mapObjID, zoomInfo, selectionData, zoomInfoCtrlID, selDataCtrlID, bkmID, bkmIDCtrlID, imgHiddenCtrlID)
{
	var map = eval("document.all." + mapObjID);
	var mapHtmlObj = document.all(mapObjID);
	var mapDisplayType = mapHtmlObj.getAttribute("mapDisplayType");
	var selBkmCtrl = $get(bkmIDCtrlID);
	var imgHiddenCtrl = $get(imgHiddenCtrlID);
	
	var sel = map.getSelection();
	
	if(sel != null)
	{
	    map.setAutoRefresh(false);
		sel.clear();
    }
	
	document.all(zoomInfoCtrlID).value = zoomInfo;
	document.all(selDataCtrlID).value = selectionData;
	
	mapHtmlObj.setAttribute("refreshMap","true",0);
	mapHtmlObj.setAttribute("doSelection", "true", 0);
	if(mapDisplayType == "ViewfinderSourceMap")
	{
		mapHtmlObj.setAttribute("refreshTarget", "true", 0);
		mapHtmlObj.setAttribute("skipZoom", "false", 0);
	}
	else if(mapDisplayType == "ViewfinderTargetMap")
	{
		mapHtmlObj.setAttribute("refreshSource", "true", 0);
		mapHtmlObj.setAttribute("skipZoom", "false", 0);
	}
	
	selBkmCtrl.value = bkmID
	imgHiddenCtrl.click();
	map.refresh();
}

function loadDefaultView(mapObjID, zoomInfo, zoomInfoCtrlID, selDataCtrlID)
{
	var map = eval("document.all." + mapObjID);
	var mapHtmlObj = document.all(mapObjID);
	var mapDisplayType = mapHtmlObj.getAttribute("mapDisplayType");
	
	var sel = map.getSelection();
	
	if(sel != null)
	{
	    map.setAutoRefresh(false);
		sel.clear();
    }
	
	document.all(zoomInfoCtrlID).value = zoomInfo;
	document.all(selDataCtrlID).value = "";
	
	mapHtmlObj.setAttribute("refreshMap","true",0);
	mapHtmlObj.setAttribute("doSelection", "false", 0);
	if(mapDisplayType == "ViewfinderSourceMap")
	{
		mapHtmlObj.setAttribute("refreshTarget", "true", 0);
		mapHtmlObj.setAttribute("skipZoom", "false", 0);
	}
	else if(mapDisplayType == "ViewfinderTargetMap")
	{
		mapHtmlObj.setAttribute("refreshSource", "true", 0);
		mapHtmlObj.setAttribute("skipZoom", "false", 0);
	}
		
	map.refresh();
}




function sendPackage(map, maxQILines, mapID, isCached, mapGUID, qiMaxScale, isGuestLogin)
{
	var lat = map.getLat();
	var lon = map.getLon();
	var scale = map.getScale();
	var selData = "";
	var oCount = 0;
	var i;
	var layerName;
	var entKey;
	var sel = map.getSelection();
	var mapHtmlObj = document.all(mapID);
	
	if(sel != null)
		oCount = sel.getNumObjects();
	
	if(oCount > 0)
	{
	    if(scale > qiMaxScale)
	    {
	        var maxScaleFormatted = "1:" + qiMaxScale;
	        alert("The maximum scale when generating a package is " + maxScaleFormatted + ". \n\nPlease adjust the current map scale.\n\nThe scale indicator is located on the right side of the map control status bar.");
	        return;
	    }
		if(oCount > maxQILines)
		{
			alert("The maximum number of lines that may be generated for a package at a time is " + maxQILines + ".\n\nPlease reduce the number of lines selected and try again.\n\nNumber of selected lines: " + oCount);
		}
		else
		{
		    var mapObjCol = sel.getMapObjects(null);
			for(i = 0; i < oCount; i++)
			{
				entKey = mapObjCol.item(i).getKey();
				if(selData == "")
					selData = selData + "'" + entKey + "'";
				else
					selData = selData + ",'" + entKey + "'";
			}
			//alert(map.getWidth(map.getUnits()));
			//alert(mapHtmlObj.style.width + " - " + mapHtmlObj.style.height);
			var w = map.getWidth(map.getUnits());
			var h = map.getHeight(map.getUnits());
			var mapExt = map.getMapExtent(true,false);
			var dt = new Date();
	        var dummy;
            //Use date and time as a url parameter so the page returned is not cached
            dummy = dt.getHours() + "" + dt.getMinutes() + "" + dt.getSeconds() + "" + dt.getMilliseconds();
			var extQueryStr = "&maxX=" + mapExt.getMaxX() + "&maxY=" + mapExt.getMaxY() + "&minX=" + mapExt.getMinX() + "&minY=" + mapExt.getMinY() + "&dummy=" + dummy;
			
			isCached = 0;
			if(isGuestLogin)
			{
			    setupRedlineInfo(map);
			    if(document.forms[0].hdnRedlineInfo.value != "")
			        openWindow("qiWin" + dummy,"GuestSendPackage.aspx?MapLines=" + selData + "&Lat=" + lat + "&Long=" + lon + "&Scale=" + scale + "&height=" + h + "&width=" + w + "&ic=" + isCached + "&mid=" + mapGUID + extQueryStr + "&red=1",985,590,false,false,false,true,false,true,true);
			    else
			        openWindow("qiWin" + dummy,"GuestSendPackage.aspx?MapLines=" + selData + "&Lat=" + lat + "&Long=" + lon + "&Scale=" + scale + "&height=" + h + "&width=" + w + "&ic=" + isCached + "&mid=" + mapGUID + extQueryStr,985,590,false,false,false,true,false,true,true);
			}
			else
			{
			    setupRedlineInfo(map);
			    if(document.forms[0].hdnRedlineInfo.value != "")
			        openWindow("qiWin" + dummy,"SendPackage.aspx?MapLines=" + selData + "&Lat=" + lat + "&Long=" + lon + "&Scale=" + scale + "&height=" + h + "&width=" + w + "&ic=" + isCached + "&mid=" + mapGUID + extQueryStr + "&red=1",985,580,false,false,false,true,false,true,true);
			    else
			        openWindow("qiWin" + dummy,"SendPackage.aspx?MapLines=" + selData + "&Lat=" + lat + "&Long=" + lon + "&Scale=" + scale + "&height=" + h + "&width=" + w + "&ic=" + isCached + "&mid=" + mapGUID + extQueryStr,985,580,false,false,false,true,false,true,true);
			}
		}
	}
	else
	{
		alert("Please select at least one line on the map to generate a package.  \n\nTo select a line, click on the arrow map toolbar button and click on a line.\n\nTo select multiple lines, click the arrow button and hold the Shift key while selecting each line.");
	}
}

function aicb_onClick(chkbox, aiMetaID, hdnAIMetaJsonCID)
{
    var hdnAIMetaJson = document.getElementById(hdnAIMetaJsonCID);
    var areaInfoMetaCol = eval("(" + hdnAIMetaJson.value + ")");
    var areaInfoMeta;
    for(i = 0; i < areaInfoMetaCol.Items.length; i++)
    {
        areaInfoMeta = areaInfoMetaCol.Items[i];
        if(areaInfoMeta.ID == aiMetaID)
            break;
    }
    if(!chkbox.checked)
    {
        for(i = 0; i < areaInfoMeta.SelectedIDList.length; i++)
        {
            if(areaInfoMeta.SelectedIDList[i] == chkbox.value)
            {
                areaInfoMeta.SelectedIDList.splice(i,1);
                break;
            }
        }
    }
    else
    {
        areaInfoMeta.SelectedIDList[areaInfoMeta.SelectedIDList.length] = chkbox.value;
    }
    //alert(aiMetaID + " - " + areaInfoMeta.Title + ": " + areaInfoMeta.SelectedIDList.length);
    hdnAIMetaJson.value = Sys.Serialization.JavaScriptSerializer.serialize(areaInfoMetaCol);
    
}

function aicbInc(chkbox, aiMetaID, map, hdnAIMetaJsonCID)
{
    var hdnAIMetaJson = document.getElementById(hdnAIMetaJsonCID);
    var areaInfoMetaCol = eval("(" + hdnAIMetaJson.value + ")");
    var areaInfoMeta;
    for(i = 0; i < areaInfoMetaCol.Items.length; i++)
    {
        areaInfoMeta = areaInfoMetaCol.Items[i];
        if(areaInfoMeta.ID == aiMetaID)
            break;
    }
    map.refresh();
    if(!chkbox.checked)
    {
        areaInfoMeta.SelectedIDList.length = 0;
        areaInfoMeta.IncludeInFilter = false;
        disableAreaFilterCheckbox(areaInfoMeta.ID, true);
    }
    else
    {
        areaInfoMeta.IncludeInFilter = true;
        disableAreaFilterCheckbox(areaInfoMeta.ID, false);
    }
    
    hdnAIMetaJson.value = Sys.Serialization.JavaScriptSerializer.serialize(areaInfoMetaCol);
    //alert(areaInfoMeta.SelectedIDList.length + " " + hdnAIMetaJson.value);
}

function disableAreaFilterCheckbox(aiMetaItemID, setting)
{
    var cbCol = eval("document.forms[0].aicb_" + aiMetaItemID);
    if(cbCol)
    {
        if(cbCol.length)
        {
            for(j = 0; j < cbCol.length; j++)
            {
                cbCol[j].disabled = setting;
                cbCol[j].checked = false;
            }
        }
    }
}

function updateAreaData(mapID, mapViewChangedDummyImgCID, hdnAIMetaJsonCID)
{
    var hdnAIMetaJson = document.getElementById(hdnAIMetaJsonCID);
    if(hdnAIMetaJson)
    {
        if(hdnAIMetaJson.value != "")
        {
            var i;
	        var j;
	        var k;
            var map = eval("document.all." + mapID);
            var scale = map.getScale();    
            var mapViewChangedDummyImg = document.getElementById(mapViewChangedDummyImgCID);
            var aiMetaItem;
            var areaInfoMetaCol = eval("(" + hdnAIMetaJson.value + ")");
            
            for(i = 0; i < areaInfoMetaCol.Items.length; i++)
            {
                aiMetaItem = areaInfoMetaCol.Items[i];
                if(aiMetaItem.IsActive && aiMetaItem.IncludeInFilter)
                {
                    aiMetaItem.CurrentScale = scale;
                    if(scale > aiMetaItem.MaxScale)
                    {
                        continue;
                    }
                    var oCount = 0;
	                var layerName;
	                var entKey;
	                var selData = "";
                	
	                var tooltipID = "";
	                var result;
	                var baIDList = "";
	                var entLyrGrp;
	                var entLyrCol;
	                var entLyr;
	                var mapObjCol;
	                var mapObj;
	                var mapExtent;
	                var mapObjExtent;
	                var jsonAreaInfo = "";
	                var isFirstGroup = true;
	                var isFirstLayer = true;
	                var isFirstObject = true;
	                var hasObject;
	                var isLayerVisible;
        	        aiMetaItem.LineIDList.length = 0;
	                mapExtent = map.getMapExtent(true, false);
	                if(aiMetaItem.IncludedMapLayers.length > 0)
	                {
	                    for(n = 0; n < aiMetaItem.IncludedMapLayers.length; n++)
	                    {
	                        entLyr = map.getMapLayer(aiMetaItem.IncludedMapLayers[n]);
	                        isLayerVisible = true;
                            if(entLyr != null)
                            {
                                entLyrGrp = entLyr.getMapLayerGroup();
                                if(entLyrGrp != null)
                                {
                                    if(!entLyrGrp.getVisibility())
                                        isLayerVisible = false;
                                }
                                if(!entLyr.isVisible())
                                    isLayerVisible = false;
                                if(isLayerVisible)
                                {
                                    mapObjCol = entLyr.getMapObjects();
                                    for(j = 0; j < mapObjCol.Count; j++)
                                    {
                                        mapObj = mapObjCol.item(j);
                                        mapObjExtent = mapObj.getExtent();
                                        if(isInRange(mapExtent, mapObjExtent))
                                        {
                                            entKey = mapObj.getKey();
                                            if(aiMetaItem.LineIDList.length <= aiMetaItem.MaxLines)
                                                aiMetaItem.LineIDList[aiMetaItem.LineIDList.length] = {"LineID" : entKey, "Tooltip" : mapObj.getName(), "URL" : mapObj.getLink()};
                                        }
                                    }
                                }
                            }
	                    }
	                }
                }
            }
            
            
	        hdnAIMetaJson.value = Sys.Serialization.JavaScriptSerializer.serialize(areaInfoMetaCol)
	        if(!holdPostback)
	        {
                mapViewChangedDummyImg.click();  
            }
        }
    } 
    //alert(hdnAIMetaJson.value);
}
