var wb=null;		      // Main workbench object
var edApplet = null;    // Engg Data applet object
var eds = null;         // Engg Data script engine
var eda = null;         // Engg Data namespace object (main.js)

var ProjectFormLoadedInterval = 0;
var hideZeroSizeFolders = true;

var doc=null;			// Current Document

var ActiveView = null;

var ProjectTree = null;
var ObjectBranch = null;
//var ObjectBranch = null;
//var ConvectionBranch = null;
//var SectionBranch = null;

var LibraryTree = null;

function EDCategoryScope ()
{
    var edaMaterialPage = null;
}

window.onunload = function window_onunload()
{
    eda.ActiveViewTree.Nodes.Clear();
    edApplet = null;
    eds = null;
    eda = null;
    ProjectTree = null;
    ObjectBranch = null;
    //ConvectionBranch = null;
    //SectionBranch = null;
    ActiveView = null;
    LibraryTree = null;
}

window.onload=function window_onload()
{
    // Go get the WB, Engg Data Applet; Script; and namespace
    wb =  window.external;
    edApplet =  wb.AppletList.Applet( "EDApplet").App;
    eds = edApplet.Script;
    eda = eds.eda;

	var SystemInfo = eds.CreateActiveXObject(eds.GenWBProgId("WBUtils.SystemInfo"));
	var platform = SystemInfo.OSType;
	if(platform == "UNIX")
	{
	   str_PathSeparator						= "/";
	}
	else
	{
	   str_PathSeparator						= "\\";
	}
 

    //
    //  ======================================================================================================================
    //  = CREATE THE APPLICATION SCOPE
    //  ======================================================================================================================
    if (edApplet.Mode == 1)	//project mode
    {
        ProjectRow.style.display = "block";
        LibRow.style.display = "none";
    }
    else
    {
        ProjectRow.style.display = "none";
        LibRow.style.display = "block";
    }

    // Create the Engg. Data App Namespace
    ProjectTree = new ProjectTreeScope();
	ProjectTree.htmlWindow = window;
    eda.ProjectViewObj = ProjectTree;
    ObjectBranch = new ProjectTreeObjectScope;
    //ObjectBranch = new ProjectTreeObjectScope;
    //ConvectionBranch = new ProjectTreeConvectionScope;
    //SectionBranch = new ProjectTreeSectionScope;
    //eda.ObjectBranch = ObjectBranch;
    //eda.ConvectionBranch = ConvectionBranch;
    //eda.SectionBranch = SectionBranch;
    eda.ObjectBranch = ObjectBranch;

    // Inform the main script about this script
    eda.ProjectViewScript   =  this;
    eda.ProjectViewScript.focusTimer = null;

    // Create the Engg. Data App Namespace
    LibraryTree = new ProjectTreeScope();
    eda.LibraryViewObj = LibraryTree;

    // Inform the main script about this script
    eda.LibraryViewScript   =  this;

    eda.OverloadDefaultEvents(document);

    for(var i=0;i<document.body.all.length;i++)
    {
        var element=document.body.all[i];
        switch(element.tagName)
        {
            case "GROUPHEADING":
                //element.onmouseenter=element.onmouseleave=GroupControlMouseFeedback;
                //element.onclick=element.onkeypress=GroupHeadingOnClick;
                break;

            case "LINK":
                element.onmouseover=element.onmouseout=linkMouseFeedback;
                element.onclick=element.onkeypress=linkActivated;
                break;
        }
    }

    ProjectFormLoadedInterval = window.setInterval("EDAProjectFormLoaded()", 250);
}


/*
 * EDAProjectFormLoaded:
 *    Purpose:  To determine if the EDAProject HTML Page has completed loading.
 */
function EDAProjectFormLoaded ()
{
    try
    {
        if( !isNaN(ProjectFormLoadedInterval) )
            window.clearInterval(ProjectFormLoadedInterval);

        ProjectFormLoadedInterval = 0;
        if ( EDAProjectForm )
        {
            // The Engg Data Project Form is loaded
            EDADataViewFormLoaded();
        }
    }
    catch (e)
    {
        if( !isNaN(ProjectFormLoadedInterval))
            window.clearInterval(ProjectFormLoadedInterval);

        ProjectFormLoadedInterval = window.setInterval("EDAProjectFormLoaded()", 250);
    }
}

function EDADataViewFormLoaded ()
{
    try
    {
        if( !isNaN(ProjectFormLoadedInterval) )
            window.clearInterval(ProjectFormLoadedInterval);

        ProjectFormLoadedInterval = 0;
        if ( eda.DataViewScript )
        {
            var node = null;
            ProjectTree.buildTree();
        }
        else
        {
            if( !isNaN(ProjectFormLoadedInterval))
                window.clearInterval(ProjectFormLoadedInterval);

            ProjectFormLoadedInterval = window.setInterval("EDADataViewFormLoaded()", 250);
        }
    }
    catch (e)
    {
    //debugger;
    }
}

function linkMouseFeedback()
{
	if(this.id!=Layout.className) this.className = event.type == "mouseover" ? "Hover" : "";
}

function linkMouseFeedbackForDropdown(event)
{
   	if(event.srcElement.id != Layout.className) event.srcElement.className = event.type == "mouseover" ? "Hover" : "";
	//if(this.id!=Layout.className) this.className=event.type=="mouseover"?"Hover":"";
}

function getCurrentView()
{
}

function linkActivated()
{
	if(event.type=="click"||(event.type=="keypress"&&(event.keyCode==13||event.keyCode==32)))
	{
		event.srcElement.className="";
		if(event.srcElement.id!=getCurrentView())
		{

		}
		else if(event.srcElement.id=="Save")
		{
			// TODO
		}
		else if(event.srcElement.id=="Print")
		{
			// TODO
		}

	}
	G_doGraphicsUpdate=true; // Reset to normal

	//window.onresize();
}

// ############################################################################
// Project Tree Scope
// ############################################################################
function ProjectTreeScope () //this contains the library as well
{
   	var myself = this;
	this.EnggData = "kProjMaterial";
	this.ActiveItem = null;
	// Event Callbacks
	this.tvNodeClick = null;
	this.tvNodeExpand = null;
	this.tvNodeCollapse = null;
	this.tvMouseUp = null;
	this.tvAfterLabelEdit = null;
	var edaMaterialPage = null;
	this.insertNewObject = false;
	this.htmlWindow = null;
}

function ProjectTreeScope.prototype.Clear()
{
   this.EnggData = "kProjMaterial";
   this.ActiveItem = null;
}

ProjectTreeScope.prototype.findCategory = function ( node )
{
    var category = node.Tag.folder;
    return category;
    // Strip off any numerics
    for (var i = category.length - 1; i >= 0; i--)
    {
        var chrCode = category.charCodeAt(i);
        if (!(chrCode > 47 && chrCode < 59))
            break;
    }
    var category = category.substring(0,i+1);
    return category;
}

/*
 * buildProjectTree
 *    Purpose: To build the engg data project tree view
 */
ProjectTreeScope.prototype.buildTree = function ()
{
//debugger;
	if (edApplet.Mode == 1)
		this.buildProjectTree();
	else
		this.buildLibraryTree();
}

ProjectTreeScope.prototype.buildLibraryTree = function()
{
    if (!EDALibraryView)
        return;

    eda.LibraryViewTree = EDALibraryView;
    eda.ActiveViewTree = EDALibraryView;
    eds.initializeTree( EDALibraryView );
    EDALibraryView.Nodes.Clear();
    var rootText = eds.wbGetLocalString( eds.stringTable, "ID_MyLibrary");

    //if (createNew)
    //	rootText += " " + eds.wbGetLocalString( eds.stringTable, "ID_Unsaved");
    //else
    //	rootText += " " + eds.wbGetLocalString( eds.stringTable, "ID_DataSyncronized");

    eda.LibraryMaterialRoot = EDALibraryView.Nodes.Add(null,0,"kLibMaterialRoot", "MyLibrary", "Library", "Library");
    eda.LibraryMaterialRoot.Image = "Library";
    eda.LibraryMaterialRoot.SelectedImage = "Library";
    var matlFolder = EDALibraryView.Nodes.Add(eda.LibraryMaterialRoot.key,4,"kLibMaterialFolder", "Material", "material", "material");
    eda.LibraryMaterialRoot.Expanded = -1;
    LibraryTree.CreateEventCallbacks(eda.ActiveViewTree);
}

ProjectTreeScope.prototype.buildProjectTree = function()
{
//debugger;
    try
    {
        if ( EDAProjectView )
        {
            eda.ActiveViewTree = EDAProjectView;
            eda.ProjectViewTree = EDAProjectView;
            eds.initializeTree( EDAProjectView );

            // TODO If there are no items of a given type then don't show the folder ??
            if (EDAProjectView.Nodes)
                EDAProjectView.Nodes.Clear();

            eda.MaterialRoot = null;
            eda.ConvectionRoot = null;
            eda.SectionRoot = null;
			   eda.LoadRoot = null;
			   eda.BeamSectionRoot = null;

            // Project
            var sp = wb.AppletList.Applet("StartPage").App;
            var projName = sp.WBDB.Name;
            if (projName == "")
                projName = eds.wbGetLocalString( eds.stringTable, "ID_Project");

            eda.ProjectRoot = EDAProjectView.Nodes.Add(null,TVW_First, "kProjectRoot", projName, "Project", "Project");
            var objTag = {folder:"kProjectRoot", clsType:"Project", dataType:null, dataObj:null, treeName:eda.ProjectRoot.Text};
            eda.ProjectRoot.Tag = objTag;

            // Materials
            var nodeName = null
            if (eda.ActivateTreeItem)
            {
                nodeName = eda.ActivateTreeItem;
            }
             else if (this.EnggData == "kProjMaterial" && this.ActiveItem == null)
            {
                // Select the default material if there is one
                if (edApplet.ProjectLibrary.DefaultMaterial)
                {
                    nodeName = edApplet.ProjectLibrary.DefaultMaterial.Name;
                }
                else
                {
                    var materials = edApplet.ProjectLibrary.Materials;
                    if (materials)
                    {
                        if(materials.Count)
                        {
                            nodeName = materials.Item(1).Name;
                        }
                    }
                }
            }
            else if (this.EnggData == "kProjConvection" && this.ActiveItem == null)
            {
                eda.ProjectRoot.Expanded = true;
                // Select the default material if there is one
                if (edApplet.ProjectLibrary.DefaultConvection)
                {
                    nodeName = edApplet.ProjectLibrary.DefaultConvection.Name;
                }
                else
                {
                    var convections = edApplet.ProjectLibrary.Convections;
                    if (convections)
                    {
                        if(convections.Count)
                        {
                            nodeName = convections.Item(1).Name;
                        }
                    }
                }
            }
            else if (this.EnggData == "kProjSection" && this.ActiveItem == null)
            {
                eda.ProjectRoot.Expanded = true;
                // Select the default material if there is one
                if (edApplet.ProjectLibrary.DefaultSection)
                {
                    nodeName = edApplet.ProjectLibrary.DefaultSection.Name;
                }
                else
                {
                    var sections = edApplet.ProjectLibrary.Sections;;
                    if (sections)
                    {
                        if(sections.Count)
                        {
                            nodeName = sections.Item(1).Name;
                        }
                    }
                }
            }
			 else if (this.EnggData == "kProjLoad " && this.ActiveItem == null)
            {
                eda.ProjectRoot.Expanded = true;
                // Select the default load if there is one
                if (edApplet.ProjectLibrary.DefaultLoadVariation)
                {
                    nodeName = edApplet.ProjectLibrary.DefaultLoadVariation.Name;
                }
                else
                {
                    var loads = edApplet.ProjectLibrary.LoadVariations;
                    if (loads)
                    {
                        if(loads.Count)
                        {
                            nodeName = loads.Item(1).Name;
                        }
                    }
                }
            }
            else
            {
					nodeName = this.ActiveItem.treeName;
            }

            //
            ObjectBranch.InitializeData();
            
            // Setup the Events for the tree
            ProjectTree.CreateEventCallbacks(eda.ActiveViewTree);
			   ObjectBranch.ProjectTreeAppend(EDAProjectView, ObjectBranch.eMaterialRoot, ObjectBranch.objMaterialBranchData, nodeName);

            // Convections
			   ObjectBranch.ProjectTreeAppend(EDAProjectView, ObjectBranch.eConvectionRoot, ObjectBranch.objConvectionBranchData, nodeName);

			//Loads
			ObjectBranch.ProjectTreeAppend(EDAProjectView, ObjectBranch.eLoadVariationRoot, ObjectBranch.objLoadBranchData, nodeName);

			// Beam Sections
         if (wb.PreferenceMgr.Preference("PID_Show_Beta_Options"))
         {
            ObjectBranch.ProjectTreeAppend(EDAProjectView, ObjectBranch.eBeamSectionRoot, ObjectBranch.objBeamSectionBranchData, nodeName);
         }

        }
        eda.ProjectRoot.Expanded = true;
    }
    catch (e)
    {
        debugger;
    }
}


