r stage 3.
//
//  STAGE 2
//  ProcessWorksheets() loads the first worksheet encountered in stage 1 into a web browser hidden behind the wait screen (Generator.htm).
//  Because worksheets load asynchronously generator execution ends until a callback is received.
//  Each worksheet calls CheckIfWorksheetInReport() (see DSMainScript.js) as the last operation in its load procedure.
//  That function calls WorksheetLoaded() below only if the report tab is active.
//  WorksheetLoaded() extracts information from the worksheet and returns control to ProcessWorksheets().
//  With all worksheets handled the function calls ComposeEngineeringData() to begin stage 3.
//
//  STAGE 3
//  See EngineeringData.js for code and comments related to generating report content from the ED applet.
//  The process is similar in approach to stage 2.
//  When complete, WrapUp() below is called to write the files and configure DS to display the report.
//
function window.onload()
{
//  Pause to allow wait screen to appear
    window.setTimeout(GenerateReport, 1);
}
function GenerateReport()
{
    try
    {
		SetGlobalVariables();
		GetPreferences();
		CreateDestinationFolders();
		LoadStrings();
		LoadRules();
		graphics.Info(3) = 1;	// inform graphics that report generation has started
		graphics.MemStreamWidth = graphicsFigureWidth * resolutionMultiplier;
		graphics.MemStreamHeight = graphicsFigureHeight * resolutionMultiplier;
		graphics.StreamMode = 1;
		LoadTemplate();
		InsertCoverPage();
		InsertUnits();

		var transactionId = ds.GenerateNewTransactionId();
		ds.UserTransactionStarted(transactionId);
		ComposeTable(project.Child, toc, null, null);
		ds.UserTransactionEnded(transactionId)
		CheckReportState();
		try
		{
			ProcessWorksheets();
		}
		catch(e)
		{
		}
	}
	catch(e)
	{
	}
	finally
	{
		graphics.StreamMode = 0;
		graphics.Info(3) = 0;	// inform graphics that report generation has ended
	}
}

function SetGlobalVariables()
{
	wb = window.external;
	ds = wb.AppletList.Applet("DSApplet").App;
    graphics = ds.Graphics;
	script = ds.Script;
	stringtable = ds.StringTable;
    outline = script.tv;
    details = script.lv;
    tabularData = script.dataGrid;
    nodes = outline.Nodes;
    project = nodes.Item(1);
    imageNumber = 0;
    materialsArray = [];

	//empty the figures array in case the user has already generated the report
//	for (var i=script.reportFiguresArray.length; i>0; i--)
//	    script.reportFiguresArray.pop();

    filesToCopy = [];
    doctype = "<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>";
    firstStateProblemID = null;
    worksheetsArray = [];
    worksheetsIndex = 0;
    worksheetFolder = script.installDirNoLocale + "html" + script.str_PathSeparator;
    kChartReportTabularDataOnly = 1;
    kChartReportChartOnly = 2;
    kChartReportChartAndTabularData	=3;
    kChartReportNone = 4;
    
    treeRoot = ds.Tree;
    if (treeRoot != null)
    {
        treeRoot.SelectingObjects = false;
		script.disableTabs(treeRoot.SelectingObjects);
		if (ds.GUIState)
			ds.GUIState.TreeObjectSelection = treeRoot.SelectingObjects;      
    }
}

function GetPreferences()
{
   try { maxColumns = Math.max(2, wb.PreferenceMgr.Preference("PID_Report_Max_Table_Columns")); }
   catch(e){ maxColumns = 6; }
   try { mergeTableCells = wb.PreferenceMgr.Preference("PID_Report_Merge_Table_Cells") == 1; }
   catch(e){ mergeTableCells = true; }
   try { omitSpecialCSYSTables = wb.PreferenceMgr.Preference("PID_Report_Omit_Special_CSYS_Tables") == 1; }
   catch(e){ omitSpecialCSYSTables = true; }
   try { graphicsFigureWidth = Math.max(200, wb.PreferenceMgr.Preference("PID_Report_Graphics_Figure_Width")); }
   catch(e){ graphicsFigureWidth = 600; }
   try { graphicsFigureHeight = Math.max(200, wb.PreferenceMgr.Preference("PID_Report_Graphics_Figure_Height")); }
   catch(e){ graphicsFigureHeight = 500; }
   try { chartFigureWidth = Math.max(200, wb.PreferenceMgr.Preference("PID_Report_Chart_Figure_Width")); }
   catch(e){ chartFigureWidth = 600; }
   try { chartFigureHeight = Math.max(200, wb.PreferenceMgr.Preference("PID_Report_Chart_Figure_Height")); }
   catch(e){ chartFigureHeight = 400; }
   try { resolutionMultiplier = wb.PreferenceMgr.Preference("PID_Report_Figure_Resolution"); }
   catch(e){ resolutionMultiplier = 1; }
   try { includeFigures = wb.PreferenceMgr.Preference("PID_Report_Include_Figures") == 1; }
   catch(e){ includeFigures = true; }
}

function CreateDestinationFolders()
{
//  reportPath - folder to contain the HTM file
//  reportFullPath - HTM file path
//  reportSubFolderPath - subfolder to contain linked files

    fso = script.GetFileSystemObject();
    reportPath = fso.BuildPath( wb.UserDataFolder, script.ReportFileDirName );
    
    try
    {
        if( fso.FolderExists( reportPath ) ) {
            fso.DeleteFolder( reportPath, true );
        }
    }
    catch(e)
    {
        // A permissions or access error may occur. If so, find a unique folder name
        var i = 1;
        while( fso.FolderExists( reportPath + ++i ) ) { }

        reportPath += i;
        script.ReportFileDirName = ( script.ReportFileName + i );
    }

    //if the report path changes the full report path should be updated as well (bug #54133)
    reportFullPath      = fso.BuildPath( reportPath, script.ReportFileName + ".htm" );
    reportSubFolderPath = fso.BuildPath( reportPath, script.ReportSubFolderName );
    
    fso.CreateFolder( reportPath );
    fso.CreateFolder( reportSubFolderPath );
}

function LoadStrings()
{
    stringTable = loadXmlDom("StringTable.xml");
//
//  Map of Outline object classes to descriptions for use in captions and the TOC
//
    classToString = loadXmlDom("ClassToString.xml");
    var strings = classToString.selectNodes("//string");
    for(var i = 0; i < strings.length; i++)
    {
        var string = strings.item(i);
        string.setAttribute("class", eval("script." + string.getAttribute("id")));
        if(string.text == "") string.text = string.getAttribute("id");
    }
//
//  Cached strings
//
    strTabularData = script.localString("ID_TabularData");
    strStepNumber = script.localString("ID_StepNumber");
    strObjectNames = getString("id_ObjectNames");
    strState = getString("id_State");
    strTABLE = getString("id_TABLE");
    strFIGURE = getString("id_FIGURE");
    strStateArray =
        [
            getString("id_NoState"),
            getString("id_FullyDefined"),
            getString("id_UnderDefined"),
            getString("id_Suppressed"),
            getString("id_NotSolved"),
            getString("id_Solved"),
            getString("id_Obsolete"),
            getString("id_Error"),
            getString("id_LicenseConflict"),
            getString("id_Ignored"),
            getString("id_Hidden"),
            getString("id_Solving"),
            getString("id_SolvedNotLoaded"),
            getString("id_SolveFailed"),
            getString("id_SolveFailedNotLoaded"),
            getString("id_PartialSolved"),
            getString("id_Meshed"),
            getString("id_WaitForValidation")
        ];
}

