var layersViewWidth;
var strActiveLayer = '';

function closeActiveDoc()
{
	var target = top.map.document.getElementById('close_DocumentTabs1');
	tabs_closeActiveTab(target);
}

function closeDocByMapId(id)
{
	var frms = top.map.document.frames;
	for(var i = 0; i < frms.length; i++)
	{
		var frame = frms[i];
		if(typeof frame.gMapWindowID == 'number')
		{
			if(frame.gMapWindowID == id)
			{
				var target = top.map.document.getElementById('close_DocumentTabs1');
				tabs_closeTabIndex(target, i)
				return;
			}
		}
	}
}

function activeDoc()
{
	var ctrl = top.map.document.getElementById('DocumentTabs1');
	var doc = tabs_activeDocument(ctrl);
	if(doc != null)
	{
		var win = doc.parentWindow;
		if(win.timeoutID > 0)
		{
			win.clearTimeout(win.timeoutID);
			win.timeoutID = 0;
		}
	}
	else
		alert("Could not find the current document frame.");

	return doc;
}

function activeFrame()
{
	var ctrl = top.map.document.getElementById('DocumentTabs1');
	return tabs_activeFrame(ctrl);
}

function getMap()
{
	var doc = activeDoc();
	if(doc != null)
	{
		var map = doc.getElementById('map');
		if(map != null)
			return map;
	}
}

function getMapById(id)
{
	var frame = getFrameByMapId(id);
	if(frame != null)
		return frame.document.getElementById('map');
}

function getFrameByMapId(id)
{
	var frms = top.map.document.frames;
	for(var i = 0; i < frms.length; i++)
	{
		var frame = frms[i];
		if(typeof frame.gMapWindowID == 'number')
		{
			if(frame.gMapWindowID == id)
				return frame;
		}
	}
}

function getViewer()
{
	var doc = activeDoc();
	if(doc != null)
	{
		var viewer = doc.getElementById('DwfViewer1');
		if(viewer != null)
			return viewer;
	}
}

function OpenDocumentWindow(Name, Caption, URL, scrolling)
{
	tabs_addTab(getTabCtrl(), Name, Caption, URL, scrolling);
}

function OpenToolFrame(url)
{
	if(GetSideFrame().location.href.indexOf(url) < 0)
		GetSideFrame().location = strApplicationPath + '/Tools/' + url;
}

function ResetToolFrame()
{
	var frame = activeFrame();
	if(typeof frame.tabs_onThisTabActivate == 'function')
		frame.tabs_onThisTabActivate();
}

function GetSideFrame()
{
	return top.SideFrame.document;
}

function SetHelpTopic(id)
{
	var doc = GetSideFrame();
	var frame = doc.frames['InnerFrame'];
	if(frame.document.location.href.indexOf('ID=' + id) < 0)
		frame.document.location = strApplicationPath + '/Help/HelpTopic.aspx?ID=' + id;
}

function copyMapAsWMF()
{
	var map = getMap();
	if(map != null)
	{
		map.copyMap();
		alert('The current view of the map has been copied to the clipboard as an Enhanced Windows Metafile.');
	}
	else
	{
		var viewer = getViewer();
		if(viewer != null)
			viewer.ExecuteCommand('COPY');
	}
}

/*

Digitize functions

*/

function digitizeOK(dsID, type, geom)
{
	var map = getMap();
	if(map == null)
	{
		alert('A map must be visible in order to create new geometry.');
		return false;
	}
	var frame = activeFrame();
	if(frame.gIsMapOwner && !frame.gIsPublic)
	{
		var layer = GetMapLayerOf(dsID);
		if(layer != null)
		{
			frame.strDigitizeAction = 'AfterDigitize.aspx';
			frame.lngMapLayerType = type;
			frame.strGeometry = geom;
			frame.lngDatasetID = dsID;
			frame.strSelLayerName = layer.getName();
			selectClear();
			OpenToolFrame('BeforeDigitize.aspx?Type=' + geom);
			return true;
		}
		alert('This dataset is not included in the current map.');
		return false;
	}

	alert('Before you can create your own geometry, you must first create your own custom map.');
	return false;
}

function digitizeCircle(dsID)
{
	if(digitizeOK(dsID, 4, 'Circle'))
		getMap().digitizeCircle('FT');
}

function digitizeLine(dsID)
{
	if(digitizeOK(dsID, 3, 'Line'))
		getMap().digitizeLine();
}

function digitizeText(dsID)
{
	if(digitizeOK(dsID, 1, 'Text'))
		getMap().digitizePoint();
}

