var m_lyrMgrTree = '_tLyrMgr';
var m_lytMgrContainer = 'divTree';
var m_lyrNodeStyle = "";
var m_activeNodeStyle = "ActiveLayer";
var m_greyedNodeStyle = "GreyedLayer";
var m_groupNodeStyle = "GroupedLayer";
var m_mapNodeStyle = "MapNode";
var m_mapSourceId = "";
function btnApplyLyrMgr()
{
	if(!sessionExpired)
	{
		if (PageMethods && PageMethods.ApplyLayerManager)
		{
			var tree = _FindTree(m_lyrMgrTree);
			if (tree != null)
			{
				var state = GetTreeState(tree);
				try{showLoading();}catch(e){}	
				PageMethods.ApplyLayerManager(escape(state),HandleApplyLyrMgr);				
			}
		}
	}
	else
		HandleSessionExpired();
}
function GetTreeState(tree)
{
	//NodeId, checkedstate,expanedstate:  ordered
	var sb = new Array();
	sb.push("<T v=\"" + (tree.GetNodesMovedStatus() ? "1" : "0") + "\">");
	var nodes = tree.GetNodes();
	for (var i=0;i<nodes.length;i++)	
		SetNodeState(nodes[i],sb);
	sb.push("</T>");
	tree.ResetNodesMovedStatus();
	return sb.join('');
}
function SetNodeState(node,stateArray)
{
	var close = true;
	if (node.NodeType != "LG")
	{
		stateArray.push("<" + node.NodeType + " v=\"");		
		stateArray.push(node.Id + "^" + (node.IsChecked() ? "1" : "0") + "^" + (node.IsExpanded() ? "1\" >" : "0\" >"));
	}
	else
		close = false;

	var children = node.Children;
	if (children != null)
	{
		for (var i=0;i<children.length;i++)
			SetNodeState(children[i],stateArray);
	}
	if (close)
		stateArray.push("</" + node.NodeType + ">");
}
function HandleApplyLyrMgr(imageUrls)
{   	
	try{hideLoading();}catch(e){};
	SetMapImages(imageUrls);
}
function RefreshLayerManager(xmlDoc)
{
	
	if (xmlDoc != null)
	{
		var nodeList = xmlDoc.getElementsByTagName("LyrMgr"); 
		if (nodeList != null && nodeList.length > 0)
		{     
			var tree = _FindTree(m_lyrMgrTree);
			var expNodes = null;			
			if (tree != null)
			{
				expNodes = tree.GetExpandedNodes();				
			}
	        
			if (m_ie5)
				_loadTree(nodeList[0].text,m_lyrMgrTree,m_lytMgrContainer);
			else
				_loadTree(nodeList[0].textContent,m_lyrMgrTree,m_lytMgrContainer);
	        
			tree = _FindTree(m_lyrMgrTree); //get new tree
			if (tree != null)
			{
				tree.RegisterDragDrop(HandleDragDrop);			
				if (expNodes != null)
				{
					for (var i=0;i<expNodes.length;i++)
						tree.ExpandNode(expNodes[i]);
				}
			}
		}
	}
}
function RedrawLayerManager(tree)
{   
	
	var expNodes = tree.GetExpandedNodes();	
	var container = document.getElementById(m_lytMgrContainer);
	if (container)
	{
		container.innerHTML = tree.GetHtml();
		tree.SetInitialExpand();	
		for (var i=0;i<expNodes.length;i++)
		{
			tree.ExpandNode(expNodes[i]);
		}
		//reset active node
		var ae=tree.GetActiveElement();
		if (ae != null)
			tree.SetActiveNode(ae.id,tree.GetStyles().Active);
	}
}
function HandleLayerEnvelope(response)
{
    if(response!=null && response.length > 0 && window.RefreshVEandOnPointMap)
    {
        RefreshVEandOnPointMap(response);
    }
}
function ZoomToLayer()
{
	_InvokeMethod('PageMethods.ZoomToLayer(mapId,lyrId,styles.Regular,styles.Active,styles.Greyed,styles.Group,styles.RootLevel,HandleServerResponse);', 0);
}
function ZoomToLyrScale()
{
	_InvokeMethod('PageMethods.ZoomToLayerScale(mapId,lyrId,styles.Regular,styles.Active,styles.Greyed,styles.Group,styles.RootLevel,HandleServerResponse);', 1);	
}
function _InvokeMethod(method, methodType)
{
	if(!sessionExpired)
	{    
		if (PageMethods && PageMethods.ZoomToLayerScale)
		{	
			var tree = _FindTree(m_lyrMgrTree);
			if (tree != null && tree.GetLastCtxNode() != null)
			{        
				var lyrId = tree.GetLastCtxNode().Id;
				if (lyrId != null)
				{
					var styles = tree.GetStyles();
					var idx = lyrId.indexOf(":");
					var mapIdx = lyrId.substr(0,idx);
					var mapId = tree.GetNode(mapIdx).Id;
					lyrId = lyrId.substr(idx+1);
                    
                    if(window.displayMapOverlay)
                    {
                        if(methodType==1)
	                        PageMethods.GetLayerVisibleEnvelope(mapId, lyrId, HandleLayerEnvelope);   
	                    else
	                        PageMethods.GetLayerEnvelope(mapId, lyrId, HandleLayerEnvelope);   
	                }
	                else
	                {
					    eval(method);
					}
				}
			}
		}
	}
	else    
		HandleSessionExpired();
}
function SetActiveLayer()
{
	if(!sessionExpired)
	{    
		if (PageMethods && PageMethods.SetActiveLayer)
		{
			try
			{
				var tree = _FindTree(m_lyrMgrTree);
				if (tree != null && tree.GetLastCtxNode() != null)
				{   
					var lyrId = tree.GetLastCtxNode().Id;
					lyrId = lyrId.substr(lyrId.indexOf(":")+1);
					PageMethods.SetActiveLayer(lyrId,HandleSetActiveLayer);
				}
			}            
			catch (e){alert('ExceptionHandler::SetActiveLayer' + e.message);}
		}
	}
	else    
		HandleSessionExpired();
}
function HandleSetActiveLayer(success)
{
	if (success)
	{
		var tree = _FindTree(m_lyrMgrTree);		
		if (tree != null && tree.GetLastCtxNode() != null)
			tree.SetActiveNode(tree.GetLastCtxNode().Id,tree.GetStyles().Active);
	}
}
function ExpandLegends()
{
	var tree = _FindTree(m_lyrMgrTree);
	if (tree != null && tree.GetLastCtxNode() != null)
		tree.GetLastCtxNode().ExpandAll();
}
function CollapseLegends()
{
	var tree = _FindTree(m_lyrMgrTree);
	if (tree != null && tree.GetLastCtxNode() != null)	
		_CollapseIfLegend(tree.GetLastCtxNode());	
}
function _CollapseIfLegend(node)
{
	var childCount = node.GetChildCount();
	if (childCount == 1 && node.GetChild(0).NodeType == "LG")	
		node.Collapse();
	else if(childCount > 0)
	{
		for (var i=0;i<childCount;i++)
			_CollapseIfLegend(node.GetChild(i));
	}
}
function CheckAllLayers(checked)
{
	var tree = _FindTree(m_lyrMgrTree);
	if (tree != null && tree.GetLastCtxNode() != null)
		tree.GetLastCtxNode().CheckNode(checked,true);
	btnApplyLyrMgr();
}
function _MoveCtxMenus()
{   
	var node = document.getElementById('cmLayer');
	if (node != null)
		document.body.appendChild(node);
	node = document.getElementById('cmLayerTheme');
	if (node != null)
		document.body.appendChild(node);
	node = document.getElementById('cmMap');
	if (node != null)
		document.body.appendChild(node);    
    node = document.getElementById('cmLayerThematicSelections');
	if (node != null)
		document.body.appendChild(node);    
}
function don(){return;}
function InitializeLyrMgr(mapSourceId)
{	
	
	//register drag-drop
	var tree = _FindTree(m_lyrMgrTree);
	tree.RegisterDragDrop(HandleDragDrop);
	var styles = tree.GetStyles();	
	m_lyrNodeStyle = styles.Regular;
	m_activeNodeStyle = styles.Active;
	m_greyedNodeStyle = styles.Greyed;
	m_groupNodeStyle = styles.Group;
	m_mapNodeStyle = styles.RootLevel;
	//Hide Apply if no layers in tree
	var count=0;
	for (var i=0;i<tree.GetNodeCount();i++)
	{
		count += tree.GetNode(i).GetChildCount();
	}	
	var applyBtn = document.getElementById(m_btnApply);
	if (applyBtn)
		applyBtn.style.display = (count > 0) ? "block" : "none";
	
	if (mapSourceId != null)
		m_mapSourceId = mapSourceId;

    // Load the theme menus for the map tab
    if (count > 0)
	    LoadThemeMenus();
}