function getString(id)
{
    try { return stringTable.selectSingleNode("//string[@id = '" + id + "']").text; }
    catch(e) { return ""; }
}

function LoadRules()
{
    rules = loadXmlDom("Rules.xml");
    var files = rules.selectNodes("//file");
    for(var i = 0; i < files.length; i++) filesToCopy[filesToCopy.length] = files.item(i).text;
    var objects = rules.selectNodes("//object");
    for(var i = 0; i < objects.length; i++) with(objects.item(i))
    {
        setAttribute("class", eval("script." + getAttribute("id")));
        var physicsType = getAttribute("physics-type-id");
        if(physicsType) setAttribute("physics-type", eval("script." + physicsType));
        var analysisType = getAttribute("analysis-type-id");
        if(analysisType) setAttribute("analysis-type", eval("script." + analysisType));
    }
    var states = rules.selectNodes("//state");
    for(var i = 0; i < states.length; i++) with(states.item(i))
    {
        setAttribute("value", eval("script." + getAttribute("id")));
    }
    var strings = rules.selectNodes("//string");
    for(var i = 0; i < strings.length; i++) with(strings.item(i))
    {
        setAttribute("dsstringtable", script.localString(getAttribute("dsstringtable-id")));
        setAttribute("stringtable", getString(getAttribute("stringtable-id")));
    }
}

function checkString(text)
{
    try
    {
        var rule = rules.selectSingleNode("//string[@dsstringtable = '" + text + "']");
        if(rule) text = rule.getAttribute("stringtable");
    }
    catch(e){}
    return text;
}

function LoadTemplate()
{
    template = loadXmlDom("Template.xml");
    html = template.selectSingleNode("//html");
    toc = template.selectSingleNode("//div[@id = 'TableOfContents']");
    body = template.selectSingleNode("//div[@id = 'Body']");
    divMaterials = template.selectSingleNode("//div[@id = 'Materials']");
	var bodyElement = template.selectSingleNode("//body");
	if(script.platform == "UNIX")
	{
		bodyElement.setAttribute("oncontextmenu", "return false");
	}
}

function InsertCoverPage()
{
//  Title
//
    ds.Script.bReportGenerating = true;
    outline.SelectedItem = project;
    ds.Script.bReportGenerating = false;
    var pageTitle = html.selectSingleNode("//title");
    var h1Title = html.selectSingleNode("//div[@id = 'CoverPage']/h1");
    pageTitle.text = h1Title.text = project.Text;
//
//  Logo
//
    var img = html.selectSingleNode("//div[@id = 'CoverPage']//img[@class = 'Logo']");
    if(img)
    {
        var file = filesToCopy[0];
        var src = script.ReportSubFolderName + "/" + (fso.FileExists(file)? fso.GetFileName(file) : file);
        img.setAttribute("src", src);
        img.setAttribute("alt", src);
    }
//
//  Project properties
//
    var table = html.selectSingleNode("//div[@id = 'CoverPage']//table");
    if(table) for(var i = 1; i <= details.GroupCount; i++)
    {
        var group = details.FindGroup(i);
        for(var j = 0; j < group.Count; j++)
        {
            var item = group.Item(j);
            if(item.Value != "")
            {
                var tr = addRow(table);
                addHeaderCell(tr, item.Name, "ItemName");
                addCell(tr, item.Value);
            }
        }
    }
    InsertMugshot();
}

function InsertUnits()
{
    var unitsString = script.localString("ID_UnitsMenu");
    
    // TOC Entry
    var ul = addElement(toc, "ul");
    var li = addElement(ul, "li");
//    var ul = toc.selectSingleNode("//ul");
//    var li = ul.selectSingleNode("li[end()]");
    
    var a = addElement(li, "a", unitsString);
    a.setAttribute("href", "#UNITS");
    a.setAttribute("class", "BoldLink");  
   
    // Report Body Entry
    var div = html.selectSingleNode("//div[@id = 'Units']");
       
    var h2Units = html.selectSingleNode("//div[@id = 'Units']/h2");
    var a1 = addElement(h2Units, "a", unitsString);
    a1.setAttribute("name", "UNITS");
        
    addCaption(div, [strTABLE]);
    var table = addTable(div);
    var tr = [ addRow(table), addRow(table), addRow(table), addRow(table)];
    addHeaderCell(tr[0], getString("id_UnitSystem"), "ItemName");
    addCell(tr[0], script.sbGetUnitsPaneString());
    
    var unitsystemtype = ds.UnitSystemID;
    if (unitsystemtype == "3" || unitsystemtype == "4" )
    {
      var value = script.localString("ID_Fahrenheit");
      addHeaderCell(tr[3], script.localString("ID_EnvironmentInsertThermalLoadKnownTemperature"), "ItemName");
      addCell(tr[3], value);
    }
    else
    {
        if (ds.ShowMetricTemperatureInCelsius)
        {
            var value = script.localString("ID_Celsius");
            addHeaderCell(tr[3], script.localString("ID_EnvironmentInsertThermalLoadKnownTemperature"), "ItemName");
            addCell(tr[3], value);
        }
        else
        {
            var value = script.localString("ID_Kelvin");
            addHeaderCell(tr[3], script.localString("ID_EnvironmentInsertThermalLoadKnownTemperature"), "ItemName");
            addCell(tr[3], value);
        }
    }
    if (ds.ShowAngularVelocityAsRads)
    {
       var value = script.localString("ID_RadsSecond");
       addHeaderCell(tr[2], script.localString("ID_RotationDefaultName"), "ItemName");
       addCell(tr[2], value);
       
    }
    else
    {
        var value = script.localString("ID_RPM");
        addHeaderCell(tr[2], script.localString("ID_RotationDefaultName"), "ItemName");
        addCell(tr[2], value);
    }
    
    if (ds.ShowAngleAsDegrees)
    {
        var value = script.localString("ID_DegreeUnits");
       addHeaderCell(tr[1], script.localString("ID_Angle"), "ItemName");
       addCell(tr[1], value);
    }
    else
    {
        var value = script.localString("ID_Radians");
       addHeaderCell(tr[1], script.localString("ID_Angle"), "ItemName");
       addCell(tr[1], value);
    }
}