ProjectTreeScope.prototype.SelectNode = function( node )
{
    if (!node)
        return;

    // Expand all items down to this node
    parentNode = node.parent;
    treeNode = null;
    while ( parentNode != null )
    {
        treeNode = parentNode;
        parentNode.Expanded = true;
        parentNode = parentNode.parent;
    }
    eda.ActiveViewTree.SelectedItem = node;
}

ProjectTreeScope.prototype.switchView = function()
{
	if (edApplet.Mode == 1)	//project mode
	{
		ProjectRow.style.display = "block";
		LibRow.style.display = "none";
	}
	else
	{
		ProjectRow.style.display = "none";
		LibRow.style.display = "block";
	}
	ProjectTree.buildTree();
	edApplet.GUIState.UpdateStandardToolbar();
}

ProjectTreeScope.prototype.CreateEventCallbacks = function ( wbTreeViewCtrl)
{
	try
	{
	   if (this.tvNodeClick) return;
	   
		this.tvNodeClick = wbTreeViewCtrl.OnNodeClick;
		this.tvNodeClick.AddCOM(this, "tv_NodeClickDelegate");

		this.tvNodeExpand = wbTreeViewCtrl.OnAfterExpand;
		this.tvNodeExpand.AddCOM(this, "tv_NodeExpandDelegate");
		this.tvNodeCollapse = wbTreeViewCtrl.OnAfterCollapse;
		this.tvNodeCollapse.AddCOM(this, "tv_NodeCollapseDelegate");

		this.tvMouseUp = wbTreeViewCtrl.OnMouseUp;
		this.tvMouseUp.AddCOM(this, "tv_MouseUpDelegate");

		this.tvAfterLabelEdit = wbTreeViewCtrl.OnAfterLabelEdit;
		this.tvAfterLabelEdit.AddCOM(this, "tv_AfterLabelEditDelegate");

		this.tvBeforeLabelEdit = wbTreeViewCtrl.OnBeforeLabelEdit;
		this.tvBeforeLabelEdit.AddCOM(this,"tv_BeforeLabelEditDelegate");

		this.tvKeyUp = wbTreeViewCtrl.OnKeyUp;
		this.tvKeyUp.AddCOM(this,"tv_KeyUpDelegate");
	}
	catch(e)
	{
	}
}

ProjectTreeScope.prototype.tv_NodeExpandDelegate = function ( sender, args )
{
	this.tv_NodeExpand(args.TreeNode);
}

ProjectTreeScope.prototype.tv_NodeExpand = function ( node )
{
    var category = this.findCategory( node );
    if (category == null)
        return;

	var temp = false;
        
    switch (node.Key)
	{
		case "kProjMaterialRoot":	ObjectBranch.objMaterialBranchData.FolderOpen = node.Expanded;
									temp = true;								
									break;
		case "kProjConvectionRoot":	ObjectBranch.objConvectionBranchData.FolderOpen = node.Expanded;
									temp = true;
									break;
		case "kProjLoadRoot":		ObjectBranch.objLoadBranchData.FolderOpen = node.Expanded;
									temp = true;								
									break;
		default:					break;
		
	}
	if (temp == false)
	{
		var length = ObjectBranch.objLoadBranchData.LeafOrder.length;
		for (var idx = 0; idx < length;	idx++)
		{
			if (node == ObjectBranch.objLoadBranchData.LeafOrder[idx].treeNode)
			{
				ObjectBranch.objLoadBranchData.LeafOrder[idx].FolderOpen = node.Expanded;
			}
		}
	}
	node.Image = "folderopen";
	node.SelectedImage = "folderopen"
    
}

ProjectTreeScope.prototype.tv_NodeCollapseDelegate = function ( sender, args )
{
	this.tv_NodeCollapse(args.TreeNode);
}

ProjectTreeScope.prototype.tv_NodeCollapse = function ( node )
{
//	debugger;
    var category = this.findCategory( node );
    if (category == null)
        return;
        
    var temp = false;
        
    switch (node.Key)
	{
		case "kProjMaterialRoot":	ObjectBranch.objMaterialBranchData.FolderOpen = node.Expanded;
									temp = true;								
									break;
		case "kProjConvectionRoot":	ObjectBranch.objConvectionBranchData.FolderOpen = node.Expanded;
									temp = true;									
									break;
		case "kProjLoadRoot":		ObjectBranch.objLoadBranchData.FolderOpen = node.Expanded;
									temp = true;
									break;
		default:					break;
		
	}
	if (temp == false)
	{
		var length = ObjectBranch.objLoadBranchData.LeafOrder.length;
		for (var idx = 0; idx < length;	idx++)
		{
			if (node == ObjectBranch.objLoadBranchData.LeafOrder[idx].treeNode)
			{
				ObjectBranch.objLoadBranchData.LeafOrder[idx].FolderOpen = node.Expanded;
			}
		}
	}
	node.Image = "folderclosed";
	node.SelectedImage = "folderclosed"; 
}

ProjectTreeScope.prototype.tv_NodeClickDelegate = function (sender, args)
{
	this.tv_NodeClick(args.TreeNode);
}

ProjectTreeScope.prototype.tv_NodeClick = function ( node )
{
	//debugger;
	try
    {
        var nodePicked = node;
        wbTreeViewCtrl = eda.ActiveViewTree;
        if (node.Key == "kProjectRoot")
        {
            this.EnggData = "kProjectRoot";
        }
        // Find selected item and update page based on ID
        var node = wbTreeViewCtrl.SelectedItem;
        var objTag = node.Tag;//{folder:"kProjectRoot", clsType:"Project", dataType:null, dataObj:null};
        if (node == nodePicked)
        {
            this.ActiveItem = objTag;
        }
        else
        {
            return;
        }

         if (eda.ProjectViewScript.focusTimer)
               eda.ProjectViewScript.window.clearTimeout(eda.ProjectViewScript.focusTimer);
        // TODO make use of the ActiveObject

        // If there is more than one item selected the data view is not valid
        // TODO how to handle this

        // TODO handle updating the ContextToolbar
        if(edApplet.GUIState && this.ActiveItem.dataObj != null)
        {
            //we want to assign the active object to the applet
            edApplet.GUIState.ActiveObject = this.ActiveItem.dataObj;
            edApplet.GUIState.UpdateContextToolbar();
        }

        var category = this.findCategory( node );
        this.EnggData = category;
        eda.DataViewScript.RefreshView(category, objTag.dataObj);
    }
    catch(e)
    {
    //debugger;
    }
}

ProjectTreeScope.prototype.tv_MouseUpDelegate = function ( sender, args )
{
	this.tv_MouseUp(args.Button, args.Modifiers, args.X, args.Y);
}

ProjectTreeScope.prototype.tv_MouseUp = function (button, shift, x, y)
{
    try
    {
        if (button == 1)
            return;	//if left mouse button return now
        var p = {MenuLoader:null};
        
         edApplet.GUIState.GUIDriver.MenuListener.AddListener(4345, ObjectBranch);
        var bContextMenuCreated = ObjectBranch.ContextMenu( p );
        
        if (!bContextMenuCreated)
        {
            edApplet.GUIState.GUIDriver.MenuListener.RemoveListener(4345);
            return;
        }

        var wndHelper  =eds.CreateActiveXObject(eds.GenWBProgId("WBControls.WBWndHelper"));
        var rect =eds.CreateActiveXObject(eds.GenWBProgId("WBControls.WBRect"));
        rect.Top = y;
        rect.Left = x;
        rect.Width = 1;
        rect.Height = 1;
        if(eda.ActiveViewTree.FirstSelectedItem && wndHelper)
        {
            var rectScreen = wndHelper.ClientToScreen(eda.ActiveViewTree.hWnd,rect);
            x = rectScreen.left;
            y = rectScreen.top;
        }
        else
        {
            x = null;
            y = null;
        }

        p.MenuLoader.ShowMenu(edApplet.GUIState.GUIDriver, x, y);
        edApplet.GUIState.GUIDriver.MenuListener.RemoveListener(4345);
    }
    catch(error)
    {
        edApplet.GUIState.GUIDriver.MenuListener.RemoveListener(4345);
    }
}

ProjectTreeScope.prototype.tv_KeyUpDelegate = function ( sender, args )
{
	this.tv_KeyUp(args.KeyCode, args.Shift);
}

ProjectTreeScope.prototype.tv_KeyUp = function ( keycode, shift )
{
   try
   {
      switch(keycode)
      {
         case 46:
            // Delete
				eda.ObjectBranch.doRemoveItems();
            break;
         case 113:
            // F2 - Rename
            eda.ObjectBranch.doRenameItem();
         default:
            break;
      }
   }
   catch(error)
   {
      debugger;
   }
}

function ProjectTreeScope.prototype.SetFocus ()
{
   try
   {
      var treeFocus = eda.ProjectViewScript.document.all["EDAProjectView"];
      if (treeFocus)
      {
         eda.wbWndHelper.SetFocus(treeFocus.hWnd);
         if ( this.insertNewObject )
         {
            eda.ActiveViewTree.StartLabelEdit();
         }
         this.insertNewObject = false;
      }
   }
   catch(error)
   {
      debugger;
   }
}

ProjectTreeScope.prototype.tv_BeforeLabelEditDelegate = function ( sender, args )
{
	this.tv_BeforeLabelEdit(args.TreeHelper);
}