function VerifyLyrMgr(mapSourceId)
{
	if (m_mapSourceId != mapSourceId)
	{
		try
		{
			var styles = _FindTree(m_lyrMgrTree).GetStyles();
			PageMethods.GetLayerManagerTree(styles.Regular,styles.Active,styles.Greyed,styles.Group,styles.RootLevel,HandleLyrMgrUpdate);
			//Update new mapsourceId
			m_mapSourceId = mapSourceId;
		}
		catch(e){}
	}
}

function HandleLyrMgrUpdate(updateScript)
{
	try
	{
		eval(updateScript);
	}
	catch(e){}
}
function HandleDragDrop(tree, draggedNode, droppedNode)
{	
	//checks to see if node is movable
	//check 1: soure and target cannot be same.
	if (draggedNode != null && droppedNode != null &&
		draggedNode.Id != droppedNode.Id)
	{	
		var draggedId = draggedNode.Id;
		var droppedId = droppedNode.Id;
		
		//check 2: both nodes should be from same map. Hence, there ids should have same index
		var m1 = draggedId.substring(0, draggedId.indexOf(":"));
		var m2 = droppedId.substring(0, droppedId.indexOf(":"));
		if (m1 == m2)
		{			
			//check 3: a group layer may not become child of group.						
			if (draggedNode.NodeType == "G")
			{
				var parentNode = tree.GetParentNode(droppedNode.Id);
				if (parentNode != null && parentNode.NodeType == "G")
					return;//cannot drop group within another group.
			}
			//SME- Added for Thematic Selections
			else if (draggedNode.NodeType == "TH")
			{			
			    //Check 4: If the draggedNode is thematic Selections then it can be dropped 
			    //within the layer (where the current thematic selections belong) 
		        var draggedNodeLayerId = getLayerId(draggedId);
		        var droppedNodeLayerId = getLayerId(droppedId);
		        if(draggedNodeLayerId == null || droppedNodeLayerId == null ||
		            draggedNodeLayerId != droppedNodeLayerId)
		            return; //cannot drop thematic selection on to another layer
			    if (droppedNode.NodeType == "L")
			        return;
			}
			tree.UpdateChecked();			
			if (tree.MoveNode(draggedId, droppedId))
			{
				RedrawLayerManager(tree);				
			}
		}
	}
}