function WriteFiles()
{
    var htmlText = html.xml;
    var tableNumber = 0;
    while(htmlText.indexOf("%T") >= 0) { htmlText = htmlText.replace("%T", ++tableNumber); }
    var figureNumber = 0;
    while(htmlText.indexOf("%F") >= 0) { htmlText = htmlText.replace("%F", ++figureNumber); }

	var textStream ;
	if(script.platform == "UNIX")
	{
		textStream = fso.CreateTextFile(reportFullPath, true /*overwrite*/, false /*non-unicode*/);
	}
	else
	{
		textStream = fso.CreateTextFile(reportFullPath, true /*overwrite*/, true /*unicode*/);
	}
    textStream.Write(doctype + "\n" + htmlText);
    textStream.Close();

    for(var i in filesToCopy)
    {
        try
        {
            if(fso.FileExists(filesToCopy[i]))
            {
                var source = filesToCopy[i];
                var destination = fso.BuildPath(reportSubFolderPath, fso.GetFileName(filesToCopy[i]));
            }
            else
            {
                var source = fso.BuildPath(script.ReportGeneratorURL, filesToCopy[i]);
                var destination = fso.BuildPath(reportSubFolderPath, filesToCopy[i]);
            }
            fso.CopyFile(source, destination, true /*overwrite*/);
            var file = fso.GetFile(destination);
            file.Attributes = 32 /*archive read-write*/;
        }
        catch(e){}
    }
}
function CheckReportState()
{
    var reportNotFinalized = template.selectSingleNode("//div[@id = 'ReportNotFinalized']");
    if(firstStateProblemID)
    {
        var a = reportNotFinalized.selectSingleNode(".//a");
        a.setAttribute("href", "#" + firstStateProblemID);
    }
    else
    {
        body.removeChild(reportNotFinalized);
    }
}
function ComposeTable(firstChild, listParent, physicsType, analysisType)
{
    var ul = listParent? addElement(listParent, "ul") : null;
    var firstNode = firstChild;
    while(firstNode)
    {
        if(firstNode.Tag.Class == script.id_Environment)
        {
            physicsType = firstNode.Tag.PhysicsType;
            analysisType = firstNode.Tag.AnalysisType;
        }
        var lastNode = firstNode;
        InsertHeading(body, firstNode);
        var exclude = new detailsExclusion(firstNode);

        if(!exclude.ExcludeNode(node))
        {
            var caption = addCaption(body, [strTABLE, getBreadcrumbs(firstNode, true)], firstNode.Tag.ID);
            var table = addTable(body);
    //
    //      Create the first row of object names
    //      The table breaks for different classes, max columns preference, or when out of objects
    //
            var tbody = addTableBody(table);
            var trName = addRow(tbody);
            var th = addHeaderCell(trName, strObjectNames, "ItemName");
            var trState = addRow(tbody);
            addHeaderCell(trState, strState, "ItemName");
            var columns = 1;
            var incomparable = rules.selectSingleNode("//do-not-compare/object[@class = '" + firstNode.Tag.Class + "']");
            while(true)
            {
                var tdName = addCell(trName);
                var a = addElement(tdName, "a", lastNode.Text);
                a.setAttribute("name", lastNode.Tag.ID);
                a.setAttribute("class", "ObjectName");
                var tdState = addCell(trState, " ");
                try
                {
                    tdState.text = strStateArray[lastNode.Tag.State];
                    var nodeStateOK = rules.selectSingleNode("//state[@value = '" + lastNode.Tag.State + "']") != null;
                    if(!nodeStateOK)
                    {
                        tdName.setAttribute("class", "Highlight");
                        tdState.setAttribute("class", "Highlight");
                        if(!firstStateProblemID) firstStateProblemID = lastNode.Tag.ID;
                    }
                }
                catch(e){}
                ++columns;
                if(incomparable || !lastNode.Next || lastNode.Next.Tag.Class != firstNode.Tag.Class || columns == maxColumns) break;
                lastNode = lastNode.Next;
            }
            var column = 1;
        }
        var node = firstNode;
        var li = null;
        var tr, td;

	    var tmpString  = "";
		var tmpString2 = "";
		var tmpString3 = "";

        while(true)
        {
            var nodeClass = node.Tag.Class;
			
//          Select the tree node to configure the GUI
            if( !includeFigures && nodeClass == script.id_Figure )
            {
                if(node == lastNode || !node.Next) break;

                node = node.Next;
                continue;
            }

            ds.Script.bReportGenerating = true;
            outline.SelectedItem = node;
            ds.Script.bReportGenerating = false;

            var hasTabularDataItem = false;

            if( nodeClass == script.id_PSDLoad)
            {
                hasTabularDataItem = true;
            }
            if( nodeClass == script.id_Load && node.Tag.loadType == script.id_SurfaceConvection )
            {
                hasTabularDataItem = true;
            }
            if( nodeClass==script.id_Result||
                nodeClass==script.id_ProbeResult||
                nodeClass==script.id_CustomResult )
            {
                if( tabularData && tabularData.RowsCount > 0 && tabularData.ColumnsCount > 0 )
                {
                    hasTabularDataItem=true;
                }
            }
            
            InsertSelectiveContent(nodeClass, "details", physicsType, analysisType, body, caption);

            if(!exclude.ExcludeNode(node))
            {
                //need a special case for the transforms on the coordinate systems objects
                for(var i = 1; i <= details.GroupCount; i++)
                {
                    var group = details.FindGroup(i);
                    if(exclude.ExcludeGroup(group.Name)) continue;

                     // Hack for Bushing joint
                    if (script.id_Joint && excludeGroupForBusingJoint(group.Name,node.Tag)) continue;
                                           
					tmpString = group.Name;
					if( tmpString.indexOf( "'" ) != -1 )
					{
						tmpString2 = "";
						tmpString2 = tmpString.substr( 0 , tmpString.indexOf("'") - 1 );
						tmpString2 = tmpString2 + "\\";
						tmpString2 = tmpString2 + tmpString.substr( tmpString.indexOf( "'" ) , tmpString.length - 1 );
					}
					else
					{
						tmpString2 = tmpString;
					}
                    try
                    {
                        th = table.selectSingleNode(".//th[. = '" + tmpString2 + "' $and$ @colspan]");
                    }
                    catch(error)
                    {
                    }

//
//                  If the group header doesn't exist create a new tbody to contain all group data
//
                    if(th)
                    {
                        tr = th.parentNode;
                        tbody = tr.parentNode;
                    }
                    else
                    {
                        tbody = addTableBody(table);
                        tr = addRow(tbody, "tr");
                        th = addHeaderCell(tr, group.Name, "GroupName");
                        th.setAttribute("colspan", columns);
                    }
                    for(var j = 0; j < group.Count; j++)
                    {
                        var item = group.Item(j);
                        if(exclude.ExcludeItem(item.Name)) continue;

						tmpString = item.Name;
						if( tmpString.indexOf( "'" ) != -1 )
						{
							tmpString2 = "";
							tmpString2 = tmpString.substr( 0 , tmpString.indexOf("'") - 1 );
							tmpString2 = tmpString2 + "\\";
							tmpString3 = "";
							tmpString3 = tmpString3 + tmpString.substr( tmpString.indexOf("'") + 1 , tmpString.length - 1);
						    if( tmpString3.indexOf( "'" ) != -1 )
						    {
						    tmpString2 = tmpString2 +  tmpString3.substr( 0 , tmpString3.indexOf("'") - 1 );
						    tmpString2 = tmpString2 + "\\";	
						    tmpString2 = tmpString2 + tmpString3.substr( tmpString3.indexOf("'") , tmpString3.length - 1 );
						    
						    }
						    else
						    {
							tmpString2 = tmpString2 + tmpString.substr( tmpString.indexOf( "'" ) , tmpString.length - 1 );
						    }
						}
						else
						{
							tmpString2 = tmpString;
						}
                        try
                        {
                        th = tbody.selectSingleNode(".//th[. = '" + tmpString2 + "' $and$ $not$ @colspan]");
                        }
                        catch(error)
                        {
                        }
//
//                      If the item header exists this node will fill in an existing column
//                      Otherwise, add the item header and blank cells to fill in the row
//
                        if(th && /*group.Name != script.localString("ID_CADAttributes") &&*/ group.name != script.localString("ID_NonlinearControlsGroup")
                            && group.Name != script.localString("ID_OutputControls"))
                        {
                            tr = th.parentNode;
                        }
                        else
                        {
                            tr = addRow(tbody);
                            th = addHeaderCell(tr, checkString(item.Name), "ItemName");
                            for(var k = 1; k < columns; k++)
                            {
                                var td = addCell(tr, " ");
                                tdName = trName.childNodes.item(k);
                                var className = tdName.getAttribute("class");
                                if(className && className != "") td.setAttribute("class", className);
                            }
                        }
//
//                      Fill in item data in the appropriate column
//
                        td = tr.childNodes.item(column);
                        td.text = checkString(item.Value);

                        hasTabularDataItem = hasTabularDataItem || item.Value.indexOf(strTabularData) == 0;
                    }
                }
            }
            else
            {
                for(var i = 1; i <= details.GroupCount; i++)
                {
                    var group = details.FindGroup(i);
                    for(var j = 0; j < group.Count; j++)
                    {
                        var item = group.Item(j);
                        hasTabularDataItem = hasTabularDataItem || item.Value.indexOf(strTabularData) == 0;
                    }
                }
            }

            InsertStepDependentProperties(body, node);
            InsertTimelineSnapshot(hasTabularDataItem, body, node, physicsType, analysisType);
            InsertTabularData(hasTabularDataItem, body, node, physicsType, analysisType);
            if(nodeClass == script.id_Figure) InsertFigure(body, node);
            if(nodeClass == script.id_AdvancedOutput) InsertSnapshot(body, node);
            if(nodeClass == script.id_CommandEditor) InsertCommandSnippet(body, node);
            if(nodeClass == script.id_Comment) InsertComment(body, node);
			InsertWorksheetPlaceholder(body, node);

            if(node == firstNode) li = InsertTableOfContentsEntry(ul, node, columns > 2);

            var expanded = node.Expanded;
            if(node.Child) ComposeTable(node.Child, li, physicsType, analysisType);
            node.Expanded = expanded;

            if(node == lastNode || !node.Next) break;
            ++column;
            node = node.Next;
        }
        MergeCellsHorizontally(table);

        firstNode = lastNode.Next;
    }
    if(ul && ul.childNodes.length == 0) listParent.removeChild(ul);
}