ProjectTreeScope.prototype.tv_BeforeLabelEdit = function ( tvHelper )
{
   try
   {
      var selItem = eda.ActiveViewTree.FirstSelectedItem;
      if (selItem.Index == 1)
      {
         tvHelper.CancelLabelEdit = true;
         return;
      }
      // Do not allow folders to be modified
      if (typeof(selItem.Tag.folderIdx)== "number")
      {
         tvHelper.CancelLabelEdit = true;
         return;
      }
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeScope.prototype.tv_AfterLabelEditDelegate = function ( sender, args )
{
	this.tv_AfterLabelEdit(args.TreeHelper);
}

ProjectTreeScope.prototype.tv_AfterLabelEdit = function ( tvHelper )
{
    try
    {
        // Make sure there are no blanks at the end of the string or that it is a blank string
        newObjectName = tvHelper.LabelEditString;
        var ObjNameLen = newObjectName.length;
        
        if(ObjNameLen)
        {
			//trimming the space at the beginning of the string
			var objStartIdx = 0;
			while (newObjectName.charAt(objStartIdx) == ' ')
			{
				objStartIdx++;
			}
			newObjectName = newObjectName.substr(objStartIdx, ObjNameLen);
			ObjNameLen = newObjectName.length;
			//trimming the space at the end of the string
            var objIdx = ObjNameLen - 1;
            while(newObjectName.charAt(objIdx) == ' ')
            {
                objIdx --;
            }
            newObjectName = newObjectName.substr(0, objIdx+1);
			
         var obj = eda.ActiveViewTree.FirstSelectedItem.Tag.dataObj;
         //see if the new name is unique
         var bUniqueName = false;
         switch (eda.ActiveViewTree.FirstSelectedItem.Tag.clsType)
			{
				case "Material":
					bUniqueName = edApplet.ProjectLibrary.IsMaterialNameUnique(newObjectName);
					break;
				case "Convection":
					bUniqueName = edApplet.ProjectLibrary.IsConvectionNameUnique(newObjectName);
					break;
				case "LoadVariation":
					bUniqueName = edApplet.ProjectLibrary.IsLoadVariationNameUnique(newObjectName);
					break;
				case "BeamSection":
					bUniqueName = edApplet.ProjectLibrary.IsBeamNameUnique(newObjectName);
					break;
				default:
					return;
					break;
			}

		 if (bUniqueName)
			{
				obj.Name = newObjectName;
				eda.BreadCrumbScript.updateBreadcrumbs();
			}
         else
			{
				tvHelper.LabelEditString = obj.Name;
				eda.ActiveViewTree.StartLabelEdit();
			}
		}
		else
		{
         eda.ActiveViewTree.StartLabelEdit();
		}
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeScope.prototype.findNodeByName = function ( name )
{
   try
   {
      var node = null;
      var count = eda.ActiveViewTree.Nodes.Count;
      for (var i = 1; i <= count; i++)
      {
         var tmpNode = eda.ActiveViewTree.Nodes.Item(i);
         if ((tmpNode.Tag.treeName == name)||((tmpNode.Tag.folderObj!=null)&&(tmpNode.Tag.folderObj.Text == name)))
         //if (tmpNode.Tag.treeName == name)
         {
			node = tmpNode;
			break;
		}
      }
      //if ((node==null) && ((tmpNode.Tag.folderObj!=null)&&(tmpNode.Tag.folderObj.Text == name)))
      //debugger;
        return node;
      
   }
   catch(error)
   {
        //debugger;
   }
}

//
// Material Branch
//
function ProjectTreeObjectScope ()
{
   // THERMAL
   this.kTemperature = eda.LoadVariationVarEnums.kLoadVariationVariableTemperature;
   this.kConvectionCoefficient = eda.LoadVariationVarEnums.kLoadVariationVariableConvectionCoefficient;
   this.kHeatFlow = eda.LoadVariationVarEnums.kLoadVariationVariableHeatFlow;
   this.kHeatGenerationRate = eda.LoadVariationVarEnums.kLoadVariationVariableHeatGenerationRate;
   this.kHeatFlux = eda.LoadVariationVarEnums.kLoadVariationVariableHeatFlux;
   // STRUCTURAL
   this.kAcceleration = eda.LoadVariationVarEnums.kLoadVariationVariableAcceleration;
   this.kRotationalAcceleration = eda.LoadVariationVarEnums.kLoadVariationVariableRotationalAcceleration;
   this.kDisplacement = eda.LoadVariationVarEnums.kLoadVariationVariableDisplacement;
   this.kRotation = eda.LoadVariationVarEnums.kLoadVariationVariableRotation;
   this.kVelocity = eda.LoadVariationVarEnums.kLoadVariationVariableVelocity;
   this.kRotationalVelocity = eda.LoadVariationVarEnums.kLoadVariationVariableRotationalVelocity;
   this.kForce = eda.LoadVariationVarEnums.kLoadVariationVariableForce;
   this.kForceIntensity = eda.LoadVariationVarEnums.kLoadVariationVariableForceIntensity;
   this.kPressure = eda.LoadVariationVarEnums.kLoadVariationVariablePressure;
   this.kMoment = eda.LoadVariationVarEnums.kLoadVariationVariableMoment;
   this.kDamping = eda.LoadVariationVarEnums.kLoadVariationVariableDamping;
   this.kFriction = eda.LoadVariationVarEnums.kLoadVariationVariableFriction;
   // PSD
   this.kPSDAcceleration = eda.LoadVariationVarEnums.kLoadVariationVariablePSDAcceleration;
   this.kPSDGAcceleration = eda.LoadVariationVarEnums.kLoadVariationVariablePSDGAcceleration;
   this.kPSDVelocity = eda.LoadVariationVarEnums.kLoadVariationVariablePSDVelocity;
   this.kPSDDisplacement = eda.LoadVariationVarEnums.kLoadVariationVariablePSDDisplacement;
   // Electric/Magnetic
   this.kVoltage = eda.LoadVariationVarEnums.kLoadVariationVariableVoltage;
   this.kCurrent = eda.LoadVariationVarEnums.kLoadVariationVariableCurrent;

   this.objMaterialBranchData = {
      NameStringID:  "ID_ProjectMaterials",
      Contents:      edApplet.ProjectLibrary.Materials,
      TreeTagID:     "kProjMaterial",
      LeafOrder:     [],
      Icon:          "edMaterial",
      FolderOpen:	true
   };

   this.objConvectionBranchData = {
      NameStringID:  "ID_ProjectConvections",
      Contents:      edApplet.ProjectLibrary.Convections,
      TreeTagID:     "kProjConvection",
      LeafOrder:     [],
      Icon:          "edConvection",
      FolderOpen:	true
   };

   this.objLoadBranchData = {
      NameStringID:  "ID_ProjectLoadVariations",
      Contents:      edApplet.ProjectLibrary.LoadVariations,
      TreeTagID:     "kProjLoad",
      LeafOrder:     [],
      FolderOpen:	true
   };
   if (this.objLoadBranchData.LeafOrder.length == 0)
   {
      var arrIdx = 0;
      var objInfo = null;
      objInfo = {dataType:[this.kTemperature], treeNode: null, folderID: "Temperatures", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kConvectionCoefficient], treeNode: null, folderID: "ConvectionCoefficients", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kHeatFlow], treeNode: null, folderID: "HeatFlows", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kHeatGenerationRate], treeNode: null, folderID: "HeatGenerationRates", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kHeatFlux], treeNode: null, folderID: "HeatFluxes", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kAcceleration], treeNode: null, folderID: "Accelerations", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kRotationalAcceleration], treeNode: null, folderID: "RotationalAccelerations", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kDisplacement], treeNode: null, folderID: "Displacements", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kRotation], treeNode: null, folderID: "Rotations", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kVelocity], treeNode: null, folderID: "Velocities", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kRotationalVelocity], treeNode: null, folderID: "RotationalVelocities", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kForce], treeNode: null, folderID: "Forces", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kPressure], treeNode: null, folderID: "Pressures", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kForceIntensity], treeNode: null, folderID: "ForceIntensities", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kMoment], treeNode: null, folderID: "Moments", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kDamping], treeNode: null, folderID: "Dampings", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[this.kFriction], treeNode: null, folderID: "Frictions", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;
      
      objInfo = {dataType:[this.kPSDAcceleration, this.kPSDGAcceleration, this.kPSDVelocity, this.kPSDDisplacement], treeNode: null, folderID: "PSDSpectrumLoads", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;  
      
      objInfo = {dataType:[this.kVoltage], treeNode: null, folderID: "Voltages", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;
      
      objInfo = {dataType:[this.kCurrent], treeNode: null, folderID: "Currents", icon: "edLoadVariation", FolderOpen: true};
      this.objLoadBranchData.LeafOrder[arrIdx++] = objInfo;
   }
   
   // Provide the order of beam folders and information needed to build generically
   this.objBeamSectionBranchData = {
      NameStringID:  "ID_ProjectBeamSections",
      Contents:      edApplet.ProjectLibrary.BeamSections,
      TreeTagID:     "kProjBeamSection",
      LeafOrder:     []
   };
   if (this.objBeamSectionBranchData.LeafOrder.length == 0)
   {
      var arrIdx = 0;
      var objInfo = null;
      objInfo = {dataType:[eda.BeamEnums.kBeamTypeRECT], treeNode: null, folderID: "Beam_RectSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeQUAD], treeNode: null, folderID: "Beam_QuadSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeCSOL], treeNode: null, folderID: "Beam_CSolSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeCTUB], treeNode: null, folderID: "Beam_CTubSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeCHAN], treeNode: null, folderID: "Beam_ChanSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeZ], treeNode: null, folderID: "Beam_ZSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeL], treeNode: null, folderID: "Beam_LSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeI], treeNode: null, folderID: "Beam_ISections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeT], treeNode: null, folderID: "Beam_TSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeHATS], treeNode: null, folderID: "Beam_HatsSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;

      objInfo = {dataType:[eda.BeamEnums.kBeamTypeHREC], treeNode: null, folderID: "Beam_HRecSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;
      
      objInfo = {dataType:[eda.BeamEnums.kBeamTypeASEC], treeNode: null, folderID: "Beam_ASecSections", icon: "edBeam"};
      this.objBeamSectionBranchData.LeafOrder[arrIdx++] = objInfo;
   }

   var rootIdx = 0;
   this.eMaterialRoot = rootIdx++;
   this.eConvectionRoot = rootIdx++;
   this.eLoadVariationRoot = rootIdx++;
   this.eBeamSectionRoot = rootIdx++;
   
}

function ProjectTreeObjectScope.prototype.InitializeData()
{
   // This array must be reinitialized each time the entire is rebuilt
   var arrIdx = 0;
   var objInfo = null;
   
   objInfo = {folderObj:null, folderIdx:arrIdx, folder:"kProjMaterialRoot", clsType:"Material", dataTypes:null, dataObj:null, treeName:"Materials"};
   eda.BranchOrder[arrIdx++] = objInfo;
   
   objInfo = {folderObj:null, folderIdx:arrIdx, folder:"kProjConvectionRoot", clsType:"Convection", dataTypes:null, dataObj:null, treeName:"Convections"};
   eda.BranchOrder[arrIdx++] = objInfo;
   
   objInfo = {folderObj:null, folderIdx:arrIdx, folder:"kProjLoadRoot", clsType:"LoadVariation", dataTypes:null, dataObj:null, treeName:"LoadHistorys"};
   eda.BranchOrder[arrIdx++] = objInfo;
   
   objInfo = {folderObj:null, folderIdx:arrIdx, folder:"kProjBeamSectionRoot", clsType:"BeamSection", dataTypes:null, dataObj:null, treeName:"BeamSections"};
   eda.BranchOrder[arrIdx++] = objInfo;
}

