// JScript source code
var wb = null;		      // Main workbench object set by config.xml
var edApplet = null;    // Engg Data applet object
var eds = null;         // Engg Data script engine
var eda = null;         // Engg Data namespace object (main.js)
var edpe = null;        // Engg Data Property Editor object

var edVDe = null;       // Engg Data Variable Data Editor object

// ListView Control Style declarations


var ListBox1Selection = 0;	// 1 when defined equations selected, 2 when mathematical operators selected
var PolynomialCoeffCount = 0, HarmonicCoeffCount = 0;			
var PolynomialCoeffIds = new Array("p0", "p1", "p2", "p3");
var HarmonicCoeffIds = new Array("h0", "h1", "h2", "h3");
var isEquationBoxActive = 0;				// status flag to check if the EquationBox is active or poly/harmonic
var isPolynomial = 0;			// flag to indicate if polynomial is selected
var isHarmonic = 0;			// flag to indicate if harmonic is selected

edVarDataFunctionScope.prototype.testCoeff = 0;		// to support testbench



// function to save the Caret position everytime its changed
edVarDataFunctionScope.prototype.saveCaret = function()
{
	if ( window.event.srcElement.isTextEdit )
		window.event.srcElement.caretPos = document.selection.createRange();
}

// function to insert the pre-defined parameters listed in the list box
edVarDataFunctionScope.prototype.insert_text = function(text1)
{
	if (document.getElementById('EquationBox') || document.getElementById('CoeffInput'))
	{
		if (isPolynomial == 0 && isHarmonic == 0)
			elem = document.getElementById('EquationBox');
		else
			elem = document.getElementById('CoeffInput');
		if ( elem.isTextEdit && elem.caretPos )
		{
			var caretPos = elem.caretPos;
			caretPos.text = text1;
		}
		else if (elem.value.length == 0)
		{
		   elem.value = text1;
		}
		else
		{
		   elem.value = elem.value + text1;
		}
	   EquationBox.setActive();
	   EquationBox.focus();
	}
}

// initialize everything
edVarDataFunctionScope.prototype.window_onload_eqn = function()
{
//	ListBox1.options[3] = new Option("Defined Equations");
	ListBox1.options[0] = new Option("Mathematical Functions");
	ListBox1.options[1] = new Option("Available Operators");
	ListBox1.options[2] = new Option("Independent Variables");
	eda.VarDataScript.remove_elements(polynomial);
	eda.VarDataScript.remove_elements(harmonic);
	eda.VarDataScript.remove_elements(Expression);
	var name = eda.DataViewScript.ActiveItem.Dependents.Item(1).name;
	var units = "("+eda.DataViewScript.ActiveItem.Dependents.Item(1).UnitsRemark(edApplet.UnitSystemID)+")";
	eda.VarDataScript.add_span(Expression, name + "&nbsp;" + units + "&nbsp;= ");
	var text_box = document.createElement("INPUT");
	text_box.setAttribute("size", "130");
	text_box.onclick = eda.VarDataScript.saveCaret;
	text_box.onkeyup = eda.VarDataScript.saveCaret;
	text_box.onchange = eda.VarDataScript.saveCaret;
	text_box.setAttribute("id", "EquationBox");
	Expression.appendChild(text_box);
	isPolynomial = 0;
	isHarmonic = 0;
	isEquationBoxActive = 0;
	PolynomialCoeffCount = 0;
	HarmonicCoeffCount = 0;
	ListBox2.style.width = 100;
	ListBox2.disabled = false;
	EquationBox.setActive();
}