function excludeGroupForBusingJoint(name , tag)
{
    if ((tag.JointType == 9) && name == "Coefficients") 
      return true;
    else
      return false;
}

function InsertHeading(parent, node)
{
    var h2 = rules.selectSingleNode("//heading-h2/object[@class = '" + node.Tag.Class + "']");
    var h3 = rules.selectSingleNode("//heading-h3/object[@class = '" + node.Tag.Class + "']");
    var suppressed = node.Tag.Class == script.id_Chart && node.Tag.ReportContent == kChartReportNone;
    if(!suppressed && (h2 || h3))
    {
        var h = addElement(parent, h2? "h2":"h3");
        var a = addElement(h, "a", node.Text);
        a.setAttribute("name", node.Tag.ID);
        if(node.Tag.Class == script.id_Chart && node.Tag.ReportCaption != "")
        {
            var p = addElement(parent, "p", node.Tag.ReportCaption);
            p.setAttribute("class", "Caption");
        }
    }
}

function InsertTableOfContentsEntry(ul, node, isComparison)
{
    var li = null;
    var permitted = rules.selectSingleNode("//exclude-from-toc/object[@class = '" + node.Tag.Class + "']") == null;
    var chartExclude = node.Tag.Class == script.id_Chart && node.Tag.ReportContent == kChartReportNone;
    if(ul && permitted && !chartExclude)
    {
        var classString = getClassString(node);
        var lastLi = ul.selectSingleNode("li[end()]");
        if(!lastLi || lastLi.text != classString || node.Tag.Class == script.id_Chart)
        {
            var text = isComparison? classString : node.Text;
            li = addElement(ul, "li");
            var a = addElement(li, "a", text);
            a.setAttribute("href", "#" + node.Tag.ID);
            var bold = rules.selectSingleNode("//toc-bold/object[@class = '" + node.Tag.Class + "']");
            a.setAttribute("class", bold? "BoldLink" : "Link");
        }
    }
    return li;
}

function InsertTimelineSnapshot(hasTabularDataItem, parent, node, physicsType, analysisType)
{
//  "permitted" is true if the class isn't ruled out
    var permitted = rules.selectSingleNode("//exclude-timeline/object[@class = '" + node.Tag.Class + "']") == null;
    if( !permitted )
        return;

//  "hasDatasetItem" is true if any curve has 2 or more points
    var timeline = script.stepControl;
    for(var hasDatasetItem = false, i = 0; i < timeline.Datasets.Count; i++)
    {
        hasDatasetItem = hasDatasetItem || timeline.Datasets.Item(i).CountDistinct >= 2;
    }

//  "modalRepeat" is true for objects in a modal analysis other than the Solution
    var modalRepeat = physicsType == script.id_PT_Mechanical && (analysisType == script.id_SimTypeModal || analysisType == script.id_SimTypeBuckling) && node.Tag.Class != script.id_AnswerSet;
    if( modalRepeat )
        return;

//  "chartExclude" is true for chart objects that specify tabular data only in the report
    var chartExclude = node.Tag.Class == script.id_Chart && (node.Tag.ReportContent == kChartReportNone || node.Tag.ReportContent == kChartReportTabularDataOnly);
    if( chartExclude )
        return;

//  "resultChartExclude" is true for result charts that are worksheets
    var resultChartExclude = node.Tag.Class == script.id_ResultChart && (node.Tag.IsHarmonic || node.Parent.Tag.Class == script.id_FatigueTool);
    if( resultChartExclude )
        return;

    if(hasTabularDataItem || hasDatasetItem )
    {
        InsertSelectiveContent(node.Tag.Class, "timeline", physicsType, analysisType, parent);

        var fileName = getNextFigureFileName();
        var fullPath = fso.BuildPath(reportSubFolderPath, fileName);
        try
        {
            graphics.Draw2(timeline.ID);
            graphics.CompositeDisplayDisp.ShowLegend = timeline.Datasets.Count < 7;
            graphics.CompositeDisplayDisp.ChartDisp.WritePngFile(fullPath, chartFigureWidth, chartFigureHeight, true);
            graphics.CompositeDisplayDisp.ShowLegend = false;
            addFigure(parent, script.ReportSubFolderName + "/" + fileName, getBreadcrumbs(node, false), node.Tag.ID, chartFigureWidth, chartFigureHeight);
        }
        catch (e)
        {
        }
    }
}