function getLayerId(nodeId)
{
    var layerId = null;
    //nodeId= mapIndex:layerId:thematicSelectionid
    if(nodeId != null)
    {
        var arrIds =  nodeId.split(":");
        if(arrIds != null && arrIds.length >= 2)
        {
            layerId = arrIds[1];
        }
    }
    return layerId;
}

function RemoveThematicSelection()
{
    if(!sessionExpired)
	{    
		if (PageMethods && PageMethods.RemoveThematicSelection)
		{
			try
			{
				var tree = _FindTree(m_lyrMgrTree);
				if (tree != null && tree.GetLastCtxNode() != null)
				{   
					var lyrId = tree.GetLastCtxNode().Id;
					var selectionId ;
					var arr = lyrId.split(":");					
					if(arr != null && arr.length == 3)
					{
					    lyrId = arr[1];
					    selectionId = arr[2];
					}					
					PageMethods.RemoveThematicSelection(lyrId, selectionId, HandleRemoveThematicSelection);
				}
			}
			catch (e){alert('ExceptionHandler::RemoveThematicSelection' + e.message);}
		}
	}
	else    
		HandleSessionExpired();
}

function HandleRemoveThematicSelection(success)
{
    if (success && window.UpdatePanel)
	{
		//Update global panels
		if(window.RefreshMap)
		{
		    RefreshMap();
		}
	}
}