// function to update the 2nd list everytime list 1 is changed
edVarDataFunctionScope.prototype.update_list2 = function ()
{	

	if (ListBox1.selectedIndex == 3)
	{
		ListBox1Selection = 3;
		eda.VarDataScript.remove_elements(ListBox2);
		ListBox2.options[0] = new Option("Polynomial");
		ListBox2.options[1] = new Option("Harmonic");
	//	ListBox2.options[2] = new Option("Table");
		ListBox2.disabled = false;
	}
	else if (ListBox1.selectedIndex == 2)
	{
		ListBox1Selection = 2;
		eda.VarDataScript.remove_elements(ListBox2);
		ListBox2.options[0] = new Option("time");
		ListBox2.disabled = false;
	}
	else if (ListBox1.selectedIndex == 0)
	{
		ListBox1Selection = 1;
		eda.VarDataScript.remove_elements(ListBox2);
		ListBox2.options[0] = new Option("sin");
		ListBox2.options[1] = new Option("cos");
		ListBox2.options[2] = new Option("tan");
		ListBox2.options[3] = new Option("asin");
		ListBox2.options[4] = new Option("acos");
		ListBox2.options[5] = new Option("atan");
		ListBox2.options[6] = new Option("atan2");
		ListBox2.options[7] = new Option("log");
		ListBox2.options[8] = new Option("log10");
		ListBox2.options[9] = new Option("pow");
		ListBox2.options[10] = new Option("sqrt");
		
		if (!document.getElementById('EquationBox'))
			ListBox2.disabled = true;
//		ListBox2.options[11] = new Option("floor");
//		ListBox2.options[12] = new Option("fmod");
//		ListBox2.options[13] = new Option("rand");
//		ListBox2.options[14] = new Option("ceil");
//		ListBox2.options[15] = new Option("exp");
	}
		else if (ListBox1.selectedIndex == 1)
	{
		ListBox1Selection = 2;
		eda.VarDataScript.remove_elements(ListBox2);
		ListBox2.options[0] = new Option("+");
		ListBox2.options[1] = new Option("-");
		ListBox2.options[2] = new Option("/");
		ListBox2.options[3] = new Option("*");
		ListBox2.options[4] = new Option("^");
		ListBox2.options[5] = new Option("%");
	}
	if (document.getElementById('EquationBox'))
		window.setTimeout("EquationBox.setActive()",20);
}

// function to create a table dynamically

edVarDataFunctionScope.prototype.create_table = function ()
{
	
	for (var index = 0;index<4;index++)
	{
		if ( document.getElementById(PolynomialCoeffIds[index]) )
		{
			if(document.getElementById(PolynomialCoeffIds[index]).isactive == 1)
				return;
		}
	}
	for (index = 0;index<4;index++)
	{
		if ( document.getElementById(HarmonicCoeffIds[index]) )
		{
			if(document.getElementById(HarmonicCoeffIds[index]).isactive == 1)
				return;
		}
	}
	if (eda.VarDataScript.testCoeff == 0)
		var Coeff = window.event.srcElement.parentNode;
	else
		var Coeff = document.getElementById(eda.VarDataScript.testCoeff);
	
	if (Coeff.isactive == 0)
	{	
		eda.VarDataScript.check_edit();
		Coeff.innerText = "";
		var newTable = Coeff.document.createElement("TABLE");
		newTable.style.display = "inline";
		Coeff.appendChild(newTable);
		if (eda.VarDataScript.testCoeff == 0)
			var newTableBody = window.event.srcElement.document.createElement("TBODY");
		else
			var newTableBody = Coeff.document.createElement("TBODY");
		newTable.appendChild(newTableBody);
		var newRow = newTableBody.insertRow();
		var col1 = newRow.insertCell();
		var inp = document.createElement("INPUT");
		col1.appendChild(inp);
		col1.setAttribute("id", "data");
		inp.setAttribute("id", "CoeffInput");
		inp.setAttribute("type", "text");
	//	inp.onclick = eda.VarDataScript.saveCaret;
	//	inp.onkeyup = eda.VarDataScript.saveCaret;
	//	inp.onchange = eda.VarDataScript.saveCaret;
		var col2 = newRow.insertCell();
		var sel = document.createElement("SELECT");
		col2.appendChild(sel);
		sel.setAttribute("id","select");
		//sel.onclick = check;
		var opt1 = document.createElement("OPTION");
		sel.appendChild(opt1);
		opt1.innerText = "Constant";
		var opt2 = document.createElement("OPTION");
		sel.appendChild(opt2);
		opt2.innerText = "Some Parameter";
		newTable.setAttribute("border","1");
		Coeff.isactive = 1;
		CoeffInput.setActive();
	}
}

//function to change the sign when it is double clicked
edVarDataFunctionScope.prototype.change_sign = function()
{
	if (window.event.srcElement.innerText == '+')
		window.event.srcElement.innerText = '-';
	else if(window.event.srcElement.innerText == '-')
		window.event.srcElement.innerText = '+';
}

// function to change the background color of the equation when clicked on the 1st parenthesis
edVarDataFunctionScope.prototype.change_color = function()
{
	id = window.event.srcElement.parentNode;
	if (id.style.backgroundColor == "beige")
		id.style.backgroundColor = "white";
	else
		id.style.backgroundColor = "beige";
}