function digitizePoint(dsID)
{
	if(digitizeOK(dsID, 2, 'Point'))
		getMap().digitizePoint();
}

function digitizePolygon(dsID)
{
	if(digitizeOK(dsID, 4, 'Polygon'))
		getMap().digitizePolygon();
}

function digitizePolyline(dsID)
{
	if(digitizeOK(dsID, 3, 'Polyline'))
		getMap().digitizePolyline();
}

function digitizeRectangle(dsID)
{
	if(digitizeOK(dsID, 4, 'Rectangle'))
		getMap().digitizeRectangle();
}

/*

End Digitize Functions

*/

function selectClear()
{
	var map = getMap();
	if(map == null) return;

	map.getSelection().clear();
}

function viewBufferDlg()
{
	var map = getMap();
	if(map == null) return;
	SetHelpTopic(11);
	map.viewBufferDlg();
}

function removeBuffers()
{
	var map = getMap();
	if(map == null) return;

	var i;
	var objLayers = map.getMapLayers();

	for(i = objLayers.size() - 1; i >= 0; i--)
	{
		if(objLayers.item(i).getLayerType() == 'Buffer')
			map.removeMapLayer(objLayers.item(i).getName());
	}
}

function getVertexInfo()
{
	var map = getMap();
	if(map == null) return;

	// Get selected features
	var selected = map.getSelection().getMapObjectsEx(null);

	// Make sure just one is selected
	if (selected.size() != 1)
		alert ('Please select one, and only one, feature.');
	else
	{  
		// Create collections to hold vertex info 
		verts = map.createObject('MGCollection');
		vertNum = map.createObject('MGCollection');

		// Get vertices of first (and only) item in selected collection
		result = selected.item(0).getVertices(verts, vertNum);

		// Display results
		if (result == 0)
			alert ('Unable to access feature\'s coordinate information');
		if (result == 1)
			alert ('This is a polyline, polygon, point, or text feature with ' + verts.size() + ' vertices');
		else
			alert ('This is a poly-polyline or poly-polygon. It has ' + result + ' vertices.');
	}
}

function toggleLegend(bChecked)
{
	var map = getMap();
	if(map == null) return;

	if(bChecked)
		map.LayersViewWidth = layersViewWidth;
	else
	{
		if(map.LayersViewWidth > 0)
			layersViewWidth = map.LayersViewWidth;
		map.LayersViewWidth = 0;
	}
}

function UltraWebMenu1_ItemClick(menuId, itemId)
{
}

function UltraWebMenu1_ItemChecked(menuId, itemId, bChecked)
{
	var item = igmenu_getItemById(itemId);
	var tag = item.getTag();

	if(tag == 'Legend')
		toggleLegend(bChecked);
}

function UpdateCommandUI()
{
}

function showHelpPage()
{
	OpenDocumentWindow("Help", "Help", "Help/Help.aspx?ID=1", "auto")
	// alert('Not implemented.');
	// parent.SideFrame.frames('bottom').frames('InnerFrame').document.location = 'Help/Help.aspx?ID=1';
}

function UltraWebMenu1_SubMenuDisplay(menuId, itemId, bDisplay)
{
	var map = getMap();
	if(map == null) return;

	if(!bDisplay)
		return;

	var mapSel = map.getSelection();
	if(mapSel == null)
		return;

	var numObjs = mapSel.getNumObjects();

	var item = igmenu_getItemById('UltraWebMenu1_5_4');
	item.setEnabled(numObjs > 0);
	item = igmenu_getItemById('UltraWebMenu1_4_4');
	item.setEnabled(numObjs > 0);
	item = igmenu_getItemById('UltraWebMenu1_4_6');
	item.setEnabled(numObjs > 0);
}

function UltraWebToolbar1_Click(oToolbar, oButton, oEvent)
{
}

function OnSubmit()
{
	return false;
}

function FindParcel()
{
	if(getMap() == null)
	{
		alert("A map window must be visible to use this function.");
		return;
	}
	var tb = igtbar_getToolbarById('UltraWebToolbar1');
	for(i = 0; i < tb.Items.length && tb.Items[i].Key != 'FindText'; i++);
	var s = tb.Items[i].Element.value;
	var re = /\w+/;
	if(s.match(re))
	{
		GetSideFrame().write('<html><head></head><body leftmargin="6" topmargin="8" bgcolor="#7f7f66"><p style="font-family: Tahoma; font-weight: bold; color: white; font-size: 13px;">Searching...</p></body></html>');
		OpenToolFrame('DoFind.aspx?DatasetID=13&SearchString=' + encodeURI(s));
	}
	else
		alert('Please enter a valid search string. You may enter all or part of a parcel number, owner name, or address');
}