ProjectTreeObjectScope.prototype.ContextMenu = function ( pMenuLoader )
{
//debugger;
    try
    {
        var menuItem;
        var menuLoader = new eds.dynamicMenuLoader();
        pMenuLoader.MenuLoader = menuLoader;

        var suppressed = 0;

        var selItem = eda.ActiveViewTree.FirstSelectedItem;

        var selCls = selItem.Tag.clsType;
        var selObj = selItem.Tag.dataObj;

        // Are we at the project top?
        if (eda.ActiveViewTree.SelectedItem.parent == null)
            return false;

        //      if (eda.ActiveViewTree.SelectedItem.Index == 1)	notRoot = 0;
        // Are we at a branch?
        //if (eda.ActiveViewTree.SelectedItem.parent.parent == null)
          //  atRoot = 0;
		if (selObj == null)
		{
			if (selCls == "Material")
			{
				newItemIcon = "edMaterialNew";
				newItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_MenuInsertNewMaterial");
				importItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_ImportMaterial");
				importItemIcon = "edMaterialBrowse";
			}
			else if (selCls == "Convection")
			{
				newItemIcon = "edConvectionNew";
				newItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_InsertNewConvection");
				importItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_ImportConvection");
				importItemIcon = "edConvectionBrowse";
			}
			else if (selCls == "Section")
			{
				newItemIcon = "section";
				newItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_InsertNewSection");
				importItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_ImportSection");
				importItemIcon = "section";
			}
			else if (selCls == "LoadVariation")
			{
				newItemIcon = "edLoadVariationNew";
				newItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_InsertNewLoadVariation");
				importItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_ImportLoadVariation");
				importItemIcon = "edLoadVariationBrowse";
			}
			else if (selCls == "BeamSection")
			{
				newItemIcon = "edBeamNew";
				newItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_InsertNewBeam");
				importItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_ImportBeam");
				importItemIcon = "edBeamBrowse";
			}
		}


        var defItemText = eds.wbGetLocalString( edApplet.stringTable, "ID_SetDefault");
        var alwaysText = eds.wbGetLocalString( edApplet.stringTable, "ID_AlwaysAvailable");

        if (selObj != null)
        {
		      suppressed = selObj.isSuppressed;
            var selCount = eda.ActiveViewTree.SelectedCount;
            if (ObjectBranch.isValidSource())
            {
                // We only show these items for a valid source (I.e. NOT a DSDB)
                if (selCount == 1 && selCls != "LoadVariation")
                {
                    var defaultItem = menuLoader.AddMenuItem(null, defItemText, null, "4345", "doSetDefault", null);
                    menuLoader.AddCheckStateCallback(defaultItem, "4345", "isDefaultItem", null);
                }
                var alwaysItem = menuLoader.AddMenuItem(null, alwaysText, null, "4345", "doAlwaysAvailable", null);
                menuLoader.AddCheckStateCallback(alwaysItem, "4345", "isAlwaysAvailable", null);
            }

            menuLoader.AddSeparator();
            if (suppressed)
            {
                //menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_Unsuppress"), "unsuppressed", "4345", "doSuppressItem", false);
            }
            else
            {
                //menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_Suppress"), "suppressed", "4345", "doSuppressItem", true);
            }
            menuItem = menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_Delete"), "delete", "4345", "doRemoveItems", ObjectBranch);
            menuLoader.AddVisibilityCallback(menuItem, "11", "CanDelete", null);
            if (selCount == 1)
            {
                menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_Duplicate"), "duplicate", "4345", "doDuplicateItem", ObjectBranch);
                menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_Rename"), "rename", "4345", "doRenameItem", ObjectBranch);
            }

            menuLoader.AddSeparator();
            if (ObjectBranch.isValidSource())
                menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_UpdateLink"), "import", "4345", "doUpdateLink", ObjectBranch);

            menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_ExportLibrary"), "export", "4345", "doExportSelectionToLibrary", ObjectBranch);
            menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_ExportExisting"), "export", "4345", "doExportSelectionToExistingLibrary", ObjectBranch);
        }
        else
        {
            menuLoader.AddMenuItem(null, newItemText, newItemIcon, "4345", "doNewItem", ObjectBranch);
            menuLoader.AddMenuItem(null, importItemText, importItemIcon, "4345", "doImportItem", null);
            menuLoader.AddSeparator();

            menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_Export"), "export", "4345", "doExportToLibrary", ObjectBranch);
            menuLoader.AddMenuItem(null, eds.wbGetLocalString( edApplet.stringTable, "ID_ExportExisting"), "export", "4345", "doExportToExistingLibrary", ObjectBranch);
        }
        return true;
    }
    catch(error)
    {
        return false;
    }
}

ProjectTreeObjectScope.prototype.doNewItem = function ( )
{
    try
    {
      var selClassType = eda.ActiveViewTree.SelectedItem.Tag.clsType;
		var newObject = null;
		if (selClassType == "Material")
			newObject = eds.doNewMaterial();
		else if (selClassType == "Convection")
			newObject = eds.doNewConvection();
		else if (selClassType == "LoadVariation")
		{
		   if (eda.ActiveViewTree.SelectedItem.Tag.dataType && eda.ActiveViewTree.SelectedItem.Tag.dataType.length > 0)
		   {
			   newObject = eds.doNewLoad(eda.ActiveViewTree.SelectedItem.Tag.dataType, null);
		   }
		   else
			   newObject = eds.doNewLoad();
		}
		else if (selClassType == "BeamSection")
		{
		   if (eda.ActiveViewTree.SelectedItem.Tag.dataType && eda.ActiveViewTree.SelectedItem.Tag.dataType.length > 0)
		   {
			   newObject = eds.doNewBeam(eda.ActiveViewTree.SelectedItem.Tag.dataType);
		   }
		   else
			   newObject = eds.doNewBeam();
		}

      newObject.Source = "";
      var node = null;
      if (selClassType == "Material")
         ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eMaterialRoot, ObjectBranch.objMaterialBranchData, newObject.Name);
		else if (selClassType == "Convection")
         ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eConvectionRoot, ObjectBranch.objConvectionBranchData, newObject.Name);
		else if (selClassType == "LoadVariation")
		{
         var loadType = newObject.Dependents.Item(1).Type;
         var loadFolder = null;
         for (var nodeIdx = 0; nodeIdx < this.objLoadBranchData.LeafOrder.length; nodeIdx++)
         {
            var curNode = this.objLoadBranchData.LeafOrder[nodeIdx];
            var loadDataType = 0;
            for (var dtIdx = 0; dtIdx < curNode.dataType.length; dtIdx++)
            {
               loadDataType = curNode.dataType[dtIdx];
               if (loadDataType == loadType)
                  break;
            }
            if (loadDataType == loadType)
            {
               loadFolder = "kProj"+curNode.folderID;
               break;
            }
         }
         ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eLoadVariationRoot, ObjectBranch.objLoadBranchData, newObject.Name, loadFolder);
		}
		else if (selClassType == "BeamSection")
		{
         var dataType = newObject.Type;
         var beamFolder = null;
         for (var nodeIdx = 0; nodeIdx < this.objBeamSectionBranchData.LeafOrder.length; nodeIdx++)
         {
            var curNode = this.objBeamSectionBranchData.LeafOrder[nodeIdx];
            var loadDataType = 0;
            for (var dtIdx = 0; dtIdx < curNode.dataType.length; dtIdx++)
            {
               loadDataType = curNode.dataType[dtIdx];
               if (loadDataType == dataType)
                  break;
            }
            if (loadDataType == dataType)
            {
               beamFolder = "kProj"+curNode.folderID;
               break;
            }
         }
         ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eBeamSectionRoot, ObjectBranch.objBeamSectionBranchData, newObject.Name, beamFolder);
		}

      eda.ProjectViewObj.insertNewObject = true;
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.doImportItem = function ( )
{
    try
    {
	  eds.beginWaitCursor();
      var selObj = eda.ActiveViewTree.FirstSelectedItem.Tag.dataObj;
      var selClassType = eda.ActiveViewTree.FirstSelectedItem.Tag.clsType;

		if (selClassType == "Material")
		{
			newItem = eds.DisplayImportDialog("MaterialData");
			if (newItem)
            ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eMaterialRoot, ObjectBranch.objMaterialBranchData, newItem.Name);
			else
				return;
		}
		else if (selClassType == "Convection")
		{
			newItem = eds.DisplayImportDialog("ConvectionData");
			if (newItem)
            ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eConvectionRoot, ObjectBranch.objConvectionBranchData, newItem.Name);
			else
				return;
		}
		else if (selClassType == "LoadVariation")
		{
			var newItem = null;
         var selDataTypes = eda.ActiveViewTree.FirstSelectedItem.Tag.dataType;
         if (selDataTypes && selDataTypes.length == 1)
			      newItem = eds.DisplayImportDialog("LoadVariationData",true,selDataTypes[0]);
			else
			      newItem = eds.DisplayImportDialog("LoadVariationData");

			if (newItem)
			{
            loadFolder = eda.ActiveViewTree.FirstSelectedItem.Tag.parentFolder;
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eLoadVariationRoot, ObjectBranch.objLoadBranchData, newItem.Name, loadFolder);
			}
			else
				return;
		}
	   else if (selClassType == "BeamSection")
		{
			newItem = eds.DisplayImportDialog("BeamSectionData");
			if (newItem)
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eBeamSectionRoot, ObjectBranch.objBeamSectionBranchData, newItem.Name);
			else
				return;
		}

        ProjectTree.ChangeState(eda.ActiveViewTree.SelectedItem);
    }
    catch(error)
    {
        debugger;
    }
    eds.endWaitCursor();
}