//function to check the span element and associate corresponding function to the elements
edVarDataFunctionScope.prototype.check_element = function(span)
{
	var temp_text = span.innerText;
	if(temp_text == "p0" || temp_text == "p1" || temp_text == "p2" || temp_text == "p3"
		|| temp_text == "h0" || temp_text == "h1" || temp_text == "h2" || temp_text == "h3")
	{
		span.isactive = 0;
		span.onclick = eda.VarDataScript.create_table;
		if (isPolynomial == 1 && PolynomialCoeffCount < 4)
		{
			span.setAttribute("id", PolynomialCoeffIds[PolynomialCoeffCount]);
			PolynomialCoeffCount++;
		}
		else if (isHarmonic == 1 && HarmonicCoeffCount < 4)
		{
			span.setAttribute("id", HarmonicCoeffIds[HarmonicCoeffCount]);
			HarmonicCoeffCount++;
		}
	}
	if(temp_text == "+" || temp_text == "-")
		span.ondblclick = eda.VarDataScript.change_sign;
		
	if(temp_text == "(")
		span.onclick = eda.VarDataScript.change_color;
}

//function to create a new span element and append that to id
edVarDataFunctionScope.prototype.add_span = function(id, text)
{
	var newSpan = document.createElement("SPAN");
	id.appendChild(newSpan);
	newSpan.innerHTML = text;
	eda.VarDataScript.check_element(newSpan);
}

//function to remove all the child nodes from a parent node
edVarDataFunctionScope.prototype.remove_elements = function(node)
{
	if(typeof(node) == "undefined" || node == null)
	{
		return;
	}
	var len = node.childNodes.length;
	if (node.id == "ListBox2")
		ListBox2.innerHTML = "<OPTION></OPTION>";
	else
	{
		while (node.hasChildNodes())
		{
			node.removeChild(node.firstChild);
		}
	}
}