function MyProfile()
{
	OpenToolFrame('MyProfile.aspx');
}

function MyAdmin()
{
	OpenToolFrame('MyAdmin.aspx');
}

function MapNew()
{
	OpenToolFrame('NewMap.aspx');

	// Get a new tab name for the new map
	// for(var i = 1; tabs_tabIndexOf(getTabCtrl(), 'mwf_newMap' + i) > 0; i++);
	// OpenDocumentWindow('mwf_newMap' + i, 'New Map ' + i, 'MapWindow.aspx', 'no');
}

function MapOpen()
{
	OpenToolFrame("OpenMap.aspx");
}

function OpenMap(id, name)
{
	OpenDocumentWindow('mwf_Map' + id, name, 'MapWindow.aspx?ID=' + id, 'no');
}

function MapOpenDefaultMap()
{
	OpenDocumentWindow('mwf_Map1', 'Default Map', 'MapWindow.aspx?ID=1', 'no');
}

function MapProperties()
{
	var map = getMap();
	if(map == null) return;
	
	var frame = activeFrame();
	if(frame.gIsMapOwner && !frame.gIsPublic)
	{
		OpenToolFrame('EditMap.aspx?MapID=' + frame.gMapWindowID);
		return;
	}

	alert('You can only edit the properties of your own custom maps.');
}

function addMapLayer(mapID, layerID, name, type, dsID, groupName)
{
	var frame = getFrameByMapId(mapID);
	if(frame == null) return;

	var map = frame.document.getElementById('map');
	if(map == null) return;

	// Here we set up the strGroupName variable, which is used in the OnAddMapLayer event
	// To add the new layer to the group
	frame.strGroupName = groupName;
	map.addMapLayer('getmlf.aspx?MapID=' + mapID + '&LayerID=' + layerID);

	frame.gMapLayers.push(new frame.MapLayerClass(layerID, name, type, dsID));
}

function reloadMapLayer(mapID, layerID, groupName)
{
	var frame = getFrameByMapId(mapID);
	if(frame == null) return;

	var map = frame.document.getElementById('map');
	if(map == null) return;

	var layer = frame.getMapLayerById(layerID);
	if(layer == null) return;

	// alert('layer = ' + layer.getName() + '  group = ' + groupName);
	
	frame.bDoSelectionChangedEvent = false;
	map.setAutoRefresh(false);
	var group = map.getMapLayerGroup(groupName);

	map.removeMapLayer(layer.getName());

	/*
	if(group != null)
		group.removeMapLayer(layer);
	else
		map.removeMapLayer(layer.getName());
	*/

	// Here we set up the strGroupName variable, which is used in the OnAddMapLayer event
	// To add the new layer to the group
	frame.strGroupName = groupName;

	map.setAutoRefresh(true);
	map.addMapLayer('getmlf.aspx?MapID=' + mapID + '&LayerID=' + layerID);

	// frame.bDoSelectionChangedEvent = true;
	setTimeout('EnableEvents(' + mapID + ')', 1000);
}

function rebuildMapLayer(mapID, layerID)
{
	var frame = getFrameByMapId(mapID);
	if(frame == null) return;

	var map = frame.document.getElementById('map');
	if(map == null) return;

	var layer = frame.getMapLayerById(layerID);
	if(layer == null) return;

	layer.setRebuild(true);
	map.refresh();
}

function EnableEvents(mapID)
{
	var frame = getFrameByMapId(mapID);
	if(frame == null) return;
	frame.bDoSelectionChangedEvent = true;
}

function DoAddMapLayer(mapID, layerID)
{
	var frame = getFrameByMapId(mapID);
	if(frame == null) return;

	var map = frame.document.getElementById('map');
	if(map == null) return;

	map.addMapLayer('getmlf.aspx?MapID=' + mapID + '&LayerID=' + layerID);
	frame.bDoSelectionChangedEvent = true;
}

function pageSetupDlg()
{
	var map = getMap();
	if(map == null) return;
	map.pageSetupDlg();
}

function printDlg()
{
	var map = getMap();
	if(map != null)
		map.printDlg();
	else
	{
		var viewer = getViewer();
		if(viewer != null)
			viewer.ExecuteCommand('PRINT');
		else
		{
			var frame = activeFrame();
			if(frame != null)
				frame.print();
		}
	}
}

function copyUrl()
{
	var map = getMap();
	if(map == null) return;
	// map.copyUrl();
	window.clipboardData.setData("Text", top.location.protocol + '//' + top.location.hostname);
}

