angeCB = null;
var ds, wb, helper;
var ver = 5;

//Variables for Grid resizing
var wndHelper = null;
var initialHeightGrid = 240;//based on the width property in Object Tag
var initialCountsPerPageGrid = 0;
var columnHeaderHeightGrid = 0;
var minHeightGrid = 20;

function window_onload()
{
	var wbTemp = window.external;
	wb = wbTemp;
	
	ds = wbTemp.AppletList.Applet("DSApplet").App;
	
	data = ds.Tree.FirstActiveObject;
	
	stringTable = wbTemp.AppletList.WBApplet("DSApplet").StringTable;

	scriptEngine = wb.ScriptEngine.Engine;
	
	wndHelper = scriptEngine.CreateActiveXObject( scriptEngine.GenWBProgId("WBControls.WBWndHelper") );

	ver = msieversion();
	
	if(ver >= 5)
		pageName.firstChild.nodeValue = stringTable.String("ID_ConvergenceHistory");
	else
		pageName.innerText = stringTable.String("ID_ConvergenceHistory");
    
    try
    {
	    if(ds.GUIState && ds.GUIState.GUIDriver)
	    {
			    ds.GUIState.GUIDriver.MenuListener.AddListener(3, this);
	    }
	}
	catch(e){}  // trap an error that may occur during report generation

	lvChangeCB = ds.Script.lv.OnChange;
	lvChangeCB.AddCOM(this, "ListClickDelegate");
	
	processStateCB = ds.OnProcessingStateFinished;
	processStateCB.AddCOM(this, "Processing_State_FinishedDelegate");
	init();
}

function msieversion()
{
  var ua = window.navigator.userAgent
  var msie = ua.indexOf ( "MSIE " )

  if ( msie > 0 )      // If Internet Explorer, return version number
     return parseInt (ua.substring (msie+5, ua.indexOf (".", msie )))
  else                 // If another browser, return 0
     return 0

}

function init()
{
	SetVars();
			
	if(numpoints > 0 )  //if data exists
	{
		WBListViewCtrl1.style.display = "inline";
		Graph1.style.display = "inline";
		setTimeout("initGrid()",200);
	}
	else		//if there is no data to display
	{
		setTimeout("initGridPropertiesForEmptyGrid()",200);
		ShowEmptyGraph();

    	ds.Script.CheckIfWorksheetInReport();
	}
}

function initGridPropertiesForEmptyGrid()
{
	ShowEmptyGrid();

	initGridProperties();
}

function initGridProperties()
{
	var lvwReport = 3;
	WBListViewCtrl1.View = lvwReport;
	WBListViewCtrl1.GridLines = true;
	WBListViewCtrl1.FullRowSelect = true;
	WBListViewCtrl1.MultiSelect = false;
	WBListViewCtrl1.HideSelection = false;
	
	var ccDefault = 0;
	WBListViewCtrl1.MousePointer = ccDefault;
	
	var lvwAutomatic = 0;
    var lvwManual = 1;
	WBListViewCtrl1.LabelEdit = lvwManual;
	
	var ccNone = 0;
    var ccFixedSingle = 1;
	WBListViewCtrl1.BorderStyle = ccFixedSingle;
	
	var ccFlat = 0;
    var cc3D = 1;
	WBListViewCtrl1.Appearance = ccFlat;
	
	initialCountsPerPageGrid = WBListViewCtrl1.GetCountPerPage();
	
    var rectTemp;
    try
    {
        rectTemp = wndHelper.GetWindowRect(WBListViewCtrl1.hWndColumnHeader);
        columnHeaderHeightGrid =  rectTemp.Height;
    }
    catch(e)
    {
        columnHeaderHeightGrid =  10;
    }
}

function initGrid()
{
	initGridProperties();	
	
	SetGrid();	

	SetGraphProps();
	SetGraphValues();
		
	ds.Script.CheckIfWorksheetInReport();
}