// function to add the selection to the expression
edVarDataFunctionScope.prototype.update_eqn = function ()
{
	//debugger;
	if(ListBox2.selectedIndex == 0 && ListBox1Selection == 3 && isPolynomial == 0)
	{
		if (isEquationBoxActive == 0)
		{
			eda.VarDataScript.remove_elements(Expression);
			isEquationBoxActive = 1;
			eda.VarDataScript.add_span(Expression, eda.DataViewScript.ActiveItem.Dependents.Item(1).name.fontcolor("Red") + "&nbsp;m".fontcolor("Green") + "&nbsp;= ");
		}
	
		var poly_op1 = "+"
		var poly_par = "(";
		var poly_a0 = "p0".fontcolor("Red");
//		var poly_t2 = "&nbsp;m ".fontcolor("Green"); //+ " + ";
		var poly_op2 = "+";
		var poly_a1 = "p1".fontcolor("Red");
		var poly_t3 = "*("+ "TIME".fontcolor("Blue") + ") "; //+ " + "
		var poly_op3 = "+";
		var poly_a2 = "p2".fontcolor("Red");
		var poly_t4 = "*("+ "TIME".fontcolor("Blue") + "^2) "; //+ " + ";
		var poly_op4 = "+";
		var poly_a3 = "p3".fontcolor("Red");
		var poly_t5 = "*("+ "TIME".fontcolor("Blue") + "^3))";
		
		isPolynomial = 1;
		eda.VarDataScript.add_span(polynomial, poly_op1);
		eda.VarDataScript.add_span(polynomial, poly_par);
		eda.VarDataScript.add_span(polynomial, poly_a0);
	//	eda.VarDataScript.add_span(polynomial, poly_t2);
		eda.VarDataScript.add_span(polynomial, poly_op2);
		eda.VarDataScript.add_span(polynomial, poly_a1);
		eda.VarDataScript.add_span(polynomial, poly_t3);
		eda.VarDataScript.add_span(polynomial, poly_op3);
		eda.VarDataScript.add_span(polynomial, poly_a2);
		eda.VarDataScript.add_span(polynomial, poly_t4);
		eda.VarDataScript.add_span(polynomial, poly_op4);
		eda.VarDataScript.add_span(polynomial, poly_a3);
		eda.VarDataScript.add_span(polynomial, poly_t5);
	}
	
	else if (ListBox2.selectedIndex == 1 && ListBox1Selection == 3 && isHarmonic == 0)
	{
		if (isEquationBoxActive == 0)
		{
			eda.VarDataScript.remove_elements(Expression);
			isEquationBoxActive = 1;
			eda.VarDataScript.add_span(Expression, eda.DataViewScript.ActiveItem.Dependents.Item(1).name.fontcolor("Red") + "&nbsp;m".fontcolor("Green") + "&nbsp;= ");
		}
		
		var har_a0 = "h0".fontcolor("Red");
		var har_a1 = "h1".fontcolor("Red");
		var har_a3 = "h2".fontcolor("Red");
		var har_a4 = "h3".fontcolor("Red");
		var har_h1 = "&nbsp";
		var har_op1 = "+";
		var har_par = "(";
		
		var har_t2 = "&nbsp;";
		var har_op2 = "+";
		
		var har_t3 = "&nbsp;*"+"sin".fontcolor("Gold") + "(";
	//	var hop3 = "+";
		
		var har_t4 = "&nbsp;*(" + "TIME".fontcolor("Blue") + ")";
		var har_op4 = "+";
		
		var har_t5 = "))";
		
		isHarmonic = 1;
		eda.VarDataScript.add_span(harmonic, har_h1);
		eda.VarDataScript.add_span(harmonic, har_op1);
		eda.VarDataScript.add_span(harmonic, har_par);	
		eda.VarDataScript.add_span(harmonic, har_a0);
		eda.VarDataScript.add_span(harmonic, har_t2);
		eda.VarDataScript.add_span(harmonic, har_op2);
		eda.VarDataScript.add_span(harmonic, har_a1);
		eda.VarDataScript.add_span(harmonic, har_t3);
		eda.VarDataScript.add_span(harmonic, har_a3);
		eda.VarDataScript.add_span(harmonic, har_t4);
		eda.VarDataScript.add_span(harmonic, har_op4);
		eda.VarDataScript.add_span(harmonic, har_a4);
		eda.VarDataScript.add_span(harmonic, har_t5);
	}
	
	else if ((ListBox1Selection == 1 || ListBox1Selection == 2) && (ListBox2.selectedIndex >=0))
	{
		if (ListBox1Selection == 1)
		{
			if (ListBox2.options[ListBox2.selectedIndex].text == "atan2" || ListBox2.options[ListBox2.selectedIndex].text == "pow")
				eda.VarDataScript.insert_text(ListBox2.options[ListBox2.selectedIndex].text+"(,)");
			else
				eda.VarDataScript.insert_text(ListBox2.options[ListBox2.selectedIndex].text+"()");
		}
		else
		{
			eda.VarDataScript.insert_text(ListBox2.options[ListBox2.selectedIndex].text);
			if (document.getElementById('EquationBox'))
				EquationBox.setActive();
			return;
		}
	
		if(document.getElementById('CoeffInput'))
		{
			CoeffInput.setActive();
			var range = document.selection.createRange();
			var bookmark = range.getBookmark();				// returns an "opaque string" as MS calls it 
			var caret_pos = bookmark.charCodeAt(2) - 2;		// in that opaque string, the third char is the cursor position + 2
			range = CoeffInput.createTextRange();
			range.collapse(true);
			range.moveStart("character", caret_pos - 1);	// starting position of the selection of text
			range.moveEnd("character", 0);					//"0" indicates the number of charaters to be selected from the starting position 	
			range.select();
		}
		
		else if (document.getElementById('EquationBox'))
		{
			EquationBox.setActive();
			var range = document.selection.createRange();
			var bookmark = range.getBookmark();
			var caret_pos = bookmark.charCodeAt(2) - 2;
			range = EquationBox.createTextRange();
			range.collapse(true);
			range.moveStart("character", caret_pos - 1);
			range.moveEnd("character", 0);
			range.select();
		}
	}
}

//function to check for the validity of the input entered in polynomial/harmonic eqns
edVarDataFunctionScope.prototype.check_for_only_numbers = function()
{
	if (document.getElementById('CoeffInput'))
	{
		fieldvalue = CoeffInput.value;
		if (!isNaN(fieldvalue)) // && (fieldvalue>0))
			return true;
		else
			{	
				edApplet.Script.WBScript.Out("Invalid input",true,"Error");
				return false;
			}
	}
}