ProjectTreeObjectScope.prototype.doSuppressItem = function ( suppress )
{
	//debugger;
    try
    {
        var selObj = eda.ActiveViewTree.FirstSelectedItem.Tag.dataObj;
        selObj.isSuppressed = suppress;
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.doRemoveItems = function ( )
{
	try
	{
		var MBBT_OK = 0;
		var MBBT_TASKMODAL = 8192;

		var materialsNode = eda.ActiveViewTree.Nodes.Item("kProjMaterialRoot");
		var convNode = eda.ActiveViewTree.Nodes.Item("kProjConvectionRoot");
		var loadNode = eda.ActiveViewTree.Nodes.Item("kProjLoadRoot");

		var selCount = eda.ActiveViewTree.SelectedCount;
		var selItem = eda.ActiveViewTree.FirstSelectedItem;
		var count = 0;
		var tempItem = new Array();
		var idx = 0;
		for (var i = 0; i < selCount; i++)
		{
			if (selItem.Key == "kProjLoadRoot" || selItem.Key == "kProjConvectionRoot" 
				|| selItem.Key == "kProjMaterialRoot" || selItem.Key == "kProjectRoot")
			{
				selItem = selItem.NextSelected;
				continue;
			}
			if (selItem.Parent)
			{
				if (selItem.Parent.Key == "kProjLoadRoot")
				{
					selItem = selItem.NextSelected;
					continue;
				}
			}
			tempItem[idx] = selItem;
			if (!selItem || !selItem.Tag)	continue;

			var rootObj = selItem.Tag.dataObj;
			if (rootObj == null)
			{
				selItem = selItem.NextSelected;
				continue;
			}
			var rootObjUsers = rootObj.IsUsedBy;
			var numRootObjUsers = rootObjUsers.Count;
			if (numRootObjUsers > 0)
				count = count + 1;
			
			selItem = selItem.NextSelected;
			idx = idx + 1;
		}
		var validSelCount = idx;
		selItem = eda.ActiveViewTree.FirstSelectedItem;
		if (count != validSelCount && validSelCount != 0)
		{		
			var retVal = 0; // do not delete by default
			//display a messagebox and get the confirmation for delete
			
			if(eds.WBScript.Silent)
				retVal = 1;
			else
				retVal = eds.wbYesNo( eds.wbGetLocalString( edApplet.stringTable, "ID_MessageBoxDelete"),eds.wbGetLocalString( edApplet.stringTable, "ID_EDA" ));
			
			if (retVal != 1)
				return;	
		}
	        	
		var newSelNode = null;
		
		for (var i = 0; i < validSelCount; i++)
		{
			if (!tempItem[i] || !tempItem[i].Tag)	continue;

			var rootObj = tempItem[i].Tag.dataObj;
			if (rootObj == null)
			{
				continue;
			}
			var rootObjUsers = rootObj.IsUsedBy;
			var numRootObjUsers = rootObjUsers.Count;
			if (rootObjUsers && numRootObjUsers)
			{
				
				var message = rootObj.Name + " " + eds.wbGetLocalString( edApplet.stringTable, "ID_MaterialInUse") + ":\n";
				var buttonType = MBBT_OK + MBBT_TASKMODAL;

				var iRootObjUserIdx;
				for(iRootObjUserIdx = 1; iRootObjUserIdx <= numRootObjUsers; iRootObjUserIdx++)
				{
					message += "    " +rootObjUsers.Item(iRootObjUserIdx) + "\n";
				}
				edApplet.Script.WBScript.Out(message, true, eds.wbGetLocalString( edApplet.stringTable, "ID_EDA" ), buttonType, this);				
				var j = i + 1;
				// Rebuild the tree and jump out if it is the last item
				if (j == selCount)
				{
					eda.DataViewScript.RefreshView(eda.ProjectViewObj.EnggData,	rootObj);
					return;
				}
				
				continue
			}
			else
			{	
				if (rootObj.Class == eds.id_Material)
				{
					edApplet.ProjectLibrary.removeMaterial(rootObj);
					tempItem[i].Previous ? newSelNode = tempItem[i].Previous : newSelNode = tempItem[i].Next;
					if (!newSelNode)
						newSelNode = materialsNode;
				}
				else if (rootObj.Class == eds.id_Convection)
				{
					edApplet.ProjectLibrary.removeConvection(rootObj);
					tempItem[i].Previous ? newSelNode = tempItem[i].Previous : newSelNode = tempItem[i].Next;
					if (!newSelNode)
						newSelNode = convNode;
				}
				else
				{
					edApplet.ProjectLibrary.removeItem(rootObj);
					if (tempItem[i].Previous == null && tempItem[i].Next == null)
						newSelNode = tempItem[i].Parent;
					else
						tempItem[i].Previous ? newSelNode = tempItem[i].Previous : newSelNode = tempItem[i].Next;
					if (!newSelNode)
						newSelNode = loadNode;	
				}		
			}

			var nodeName = null;	
			if (newSelNode.Tag.dataObj)
				nodeName = newSelNode.Tag.dataObj.Name;
				
			if (newSelNode  == materialsNode)
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eMaterialRoot, ObjectBranch.objMaterialBranchData, nodeName);
			else if (newSelNode == convNode)
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eConvectionRoot, ObjectBranch.objConvectionBranchData, nodeName);
			else if (newSelNode == loadNode)
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eLoadVariationRoot, ObjectBranch.objLoadBranchData, nodeName, newSelNode.Tag.parentFolder);
			else if (newSelNode.Tag.clsType == "Material")
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eMaterialRoot, ObjectBranch.objMaterialBranchData, nodeName);
			else if (newSelNode.Tag.clsType == "Convection")
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eConvectionRoot, ObjectBranch.objConvectionBranchData, nodeName);
			else if (newSelNode.Tag.clsType == "LoadVariation")
				ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eLoadVariationRoot, ObjectBranch.objLoadBranchData, nodeName, newSelNode.Tag.parentFolder);
		
		}	
		/*if (validSelCount > 1)
		{
			eda.ProjectViewObj.EnggData = "kProjectRoot";
			eda.DataViewScript.RefreshView(eda.ProjectViewObj.EnggData, eda.ActiveViewTree.Nodes.Item("kProjectRoot"));	
		}*/
	}
	catch(error)
	{
		//debugger;
	}
}

ProjectTreeObjectScope.prototype.doDuplicateItem = function ( )
{
	try
	{
	   //debugger;
		var newItem = null;

		if (eda.ActiveViewTree.SelectedItem && !eda.ActiveViewTree.SelectedItem.Tag)
			return;

		var selObj = eda.ActiveViewTree.SelectedItem.Tag.dataObj;

		if (selObj.Class == eds.id_Material)
			newItem = edApplet.ProjectLibrary.addMaterial(selObj.Name,true);
		else if (selObj.Class == eds.id_Convection)
			newItem = edApplet.ProjectLibrary.addConvection(selObj.Name,true);
		else if (selObj.Class == eds.id_LoadVariation)
			newItem = edApplet.ProjectLibrary.addLoadVariation(selObj.Name,true);
		else if (selObj.Class == eds.id_BeamSection)
			newItem = edApplet.ProjectLibrary.addBeamSection(selObj.Name,true);

		newItem.Clone(selObj);
		//def-33409 newItem.Source = "";

		if (selObj.Class == eds.id_Material)
			ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eMaterialRoot, ObjectBranch.objMaterialBranchData, newItem.Name);
		else if (selObj.Class == eds.id_Convection)
			ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eConvectionRoot, ObjectBranch.objConvectionBranchData, newItem.Name);
		else if (selObj.Class == eds.id_LoadVariation)
		{
			var lvType = 0;
			var lvDependentType = newItem.Dependents.Item(1).Type;
			if (lvDependentType == 0)
			    lvType = newItem.Type;
			var loadFolder = null;
			for (var nodeIdx = 0; nodeIdx < this.objLoadBranchData.LeafOrder.length; nodeIdx++)
			{
				var curNode = this.objLoadBranchData.LeafOrder[nodeIdx];
				var objDataType = 0;
				for (var dtIdx = 0; dtIdx < curNode.dataType.length; dtIdx++)
				{
					objDataType = curNode.dataType[dtIdx];
					if (objDataType == lvType || objDataType == lvDependentType)
						break;
				}
				if (objDataType == lvType || objDataType == lvDependentType)
				{
					loadFolder = "kProj"+curNode.folderID;
					break;
				}
			}
			ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eLoadVariationRoot, ObjectBranch.objLoadBranchData, newItem.Name, loadFolder);
		}
		else if (selObj.Class == eds.id_BeamSection)
		{
			var dataType = newItem.Type;
			var beamFolder = null;
			for (var nodeIdx = 0; nodeIdx < this.objBeamSectionBranchData.LeafOrder.length; nodeIdx++)
			{
			var curNode = this.objBeamSectionBranchData.LeafOrder[nodeIdx];
			var objDataType = 0;
			for (var dtIdx = 0; dtIdx < curNode.dataType.length; dtIdx++)
			{
				objDataType = curNode.dataType[dtIdx];
				if (objDataType == dataType)
					break;
			}
			if (objDataType == dataType )
			{
				beamFolder = "kProj"+curNode.folderID;
				break;
			}
			}
			ObjectBranch.ProjectTreeAppend(eda.ActiveViewTree, ObjectBranch.eBeamSectionRoot, ObjectBranch.objBeamSectionBranchData, newItem.Name, beamFolder);
		}
	}
	catch(error)
	{
		//debugger;
	}
}