function InsertTabularData(hasTabularDataItem, parent, node, physicsType, analysisType)
{
    var isPretensionBolt = node.Tag.Class == script.id_PretensionBoltLoad;
    var isChart = node.Tag.Class == script.id_Chart && node.Tag.ReportContent !=  kChartReportNone && node.Tag.ReportContent != kChartReportChartOnly;

//  "isModal" is true only for the Solution object inside a modal or buckling analysis
    var isModal = physicsType == script.id_PT_Mechanical && (analysisType == script.id_SimTypeModal || analysisType == script.id_SimTypeBuckling) && node.Tag.Class == script.id_AnswerSet;

    if(hasTabularDataItem || isPretensionBolt || isChart || isModal)
    {
        InsertSelectiveContent(node.Tag.Class, "tabularData", physicsType, analysisType, parent);

        addCaption(parent, [strTABLE, getBreadcrumbs(node, false)], node.Tag.ID);
        var table = addTable(parent);
        for(var i = 1; i <= tabularData.RowsCount; i++)
        {
            var tr = addRow(table);
            for(var j = 2; j <= tabularData.ColumnsCount; j++)
            {
                if( j-1 > maxColumns )
                    continue;
                var value = tabularData.Cell(i, j).Text;
                if(i==1) addHeaderCell(tr, value, "ItemNameColumn");
                else addCell(tr, value);
            }
//          Delete the last row if blank
            if(i == tabularData.RowsCount && !tr.selectSingleNode("td[. != '']")) table.removeChild(tr);
        }
        MergeCellsVertically(table);
    }
}

function InsertMugshot()
{
    //determine if a model exists
    var models = project.Tag.Models;
    if( models.Count == 0 )
        return;

    //use image of the first model
    var src = writeGraphicsBitmap(models(1).ID, graphicsFigureWidth, graphicsFigureHeight);
    var coverPage = html.selectSingleNode("//div[@id = 'CoverPage']");
    var p = addParagraph(coverPage, null, "Centered");
    var img = addElement(p, "img");
    img.setAttribute("src", src);
    img.setAttribute("alt", src);
    img.setAttribute("width", graphicsFigureWidth);
    img.setAttribute("height", graphicsFigureHeight);
}

function InsertFigure(parent, node)
{
    var src = writeGraphicsBitmap(node.Tag.ID, graphicsFigureWidth, graphicsFigureHeight);
    addFigure(parent, src, [getBreadcrumbs(node, false), node.Tag.Text], node.Tag.ID, graphicsFigureWidth, graphicsFigureHeight);
}

function writeGraphicsBitmap(id, width, height)
{
    try
    {
        var fileName = getNextFigureFileName();
        var fullPath = fso.BuildPath(reportSubFolderPath, fileName);
        var imageCaptureControl = graphics.ImageCaptureControl;
        graphics.Draw2(id);
        imageCaptureControl.Write(0, fullPath);
        return script.ReportSubFolderName + "/" + fileName;
    }
    catch (e)
    {
    }
}

function InsertSnapshot(parent, node)
{
    var fullPath = node.Tag.ImagePath;
    if(fso.FileExists(fullPath))
    {
        filesToCopy[filesToCopy.length] = fullPath;
        var src = script.ReportSubFolderName + "/" + fso.GetFileName(fullPath);
        addFigure(parent, src, getBreadcrumbs(node, false), node.Tag.ID);
    }
}

function InsertCommandSnippet(parent, node)
{
    addCaption(parent, [getBreadcrumbs(node, false)], node.Tag.ID);
    addElement(body, "pre", node.Tag.Text);
}

function InsertComment(parent, node)
{
    var author = node.Tag.CommentOwner;
    addCaption(parent, [getBreadcrumbs(node, false), author], node.Tag.ID);
    Comment.innerHTML = node.Tag.Text;
    var div = addElement(parent, "div");
    div.setAttribute("class", "Comment");
    addComment(Comment, div);
}

function addComment(sourceParent, targetParent)
{
    var nodes = sourceParent.childNodes;
    for(var i = 0; i < nodes.length; i++)
    {
        var node = nodes.item(i);
        if(node.nodeType == 3 /*TextNode*/) addTextNode(targetParent, node.data);
        else
        {
            var targetNode = addElement(targetParent, node.tagName);
			if(node.style.cssText != "") targetNode.setAttribute("style", node.style.cssText);
			for(var j = 0; j < node.attributes.length; j++)
			{
				try
				{
					var attribute = node.attributes.item(j);
					if(attribute.nodeValue && attribute.nodeValue != "" )
					{
						targetNode.setAttribute(attribute.name, attribute.value);
					}
				}
				catch(e)
				{
				}
			}
            addComment(node, targetNode);
        }
    }
}

function getBreadcrumbs(treeNode, useClassString)
{
    var location = treeNode.Parent.FullPath; // get path string from TreeView
    location = location.replace(project.Text + "\\", ""); // chop the project off the front
    location = location.replace( /\\/g, " > "); // replaces slashes with >
    var text = useClassString? getClassString(treeNode) : treeNode.Text;
    var breadcrumbs = (location != "")? location : "";
    breadcrumbs += text;
    return breadcrumbs;
}

function getClassString(node)
{
    var string = classToString.selectSingleNode("//string[@class = '" + node.Tag.Class + "']");
    return string? string.text : node.Text;
}

function loadXmlDom(url)
{
    var dom = new ActiveXObject("Microsoft.XMLDOM");
    dom.async = false;
    dom.load(url);
    if(dom.parseError.errorCode == 0) return dom;
    else
    {
        var m = "Microsoft.XMLDOM.parseError";
        var p = ["url", "errorCode", "reason", "line", "filepos", "linepos", "srcText"];
        for(var i in p)
        {
            try { m += "\n" + p[i] + ": " + dom.parseError[p[i]]; }
            catch(e){}
        }
        throw new Error(m);
    }
}

function addElement(parent, tagName, text, nextSibling)
{
     var element = template.createElement(tagName);
     if(text)
     {
        if(text == " ") element.appendChild(template.createEntityReference("nbsp"));
        else element.text = text.toString();
     }
     return parent.insertBefore(element, nextSibling);
}