//function executed when clicked on body to replace the table with the value entered
edVarDataFunctionScope.prototype.check_edit = function ()
{		
	if(eda.VarDataScript.check_for_only_numbers())
	{		
		for (var index = 0;index<4;index++)
		{
			if ( document.getElementById(PolynomialCoeffIds[index]) )
			{
				t = document.getElementById(PolynomialCoeffIds[index]).isactive;
				var id = document.getElementById(PolynomialCoeffIds[index]);
				
				if(t == 1)
				{
					if (CoeffInput.value == "")
					{
						text = id.id; 
						eda.VarDataScript.remove_elements(id);
						id.innerHTML = text.fontcolor("Red");
					}
					else
					{
						text = CoeffInput.value;
						eda.VarDataScript.remove_elements(id);
						id.innerHTML = text.fontcolor("Black");
					}
					id.isactive = 0;
				}
			}
		}
		
		for (index = 0;index<4;index++)
		{
			if ( document.getElementById(HarmonicCoeffIds[index]) )
			{
				t = document.getElementById(HarmonicCoeffIds[index]).isactive;
				var id = document.getElementById(HarmonicCoeffIds[index]);
				if(t == 1)
				{
					if (CoeffInput.value == "")
					{
						text = id.id; 
						eda.VarDataScript.remove_elements(id);
						id.innerHTML = text.fontcolor("Red");
					}
					else
					{
						text = CoeffInput.value;
						eda.VarDataScript.remove_elements(id);
						id.innerHTML = text.fontcolor("Black");
					}
					id.isactive = 0;
				}
			}
		}
	}// end of if
}

//function to check which element is clicked
edVarDataFunctionScope.prototype.whichElement = function(e)
{
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ)
	{
		if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
		var tname;
		tname=targ.tagName;
		if (tname == "BODY" || tname == "P")
			eda.VarDataScript.check_edit();
	}
}

//function to delete the equation when the delete key is pressed and perform the 'enter' function
edVarDataFunctionScope.prototype.delete_eqn = function()
{
	if (window.event.keyCode == 13)
	{
		if (!document.getElementById('CoeffInput'))
			eda.VarDataScript.evaluate_eqn();
		else
			eda.VarDataScript.check_edit();
	}
	else if (window.event.keyCode == 46)
	{
		if (polynomial.style.backgroundColor == "beige")
		{
			polynomial.style.backgroundColor = "white";
			eda.VarDataScript.remove_elements(polynomial);
			isPolynomial = 0;
			PolynomialCoeffCount = 0;
			if (isPolynomial == 0 && isHarmonic == 0)
			{
				eda.VarDataScript.window_onload_eqn();
				isEquationBoxActive = 0;
			}
		}
		if (harmonic.style.backgroundColor == "beige")
		{
			harmonic.style.backgroundColor = "white";
			eda.VarDataScript.remove_elements(harmonic);
			isHarmonic = 0;
			HarmonicCoeffCount = 0;
			if (isPolynomial == 0 && isHarmonic == 0)
			{
				eda.VarDataScript.window_onload_eqn();
				isEquationBoxActive = 0;
			}
		}
	}			
}