function SetVars()
{
	numpoints = data.DataSet.Count;   //number of points to include in the chart
	criteria  = data.Criteria;
	helper	  = ds.Script.WBUtilsHelper;
	sigDigits = ds.AccessControl.ValueLength;
}

function SetGrid()
{
    if( (WBListViewCtrl1 == null) || (typeof(WBListViewCtrl1) == "undefined") )
        return;

    try
    {
        wndHelper.SetRedraw(WBListViewCtrl1.hWndColumnHeader,false);
        wndHelper.SetRedraw(WBListViewCtrl1.hWnd,false);
    }
    catch(e)
    {
    }

    if( (WBListViewCtrl1.ColumnHeaders == null) || (typeof(WBListViewCtrl1.ColumnHeaders) == "undefined") )
        return;

	if(0 == WBListViewCtrl1.ColumnHeaders.Count)
	{
		var lvwColumnCenter = 2;
		WBListViewCtrl1.ColumnHeaders.Add(null,null," ",25,lvwColumnCenter);

		var str = data.Parent.Name;
		if (data.Criteria == 2)
			str = "Force Summation";
		if(data.Criteria == 3)
			str = " Torque "+"("+ds.UnitSystem.UnitString(ds.Script.id_utMOMENT)+")";
		else if (data.Criteria == 4)
		    str = "Frequency" + "(" + ds.UnitSystem.UnitString(ds.Script.id_utFREQUENCY) + ")";
		else if (data.UnitString != " ")
			str += " "+"("+data.UnitString+")";
		WBListViewCtrl1.ColumnHeaders.Add(null,null,str,125,lvwColumnCenter);
	
		var strTemp = stringTable.String("ID_PercentChange");
		WBListViewCtrl1.ColumnHeaders.Add(null,null,strTemp,100,lvwColumnCenter);
	
		strTemp = stringTable.String("ID_Nodes");
		WBListViewCtrl1.ColumnHeaders.Add(null,null,strTemp,100,lvwColumnCenter);
	
		strTemp = stringTable.String("ID_Elements");
		WBListViewCtrl1.ColumnHeaders.Add(null,null,strTemp,100,lvwColumnCenter);
	}
	else
	{
		//column headers already added
		//just update the text
		WBListViewCtrl1.ColumnHeaders(1).Text = " ";
	    if( data && data.Parent )
	    {
		    var str = data.Parent.Name;
		    if (data.Criteria == 2)
			    str = "Force Summation";
		    if(data.Criteria == 3)
			    str = " Torque "+"("+ds.UnitSystem.UnitString(ds.Script.id_utMOMENT)+")";
		    else if (data.Criteria == 4)
		        str = "Frequency" + "(" + ds.UnitSystem.UnitString(ds.Script.id_utFREQUENCY) + ")";
		    else if (data.UnitString != " ")
			    str += " "+"("+data.UnitString+")";
		    WBListViewCtrl1.ColumnHeaders(2).Text = str;
    			
		    var strTemp = stringTable.String("ID_PercentChange");
		    WBListViewCtrl1.ColumnHeaders(3).Text = strTemp;
    	
		    strTemp = stringTable.String("ID_Nodes");
		    WBListViewCtrl1.ColumnHeaders(4).Text = strTemp;
    	
		    strTemp = stringTable.String("ID_Elements");
		    WBListViewCtrl1.ColumnHeaders(5).Text = strTemp;
		}
	}
	
	WBListViewCtrl1.ListItems.Clear();
	
	var i, numNEPoints, startPoint;
	
	for(i=1; i<=numpoints; i++)
	{
		var lstItem = WBListViewCtrl1.ListItems.Add(null,null,i);
		lstItem.ListSubItems.Add(null,null,data.DataSet.Value(i, 1));
		var changeValue = helper.GetFixedLengthFormat(data.DataSet.ValueDbl(i, 2)*100, sigDigits)
		lstItem.ListSubItems.Add(null,null,changeValue);
		lstItem.ListSubItems.Add(null,null,"");
		lstItem.ListSubItems.Add(null,null,"");
		
	}

	// work backwards for node/elements because old dsdb's won't have the data
	numNEPoints = data.NodeElemDataSet.Count;
	startPoint = numpoints - numNEPoints;
	for (i=1; i+startPoint<=numpoints; i++)
	{
		var nodes = parseInt(data.NodeElemDataSet.ValueDbl(i,1));  // num nodes
		var numElements = parseInt(data.NodeElemDataSet.ValueDbl(i,2));  // num elements
		WBListViewCtrl1.ListItems(i+startPoint).ListSubItems(3).Text = nodes;
		WBListViewCtrl1.ListItems(i+startPoint).ListSubItems(4).Text = numElements;
	}

	if(numpoints >= 1)
	{
		//set first solution's %change data to be empty
		WBListViewCtrl1.ListItems(1).ListSubItems(2).Text = "";
	}
	
	WBListViewCtrl1.AutoSizeColumns(0);
	
	resizeGrid(false);
	
	wndHelper.SetRedraw(WBListViewCtrl1.hWndColumnHeader,true);
	wndHelper.SetRedraw(WBListViewCtrl1.hWnd,true);
	
	wndHelper.Invalidate(WBListViewCtrl1.hWndColumnHeader,true);
	wndHelper.Invalidate(WBListViewCtrl1.hWnd,true);
}