function EditFind()
{
	var map = getMap();
	if(map == null) return;

	var frame = activeFrame();
	if(frame != null)
		OpenToolFrame('AdvancedFind.aspx?MapID=' + frame.gMapWindowID);
}

function refresh()
{
	var map = getMap();
	if(map == null) return;
	map.refresh();
}

function redrawLegend()
{
	var map = getMap();
	if(map == null) return;
	map.redrawLegend();
}

function zoomInMode()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(3);
		map.zoomInMode();
	}
	else
	{
		var viewer = getViewer();
		if(viewer != null)
			viewer.ExecuteCommand('ZOOMRECT');
	}
}

function zoomOutMode()
{
	var map = getMap();
	if(map == null) return;
	SetHelpTopic(3);
	map.zoomOutMode();
}

function zoomOut()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(3);
		map.zoomOut();
	}
	else
	{
		var viewer = getViewer();
		if(viewer != null)
		{
			var page = viewer.Viewer;
			page.View = page.NamedViews(1);
		}
	}
}

function panMode()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(3);
		map.panMode();
	}
	else
	{
		var viewer = getViewer();
		if(viewer != null)
			viewer.ExecuteCommand('PAN');
	}
}

function zoomPrevious()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(3);
		map.zoomPrevious();
	}
	else
	{
		var viewer = getViewer();
		if(viewer != null)
			viewer.ExecuteCommand('PREVIOUSVIEW');
	}
}

function selectMode()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(4);
		map.selectMode();
	}
	else
	{
		var viewer = getViewer();
		if(viewer != null)
			viewer.ExecuteCommand('SELECT');
	}
}

function selectPolygonMode()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(4);
		map.selectPolygonMode();
	}
}

function selectRadiusMode()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(4);
		map.selectRadiusMode();
	}
}

function selectWithinDlg()
{
	var map = getMap();
	if(map != null)
	{
		SetHelpTopic(4);
		map.selectWithinDlg();
	}
}

function preferencesDlg()
{
	var map = getMap();
	if(map != null)
		map.preferencesDlg();
}

function aboutDlg()
{
	var map = getMap();
	if(map != null)
		map.aboutDlg();
}

function setDigitizeAction(s)
{
	var frame = activeFrame();
	if(frame != null)
	{
		frame.strDigitizeAction = s;
		return true;
	}
	return false;
}

function digitizeDistance()
{
	var map = getMap();
	if(map != null)
		map.viewDistance('FT');
}

function digitizeArea()
{
	var map = getMap();
	if(map != null)
	{
		if(setDigitizeAction('GetArea.aspx'))
			map.digitizePolygon();
	}
}

function zoomTo(x1, y1, x2, y2)
{
	var map = getMap();
	if(map != null)
	{
		var mapWidth = (x2 - x1) * 1.3;
		var mapHeight = (y2 - y1) * 1.3;
		var aspectRatio = map.getWidth("FT") / map.getHeight("FT");
		var newWidth = mapWidth;

		if((mapWidth / mapHeight) < aspectRatio)
			newWidth = mapHeight * aspectRatio;

		newWidth = newWidth < 1000 ? 1000 : newWidth;

		var centerPoint = map.mcsToLonLat((x1 + x2) / 2.0, (y1 + y2) / 2.0);
		var mapCenterLAT = centerPoint.getY();
		var mapCenterLON = centerPoint.getX();

		map.zoomWidth(mapCenterLAT, mapCenterLON, newWidth, 'FT');
	}
}

function zoomAndSelect(x1, y1, x2, y2, dataFile, keyString)
{
	var map = getMap();
	if(map != null)
	{
		var mapWidth = (x2 - x1) * 3;
		var mapHeight = (y2 - y1) * 3;
		var aspectRatio = map.getWidth("FT") / map.getHeight("FT");
		var newWidth = mapWidth;
		
		if((mapWidth / mapHeight) < aspectRatio)
			newWidth = mapHeight * aspectRatio;

		newWidth = newWidth < 1000 ? 1000 : newWidth;

		var centerPoint = map.mcsToLonLat((x1 + x2) / 2.0, (y1 + y2) / 2.0);
		var mapCenterLAT = centerPoint.getY();
		var mapCenterLON = centerPoint.getX();

		var frame = activeFrame();
		if(frame != null)
		{
			frame.strSelDataFile = dataFile;
			frame.strSelKey = keyString;
		}

		map.zoomWidth(mapCenterLAT, mapCenterLON, newWidth, 'FT');

	}
}

function getTabCtrl()
{
	return top.map.document.getElementById('DocumentTabs1');
}