//function to evaluate the equation, executed when clicked on "get result"
edVarDataFunctionScope.prototype.evaluate_eqn = function()
{
	//debugger;
	var equation = "";
	if (isPolynomial == 0 && isHarmonic == 0)
	{
		if (EquationBox.value == "")
			return;
		equation = EquationBox.value;
	}
	else 
	{
		if (isPolynomial == 1)
			equation = polynomial.innerText;
		if (isHarmonic == 1)
			equation = equation + harmonic.innerText;
	}	
	try
	{
		var eqnSolver =eds.CreateActiveXObject(eds.GenWBProgId("WBEqnSolver.EqnSolver"));
		eqnSolver.AnsysSolverCheck = true;
		var eqn_var = eqnSolver.Variables;
		eqn_var.Add("time", (0.1/100)*eTime.value );
		eqnSolver.Equation = equation + ";";
		var ParseCheck = false;
		var myGraph = eda.DataViewScript.ActiveItem;
		myGraph.setGraphInformation(sTime.value,eTime.value,nPoints.value,edApplet.UnitSystemID);
		var objLVXFunc = myGraph.Dependents.Item(1).Function;
		if (objLVXFunc.ActiveDomain == 1)
		{
			objLVXFunc.AddDomain(0.0,-999.0,equation);
			objLVXFunc.ActiveDomain = 2;
			objLVXFunc.UnitSystem = edApplet.UnitSystemID;
		}
		else
		{
			objLVXFunc.Domains.Item(objLVXFunc.ActiveDomain).Expression = equation;
		}
		var objGraph = myGraph.GraphObject;
		var msg = objGraph.Source;
		var isValid;
		try
		{
			isValid = objGraph.Validation(msg);
		}
		catch(err)
		{
			var buttonType = 0;

			var MBBT_OK = 0;
			var MBBT_TASKMODAL = 8192;

			buttonType = buttonType + MBBT_OK + MBBT_TASKMODAL;

			var retval = edApplet.Script.WBScript.Out(err.description, true, "Expression Error", buttonType);
			
			//edApplet.Script.WBScript.Out( err.description,true,"Expression Error");
		}
		eqnSolver.Parse();
		ParseCheck = true;
		var result = eqnSolver.Evaluate();
		if (eda.PropGraphScript)
		{
			eda.PropGraphScript.GetGraphData(myGraph);
			eda.ProjectViewObj.ChangeState(eda.ActiveViewTree.SelectedItem)
		}
	}
	catch(err)
	{
		if (isNaN(sTime.value) || sTime.value == "")
		{
			edApplet.Script.WBScript.Out("Graph Start Time invalid", true, "Error");
			return;
		}
		if (isNaN(eTime.value) || eTime.value == "")
		{
			edApplet.Script.WBScript.Out("Graph End Time invalid", true, "Error");
			return;
		}
		else if (isNaN(nPoints.value) || nPoints.value == "")
		{
			edApplet.Script.WBScript.Out("Number of points invalid",true,"Error");
			return;
		}
		else if (isPolynomial == 0 && isHarmonic == 0)
		{
		/*	if (ParseCheck == false)
			{
				var error = err.description;
				var arr1 = new Array();
				arr1 = error.split(" ");
				var temp = arr1[arr1.length - 1];
				if (temp == "undefined" || temp == "defined")
				{
					var arr = new Array();
					arr = error.split("'");
					var pos;
					pos = equation.search(arr[1]);
					var l = arr[1].length;
					var range = EquationBox.createTextRange();
					range.collapse(true);
					range.moveStart("character", pos);
					range.moveEnd("character", l);
					range.select();
				}
				else if (arr1[2] == "unexpected")
				{	
					try
					{
						var pos;
						var arr = new Array();
						if ( arr1[3] == "token:")
						{
							arr = error.split(" ");
							arr2 = arr[1].split(":");
							//pos = equation.indexOf(arr[arr.length-1]);
							pos = arr2[1];
							var l = arr[arr.length-1].length;
						}
						else if (arr1[3] == "char:")
						{
							arr = error.split("'");
							pos = equation.indexOf(arr[arr.length-2]);
							var l = arr[arr.length-2].length;
						}
						var range = EquationBox.createTextRange();
						range.collapse(true);
						range.moveStart("character", pos);
						range.moveEnd("character", l);
						range.select();
						EquationBox.setActive();
					}
					catch(err)
					{
					}
				}	
			}
		//	edApplet.Script.WBScript.Out( err.description,true,"Error");
		//	EquationBox.setActive();*/
		}// end of else
		
		
	}// end of catch
}

function GenWBProgId(str)
{
	return str + ".161";
}

function edVarDataFunctionScope ()
{
   this.m_lCurrentCurve = 1;
   this.m_lActiveUSBegin = 1;     // The active UniqueSet begin value
   this.m_lActiveUSEnd = 1;       // The active UniqueSet end value
   this.m_lActiveDependent = 1;
   
   this.m_objColHeading_DepVsPrim = null;
   this.m_objWBDGCtrl_DepVsPrim = null;
   this.m_objColHeading_Independents = null;
   this.m_objWBDGCtrl_Independents = null;
   
   this.m_objOptionwbGH = null;
   
   //For testing only
   this.TBRefreshDone = false;
}

function edPropEditScope ()
{
   this.document = null;
   this.timeInterval = 0;
   this.editCurveData = null;
   this.editXYData = null;
   this.scaleValue = 1.0;
   this.offsetValue = 0.0;
   this.IndependentArr = [];
   this.PrimaryIndependent = null;
   this.currentCurve = 1;
   this.currentDependent = 0;
   this.DependentArr = [];
   this.xmlDoc = null;
   this.menuLoader = null;
   this.varOptions = [];
   this.CurrentProperty = null;
}