function resizeGrid(bInvaliate)
{
	if(bInvaliate)
	{
		wndHelper.SetRedraw(WBListViewCtrl1.hWndColumnHeader,false);
		wndHelper.SetRedraw(WBListViewCtrl1.hWnd,false);
	}
	
	var countGrid = WBListViewCtrl1.ListItems.Count;
	if((countGrid+1) <= initialCountsPerPageGrid)
	{
		var height = minHeightGrid;
		if(countGrid > 0)
		{
			height = WBListViewCtrl1.ListItems.Item(1).Height;
		}
		WBListViewCtrl1.style.posHeight = (countGrid + 1) * height + columnHeaderHeightGrid;
	}
	else
	{
		if(WBListViewCtrl1.style.posHeight != initialHeightGrid)
		{
			WBListViewCtrl1.style.posHeight = initialHeightGrid;
		}
	}

	if(bInvaliate)
	{
		wndHelper.SetRedraw(WBListViewCtrl1.hWndColumnHeader,true);
		wndHelper.SetRedraw(WBListViewCtrl1.hWnd,true);
	
		wndHelper.Invalidate(WBListViewCtrl1.hWndColumnHeader,true);
		wndHelper.Invalidate(WBListViewCtrl1.hWnd,true);
	}
}

function ShowEmptyGrid()
{
	WBListViewCtrl1.style.display = "none";
}