function GetContextLayerId()
{
	var tree = _FindTree(m_lyrMgrTree);
	var lyrId = null;
	if (tree != null && tree.GetLastCtxNode() != null)
	{   
		lyrId = tree.GetLastCtxNode().Id;
		lyrId = lyrId.substr(lyrId.indexOf(":")+1);
    }
    return lyrId;
}

function ClearTheme()
{
	if(!sessionExpired)
	{
		if (PageMethods && PageMethods.ClearTheme)
		{
			try
			{
				var layerId = GetContextLayerId();
			    if ( layerId != null )
			    {
			        showLoading();
                    PageMethods.ClearTheme(layerId, HandleClearTheme);
                }
			}
			catch (e)
			{
			    alert('ExceptionHandler::ClearTheme ' + e.message);
			    hideLoading();
			}
		}
	}
	else
	{
		HandleSessionExpired();
    }
}

function HandleClearTheme( errorMessage )
{
    if ( errorMessage == null )
    {
        if(window.RefreshMap)
		{
		    RefreshMap();
		}
    }
	else
	{
	    alert( errorMessage );
	    hideLoading();
	}
}

function ApplyTheme(themeId)
{
	if(!sessionExpired)
	{
		if (PageMethods && PageMethods.ApplyTheme)
		{
			try
			{
			    showLoading();
                PageMethods.ApplyTheme(themeId, HandleApplyTheme);
			}
			catch (e)
			{
			    alert('ExceptionHandler::ApplyTheme ' + e.message);
			    hideLoading();
			}
		}
	}
	else
	{
		HandleSessionExpired();
    }
}

function HandleApplyTheme( errorMessage )
{
    if ( errorMessage == null )
    {
        if(window.RefreshMap)
		{
		    RefreshMap();
		}
    }
	else
	{
	    alert( errorMessage );
	    hideLoading();
	}
}

function NewTheme()
{
	if(!sessionExpired)
	{
		if (PageMethods && PageMethods.SetThematicMappingLayer)
		{
			try
			{
			    var layerId = GetContextLayerId();
			    if ( layerId != null )
			    {
                    PageMethods.SetThematicMappingLayer(layerId, true, HandleNewTheme);
                }
			}
			catch (e){alert('ExceptionHandler::NewTheme ' + e.message);}
		}
	}
	else
	{
		HandleSessionExpired();
    }
}

function HandleNewTheme( errorMessage )
{
    if ( errorMessage == null )
    {
        window.HandleThemeFrame(NGServerUrl()+'/WebPages/ThematicMap/ThematicMapPage.aspx');
    }
	else
	{
	    alert( errorMessage );
	}
}

function ManageTheme()
{
	if(!sessionExpired)
	{
		if (PageMethods && PageMethods.SetThematicMappingLayer)
		{
			try
			{
			    var layerId = GetContextLayerId();
			    if ( layerId != null )
			    {
                    PageMethods.SetThematicMappingLayer(layerId, false, HandleManageTheme);
                }
			}
			catch (e){alert('ExceptionHandler::ManageTheme ' + e.message);}
		}
	}
	else
	{
		HandleSessionExpired();
    }
}