function addTextNode(parent, text)
{
     var textNode = template.createTextNode(text.toString());
     return parent.appendChild(textNode);
}

function addTable(parentElement, nextSibling)
{
    var table = addElement(parentElement, "table", null, nextSibling);
    table.setAttribute("align", "center");
    table.setAttribute("class", "Details");
    table.setAttribute("border", "1");
    table.setAttribute("cellpadding", "0");
    table.setAttribute("cellspacing", "0");
    return table;
}
function addTableBody(table)
{
    return addElement(table, "tbody");
}
function addRow(parent)
{
    return addElement(parent, "tr");
}
function addCell(row, text)
{
    return addElement(row, "td", text);
}
function addHeaderCell(row, text, className)
{
    var th = addElement(row, "th", text);
    if(className) th.setAttribute("class", className);
    return th;
}
function addParagraph(parent, text, className, nextSibling)
{
    var p = addElement(parent, "p", text, nextSibling);
    if(className) p.setAttribute("class", className);
    return p;
}
function addCaption(parent, textArray, name, nextSibling)
{
    var p = addParagraph(parent, null, "Caption", nextSibling);
    var a = p;
    if(name)
    {
        a = addElement(p, "a");
        a.setAttribute("name", name);
    }
    a.text = textArray[0];
    for(var i = 1; i < textArray.length; i++)
    {
        if(textArray[i] != "")
        {
            addElement(a, "br");
            addTextNode(a, textArray[i]);
        }
    }
    return p;
}
function getNextFigureFileName()
{
    var i = (++imageNumber).toString();
    while(i.length < 4) { i = "0" + i; }
    return "Figure" + i + ".png";
}
function addFigure(parent, src, caption, name, width, height, nextSibling)
{
    addCaption(parent, [strFIGURE].concat(caption), name, nextSibling);
    var p = addParagraph(parent, null, "Figure", nextSibling);
    var img = addElement(p, "img");
    img.setAttribute("src", src);
    img.setAttribute("alt", src);
    if(width) img.setAttribute("width", width);
    if(height) img.setAttribute("height", height);
    return p;
}

function detailsExclusion(node)
{
    var rulesCollection = rules.selectNodes("//exclude-details/object[@class = '" + node.Tag.Class + "']");
    var isSpecialCSYS = node.Tag.Class == script.id_CoordinateSystem && node.Parent.Tag.Class != script.id_CoordinateSystemGroup;
    this.isExcludedCSYS = isSpecialCSYS && omitSpecialCSYSTables;
    
    this.Group = []; this.Item = [];
    for(var i = 0; i < rulesCollection.length; i++)
    {
        var rule = rulesCollection(i);
        this.Group[i] = rule? stringTableOrLiteral(rule.getAttribute("group")) : null;
        this.Item[i] = rule? stringTableOrLiteral(rule.getAttribute("item")) : null;
    }

    this.ExcludeNode = function ExcludeNode(node)
    {
        if( this.isExcludedCSYS ) 
            return true;
            
        for( var i=0; i<this.Group.length; i++ )
        {
            if( !this.Group[i] && !this.Item[i] )
                return true;
        }
        
        return false;        
    }
    
    this.ExcludeGroup = function ExcludeGroup(GroupName)
    {
        for( var i=0; i<this.Item.length; i++ )
        {
            if( this.Group[i] == GroupName && !this.Item[i] )
                return true;
        }
        
        return false;
    }
    
    this.ExcludeItem = function ExcludeItem(ItemName)
    {
        for( var i=0; i<this.Item.length; i++ )
        {
            if( this.Item[i] == ItemName )
                return true;
        }
        
        return false;
    }
    
}

function excludeGroup()
{

}
function excludeItem()
{

}