function edPropEditListViewCtrl ( wbListViewCtrl )
{
   this.lv = wbListViewCtrl;
   this.initialCountsPerPageGrid = 30;
   this.columnHeaderHeightGrid =  25;
   this.initialHeightGrid = 389;//based on the width property in Object Tag
}

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;
	//invalidColor = eds.color(255,240,0);

	// Don't allow the user to select on the IE page
	eda.OverloadDefaultEvents(document);
	edpe = new edPropEditScope();
	eda.ActiveScript = edpe;
	eda.PropEditScript = edpe;
	edVDe = new edVarDataFunctionScope();
	eda.VarDataScript = edVDe;
	edVDe.window = window;
	edVDe.document = document;

	EDAPropertyEditor.onkeypress = eda.VarDataScript.delete_eqn;
	EDAPropertyEditor.onmousedown = eda.VarDataScript.whichElement;
	ListBox1.onchange = eda.VarDataScript.update_list2;
	ListBox2.ondblclick = eda.VarDataScript.update_eqn;
	InsertButton.onclick = eda.VarDataScript.update_eqn;
	DisplayButton.onclick = eda.VarDataScript.evaluate_eqn;
	    
	//	ListBox1.options[3] = new Option("Defined Equations");
	ListBox1.options[0] = new Option("Mathematical Functions");
	ListBox1.options[1] = new Option("Available Operators");
	ListBox1.options[2] = new Option("Independent Variables");
	eda.VarDataScript.remove_elements(polynomial);
	eda.VarDataScript.remove_elements(harmonic);
	eda.VarDataScript.remove_elements(Expression);
	var text_box = document.createElement("INPUT");
	text_box.setAttribute("size", "73");
	text_box.onclick = eda.VarDataScript.saveCaret;
	text_box.onkeyup = eda.VarDataScript.saveCaret;
	text_box.onchange = eda.VarDataScript.saveCaret;
	text_box.setAttribute("id", "EquationBox");
	isPolynomial = 0;
	isHarmonic = 0;
	isEquationBoxActive = 0;
	PolynomialCoeffCount = 0;
	HarmonicCoeffCount = 0;	
	ListBox2.style.width = 100;	

	var name = eda.DataViewScript.ActiveItem.Dependents.Item(1).name;
	
	var units = "("+eda.DataViewScript.ActiveItem.Dependents.Item(1).UnitsRemark(edApplet.UnitSystemID)+")";
	//eda.VarDataScript.add_span(Expression, name + "&nbsp;" + units + "&nbsp;= ");
	eda.VarDataScript.add_span(Expression, name + "&nbsp;= ");
	Expression.appendChild(text_box);
	// This determines Internet Explorer's major version number,
	// or 0 for others. It works by finding the "MSIE " string and
	// extracting the version number following the space, up to the decimal
	// point, ignoring the minor version number
	var ieVersion = 0;
	var ua = window.navigator.userAgent;
	var msie = ua.indexOf ( "MSIE " );

	if ( msie > 0 )      // The version for Internet Explorer is available
		ieVersion = parseInt (ua.substring (msie+5, ua.indexOf (".", msie )));

	if(ieVersion < 6)
	{
		edpe.timeInterval = window.setInterval("edpe.PageLoaded()", 250);
	}
	else
	{
		edpe.PageLoaded();
	}
	eda.VarDataScript.RefreshView();
	edpe.document = document;
	ListBox1.selectedIndex = 0;
	eda.VarDataScript.update_list2();
	
//	debugger;
	if (EquationBox.value == "")
	{
		var unitsys = edApplet.UnitSystemID;
		eda.DataViewScript.ActiveItem.Function.UnitSystem = unitsys;
	}
	else 
		var unitsys = eda.DataViewScript.ActiveItem.Function.UnitSystem;
		
	
	if (eda.DataViewScript.ActiveItem.Function.AngleInDegrees)
		var angle = "Degrees";
	else
		var angle = "Radians";
		
	var unitString = eds.GetUnitSystemString(unitsys);
	eda.VarDataScript.evaluate_eqn();
//	EquationBox.setActive();
	eda.VarDataScript.add_span(UnitSystem, "Function Unit System: "+unitString + " " + angle);
 
}

function window_onunload()
{
   try
   {
		var lActiveItem = eda.DataViewScript.ActiveItem;
		var lobjLVXFunc = lActiveItem.Dependents.Item(1).Function;
		var lExpression = EquationBox.value;
		if (lExpression.length)
		   lobjLVXFunc.Domains.Item(lobjLVXFunc.ActiveDomain).Expression = lExpression;
   
		eda.PropEditScript = null;
		eda.VarDataScript = null;
		if (eda.ActiveScript == edpe)
			eda.ActiveScript = null;
   }
   catch(error)
   {
      debugger;
   }
   try
   {
      var VarData = edVDe.m_objWBDGCtrl_DepVsPrim.dg.Cell(1,1).Tag;
      VarData.AllowSort = true;
   }
   catch(error)
   {
     // debugger;
   }
}

