protected void treeElem_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        e.Node.ChildNodes.Clear();
        e.Node.PopulateOnDemand = false;

        int nodeId = ValidationHelper.GetInteger(e.Node.Value, 0);

        // Get the document
        TreeNode node = TreeProvider.SelectSingleNode(nodeId);

        // Check explore tree permission for current node
        bool userHasExploreTreePermission = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed);

        if (userHasExploreTreePermission)
        {
            SiteMapNodeCollection childNodes = MapProvider.GetChildNodes(nodeId);
            int index = 0;
            foreach (TreeSiteMapNode childNode in childNodes)
            {
                int childNodeId = (int)childNode.NodeData["NodeID"];
                if (childNodeId != nodeId)
                {
                    System.Web.UI.WebControls.TreeNode newNode = CreateNode(childNode, index, true);
                    e.Node.ChildNodes.Add(newNode);
                    index++;
                }
            }
        }
        else
        {
            // Add 'access denied node'
            System.Web.UI.WebControls.TreeNode tempNode = new System.Web.UI.WebControls.TreeNode();
            tempNode.Text        = GetString("ContentTree.ExploreChildsDenied");
            tempNode.NavigateUrl = (DeniedNodePostback ? mBasePath + "#" : "");
            e.Node.ChildNodes.Add(tempNode);
        }
    }
    /// <summary>
    /// Used for maxnodes in collapsed node.
    /// </summary>
    /// <param name="itemData">The item data</param>
    /// <param name="defaultNode">The default node</param>
    protected System.Web.UI.WebControls.TreeNode treeElem_OnNodeCreated(DataRow itemData, System.Web.UI.WebControls.TreeNode defaultNode)
    {
        if (UseMaxNodeLimit)
        {
            // Get parentID from data row
            int    parentID   = ValidationHelper.GetInteger(itemData["ParentID"], 0);
            string objectType = ValidationHelper.GetString(itemData["ObjectType"], String.Empty);

            // Don't use maxnodes limitation for categories
            if (objectType.ToLower() == "pagetemplatecategory")
            {
                return(defaultNode);
            }

            // Increment index count in collapsing
            indexMaxTreeNodes++;
            if (indexMaxTreeNodes == MaxTreeNodes)
            {
                // Load parentid
                int parentParentID = 0;
                PageTemplateCategoryInfo parentParent = PageTemplateCategoryInfoProvider.GetPageTemplateCategoryInfo(parentID);
                if (parentParent != null)
                {
                    parentParentID = parentParent.ParentId;
                }

                System.Web.UI.WebControls.TreeNode node = new System.Web.UI.WebControls.TreeNode();
                node.Text = "<span class=\"ContentTreeItem\" onclick=\"SelectNode(" + parentID + " ,'pagetemplatecategory'," + parentParentID + ",true ); return false;\"><span class=\"Name\" style=\"font-style: italic;\">" + GetString("general.seelisting") + "</span></span>";
                return(node);
            }
            if (indexMaxTreeNodes > MaxTreeNodes)
            {
                return(null);
            }
        }
        return(defaultNode);
    }
    protected void treeElem_TreeNodePopulate(object sender, TreeNodeEventArgs e)
    {
        e.Node.ChildNodes.Clear();
        e.Node.PopulateOnDemand = false;

        int nodeId = ValidationHelper.GetInteger(e.Node.Value, 0);

        // Get the document
        TreeNode node = TreeProvider.SelectSingleNode(nodeId);

        // Check explore tree permission for current node
        bool userHasExploreTreePermission = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ExploreTree) == AuthorizationResultEnum.Allowed);
        if (userHasExploreTreePermission)
        {
            SiteMapNodeCollection childNodes = MapProvider.GetChildNodes(nodeId);
            int index = 0;
            foreach (TreeSiteMapNode childNode in childNodes)
            {
                int childNodeId = (int)childNode.NodeData["NodeID"];
                if (childNodeId != nodeId)
                {
                    System.Web.UI.WebControls.TreeNode newNode = CreateNode(childNode, index, true);
                    e.Node.ChildNodes.Add(newNode);
                    index++;
                }
            }
        }
        else
        {
            // Add 'access denied node'
            System.Web.UI.WebControls.TreeNode tempNode = new System.Web.UI.WebControls.TreeNode();
            tempNode.Text = GetString("ContentTree.ExploreChildsDenied");
            tempNode.NavigateUrl = (DeniedNodePostback ? mBasePath + "#" : "");
            e.Node.ChildNodes.Add(tempNode);
        }
    }
    /// <summary>
    /// Creates the tree node.
    /// </summary>
    /// <param name="sourceNode">Source node</param>
    /// <param name="index">Node index</param>
    /// <param name="childNode">True if the node is child node</param>
    protected System.Web.UI.WebControls.TreeNode CreateNode(TreeSiteMapNode sourceNode, int index, bool childNode)
    {
        System.Web.UI.WebControls.TreeNode newNode = new System.Web.UI.WebControls.TreeNode();
        ISimpleDataContainer container = sourceNode;

        int sourceNodeId = (int)container.GetValue("NodeID");
        int nodeLevel = (int)container.GetValue("NodeLevel");

        if (sourceNodeId < 0)
        {
            newNode.SelectAction = TreeNodeSelectAction.None;
            newNode.Text = GetString("ContentTree.ReadDocumentDenied");
            newNode.NavigateUrl = (DeniedNodePostback ? mBasePath + "#" : "");
            return newNode;
        }

        if ((index < MaxTreeNodes) || (nodeLevel <= MapProvider.RootNodeLevel + 1))
        {
            allNodes[sourceNodeId] = newNode;

            // Set the base data
            newNode.Value = sourceNodeId.ToString();
            newNode.NavigateUrl = "javascript:void(0);";

            int classId = ValidationHelper.GetInteger(container.GetValue("NodeClassID"), 0);
            DataClassInfo ci = DataClassInfoProvider.GetDataClass(classId);
            if (ci == null)
            {
                throw new Exception("[ContentTree.CreateNode]: Node class not found.");
            }

            string className = ci.ClassName.ToLower(SqlHelperClass.EnglishCulture);
            string imageUrl = string.Empty;
            string tooltip = string.Empty;

            // Use file type icons for cms.file
            if (UseCMSFileIcons && (className == "cms.file"))
            {
                string extension = ValidationHelper.GetString(container.GetValue("DocumentType"), "");
                imageUrl = GetFileIconUrl(extension, CMSFileIconSet);
                tooltip = " title=\"" + extension.ToLower().TrimStart('.') + "\" ";
            }
            // Use class icons
            else
            {
                imageUrl = ResolveUrl(GetDocumentTypeIconUrl(className));
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<img src=\"", imageUrl, "\" alt=\"\" style=\"border:0px;vertical-align:middle;\" onclick=\"return false;\"", tooltip, " class=\"", (className == "cms.root" ? "Image20" : "Image16"), "\" />");
            string imageTag = sb.ToString();

            string nodeName = HttpUtility.HtmlEncode(ValidationHelper.GetString(container.GetValue("DocumentName"), ""));
            string nodeNameJava = ScriptHelper.GetString(nodeName);

            // Render special marks only if allowed
            if (AllowMarks)
            {
                string siteName = SiteName;
                int workflowStepId = ValidationHelper.GetInteger(container.GetValue("DocumentWorkflowStepID"), 0);
                string stepName = null;

                if (workflowStepId > 0)
                {
                    WorkflowStepInfo stepInfo = WorkflowStepInfoProvider.GetWorkflowStepInfo(workflowStepId);
                    if (stepInfo != null)
                    {
                        stepName = stepInfo.StepName;
                    }
                }

                // Add icons
                nodeName += UIHelper.GetDocumentMarks(Page, SiteName, PreferredCulture, stepName, sourceNode);
            }

            // Prepare the node text
            if ((NodeID > 0) && (sourceNodeId == NodeID))
            {
                newNode.Text = SelectedNodeTextTemplate.Replace("##NODEID##", sourceNodeId.ToString()).Replace("##NODENAMEJAVA##", nodeNameJava).Replace("##NODENAME##", nodeName).Replace("##ICON##", imageTag); //.DocumentName
                selectedRendered = true;
            }
            else
            {
                newNode.Text = NodeTextTemplate.Replace("##NODEID##", sourceNodeId.ToString()).Replace("##NODENAMEJAVA##", nodeNameJava).Replace("##NODENAME##", nodeName).Replace("##ICON##", imageTag); //.DocumentName
            }
            int childNodesCount = ValidationHelper.GetInteger(container.GetValue("NodeChildNodesCount"), 0);
            newNode.Text = newNode.Text.Replace("##NODECHILDNODESCOUNT##", childNodesCount.ToString());

            // Drag and drop envelope
            if (AllowDragAndDrop)
            {
                sb.Length = 0;

                if (childNode)
                {
                    sb.Append("<span id=\"target_", sourceNodeId, "\"><span class=\"DDItem\" id=\"node_", sourceNodeId, "\"><span class=\"DDHandle\" id=\"handle_", sourceNodeId, "\" onmousedown=\"return false;\" onclick=\"return false;\">", newNode.Text, "</span></span></span>");
                }
                else
                {
                    sb.Append("<span id=\"target_", sourceNodeId, "\" class=\"RootNode\"><span class=\"DDItem\" id=\"node_", sourceNodeId, "\">", newNode.Text, "</span></span>");
                }

                newNode.Text = sb.ToString();
            }

            // Check if can expand
            if (childNodesCount == 0)
            {
                newNode.PopulateOnDemand = false;
                newNode.Expanded = true;
            }
            else
            {
                if ((sourceNode.ChildNodes.Count > 0) || !sourceNode.ChildNodesLoaded)
                {
                    newNode.PopulateOnDemand = true;
                }
            }

            // Set expanded status
            string aliasPath = ValidationHelper.GetString(container.GetValue("NodeAliasPath"), "");
            if ((aliasPath.ToLower() != MapProvider.UsedPath.ToLower()) && (!expandNodes.Contains(sourceNodeId)))
            {
                newNode.Expanded = false;
            }
            else
            {
                newNode.Expanded = true;
            }
        }
        else
        {
            string parentNodeId = ValidationHelper.GetString(container.GetValue("NodeParentID"), "");
            newNode.Value = sourceNodeId.ToString();
            newNode.Text = MaxTreeNodeText.Replace("##PARENTNODEID##", parentNodeId);
            newNode.NavigateUrl = "#";
        }

        return newNode;
    }
    /// <summary>
    /// Creates the tree node.
    /// </summary>
    /// <param name="sourceNode">Source node</param>
    /// <param name="index">Node index</param>
    /// <param name="childNode">True if the node is child node</param>
    protected System.Web.UI.WebControls.TreeNode CreateNode(TreeSiteMapNode sourceNode, int index, bool childNode)
    {
        System.Web.UI.WebControls.TreeNode newNode = new System.Web.UI.WebControls.TreeNode();
        ISimpleDataContainer container             = sourceNode;

        int sourceNodeId = (int)container.GetValue("NodeID");
        int nodeLevel    = (int)container.GetValue("NodeLevel");

        if (sourceNodeId < 0)
        {
            newNode.SelectAction = TreeNodeSelectAction.None;
            newNode.Text         = GetString("ContentTree.ReadDocumentDenied");
            newNode.NavigateUrl  = (DeniedNodePostback ? mBasePath + "#" : "");
            return(newNode);
        }

        if ((index < MaxTreeNodes) || (nodeLevel <= MapProvider.RootNodeLevel + 1))
        {
            allNodes[sourceNodeId] = newNode;

            // Set the base data
            newNode.Value       = sourceNodeId.ToString();
            newNode.NavigateUrl = "javascript:void(0);";

            int           classId = ValidationHelper.GetInteger(container.GetValue("NodeClassID"), 0);
            DataClassInfo ci      = DataClassInfoProvider.GetDataClass(classId);
            if (ci == null)
            {
                throw new Exception("[ContentTree.CreateNode]: Node class not found.");
            }

            string className = ci.ClassName.ToLower(SqlHelperClass.EnglishCulture);
            string imageUrl  = string.Empty;
            string tooltip   = string.Empty;

            // Use file type icons for cms.file
            if (UseCMSFileIcons && (className == "cms.file"))
            {
                string extension = ValidationHelper.GetString(container.GetValue("DocumentType"), "");
                imageUrl = GetFileIconUrl(extension, CMSFileIconSet);
                tooltip  = " title=\"" + extension.ToLower().TrimStart('.') + "\" ";
            }
            // Use class icons
            else
            {
                imageUrl = ResolveUrl(GetDocumentTypeIconUrl(className));
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("<img src=\"", imageUrl, "\" alt=\"\" style=\"border:0px;vertical-align:middle;\" onclick=\"return false;\"", tooltip, " class=\"", (className == "cms.root" ? "Image20" : "Image16"), "\" />");
            string imageTag = sb.ToString();

            string nodeName     = HttpUtility.HtmlEncode(ValidationHelper.GetString(container.GetValue("DocumentName"), ""));
            string nodeNameJava = ScriptHelper.GetString(nodeName);

            // Render special marks only if allowed
            if (AllowMarks)
            {
                string siteName       = SiteName;
                int    workflowStepId = ValidationHelper.GetInteger(container.GetValue("DocumentWorkflowStepID"), 0);
                string stepName       = null;

                if (workflowStepId > 0)
                {
                    WorkflowStepInfo stepInfo = WorkflowStepInfoProvider.GetWorkflowStepInfo(workflowStepId);
                    if (stepInfo != null)
                    {
                        stepName = stepInfo.StepName;
                    }
                }

                // Add icons
                nodeName += UIHelper.GetDocumentMarks(Page, SiteName, PreferredCulture, stepName, sourceNode);
            }

            // Prepare the node text
            if ((NodeID > 0) && (sourceNodeId == NodeID))
            {
                newNode.Text     = SelectedNodeTextTemplate.Replace("##NODEID##", sourceNodeId.ToString()).Replace("##NODENAMEJAVA##", nodeNameJava).Replace("##NODENAME##", nodeName).Replace("##ICON##", imageTag); //.DocumentName
                selectedRendered = true;
            }
            else
            {
                newNode.Text = NodeTextTemplate.Replace("##NODEID##", sourceNodeId.ToString()).Replace("##NODENAMEJAVA##", nodeNameJava).Replace("##NODENAME##", nodeName).Replace("##ICON##", imageTag); //.DocumentName
            }
            int childNodesCount = ValidationHelper.GetInteger(container.GetValue("NodeChildNodesCount"), 0);
            newNode.Text = newNode.Text.Replace("##NODECHILDNODESCOUNT##", childNodesCount.ToString());

            // Drag and drop envelope
            if (AllowDragAndDrop)
            {
                sb.Length = 0;

                if (childNode)
                {
                    sb.Append("<span id=\"target_", sourceNodeId, "\"><span class=\"DDItem\" id=\"node_", sourceNodeId, "\"><span class=\"DDHandle\" id=\"handle_", sourceNodeId, "\" onmousedown=\"return false;\" onclick=\"return false;\">", newNode.Text, "</span></span></span>");
                }
                else
                {
                    sb.Append("<span id=\"target_", sourceNodeId, "\" class=\"RootNode\"><span class=\"DDItem\" id=\"node_", sourceNodeId, "\">", newNode.Text, "</span></span>");
                }

                newNode.Text = sb.ToString();
            }

            // Check if can expand
            if (childNodesCount == 0)
            {
                newNode.PopulateOnDemand = false;
                newNode.Expanded         = true;
            }
            else
            {
                if ((sourceNode.ChildNodes.Count > 0) || !sourceNode.ChildNodesLoaded)
                {
                    newNode.PopulateOnDemand = true;
                }
            }

            // Set expanded status
            string aliasPath = ValidationHelper.GetString(container.GetValue("NodeAliasPath"), "");
            if ((aliasPath.ToLower() != MapProvider.UsedPath.ToLower()) && (!expandNodes.Contains(sourceNodeId)))
            {
                newNode.Expanded = false;
            }
            else
            {
                newNode.Expanded = true;
            }
        }
        else
        {
            string parentNodeId = ValidationHelper.GetString(container.GetValue("NodeParentID"), "");
            newNode.Value       = sourceNodeId.ToString();
            newNode.Text        = MaxTreeNodeText.Replace("##PARENTNODEID##", parentNodeId);
            newNode.NavigateUrl = "#";
        }

        return(newNode);
    }
    /// <summary>
    /// Ensures the given node within the tree.
    /// </summary>
    /// <param name="node">Node to ensure</param>
    /// <param name="nodeId">Ensure by NodeID</param>
    protected void EnsureNode(TreeNode node, int nodeId)
    {
        if (node == null)
        {
            // If not already exists, do not add
            if (allNodes[nodeId] != null)
            {
                return;
            }
            else
            {
                // Get the node
                node = TreeProvider.SelectSingleNode(nodeId, TreeProvider.ALL_CULTURES, true);

                if (!SelectPublishedData)
                {
                    node = DocumentHelper.GetDocument(node, TreeProvider);
                }
            }
        }
        else
        {
            nodeId = node.NodeID;
        }

        if (node != null)
        {
            // Get the correct parent node
            System.Web.UI.WebControls.TreeNode parentNode = (System.Web.UI.WebControls.TreeNode)allNodes[node.NodeParentID];
            if (parentNode != null)
            {
                // Expand the parent
                parentNode.Expanded = true;

                // If still not present, add the node
                if (allNodes[nodeId] == null)
                {
                    TreeSiteMapNode sourceNode = new TreeSiteMapNode(MapProvider, nodeId.ToString());
                    sourceNode.TreeNode = node;

                    System.Web.UI.WebControls.TreeNode newNode = CreateNode(sourceNode, 0, true);

                    parentNode.ChildNodes.Add(newNode);
                }
            }
            else
            {
                // Get the correct node and add it to list of processed nodes
                TreeSiteMapNode targetNode = MapProvider.GetNodeByAliasPath(node.NodeAliasPath);

                if (targetNode != null)
                {
                    ArrayList procNodes = new ArrayList();
                    procNodes.Add(targetNode.NodeData["NodeID"]);

                    if (targetNode.ParentNode != null)
                    {
                        // Repeat until existing parent node in allNodes is found
                        do
                        {
                            int targetParentNodeId = (int)((TreeSiteMapNode)targetNode.ParentNode).NodeData["NodeID"];
                            procNodes.Add(targetParentNodeId);
                            targetNode = (TreeSiteMapNode)targetNode.ParentNode;
                        } while ((targetNode.ParentNode != null) && (allNodes[(int)(((TreeSiteMapNode)(targetNode.ParentNode)).NodeData["NodeID"])] == null));
                    }

                    // Process nodes in reverse order
                    procNodes.Reverse();
                    foreach (int nodeID in procNodes)
                    {
                        EnsureNode(null, nodeID);
                    }
                }
            }
        }

        return;
    }
    /// <summary>
    /// Used for maxnodes in collapsed node.
    /// </summary>
    /// <param name="itemData">The item data</param>
    /// <param name="defaultNode">The default node</param>
    protected System.Web.UI.WebControls.TreeNode treeElem_OnNodeCreated(DataRow itemData, System.Web.UI.WebControls.TreeNode defaultNode)
    {
        if (UseMaxNodeLimit)
        {
            // Get parentID from data row
            int parentID = ValidationHelper.GetInteger(itemData["ParentID"], 0);
            string objectType = ValidationHelper.GetString(itemData["ObjectType"], String.Empty);

            // Don't use maxnodes limitation for categories
            if (objectType.ToLower() == "pagetemplatecategory")
            {
                return defaultNode;
            }

            // Increment index count in collapsing
            indexMaxTreeNodes++;
            if (indexMaxTreeNodes == MaxTreeNodes)
            {
                // Load parentid
                int parentParentID = 0;
                PageTemplateCategoryInfo parentParent = PageTemplateCategoryInfoProvider.GetPageTemplateCategoryInfo(parentID);
                if (parentParent != null)
                {
                    parentParentID = parentParent.ParentId;
                }

                System.Web.UI.WebControls.TreeNode node = new System.Web.UI.WebControls.TreeNode();
                node.Text = "<span class=\"ContentTreeItem\" onclick=\"SelectNode(" + parentID + " ,'pagetemplatecategory'," + parentParentID + ",true ); return false;\"><span class=\"Name\" style=\"font-style: italic;\">" + GetString("general.seelisting") + "</span></span>";
                return node;
            }
            if (indexMaxTreeNodes > MaxTreeNodes)
            {
                return null;
            }
        }
        return defaultNode;
    }