function stringTableOrLiteral(id)
{
    if(!id) return null;
    var text = script.localString(id);
    if(text == "") text = id;
    return text;
}
function InsertSelectiveContent(id, target, physicsType, analysisType, parentElement, followingElement)
{
    var rule = rules.selectSingleNode("//selective-content/object[@class = '" + id + "' $and$ @target = '" + target + "']");
    if(rule)
    {
        var p = rule.getAttribute("physics-type");
        var a = rule.getAttribute("analysis-type");
        if((physicsType == null || p == null || p == physicsType) && (analysisType == null || a == null || a == analysisType ))
        {
            for(var i = 0; i < rule.childNodes.length; i++)
            {
                var ruleElement = rule.childNodes(i);
                var cloneElement = ruleElement.cloneNode(true /*deep*/);
                parentElement.insertBefore(cloneElement, followingElement);
            }
            if(rule.getAttribute("instance") == "first") rule.parentNode.removeChild(rule);
        }
    }
}
function InsertStepDependentProperties(parent, node)
{
    if(node.Tag.Class == script.id_AnalysisSettings || node.Tag.Class == script.id_ThermalCondition || node.Tag.Class == script.id_EmagCondition)
    {
        var environment = node.Parent.Tag;
        var analysisSettings = environment.AnalysisSettings;
        var timePoint = environment.CurrentTransientTime;
        var groupArray = [];
        for(var i = 1; i <= analysisSettings.NumberOfSteps; i++)
        {
            analysisSettings.CurrentStepNumber = i;
            for(var j = 1; j <= details.GroupCount; j++)
            {
                var group = details.FindGroup(j);
                for(var k = 0; k < group.Count; k++)
                {
                    var item = group.Item(k);
                    if(item.Name == strStepNumber) continue;
                    if(!groupArray[group.Name]) groupArray[group.Name] = [];
                    if(!groupArray[group.Name][item.Name]) groupArray[group.Name][item.Name] = [];
                    groupArray[group.Name][item.Name][i] = item.Value;
                }
            }
        }
        for(var i in groupArray)
        {
            var allIdentical = true;
            for(var j in groupArray[i])
            {
                var identical = true;
                for(var k = 2; k <= analysisSettings.NumberOfSteps; k++)
                {
                    identical = identical && groupArray[i][j][k] == groupArray[i][j][1];
                    allIdentical = allIdentical && identical;
                }
                if(identical) delete groupArray[i][j];
            }
            if(allIdentical) delete groupArray[i];
        }
        for(var i in groupArray)
        {
            var text = getString("id_StepTableCaption").replace("%1", i);
            addCaption(parent, [strTABLE, getBreadcrumbs(node, false), text]);
            var table = addTable(parent);
            for(var k = 0; k <= analysisSettings.NumberOfSteps; k++)
            {
                tr = addRow(table);
                if(k == 0) addHeaderCell(table.childNodes(k), script.localString("ID_Step"), "ItemNameColumn");
                else addCell(table.childNodes(k), k);
            }
            for(var j in groupArray[i])
            {
                for(var k = 0; k <= analysisSettings.NumberOfSteps; k++)
                {
                    if(k == 0) addHeaderCell(table.childNodes(k), j, "ItemNameColumn");
                    else addCell(table.childNodes(k), groupArray[i][j][k]);
                }
            }
        }
        MergeCellsVertically(table);
        environment.CurrentTransientTime = timePoint;
    }
}
function InsertWorksheetPlaceholder(parent, node)
{
    var url = worksheetFolder, events = 1, worksheetType;

    switch(node.Tag.Class)
    {
        case script.id_Joint:
          if(node.Tag.JointType == 9) 
          {
            url += "BushingFolder.htm";
            worksheetType = "BushingJointCoefficients"; //Stiffness Coefficients //Damping Coefficients
          } 
          else 
            return;
          break;
        case script.id_FatigueTool:
            url += "DSFatigueTool.htm";
            worksheetType = "Fatigue";
            break;
        case script.id_ResultChart:
            if(node.Tag.IsHarmonic)
            {
                if(node.Tag.ResponseType == 0)
                {
                    url += "DSFrequencyResponse.htm";
                    events = 3;
                    worksheetType = "FrequencyResponse";
                }
                else
                {
                    url += "DSPhaseResponse.htm";
                    worksheetType = "PhaseResponse";
                }
            }
            else if(node.Parent.Tag.Class == script.id_FatigueTool)
            {
                url += "DSResultChart.htm";
                worksheetType = "ResultChart";
            }
            else if (node.Tag.ResultChartType == script.id_RotordynamicCampbellDiagram)
            {
                url += "DSCampbellChart.htm";
                worksheetType = "CampbellDiagram";            
            }
            else return;
            break;
        case script.id_SolutionInfoTool:
            url += "DSSolutionOutputGraph.htm";
            worksheetType = "SolutionInformation";
            break;
        case script.id_ConstraintEquation:
            url += "DSConstraintEquation.htm";
            worksheetType = "ConstraintEquation";
            break;
        case script.id_Convergence:
            url += "DSConvergence.htm";
            worksheetType = "Convergence";
            break;
        case script.id_ContactTool:
            url += "ContactTool.htm";
            worksheetType = "ContactTool";
            break;
        case script.id_SolutionCombination:
            url += "DSSolutionCombination.htm";
            worksheetType = "SolutionCombination";
            break;
        case script.id_DASolutionCombination:
            url += "DSDASolutionCombination.htm";
            worksheetType = "DASolutionCombination";
            break;
        case script.id_ResultTable:
            url += "Inductance.htm";
            worksheetType = "InductanceFluxLinkage";
            break;
        case script.id_ExternalLoad:
            url += "Worksheet.htm";
            worksheetType = "ExternalLoad";
            break;
        case script.id_ContactDataTable:
            url += "ContactInitialInformation.htm";
            worksheetType = "ContactInitialInformation";
            break;
        default: return;
    }

    worksheetsArray[worksheetsArray.length] = new _Worksheet();

    function _Worksheet()
    {
        this.TreeNode = node;
        this.Type = worksheetType;
        this.URL = url;
        this.EventsRequired = events;
        this.EventsReceived = 0;
        this.Parent = parent;
        this.Placeholder = addElement(parent, "worksheet");
    }
}
function ProcessWorksheets()
{
    if(worksheetsIndex < worksheetsArray.length)
    {
        var worksheet = worksheetsArray[worksheetsIndex];
        ds.Script.bReportGenerating = true;
        outline.SelectedItem = worksheet.TreeNode;
        script.tv_Click();
        ds.Script.bReportGenerating = false;
        script.reportWorksheetControl.Navigate(worksheet.URL);
    }
    else
    {
		ComposeEngineeringData();
	}
}
function WorksheetLoaded()
{
    var worksheet = worksheetsArray[worksheetsIndex];
    if(++worksheet.EventsReceived == worksheet.EventsRequired)
    {
        var nextSibling = worksheet.Placeholder.nextSibling;
        worksheet.Parent.removeChild(worksheet.Placeholder);
        var worksheetDocument = script.reportWorksheetControl.Document;
        var worksheetWindow = worksheetDocument.parentWindow;
        var breadcrumbs = getBreadcrumbs(worksheet.TreeNode, false);

        switch(worksheet.Type)
        {
            case "BushingJointCoefficients":
            if(worksheetWindow.List1.style.display != "none") _addTableDatagridControl( worksheetWindow.List1 );
            if(worksheetWindow.List2.style.display != "none") _addTableDatagridControl( worksheetWindow.List2 );
            break;
            case "FrequencyResponse":
                _addFigure(worksheetWindow.TopFrame.Graph1);
                if(worksheet.TreeNode.Tag.TimeHistoryDisplayType == 4 /*Bode*/) _addFigure(worksheetWindow.BottomFrame.Graph2);
                break;
            case "Fatigue":
            case "SolutionInformation":
                if(worksheetWindow.Graph1.style.display != "none") _addFigure(worksheetWindow.Graph1);
                if(worksheetWindow.Graph2.style.display != "none") _addFigure(worksheetWindow.Graph2);
                break;
            case "Convergence":
                if(worksheetWindow.Graph1.style.display != "none") _addFigure(worksheetWindow.Graph1);
                if(worksheetWindow.WBListViewCtrl1.style.display != "none") _addTable(worksheetWindow.WBListViewCtrl1);
                break;
            case "PhaseResponse":
            case "ResultChart":
                _addFigure(worksheetWindow.Graph1);
                break;
            case "ContactInitialInformation":            
                _addTableDatagridControl(worksheetWindow.DataGrid1);
                break;
            case "ContactTool":
                _addTableContactTool(worksheetWindow.DataGrid);
                break;
            case "ConstraintEquation":
            case "SolutionCombination":
            case "DASolutionCombination":
                _addTable(worksheetWindow.List1);
                break;
            case "ExternalLoad":           
                 _addExternalLoadDatagridControl(worksheetWindow.WBDataGridCtrl);
                break;

            case "InductanceFluxLinkage":
                if(worksheetWindow.List1.style.display != "none")
                    _addTable(worksheetWindow.List1);
				break;
            case "CampbellDiagram":
                _addFigure(worksheetWindow.Graph1);
                _addTableDatagridControl(worksheetWindow.CampbellDiagramDataGrid);
                break;
                break;
        }

        worksheetsIndex++;
        script.reportWorksheetControl.Navigate("about:blank");
        ProcessWorksheets();
    }

    function _addFigure(graph)
    {
        var fileName = getNextFigureFileName();
        var fullPath = fso.BuildPath(reportSubFolderPath, fileName);
        var src = script.ReportSubFolderName + "/" + fileName;
        graph.WritePngFile(fullPath, chartFigureWidth, chartFigureHeight, false);
        addFigure(worksheet.Parent, src, breadcrumbs, null, chartFigureWidth, chartFigureHeight, nextSibling);
    }
    function _addTable(listView)
    {
        addCaption(worksheet.Parent, [breadcrumbs], null, nextSibling);
        var table = addTable(worksheet.Parent, nextSibling);
        var trHeader = addRow(table);
        for(var i = 1; i <= listView.ColumnHeaders.Count; i++)
        {
            if(i == 1 && listView.Checkboxes) continue;
            if(i == listView.ColumnHeaders.Count && listView.ColumnHeaders(i).Text == "") break;
            addHeaderCell(trHeader, listView.ColumnHeaders(i).Text, "ItemNameColumn");
        }
        for(var i = 1; i <= listView.ListItems.Count; i++)
        {
            if(listView.Checkboxes && !listView.ListItems(i).Checked) continue;
            var tr = addRow(table);
            if(!listView.Checkboxes) addCell(tr, listView.ListItems(i).Text);
            for(var j = 1; j <= listView.ListItems(i).ListSubItems.Count; j++)
            {
                addCell(tr, listView.ListItems(i).ListSubItems(j).Text);
                if(tr.childNodes.length == trHeader.childNodes.length) break;
            }
        }
        MergeCellsVertically(table);
    }
    function _addTableContactTool(datagrid)
    {
        addCaption(worksheet.Parent, [breadcrumbs], null, nextSibling);
        var table = addTable(worksheet.Parent, nextSibling);
        var trHeader = addRow(table);
        for(var i = 2; i <= 3; i++)  //only show the name (2) and contact scope side (3) columns
        {
            if(datagrid.Cell(1,i).Text == "") break;
            addHeaderCell(trHeader, datagrid.Cell(1,i).Text, "ItemNameColumn");
        }
        
        for(var i = 2; i <= datagrid.RowsCount; i++)
        {
            if(datagrid.Cell(i,1).CheckStateChecked == false) continue; //don't show unchecked items
            var table2 = table;
            var tr = addRow(table2);
            for(var j = 2; j <= 3; j++) //only show the name (2) and contact scope side (3) columns
            {
                addCell(tr, datagrid.Cell(i,j).Text);
            }
        }
    }
    function _addTableDatagridControl(datagrid)
    {
        addCaption(worksheet.Parent, [breadcrumbs], null, nextSibling);
        var table = addTable(worksheet.Parent, nextSibling);
        var trHeader = addRow(table);
        for(var i = 1; i <= datagrid.ColumnsCount; i++)
        {
            if(i == datagrid.ColumnsCount && datagrid.Cell(1,i).Text == "") break;
            addHeaderCell(trHeader, datagrid.Cell(1,i).Text, "ItemNameColumn");
        }
        
        for(var i = 2; i <= datagrid.RowsCount; i++)
        {
            if(datagrid.Cell(i,1).Text == "") continue;
            var table2 = table;
            var tr = addRow(table2);
            addHeaderCell(tr, datagrid.Cell(i,1).Text, "ItemNameColumn");
            for(var j = 2; j <= datagrid.ColumnsCount; j++)
            {
                addCell(tr, datagrid.Cell(i,j).Text);
            }
        }
    }
    function _addExternalLoadDatagridControl(datagrid)
    {
      if(ds.Script.platform == "UNIX") 
        return;
        
        addCaption(worksheet.Parent, [breadcrumbs], null, nextSibling);
        var table = addTable(worksheet.Parent, nextSibling);
        var trHeader = addRow(table);
        for(var i = 1; i <= datagrid.ColumnsCount; i++)
        {
            if(i == datagrid.ColumnsCount && datagrid.Cell(1,i).Text == "") break;
            addHeaderCell(trHeader, datagrid.Cell(1,i).Text, "ItemNameColumn");
        }
        
        for(var i = 2; i <= datagrid.RowsCount; i++)
        {
            var table2 = table;
            var tr = addRow(table2);
            addHeaderCell(tr, datagrid.Cell(i,1).Text, "ItemNameColumn");
            for(var j = 2; j <= datagrid.ColumnsCount; j++)
            {
                if( j == 2 && datagrid.Cell(1,2).Text == "Active" )//Thermal-Stress addin has checkbox that can be activated/deactivated
                {
                    if(datagrid.Cell(i,j).CheckStateChecked == true)
                        addCell(tr,  script.localString("ID_Yes"));
                    else
                        addCell(tr, script.localString("ID_No"));
                }
                else
                    addCell(tr, datagrid.Cell(i,j).Text);
            }
        }
    }
}
function WrapUp()
{
	wb.TabCtrl.SelectedItem = wb.TabCtrl.TabItems.ItemByTag("DSApplet");
	ds.Script.bReportGenerating = true;
    outline.SelectedItem = outline.nodes(1);
    ds.Script.bReportGenerating = false;
    WriteFiles();
    window.navigate(reportFullPath);
}
function MergeCellsHorizontally(table)
{
    if(mergeTableCells && table) try
    {
        var table2 = table.cloneNode(true);
        var rows = table2.selectNodes(".//tr");
        if(rows && rows(1).childNodes.length > 2)
        {
            for(var i = 1; i < rows.length; i++)
            {
                var cells = rows(i).childNodes;
                if(cells && cells.length > 0)
                {
                    var cell = cells(0);
                    while(cell)
                    {
                        var colSpan = 1;
                        while(true)
                        {
                            var cellClass = cell.getAttribute("class");
                            var nextCell = cell.nextSibling;
                            var nextCellClass = nextCell? nextCell.getAttribute("class") : null;
                            var classesDiffer = (cellClass || nextCellClass) && cellClass != nextCellClass;
                            if(!nextCell || cell.text != nextCell.text || classesDiffer) break;
                            colSpan++;
                            rows(i).removeChild(nextCell);
                        }
                        if(colSpan > 1) cell.setAttribute("colspan", colSpan);
                        cell = nextCell;
                    }
                }
            }
            var parent = table.parentNode;
            parent.insertBefore(table2, table);
            parent.removeChild(table);
        }
    }
    catch(e) { /* original table is unchanged */ }
}
function MergeCellsVertically(table)
{
    if(mergeTableCells && table) try
    {
        var table2 = table.cloneNode(true);
        var rows = table2.selectNodes(".//tr");
        if(rows && rows.length > 2)
        {
            for(var i = rows(0).childNodes.length-1; i >= 0; i--)  // cells right to left
            {
                var row = rows(1);
                var nextRow = row.nextSibling;
                var rowSpan = 1;
                while(row)
                {
                    if(!nextRow || nextRow.childNodes(i).text != row.childNodes(i).text)
                    {
                        if(rowSpan > 1) row.childNodes(i).setAttribute("rowspan", rowSpan);
                        if(!nextRow) break;
                        row = nextRow;
                        rowSpan = 1;
                    }
                    else
                    {
                        nextRow.removeChild(nextRow.childNodes(i));
                        rowSpan++;
                    }
                    nextRow = nextRow.nextSibling;
                }
            }
            var parent = table.parentNode;
            parent.insertBefore(table2, table);
            parent.removeChild(table);
        }
    }
    catch(e) { /* original table is unchanged */ }
}