edPropEditScope.prototype.PageLoaded = function ()
{
	try
	{
		if( !isNaN(edpe.timeInterval) )
			window.clearInterval(edpe.timeInterval);
		edpe.timeInterval = 0;
		if ( EDAPropertyEditor )
		{
			// The page is loaded so initialize all of the information
			// edVDe.m_objWBDGCtrl_Independents = new edVDDataGridCtrl();
			// edVDe.m_objWBDGCtrl_DepVsPrim = new edVDDataGridCtrl();
			if (typeof(EDA_VDE_FitTestDataButton) != "undefined")
			{
				var prop = edVDe.getCurrentProperty();
				if (prop && prop.CurveFit)
				{
					EDA_VDE_FitTestDataButton.style.display = "block";
					EDA_VDE_FitTestDataButton.innerHTML = eds.wbGetLocalString( edApplet.stringTable, "ID_FitTestData");
				}
				else
				{
					EDA_VDE_FitTestDataButton.style.display = "none";
				}
					EDA_VDE_FitTestDataButton.onclick = edVDe.FitTestData;
			}
			edVDe.RefreshView();
			edVDe.updateBreadcrumbs();
		}
	}
	catch (e)
	{
		if( !isNaN(edpe.timeInterval))
			window.clearInterval(edpe.timeInterval);
		edpe.timeInterval = window.setInterval("edpe.PageLoaded()", 250);
	}
}


function edVarDataFunctionScope.prototype.RefreshView ( prop )
{
	//debugger;
	if (prop) this.CurrentProperty = prop;
	try
	{	
		var g = eda.DataViewScript.ActiveItem;
		var objLVXFunc = g.Dependents.Item(1).Function;
		if (eda.PropGraphScript)
		{
			eda.PropGraphScript.GetGraphData( );	        
			if (objLVXFunc.ActiveDomain != 1)
			{
            EquationBox.value = objLVXFunc.Domains.Item(objLVXFunc.ActiveDomain).Expression;

            sTime.value = g.get_GraphInformation(0);
            eTime.value = g.get_GraphInformation(1);
            nPoints.value = g.get_GraphInformation(2);
			}
		}
	}
	catch(error)
	{
	}

	this.TBRefreshDone = true;
}

function edVarDataFunctionScope.prototype.FitTestData ( )
{
	var prop = edVDe.getCurrentProperty();
	eds.beginWaitCursor();

	try
	{
		prop.FitToExperiments();
	}
	catch(error)
	{
		var errString = eds.wbGetLocalString( edApplet.stringTable, "ID_UnableToFit");
		eds.wbErrorMsgBox(errString, eds.wbGetLocalString( eds.stringTable, "ID_FitTestData"));
	}	
	eds.endWaitCursor();
	edVDe.RefreshView();
}

function edVarDataFunctionScope.prototype.getCurrentProperty ( )
{
   var prop = null;

   if ( this.CurrentProperty == null && (eda.DataViewScript && eda.DataViewScript.ActiveSubItem == null)) return prop;

   if (!eda.DataViewScript.ActiveSubItem)
   {
	 if (eda.DataViewScript.ActiveSubItemName != "")
	  {
		var propStr = "eda.DataViewScript.ActiveItem.getProperty(\"" + eda.DataViewScript.ActiveSubItemName + "\")";
		prop = eval(propStr);
		return prop;	
	  }
   }

   try
   {
	   var propStr = "eda.DataViewScript.ActiveItem.getProperty(eda.matPropEnums." + eda.DataViewScript.ActiveSubItem + ")";
	   prop = eval(propStr);
   }
   catch(error)
   {
		try
		{
			var propStr = "eda.DataViewScript.ActiveItem.getProperty(eda.DataViewScript.ActiveSubItem)";
			prop = eval(propStr);
		}
		catch(error)
		{
			try
			{
				// The ActiveSubItem is likely the property
				prop = eda.DataViewScript.ActiveSubItem;
			}
			catch(error)
			{
			}
		}
   }
   return prop;
}
function edVarDataFunctionScope.prototype.updateBreadcrumbs ()
{
	try
	{
		var breadcrumbs =	eda.BreadCrumbScript.HTMLBreadCrumbs;
		var activeObj = eda.DataViewScript.ActiveItem;
		var prop = this.getCurrentProperty ( );

		if (activeObj.Class == id_Material)
			breadcrumbs.children[0].innerText = activeObj.Name + " - " + prop.Name ;
		else if (activeObj.Class == id_Convection)
			breadcrumbs.children[0].innerText = activeObj.Name;// + " - " + activeObj.Dependents.Item(1).Name ;
		else if (activeObj.Class == id_LoadVariation)
			breadcrumbs.children[0].innerText = activeObj.Name;// + " - " + activeObj.Dependents.Item(1).Name ;
	}
	catch(error)
	{
		debugger;
	}
}