function tabs_onTabActivate(name)
{
	if(name.indexOf('dwf') == 0)
		OpenToolFrame("DwfTools.aspx");

	if(name.indexOf('mwf') == 0)
		OpenToolFrame("Selection.aspx");
}

function tabs_onTabAdded(Name, Caption, URL)
{
}

function getSelectedObject()
{
	var map = getMap();

	// Check the map object
	if(map == null)
		return null;

	// Try to get the selection object
	var mapSel = map.getSelection();
	if(mapSel == null)
		return null;

	// Make sure there is only one object selected
	var numObjs = mapSel.getNumObjects();
	if(numObjs != 1)
		return null;

	return mapSel.getMapObjectsEx(null).item(0);
}

function doOverlay(id, key)
{
	var obj = getSelectedObject();
	if(obj == null)
	{
		alert('Please select a single object on the map.');
		return;
	}

	OpenToolFrame('Overlay.aspx?ID=' + id + '&Key=' + key);
	// alert(obj.getName());	
}

function DeleteFeature(MapID, LayerID, ds, key)
{
	if(confirm("You are about to permanently delete this object."))
	{
		OpenToolFrame('DeleteFeature.aspx?MapID=' + MapID + '&LayerID=' + LayerID + '&DatasetID=' + ds + '&Key=' + key);
	}
}

function NewDataset()
{
	var map = getMap();
	if(map == null)
	{
		alert('A map must be visible in order to place features.');
		return;
	}
	var frame = activeFrame();
	if(frame.gIsMapOwner && !frame.gIsPublic)
	{
		OpenToolFrame('EditFeatureDataset.aspx?MapWindowID=' + frame.gMapWindowID);
		return;
	}

	alert('you must open or create your own custom map before placing features.');
	MapOpen();
}

function PlaceFeatures()
{
	var map = getMap();
	if(map == null)
	{
		alert('A map must be visible in order to place features.');
		return;
	}
	var frame = activeFrame();
	if(frame.gIsMapOwner && !frame.gIsPublic)
	{
		OpenToolFrame('PlaceFeatures.aspx?MapWindowID=' + frame.gMapWindowID);
		return;
	}

	alert('you must open or create your own custom map before placing features.');
	MapOpen();
}

function GetMapLayerOf(dsID)
{
	var map = getMap();
	if(map == null) return null;

	var frame = activeFrame();
	var layers = frame.gMapLayers;

	for(var i = 0; i < layers.length; i++)
	{
		if(layers[i].dataset == dsID)
			return map.getMapLayer(layers[i].name);
	}
	return null;
}

function OnObjectAdded(key)
{
	var map = getMap();
	if(map == null) return null;

	var frame = activeFrame();
	var layerName = frame.strSelLayerName;
	frame.strSelKey = key;
	
	var layer = map.getMapLayer(layerName);
	layer.setRebuild(true);
	map.refresh();
}

function ExplorerBar_OnGroupExpand(caption)
{
	var dir = '';
	if(document.location.href.indexOf('/Tools/') >= 0)
		dir = '../';
		
	top.Hidden.location = dir + 'SetUserPref.aspx?Setting=ExplorerBarGroup&Caption=' + caption + '&Visible=True';
}

function ExplorerBar_OnGroupCollapse(caption)
{
	var dir = '';
	if(document.location.href.indexOf('/Tools/') >= 0)
		dir = '../';
		
	top.Hidden.location = dir + 'SetUserPref.aspx?Setting=ExplorerBarGroup&Caption=' + caption + '&Visible=False';
}

function GenerateReport(mapID, layerID)
{
	var frame = getFrameByMapId(mapID);
	if(frame == null) return;
	var layer = frame.getMapLayerClassById(layerID);
	tabs_addTab2(getTabCtrl(), 'Report_' + mapID + '_' + layerID, "Report", strApplicationPath + '/Tools/Report.aspx?MapID=' + mapID + '&LayerID=' + layerID + '&DatasetID=' + layer.dataset, 'yes');
}

function removeSelectedObjects()
{
	var frame = activeFrame();
	if(frame == null) return;

	var map = getMap();
	if(map == null) return;

	// Try to get the selection object
	var mapSel = map.getSelection();
	if(mapSel == null) return;

	// Loop through all the layers in the map
	var objLayers = map.getMapLayersEx();
	for(var i = 0; i < objLayers.size(); i++)
	{
		var layer = objLayers.item(i);
		if(layer.getLayerType() == 'Redline' || layer.getLayerType() == 'Buffer')
		{
			var sel = mapSel.getMapObjectsEx(layer);
			if(sel.size() > 0)
				layer.removeObjects(sel);
				
		}
	}

	frame.tabs_onThisTabActivate();	
}