function SetGraphValues()
{
	//set the y-axis data from the array passed to this file
	var yLabel = data.Parent.Name;
	if(data.Criteria == 2)
		yLabel = "Force Summation";
	if(data.Criteria == 3)
		yLabel = " Torque "+"("+ds.UnitSystem.UnitString(ds.Script.id_utMOMENT)+")";
	else if (data.Criteria == 4)
	    yLabel = "Frequency" + "(" + ds.UnitSystem.UnitString(ds.Script.id_utFREQUENCY) + ")";
	else if (data.UnitString != " ")
		yLabel += "  ("+data.UnitString+")";
	var xLabel = stringTable.String("ID_SolutionNumber");
	
	Graph1.Datasets.Clear();
	Graph1.Axes(0).Label = xLabel;						//set the x axis label
	Graph1.Axes(1).Label = yLabel;						//set the y axis label
	Graph1.Datasets.Add();								//create one dataset for the line
	Graph1.Datasets(0).LineColor = color(255, 0, 0);	//make the line red
	Graph1.TitleClear();								//clear any title that may exist
	Graph1.Axes(0).ShowDataLabel = false;
	
	for(var i=1; i<=numpoints; i++)
	{
		Graph1.Datasets(0).Add(i, data.DataSet.Value(i, 1), 0);  //always specify the z-value as zero because we are only using 2d
		Graph1.Axes(0).AddTextLabel(i, i);
	}
			
	Graph1.Axes(0).AutomaticLimits = true;	//graph will automatically set the x-axis limits
	Graph1.Axes(1).AutomaticLimits = true;	//graph will automatically set the y-axis limits
	Graph1.PickLines = true;
	
	if(numpoints > 1)
		Graph1.Axes(0).Divisions = (numpoints - 1);		//set the number of divisions so that each solution number will show on the grid
			
	Graph1.Axes(0).LabelFieldPrecision = 0;			//no decimal places on the x-axis
	Graph1.Axes(1).Divisions = 10;					//ten divisions for the y-axis
	Graph1.Axes(1).LabelFieldPrecision = 3;			//show three decimal places on the y-axis
	
	var maxy = Graph1.Datasets(0).Max(1);
	var miny = Graph1.Datasets(0).Min(1);
	var dif = Math.abs(maxy - miny)
	
	//if the data is very large or very small numbers, or if the difference 
	//between the min and max is small, show as an exponential 
	if(miny < 0.01 || maxy > 999 || dif <= 0.01 || dif >= 99)
		Graph1.Axes(1).LabelUseExponential  = true;
	
	if(numpoints == 1)
	{
		Graph1.Axes(0).AutomaticLimits = false;
		Graph1.Axes(0).ImposedLimitsMin = 0;
		Graph1.Axes(0).ImposedLimitsMax = 2;
		Graph1.Axes(0).Divisions = 2;
	}
	if(miny == maxy)
	{
		Graph1.Axes(1).AutomaticLimits = false;
		Graph1.Axes(1).ImposedLimitsMin = miny - 1;
		Graph1.Axes(1).ImposedLimitsMax = miny + 1;
	}
	
	if(numpoints == 1 || miny == maxy)
	{
		//if there is only one point, or if all points have the same value,
		//don't allow the user to click on the line to get a value
		Graph1.PickLines = false;
	}
	Graph1.Draw();
}

function SetGraphProps()
{
	//set the chart properties
	Graph1.Type = 4;						//2d line chart
	Graph1.Legend.Visible = false;			//hide the legend
	Graph1.TitleClear();					//clear titles
	Graph1.BackColor = wb.GetWindowColor();	//set backcolor to the window color
	Graph1.AxesLabelPointSize = 16;			//set font size for the axis labels
	Graph1.Axes(0).LabelPointSize = 13;		//set font size for the axis labels
	Graph1.Axes(1).LabelPointSize = 13;		//set font size for the axis labels
	Graph1.ZoomPanCtrlEnable = false;		//turn off the zoom/pan control 
	Graph1.Axes(0).LabelBold = true;		//make the x-axis title bold
	Graph1.Axes(1).LabelBold = true;		//make the y-axis title bold
    Graph1.Axes(1).LabelFieldSignificantDigits = ds.Script.DSSigDigitsForGraph;
    Graph1.Axes(0).LabelFieldSignificantDigits = ds.Script.DSSigDigitsForGraph;
}

function ShowEmptyGraph()
{
	Graph1.style.display = "none";
}

function refreshPage()
{
	numpoints = data.DataSet.Count;

	if(numpoints > 0 )  //if data exists
	{
		SetGrid();
		SetGraphValues();
	}
	else		//if there is no data to display
	{
		ShowEmptyGraph();
		ShowEmptyGrid();
	}
}

function window_onunload() 
{
	if(ds && ds.GUIState && ds.GUIState.GUIDriver)
        ds.GUIState.GUIDriver.MenuListener.RemoveListener(3);
	
	if(lvChangeCB)
	{
		lvChangeCB.RemoveCOM(this, "ListClickDelegate");
		lvChangeCB = null;
	}
	if(processStateCB)
	{
		processStateCB.RemoveCOM(this, "Processing_State_FinishedDelegate");
		processStateCB = null;
	}
	
	data = null;
	ds = null;
	wb = null;
}