ProjectTreeObjectScope.prototype.doRenameItem = function ( )
{
//debugger;
    try
    {
        eda.ActiveViewTree.StartLabelEdit();
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.doExportToLibrary = function ( )
{
	try
	{
		eds.doExportSelectedItems();
	}
	catch(error)
	{
		//debugger;
	}
}

ProjectTreeObjectScope.prototype.doExportToExistingLibrary = function ( )
{
	try
	{
		eds.doExportSelectedItems(true);
	}
	catch(error)
	{
		//debugger;
	}
}

ProjectTreeObjectScope.prototype.doUpdateLink = function()
{
	try
	{
		var selItem	= eda.ActiveViewTree.FirstSelectedItem;
		if	(!selItem)	return;
		var rootObj	= selItem.Tag.dataObj;
		if	(rootObj == null) return;

		rootObj.Refresh();
		eda.DataViewScript.RefreshView(eda.ProjectViewObj.EnggData,	rootObj);
			//obsolete the ds sovled scenarios -- adr
		/* if ( wb.AppletList.WBApplet("DSApplet").InMemory )
		{
		var ds = wb.AppletList.Applet("DSApplet").App;
				var branches = ds.Tree.Branches;
				if (branches)
				{
					for (var j=1; j <= branches.Count; j++)
					{
						var branch = branches.Item(j);
						if (!branch) continue;
						var paramManager = branch.ParameterSet;
						paramManager.ChangeStatus(eds.wbGetLocalString( eds.stringTable, "ID_Obsolete"), "", "");
						paramManager = null;
					}
				}
			}*/
	}
	catch(error)
	{
	//debugger;
	}
}

ProjectTreeObjectScope.prototype.doExportSelectionToLibrary = function ( )
{
    try
    {
         eds.doExportSelectedItems();
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.doExportSelectionToExistingLibrary = function ( )
{
    try
    {
         eds.doExportSelectedItems(true);
    }
    catch(error)
    {
        //debugger;
    }
}

function ProjectTreeObjectScope.prototype.ProjectTreeAppend( objProjectTree, branchIdx, objBranchData, selectNode, buildFolder )
{
	//debugger;
    eds.beginWaitCursor();
    try
    {
        try
        {
            if (buildFolder == null)
            {
               for (var nodeIdx = 0; nodeIdx < objBranchData.LeafOrder.length; nodeIdx++)
               {
                  var curNode = objBranchData.LeafOrder[nodeIdx];
                  curNode.treeNode = null;
                  //curNode.numChildren = 0;
               }
               var notPresent = objProjectTree.Nodes.Item(objBranchData.TreeTagID+"Root");
               objProjectTree.Nodes.Remove(objBranchData.TreeTagID+"Root");
            }
            else
            {
               var notPresent = objProjectTree.Nodes.Item(buildFolder);
               objProjectTree.Nodes.Remove(buildFolder);
            }
        }
        catch(e)
        {
        }
        var proj = eds.wbGetLocalString( eds.stringTable, objBranchData.NameStringID);
        proj += " (" + objBranchData.Contents.Count + ")";

        var thisRoot = eda.BranchOrder[branchIdx];
        if (buildFolder == null)
        {
            // Maintain the position of the folder in the tree
            var prevRoot = null;
            var nextRoot = null;
            if (eda.BranchOrder[branchIdx-1])
               prevRoot = eda.BranchOrder[branchIdx-1].folderObj;
            if (eda.BranchOrder[branchIdx+1])
               nextRoot = eda.BranchOrder[branchIdx+1].folderObj;
            if (prevRoot)
                  thisRoot.folderObj = objProjectTree.Nodes.Add(prevRoot.key, TVW_Next, objBranchData.TreeTagID+"Root", proj, "folderopen", "folderopen");
            else if (nextRoot)
                  thisRoot.folderObj = objProjectTree.Nodes.Add(nextRoot.key, TVW_Previous, objBranchData.TreeTagID+"Root", proj, "folderopen", "folderopen");
            else
                  thisRoot.folderObj = objProjectTree.Nodes.Add(eda.ProjectRoot.key, TVW_Child, objBranchData.TreeTagID+"Root", proj, "folderopen", "folderopen");

            thisRoot.folderObj.Tag = thisRoot;
        }
        else
        {
            thisRoot.folderObj.Text = proj;
        }

        // Place the contents into an array so that it can be sorted to display alphabetically
        var sortArr = [];
        for (var i=1; i <= objBranchData.Contents.Count; i++)
        {
            var beam = objBranchData.Contents.Item(i);
            var obj = { text:beam.Name, node:beam};
            sortArr.push(obj);
        }
        ArrayAlphaCompare = function (one,two)
        {
            return (one.text < two.text) ? -1 : (one.text > two.text) ? 1 : 0;
        }
        sortArr.sort(ArrayAlphaCompare);
        
        if (objBranchData.LeafOrder.length == 0)
        {
            for (var i=0; i < sortArr.length; i++)
            {
                  var beam = sortArr[i].node;
                  var beamNode = EDAProjectView.Nodes.Add(thisRoot.folderObj.key, TVW_Child,objBranchData.TreeTagID+"_"+beam.ID, beam.Name);
                  var objTag = {folder:objBranchData.TreeTagID, parentFolder:objBranchData.TreeTagID+"Root", clsType:thisRoot.clsType, dataType:null, dataObj:beam, treeName:beamNode.Text};
                  objTag.treeName = beamNode.Text;
                  objTag.parentFolder = thisRoot.folder;

                  var icon = eds.AddImage(objBranchData.Icon);
                  if (icon)
                  {
                     beamNode.Image = icon;
                     beamNode.SelectedImage = icon;
                  }
                  beamNode.Tag = objTag;

                  ProjectTree.ChangeState(beamNode);
            }

        }
        else 
        {
            // Create sub-folders to hold each content type
            for (var nodeIdx = 0; nodeIdx < objBranchData.LeafOrder.length; nodeIdx++)
            {
               var curNode = objBranchData.LeafOrder[nodeIdx];
               var nxtNode = null;
               // Does this folder already exist because of grouping various types into a single folder
               var childFolder = thisRoot.folderObj.Child;
               for (var childIdx = 0; childIdx < thisRoot.folderObj.Children; childIdx++)
               {
                  if (childFolder.Key == "kProj"+curNode.folderID)
                     break;
                  childFolder = childFolder.Next;
               }
               if (childFolder == null)
               {
                  for (var nxtNodeIdx = nodeIdx + 1; nxtNodeIdx < objBranchData.LeafOrder.length; nxtNodeIdx++)
                  {
                     // Find the next available folder in the tree
                     nxtNode = objBranchData.LeafOrder[nxtNodeIdx];
                     if (nxtNode && nxtNode.treeNode != curNode.treeNode)
                        break;
                     nxtNode = null;
                  }
                  var bsFolderName = eds.wbGetLocalString( eds.stringTable, "ID_"+curNode.folderID);
                  if  (buildFolder == null || buildFolder == "kProj"+curNode.folderID)
                  {
                     if (typeof(nxtNode) != "undefined" && nxtNode && nxtNode.treeNode)
                     {
                        // Insert this folder before the next in the order
                        curNode.treeNode = objProjectTree.Nodes.Add(nxtNode.treeNode.key, TVW_Previous, "kProj"+curNode.folderID, bsFolderName, "folderopen", "folderopen");
                     }
                     else
                     {
                        // Place this folder at the end of the tree
                        curNode.treeNode = objProjectTree.Nodes.Add(thisRoot.folderObj.key, TVW_Child, "kProj"+curNode.folderID, bsFolderName, "folderopen", "folderopen");
                     }
                      curNode.treeNode.Tag = {folder:objBranchData.TreeTagID+"Root", parentFolder: "kProj"+curNode.folderID, clsType:thisRoot.clsType, dataType:curNode.dataType, dataObj:null, treeName:curNode.treeNode.Text};
                      curNode.treeNode.Text += " (0)";
                    
                  }
               }
               else
               {
                  curNode.treeNode = childFolder;
               }
            }
            var buildBeamType = null;
            for (var nodeIdx = 0; nodeIdx < objBranchData.LeafOrder.length; nodeIdx++)
            {
               var curNode = objBranchData.LeafOrder[nodeIdx];
               if ("kProj"+curNode.folderID == buildFolder)
               {
                  buildBeamType = curNode.dataType;
                  break;
               }
            }

         // Must use this form for IE < 5.5 to work
         for (var i=0; i < sortArr.length; i++)
         {
               var objVarData = sortArr[i].node;
               var VarDataType = 0;
               var VarDataDependentType = 0;
               // The dataType that is used for the LeafOrder is the variable type not the variabledata type
               if (objVarData.Dependents)
                  VarDataDependentType = objVarData.Dependents.Item(1).Type;
               else
                  VarDataType = objVarData.Type;
                  

               // Don't attempt to build those folders that are already present
               if (buildBeamType)
               {
                  var objDataType = 0;
                  for (var dtIdx = 0; dtIdx < buildBeamType.length; dtIdx++)
                  {
                     objDataType = buildBeamType[dtIdx];
                     if (objDataType == VarDataType || objDataType == VarDataDependentType)
                        break;
                  }
                  if (objDataType != VarDataType && objDataType != VarDataDependentType)
                     continue;
               }
               var objTag = {folder:objBranchData.TreeTagID, parentFolder:null, clsType:thisRoot.clsType, dataType:null, dataObj:objVarData, treeName:""};
               var beamNode = null;   
               for (var nodeIdx = 0; nodeIdx < objBranchData.LeafOrder.length; nodeIdx++)
               {
                  var curNode = objBranchData.LeafOrder[nodeIdx];
                  var objDataType = 0;
                  for (var dtIdx = 0; dtIdx < curNode.dataType.length; dtIdx++)
                  {
                     objDataType = curNode.dataType[dtIdx];
                     if (objDataType == VarDataType || objDataType == VarDataDependentType)
                        break;
                  }
                  if (objDataType == VarDataType || objDataType == VarDataDependentType )
                  {
                     var bsFolderName = eds.wbGetLocalString( eds.stringTable, "ID_"+curNode.folderID);
                     beamNode = EDAProjectView.Nodes.Add(curNode.treeNode.key, TVW_Child,"kProj"+curNode.folderID+objVarData.ID, objVarData.Name);
                     objTag.treeName = beamNode.Text;
                     objTag.parentFolder = "kProj"+curNode.folderID;
                     curNode.treeNode.Text = bsFolderName + " ("+ curNode.treeNode.Children + ")";
                     break;
                  }
               }
               var icon = eds.AddImage(curNode.icon);
               if (icon)
               {
                  beamNode.Image = icon;
                  beamNode.SelectedImage = icon;
               }
               beamNode.Tag = objTag;

               ProjectTree.ChangeState(beamNode);
         }
         if (hideZeroSizeFolders)
         {
            for (var nodeIdx = 0; nodeIdx < objBranchData.LeafOrder.length; nodeIdx++)
            {
               var curNode = objBranchData.LeafOrder[nodeIdx];

               // Does this folder exist because of grouping various types into a single folder
               var childFolder = thisRoot.folderObj.Child;
               for (var childIdx = 0; childIdx < thisRoot.folderObj.Children; childIdx++)
               {
                  if (childFolder.Key == "kProj"+curNode.folderID)
                     break;
                  childFolder = childFolder.Next;
               }
               if (childFolder && curNode.treeNode.Children == 0)
               {
                  // Remove this folder
                  if (curNode.treeNode)
                     objProjectTree.Nodes.Remove("kProj"+curNode.folderID);
                  curNode.treeNode = null;
               }
               else if (childFolder == null)
               {
                  curNode.treeNode = null;
               }
            }
         }
      }
      
      eda.ProjectRoot.Expanded = true;
		if (selectNode)
		{
			node = ProjectTree.findNodeByName(selectNode);
			if (node != null)
			{
				var category = ProjectTree.findCategory( node );
				if (category == objBranchData.TreeTagID || category == "kProjBeamSection" || category == "kProjLoadRoot")
				{
					ProjectTree.SelectNode( node );
				}
			}
		}
		//debugger;
		if (thisRoot.folderObj.Child)
		{
			var length = thisRoot.folderObj.Children;
			var obj = thisRoot.folderObj.Child;
			for (var idx = 0; idx < length; idx++)
			{
				for (var i = 0; i < objBranchData.LeafOrder.length; i++)
				{
					if (obj == objBranchData.LeafOrder[i].treeNode)
					{
						obj.Expanded = objBranchData.LeafOrder[i].FolderOpen;
						if (obj.Expanded == false)
						{
							obj.Image = "folderclosed";
							obj.SelectedImage = "folderclosed";
						}
						else
						{
							obj.Image = "folderopen";
							obj.SelectedImage = "folderopen";
						}	
					}		
				}
				obj = obj.Next;
			}
		}
		
      thisRoot.folderObj.Expanded = objBranchData.FolderOpen;
      if (thisRoot.folderObj.Expanded == false)
      {
			thisRoot.folderObj.Image = "folderclosed";
			thisRoot.folderObj.SelectedImage = "folderclosed";
	  }
	  else
	  {
			thisRoot.folderObj.Image = "folderopen";
			thisRoot.folderObj.SelectedImage = "folderopen";
	  }
		
   }
   catch (error)
   {
      debugger;
   }
   eds.endWaitCursor();
}

ProjectTreeObjectScope.prototype.isValidSource = function ( obj )
{
    try
    {
        if (!obj)
        {
            var selCount = eda.ActiveViewTree.SelectedCount;
            if (!selCount)
                return false;

            var item = eda.ActiveViewTree.FirstSelectedItem;
            if (!item)
                return false;

            for (var selIdx=1; selIdx <= selCount; selIdx++)
            {
                if (!item)
                    continue;

                var obj = item.Tag.dataObj;
                
               if (!obj.DataInSource)
                     return false;

			      if (obj.Class == eds.id_Material)
               {
				      if (!eds.ValidateSource("MaterialData",obj.source))
					      return false;
			      }
			      else if (obj.Class == eds.id_Convection)
			      {
				      if (!eds.ValidateSource("ConvectionData",obj.source))
						      return false;
			      }
			      else if (obj.Class == eds.id_LoadVariation)
			      {
				      if (!eds.ValidateSource("LoadVariationData",obj.source))
					      return false;
			      }
			      else if (obj.Class == eds.id_BeamSection)
			      {
				      if (!eds.ValidateSource("BeamSectionData",obj.source))
					      return false;
			      }

                item = item.NextSelected;
            }
        }
        else
        {
         if (!obj.DataInSource)
               return false;
               
			if (obj.Class == eds.id_Material)
         {
				if (!eds.ValidateSource("MaterialData",obj.source))
					return false;
			}
			else if (obj.Class == eds.id_Convection)
			{
				if (!eds.ValidateSource("ConvectionData",obj.source))
						return false;
			}
			else if (obj.Class == eds.id_LoadVariation)
			{
				if (!eds.ValidateSource("LoadVariationData",obj.source))
					return false;
			}
			else if (obj.Class == eds.id_BeamSection)
			{
				if (!eds.ValidateSource("BeamSectionData",obj.source))
					return false;
			}

        }
        return true;
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.isDefaultItem = function ( rootObj )
{
    try
    {
        if (!rootObj)
        {
            if (!eda.ActiveViewTree.SelectedItem)
            {
                return false;
            }
            rootObj = eda.ActiveViewTree.SelectedItem.Tag.dataObj;
        }

        // The default material should already be set in the library
		   if (rootObj.Class == eds.id_Material)
		   {
            var defaultMaterial = edApplet.ProjectLibrary.DefaultMaterial;
            if (defaultMaterial && (rootObj == defaultMaterial)) return true;
		   }
		   else if (rootObj.Class == eds.id_Convection)
		   {
            var defaultConvection = edApplet.ProjectLibrary.DefaultConvection;
            if (defaultConvection && (rootObj == defaultConvection)) return true;
		   }
		   else if (rootObj.Class == eds.id_LoadVariation)
		   {
		   }
        return false;
    }
    catch(error)
    {
        return false;
    }
}

ProjectTreeScope.prototype.ChangeState = function(node)
{
//	debugger;
	if (!node || !node.Image || !node.Tag)	return;
	var obj = node.Tag.dataObj;
	if (obj == null)
	   return;
	var bitmap;

	var state = obj.State;
	if (obj.Class == eds.id_Material)
	{
		if (state == 1)		//	underdefined
			bitmap = "MaterialUnderdefined";
		else if (state == 2)	//state defined
			bitmap = "material";
		else if (state == 3)	//invalid
			bitmap = "MaterialUnderdefined";


	}
	else if (obj.Class == eds.id_LoadVariation 
	      && obj.PrimaryIndependent.Type == eda.LoadVariationVarEnums.kLoadVariationVariableTemperature)
	{
		if (state == 1)		//	underdefined
			bitmap = "convectionunderdefined";
		else if (state == 2)	//state defined
			bitmap = "convection";
		else if (state == 3)	//invalid
			bitmap = "convectionunderdefined";
	}
	else if (obj.Class == eds.id_LoadVariation)
	{
		if (state == 1)		//	underdefined
			bitmap = "edLoadVariationUnderdefined";
		else if (state == 2)	//state defined
			bitmap = "edLoadVariation";
		else if (state == 3)	//invalid
			bitmap = "edLoadVariationUnderdefined";
	}
	else if (obj.Class == eds.id_BeamSection)
	{
		if (state == 1)		//	underdefined
			bitmap = "edBeamUnderdefined";
		else if (state == 2)	//state defined
			bitmap = "edBeam";
		else if (state == 3)	//invalid
			bitmap = "edBeamUnderdefined";
	}
	else
	{
	   return;
	}
	var validSource = ObjectBranch.isValidSource(obj)
	var newBitmap;
	
	var is_Locked;
	if (obj.isLockedBy.Count == 0)
		is_Locked = false;
	else
		is_Locked = true;
	if (validSource)
	{
      if (!obj.DataMatchesSource)
	      newBitmap = eds.MergeBitmaps(bitmap,eds.bitmapStateArray[eds.id_OutOfSync],is_Locked);
      else
	      newBitmap = eds.MergeBitmaps(bitmap,eds.bitmapStateArray[eds.id_InSync],is_Locked);
	}
	else
	{
	   newBitmap = eds.MergeBitmaps(bitmap,eds.bitmapStateArray[eds.id_Stateless],is_Locked);
	}

	if( newBitmap != "" )
	{
		node.Image			= newBitmap;
		node.SelectedImage	= newBitmap;
	}
}




ProjectTreeObjectScope.prototype.doSetDefault = function ( )
{
    try
    {
        var selectedItem = eda.ActiveViewTree.SelectedItem;
        if (!selectedItem)
            return false;

         var selObj = selectedItem.Tag.dataObj;

		   if (selObj.Class == eds.id_Material)
		   {
		      ObjectBranch.doSetDefaultMaterial(selectedItem);
		   }
		   else if (selObj.Class == eds.id_Convection)
		   {
		      ObjectBranch.doSetDefaultConvection(selectedItem);
		   }
		   else if (selObj.Class == eds.id_LoadVariation)
		   {
		      // NA
		   }

    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.doSetDefaultMaterial = function ( selectedItem )
{
    try
    {
        if (!ObjectBranch.isDefaultItem())
        {
            // Switch the default material value in the preference file
            var prefMgr = wb.PreferenceMgr;
            var pref = prefMgr.PreferenceItem("PID_EDAMaterialDefault");
            if (pref)
            {
                var node = ProjectTree.findNodeByName(pref.Value);
                if(node)
                    node.Bold = false;

                var matl = selectedItem.Tag.dataObj;
                pref.Value = matl.NameInSource;
                pref.Source = matl.Source;
                prefMgr.Save();
                var infoMsg = "";
                if (matl.Dirty)
                {
                   infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_DefaultNoteBadLink", matl.Name) + "\n\n";
	        }

                infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_DefaultNoteGoodLink", matl.NameInSource, matl.Source);

                infoMsg += "  " + eds.wbGetLocalString( eds.stringTable, "ID_DefaultNoteUsedLink");
                eds.wbWarningMsgBox(infoMsg, eds.wbGetLocalString( eds.stringTable, "ID_EDA"));

                //selectedItem.Bold = true;
                edApplet.ProjectLibrary.DefaultMaterial = matl;
            }

        }
    }
    catch(error)
    {
        //debugger;
    }
}
ProjectTreeObjectScope.prototype.doSetDefaultConvection = function (selectedItem)
{
   try
    {
        if (!ObjectBranch.isDefaultItem())
        {
            // Switch the default convection value in the preference file
            var prefMgr = wb.PreferenceMgr;
            var pref = prefMgr.PreferenceItem("PID_EDAConvectionDefault");
            if (pref)
            {
                var node = ProjectTree.findNodeByName(pref.Value);
                if(node)
                    node.Bold = false;

                conv = selectedItem.Tag.dataObj;
                pref.Value = conv.NameInSource;
                pref.Source = conv.Source;
                prefMgr.Save();
                var infoMsg = "";
                if (conv.Dirty)
                {
                   infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_DefaultNoteBadLink", conv.Name) + "\n\n";
	        }
                infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_DefaultNoteGoodLink", conv.NameInSource, conv.Source );
                infoMsg += "  " + eds.wbGetLocalString( eds.stringTable, "ID_DefaultNoteUsedLink", conv.NameInSource, conv.Source );
                eds.wbWarningMsgBox(infoMsg, eds.wbGetLocalString( eds.stringTable, "ID_EDA"));

               // selectedItem.Bold = true;
                edApplet.ProjectLibrary.DefaultConvection = conv;
            }
         }
    }
    catch(error)
    {
        //debugger;
    }
}

ProjectTreeObjectScope.prototype.isAlwaysAvailable = function ( rootObj )
{
    try
    {
        if (!rootObj)
        {
            if (!eda.ActiveViewTree.SelectedItem)
            {
                return false;
            }
            rootObj = eda.ActiveViewTree.SelectedItem.Tag.dataObj;
        }

		   if (rootObj.Class == eds.id_Material)
		   {
		      return ObjectBranch.isAlwaysAvailableMaterial(rootObj);
		   }
		   else if (rootObj.Class == eds.id_Convection)
		   {
		      return ObjectBranch.isAlwaysAvailableConvection(rootObj);
		   }
		   else if (rootObj.Class == eds.id_LoadVariation)
		   {
		      return ObjectBranch.isAlwaysAvailableLoadVariation(rootObj);
		   }
    }
    catch(error)
    {
        return false;
    }
}

ProjectTreeObjectScope.prototype.doAlwaysAvailable = function ( )
{
    try
    {
        var selCount = eda.ActiveViewTree.SelectedCount;
        if (!selCount)
        {
            return false;
        }

        var item = eda.ActiveViewTree.FirstSelectedItem;
        if (!item)
        {
            return false;
        }

        for (var selIdx=1; selIdx <= selCount; selIdx++)
        {
            if (!item)
                continue;

            var rootObj = item.Tag.dataObj;

		      if (rootObj.Class == eds.id_Material)
		      {
		         ObjectBranch.doAlwaysAvailableMaterial(rootObj);
		      }
		      else if (rootObj.Class == eds.id_Convection)
		      {
		         ObjectBranch.doAlwaysAvailableConvection(rootObj);
		      }
		      else if (rootObj.Class == eds.id_LoadVariation)
		      {
		         ObjectBranch.doAlwaysAvailableLoadVariation(rootObj);
		      }

            item = item.NextSelected;
        }
    }
    catch(error)
    {
        debugger;
    }
}

ProjectTreeObjectScope.prototype.isAlwaysAvailableMaterial = function ( matl )
{
    try
    {

        var pidAlwaysAvailable = new String("PID_EDAMaterialDefaults");
        var alwaysAvailable = wb.PreferenceMgr.Preferences(pidAlwaysAvailable);

        for (var i=1; i <= alwaysAvailable.Count; i++)
        {
            var prefItem = alwaysAvailable.Item(i);
            // Do the names match
            var prefName = prefItem.Value;
            var epc1=10;
            var itemName = matl.NameInSource;
            if (prefName != itemName)
                continue;

            // Do the sources match
            var prefSource = prefItem.Source;
            var itemSource = matl.Source;
            if (prefSource == itemSource)
                return true;
        }
        return false;
    }
    catch(error)
    {
        return false;
    }
}

ProjectTreeObjectScope.prototype.doAlwaysAvailableMaterial = function ( matl )
{
    try
    {
            // Add the new material source to the preference file
            var prefMgr = wb.PreferenceMgr;
            var prefCats = wb.PreferenceMgr.PreferencesCategories
            var prefCat = null;

            // Search for ED Applet
            for (var i = 1; i <= prefCats.Count; i++)
            {
                prefCat = prefCats.Item(i);
                if (prefCat.Name == "CATNAME_EDA")
                    break;
                prefCat = null;
            }
            if (!prefCat) return false;

            // Search for Material Data Group
            var prefGroups = prefCat.PreferencesGroups
            var prefGroup = null;
            for (var i = 1; i <= prefGroups.Count; i++)
            {
                prefGroup = prefGroups.Item(i);
                if (prefGroup.NonTranslatableName == "EDA_MaterialData")
                    break;
                prefGroup = null;
            }
            if (!prefGroup) return false;

            // Search for Material Sources
            var prefPreferences = prefGroup.Preferences
            var prefPreference = null;
            for (var i = 1; i <= prefPreferences.Count; i++)
            {
                prefPreference = prefPreferences.Item(i);
                if (prefPreference.PreferenceID == "PID_EDAMaterialDefaults")
                    break;
                prefPreference = null;
            }

            if (ObjectBranch.isAlwaysAvailable(matl))
            {
                // Remove this item from the preferences
                for (var i = 1; i <= prefPreferences.Count; i++)
                {
                    pref = prefPreferences.Item(i);
                    if (pref.PreferenceID == "PID_EDAMaterialDefaults")
                    {
                        if (pref.Value != matl.NameInSource) continue;
                        if (pref.Source == matl.Source) break;
                    }
                    pref = null;
                }
                if (pref)
                {
                    prefPreferences.Remove(i);
                    wb.PreferenceMgr.Save();
                }
            }
            else
            {
                /*
                if (!prefPreference)
                {
                var pref = prefGroup.Add();
                prefGroup.Name = eds.wbGetLocalString( eds.stringTable, "ID_PrefMaterialData");
                prefGroup.NonTranslatableName = eds.wbGetLocalString( eds.stringTable, "ID_PrefMaterialGroup");
                }
                */
                // Add this item to the preferences
                var pref	= prefPreferences.Add();

                pref.NonTranslatableName = eds.wbGetLocalString( eds.stringTable, "ID_PrefMaterialDefaults");
                pref.Name = eds.wbGetLocalString( eds.stringTable, "ID_PrefMaterial");
                pref.GroupName = eds.wbGetLocalString( eds.stringTable, "ID_PrefMaterialData");

                pref.PreferenceID = "PID_EDAMaterialDefaults";
                pref.PreferenceType = 2;
                pref.GroupTitle = eds.wbGetLocalString( eds.stringTable, "ID_PrefMaterialDefaultsTitle");
                pref.Value = matl.NameInSource;
                pref.Source = matl.Source;
                wb.PreferenceMgr.Save();

                var infoMsg = "";
                if (matl.Dirty)
                {
                   infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_FavoriteNoteBadLink", matl.Name) + "\n\n";
	        }
                infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_FavoriteNoteGoodLink", matl.NameInSource, matl.Source );
                infoMsg += "  " + eds.wbGetLocalString( eds.stringTable, "ID_FavoriteNoteUsedLink", matl.NameInSource, matl.Source );
                eds.wbWarningMsgBox(infoMsg, eds.wbGetLocalString( eds.stringTable, "ID_FavoriteAdded"));
            }
    }
    catch(error)
    {
        debugger;
    }
}

ProjectTreeObjectScope.prototype.doAlwaysAvailableConvection = function ( conv )
{
    try
    {
            // Add the new material source to the preference file
            var prefMgr = wb.PreferenceMgr;
            var prefCats = wb.PreferenceMgr.PreferencesCategories
            var prefCat = null;

            // Search for ED Applet
            for (var i = 1; i <= prefCats.Count; i++)
            {
                prefCat = prefCats.Item(i);
                if (prefCat.Name == "CATNAME_EDA")
                    break;

                prefCat = null;
            }
            if (!prefCat)
                return false;

            // Search for Convection Data Group
            var prefGroups = prefCat.PreferencesGroups
            var prefGroup = null;
            for (var i = 1; i <= prefGroups.Count; i++)
            {
                prefGroup = prefGroups.Item(i);
                if (prefGroup.NonTranslatableName == "EDA_ConvectionData")
                    break;

                prefGroup = null;
            }
            if (!prefGroup)
                return false;

            // Search for Convection Sources
            var prefPreferences = prefGroup.Preferences
            var prefPreference = null;
            for (var i = 1; i <= prefPreferences.Count; i++)
            {
                prefPreference = prefPreferences.Item(i);
                if (prefPreference.PreferenceID == "PID_EDAConvectionDefaults")
                    break;

                prefPreference = null;
            }

            if (ObjectBranch.isAlwaysAvailable(conv))
            {
                // Remove this item from the preferences
                for (var i = 1; i <= prefPreferences.Count; i++)
                {
                    pref = prefPreferences.Item(i);
                    if (pref.PreferenceID == "PID_EDAConvectionDefaults")
                    {
                        if (pref.Value != conv.NameInSource) continue;
                        if (pref.Source == conv.Source) break;
                    }
                    pref = null;
                }
                if (pref)
                {
                    prefPreferences.Remove(i);
                    wb.PreferenceMgr.Save();
                }
            }
            else
            {
                /*
                if (!prefPreference)
                {
                    var pref = prefGroup.Add();
                    prefGroup.Name = eds.wbGetLocalString( eds.stringTable, "ID_PrefConvectionData");
                    prefGroup.NonTranslatableName = eds.wbGetLocalString( eds.stringTable, "ID_PrefConvectionGroup");
                }
                */
                // Add this item to the preferences
                var pref = prefPreferences.Add();
                pref.NonTranslatableName = eds.wbGetLocalString( eds.stringTable, "ID_PrefConvectionDefaults");
                pref.Name = eds.wbGetLocalString( eds.stringTable, "ID_PrefConvection");
                pref.GroupName = eds.wbGetLocalString( eds.stringTable, "ID_PrefConvectionData");

                pref.PreferenceID = "PID_EDAConvectionDefaults";
                pref.PreferenceType = 2;
                pref.GroupTitle = eds.wbGetLocalString( eds.stringTable, "ID_PrefConvectionDefaultsTitle");
                pref.Value = conv.NameInSource;
                pref.Source = conv.Source;
                wb.PreferenceMgr.Save();

               var infoMsg = "";
               if (conv.Dirty)
               {
                  infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_FavoriteNoteBadLink", conv.Name) + "\n\n";
	       }
               infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_FavoriteNoteGoodLink", conv.NameInSource, conv.Source );
               infoMsg += "  " + eds.wbGetLocalString( eds.stringTable, "ID_FavoriteNoteUsedLink", conv.NameInSource, conv.Source );
               eds.wbWarningMsgBox(infoMsg, eds.wbGetLocalString( eds.stringTable, "ID_FavoriteAdded"));
            }
    }
    catch(error)
    {
        debugger;
    }
}

ProjectTreeObjectScope.prototype.isAlwaysAvailableConvection = function ( matl )
{
    try
    {
      var pidAlwaysAvailable = new String("PID_EDAConvectionDefaults");
      var alwaysAvailable = wb.PreferenceMgr.Preferences(pidAlwaysAvailable);

      for (var i=1; i <= alwaysAvailable.Count; i++)
      {
         var prefItem = alwaysAvailable.Item(i);
         // Do the names match
         var prefName = prefItem.Value;
			var itemName = matl.NameInSource;
			if (prefName != itemName) continue;
         // Do the sources match
         var prefSource = prefItem.Source;
         var itemSource = matl.Source;
         if (prefSource == itemSource) return true;
      }
      return false;
   }
   catch(error)
   {
      return false;
   }
}

ProjectTreeObjectScope.prototype.doAlwaysAvailableLoadVariation = function ( conv )
{
    try
    {
            // Add the new material source to the preference file
            var prefMgr = wb.PreferenceMgr;
            var prefCats = wb.PreferenceMgr.PreferencesCategories
            var prefCat = null;

            // Search for ED Applet
            for (var i = 1; i <= prefCats.Count; i++)
            {
                prefCat = prefCats.Item(i);
                if (prefCat.Name == "CATNAME_EDA")
                    break;

                prefCat = null;
            }
            if (!prefCat)
                return false;

            // Search for LoadVariation Data Group
            var prefGroups = prefCat.PreferencesGroups
            var prefGroup = null;
            for (var i = 1; i <= prefGroups.Count; i++)
            {
                prefGroup = prefGroups.Item(i);
                if (prefGroup.NonTranslatableName == "EDA_LoadVariationData")
                    break;

                prefGroup = null;
            }
            if (!prefGroup)
                return false;

            // Search for LoadVariation Sources
            var prefPreferences = prefGroup.Preferences
            var prefPreference = null;
            for (var i = 1; i <= prefPreferences.Count; i++)
            {
                prefPreference = prefPreferences.Item(i);
                if (prefPreference.PreferenceID == "PID_EDALoadVariationDefaults")
                    break;

                prefPreference = null;
            }

            if (ObjectBranch.isAlwaysAvailable(conv))
            {
                // Remove this item from the preferences
                for (var i = 1; i <= prefPreferences.Count; i++)
                {
                    pref = prefPreferences.Item(i);
                    if (pref.PreferenceID == "PID_EDALoadVariationDefaults")
                    {
                        if (pref.Value != conv.NameInSource) continue;
                        if (pref.Source == conv.Source) break;
                    }
                    pref = null;
                }
                if (pref)
                {
                    prefPreferences.Remove(i);
                    wb.PreferenceMgr.Save();
                }
            }
            else
            {
                /*
                if (!prefPreference)
                {
                    var pref = prefGroup.Add();
                    prefGroup.Name = eds.wbGetLocalString( eds.stringTable, "ID_PrefLoadVariationData");
                    prefGroup.NonTranslatableName = eds.wbGetLocalString( eds.stringTable, "ID_PrefLoadVariationGroup");
                }
                */
                // Add this item to the preferences
                var pref = prefPreferences.Add();
                pref.NonTranslatableName = eds.wbGetLocalString( eds.stringTable, "ID_PrefLoadVariationDefaults");
                pref.Name = eds.wbGetLocalString( eds.stringTable, "ID_PrefLoadVariation");
                pref.GroupName = eds.wbGetLocalString( eds.stringTable, "ID_PrefLoadVariationData");

                pref.PreferenceID = "PID_EDALoadVariationDefaults";
                pref.PreferenceType = 2;
                pref.GroupTitle = eds.wbGetLocalString( eds.stringTable, "ID_PrefLoadVariationDefaultsTitle");
                pref.Value = conv.NameInSource;
                pref.Source = conv.Source;
                wb.PreferenceMgr.Save();

               var infoMsg = "";
               if (conv.Dirty)
               {
                  infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_FavoriteNoteBadLink", conv.Name) + "\n\n";
	       }
               infoMsg += eds.wbGetLocalFillString( eds.stringTable, "ID_FavoriteNoteGoodLink", conv.NameInSource, conv.Source );
               infoMsg += "  " + eds.wbGetLocalString( eds.stringTable, "ID_FavoriteNoteUsedLink", conv.NameInSource, conv.Source );
               eds.wbWarningMsgBox(infoMsg, eds.wbGetLocalString( eds.stringTable, "ID_FavoriteAdded"));
            }
    }
    catch(error)
    {
        debugger;
    }
}

ProjectTreeObjectScope.prototype.isAlwaysAvailableLoadVariation = function ( matl )
{
    try
    {
      var pidAlwaysAvailable = new String("PID_EDALoadVariationDefaults");
      var alwaysAvailable = wb.PreferenceMgr.Preferences(pidAlwaysAvailable);

      for (var i=1; i <= alwaysAvailable.Count; i++)
      {
         var prefItem = alwaysAvailable.Item(i);
         // Do the names match
         var prefName = prefItem.Value;
			var itemName = matl.NameInSource;
			if (prefName != itemName) continue;
         // Do the sources match
         var prefSource = prefItem.Source;
         var itemSource = matl.Source;
         if (prefSource == itemSource) return true;
      }
      return false;
   }
   catch(error)
   {
      return false;
   }
}