function HandleManageTheme( errorMessage )
{
	if ( errorMessage == null )
	{
        window.HandleManageThemeFrame(NGServerUrl()+'/WebPages/ThematicMap/ManageThemes.aspx');
	}
	else
	{
	    alert( errorMessage );
	}
}

function LoadThemeMenu(layerId)
{
    if(!sessionExpired)
	{
		if (PageMethods && PageMethods.GetThemeMenu)
		{
			try
			{
			    PageMethods.GetThemeMenu(layerId,HandleLoadThemeMenu);
			}
			catch (e){alert('ExceptionHandler::LoadThemeMenu ' + e.message);}
		}
	}
	else
	{
		HandleSessionExpired();
    }
}

function LoadThemeMenus()
{
    if(!sessionExpired)
	{
		if (PageMethods && PageMethods.GetThemeMenus)
		{
			try
			{
			    PageMethods.GetThemeMenus(HandleLoadThemeMenu);
			}
			catch (e){alert('ExceptionHandler::LoadThemeMenus ' + e.message);}
		}
	}
	else
	{
		HandleSessionExpired();
    }
}

function HandleLoadThemeMenu(themeMenuData)
{
    if (themeMenuData != null)
    {
        LoadMenu(themeMenuData);
    }
}


function SetThematic(){return;}

function GetThematicItems()
{
    //Make an AJAX call to server to get data for thematic child items for this layer.
    //layer in context can be retrieved from tree.GetLastCtxNode() method.
    
    childItemsData = 1
    
    return childItemsData;
}

function FillThematicContainer( layerId, tableClass, itemTableClass, linkClass, tableHoverClass, linkHoverClass )
{
    //Set thematic context menu div based on the theme menu for the datausing the passed data.
    
    var themeMenu = FindMenu( 'Theme', layerId );
    var themeMenuHtml = '';
    if ( themeMenu != null )
    {
        themeMenuHtml = themeMenu.GetHtml( tableClass, itemTableClass, linkClass, tableHoverClass, linkHoverClass );
    }
    
    document.getElementById('cmThematic').innerHTML = themeMenuHtml;

}

function ClearThematicContainer()
{
    document.getElementById('cmThematic').innerHTML = '';
}

function CustomMenuHover(item) 
{
    var node = Menu_HoverRoot(item);
    var data = Menu_GetData(item);
    if (!data)
        return;
    __disappearAfter = data.disappearAfter;
    //Hook when menu item is for thematic layer                
    if (node.href == "javascript:SetThematic()")
    {
        var menuCreated = false;
        
		try
		{
		    // Get the id of the layer that was clicked
		    
			var layerId = GetContextLayerId();
		    if ( layerId != null )
		    {
		        // Get the css classes for table, item table and link from the menu's controls
    		    
		        var menuTable = Menu_FindParentContainer(item);
		        var tableClass = menuTable.className;
    		    
    		    // Use previous node to get link so don't have the css class for hovering
    		    var previousNode = Menu_FindPrevious( item );
    		    //                   <td>       <tr>       <tbody>    <table>
    		    var itemTable = previousNode.parentNode.parentNode.parentNode.parentNode;
    		    var itemTableClass = itemTable.className;
    		    
		        var itemLink = Menu_FindNext( item );
		        var linkClass = itemLink.className;
		        var tableHoverClass = data.staticHoverClass;
		        var linkHoverClass = data.staticHoverHyperLinkClass;
		    
                // Populate the theme menu for the layer
                                
                FillThematicContainer( layerId, tableClass, itemTableClass, linkClass, tableHoverClass, linkHoverClass );
                menuCreated = true;
            }
		}
		catch (e){alert('ExceptionHandler::CustomMenuHover ' + e.message);}
		
		// If theme menu was not created, clear the thematic container to ensure old menu is not shown
		if ( !menuCreated )
		{
		    ClearThematicContainer();
		}
    }
    Menu_Expand(node, data.horizontalOffset, data.verticalOffset); 
}