function ListClickDelegate(sender, args)
{
    ListClick();
}

function ListClick()
{
	if(criteria != data.criteria)
	{
		if(data.DataSet.Count > 0)
		{
			SetGrid();
			//SizePageItems();
			SetGraphValues();
			criteria = data.criteria;
		}
	}
}

function color(red, green, blue)
{
	//returns an rgb color value
	return red + (256*green) + (65536*blue);
}

function Processing_State_FinishedDelegate(sender, args)
{
	Processing_State_Finished(args.Type);
}

function Processing_State_Finished(processCode)
{
	if(processCode == 2)
	{
		numpoints = data.DataSet.Count;   //number of points to include in the chart
		if(numpoints > 0 )  //if data exists
		{
			WBListViewCtrl1.style.display = "inline";
			Graph1.style.display = "inline";
			SetGrid();
			SetGraphProps();
			SetGraphValues();
		}
		else		//if there is no data to display
		{
			ShowEmptyGraph();
			ShowEmptyGrid();
		}
	}
}

function window_onresize() 
{
	SetGrid();
}

function WriteGraphToFile(imageMode, fileName)
{
	var height = parseInt(Graph1.style.height);
	var width = parseInt(Graph1.style.width);
	
	switch( imageMode )
	{
		case 0:  //png
			Graph1.WritePngFile( fileName, width, height, true );
			break;
			
		case 1:  //jpg
			Graph1.WriteJpgFile( fileName, width, height, true );
			break;
			
		case 3:  //bmp
			Graph1.WriteBmpFile( fileName, width, height, true );
			break;
			
	    default :
			break;
	}
}

function exportDataToFile( fileName )
{
	var fileText = createTextForFile();
	ds.Script.WriteTextInFile(fileName, fileText);
}

function createTextForFile()
{
	var fileText = "";
	
	var count = WBListViewCtrl1.ColumnHeaders.Count;
	
	//write the column titles to the file
	for(var i=1; i<=count; i++)
	{
		fileText += WBListViewCtrl1.ColumnHeaders.Item(i).Text;
		fileText += "\t";
	}
	fileText += "\n";
	
	var itemCount = WBListViewCtrl1.ListItems.Count;
	for(i=1; i<=itemCount; i++)
	{
		fileText += WBListViewCtrl1.ListItems.Item(i).Text;
		fileText += "\t";
		
		var subItemCount = WBListViewCtrl1.ListItems.Item(i).ListSubItems.Count;
		for(var j=1; j<=subItemCount; j++)
		{
			fileText += WBListViewCtrl1.ListItems.Item(i).ListSubItems(j).Text;
			fileText += "\t";
		}
		
		fileText += "\n";	
	}

	return fileText;
}

//-->
            </SCRIPT>
    </HEAD>
    <BODY LANGUAGE="javascript" onload="return window_onload()" onunload="return window_onunload()"
        onresize="return window_onresize()">
        <DIV id="div" class="gradient">
            <H1 id="pageName" LANGUAGE="javascript">&nbsp;</H1>
        </DIV>
        <OBJECT id="WBListViewCtrl1" style="LEFT: 15px; WIDTH: 468px; POSITION: absolute; TOP: 408px; HEIGHT: 240px"
            classid="clsid:8FD1FC60-73C7-4847-8199-1AFD5724F190">
        </OBJECT>
        <OBJECT id="Graph1" style="DISPLAY: none; LEFT: 0px; WIDTH: 472px; POSITION: absolute; TOP: 45px; HEIGHT: 354px"
            classid="clsid:F113A120-C83C-47B5-847C-179B339C42B7">
        </OBJECT>
    </BODY>
</HTML>
