/**************
** By Kevin Cooper, Washington State University
** December 2001
**
**  This script provides tools to make various types of Java applets, 
**  using the JaMBA beans.  This script writes the HTML required to 
**  take advantage of those Java elements.
**
**  Take note: this script must be used in conjunction with a framed
**  HTML setup.  The following frame script works:
**
**  <frameset cols="40%,60%">
**  <frame src="your_file_name_here.html" name="left">
**  <frame src="blank.html" name="right">
**  </frameset>
**
**  The critical line is the third, which opens a blank frame labeled 
**  "right".  You could even leave the frame empty, if you wish.
***************/
var rightwin = parent.right;
var doc=rightwin.document;
var indepvar="none";
var depvar="none";
var parambox=false;
var setbox=false;
var display2d=false;
var bvpdisplay=false;
var icbox=false;
var sizebox=false;
var numcurves=0;
var message=new String();
var eq_htmlstring = new String('Legend:<br>');
var eq_strings = new Array();
var displaytype = new Array();
var dependent_vars = new Array();
var numfunction = 0;
/*
** This is supposed to parse each of the entries from the form and write the corresponding 
** display element tags.  In other words, this is supposed to write the display(), parambox,
** setbox, and other such tags for the applet.
*/
function ElementHandler(nelements,writewin){
	var i,j,k;
	var indarray;
	var ind;
	var t1;
	var paramboxlocation;
	var side;
	var parsearray;
	var parameternames = new Array();
	numfunction = 0;
	for(i=0;i<nelements;i++){
		var elt = document.appletform.elements[i];
		if(elt.name.indexOf('equation')>=0){
			ind = elt.name.split("_")[1];
			t1 = elt.value;
			eq_strings[ind] = t1;
			if(t1 != ''){
				doc.writeln('<param name="equation('+ind+')" value="'+t1+'">');
				writeCurveVars(t1,ind);
			}
		}
		else if(elt.name.indexOf('color')>=0){
			ind = elt.name.split('_')[1];
			if(eq_strings.length > ind){
				if(elt.name.indexOf('traj')>=0){
					writeTrajColor(document.appletform.elements[i],ind);
				}
				else{
					writeCurveColor(document.appletform.elements[i],ind);
				}
			}
		}
		else if(elt.name.indexOf('parameter_name')>=0){
		    side = elt.name.split('_')[2];		// Actually this is the index of the parameter
		    t1 = elt.value;				// This is the parameter name...
		    parameternames[side] = t1;
		}
		else if(elt.name.indexOf('parameter_value')>=0){
		    side = elt.name.split('_')[2];		// Actually this is the index of the parameter
		    t1 = elt.value;				// This is the parameter value
		    doc.writeln('<param name="'+parameternames[side]+'.value" value="'+t1+'">');
		}
		else if(elt.name.indexOf('displaytype')>=0){
		    side = elt.name.split('_')[1];
		    t1 = elt.value;
			displaytype[side]=t1;
			/*
			** Possible display types should include
			** plain - a plot of the independent variable against the first dependent variable
			** plain_j - a plot of the independent variable against the jth dependent var.
			** i_j - a plot of the i-th dependent variable against the j-th.
			*/
		}
		else if(elt.name.indexOf('displaylocation')>=0){
		    side = elt.name.split('_')[1];
		    dims = elt.value.split('_');
			/*
			** dims should be indexed so that 
			** element 0 is the left bound within the applet (usually zero), element
			** 1 is the right bound, element 2 is the top, and element 3 is the
			** bottom.
			*/
			doc.writeln('<param name="display('+side+').background.red" value=".95">\n');
			doc.writeln('<param name="display('+side+').background.green" value=".95">\n');
			doc.writeln('<param name="display('+side+').background.blue" value=".95">\n');
			doc.writeln('<param name="display('+side+').foreground.red" value="0">\n');
			doc.writeln('<param name="display('+side+').foreground.green" value="0">\n');
			doc.writeln('<param name="display('+side+').foreground.blue" value="0">\n');
			doc.writeln('<param name="display('+side+').left" value="'+dims[0]+'">\n');
			doc.writeln('<param name="display('+side+').top" value="'+dims[2]+'">\n');
			doc.writeln('<param name="display('+side+').right" value="'+dims[1]+'">\n');
			doc.writeln('<param name="display('+side+').bottom" value="'+dims[3]+'">');
		}
		else if(elt.name.indexOf('setbox')>=0){
		    side = elt.name.split('_')[1];
		    t1 = elt.value;
		    doc.writeln('<param name="setbox.'+side+'" value="'+t1+'">');
		}
		else if(elt.name.indexOf('parambox')>=0){
		    side = elt.name.split("_")[1];
		    t1 = elt.value;
		    doc.writeln('<param name="parambox.'+side+'" value="'+t1+'">');
		}
		else if(elt.name.indexOf('icbox')>=0){
		    side = elt.name.split('_')[1];
		    t1 = elt.value;
		    doc.writeln('<param name="icbox.'+side+'" value="'+t1+'">');
		}
		else if(elt.name.indexOf('boundbox')>=0){
		    side = elt.name.split('_')[1];
		    t1 = elt.value;
		    doc.writeln('<param name="boundbox.'+side+'" value="'+t1+'">');
		}
		else if(elt.name.indexOf('limit')>=0){
			/*
			** Setting limits is a little problematic.  If this is just a one-D plot
			** of functions, then we have only some independent variable and some
			** dependent variable to plot.  If, on the other hand, it is a DE plot
			** or one of several DE plots, then it might have any variables on the
			** axis.  Thus, we offer several forms for the tags this parses:
			** limit_x_minimum - sets the minimum of the independent variable
			** limit_x_maximum - sets the maximum of the independent variable
			** limit_y_m##imum - sets the min or max of the single dependent variable.
			** limit_0_m##imum - sets the min or max of the 0-th dependent variable.
			** limit_i_m##imum - sets the min or max of the i-th dependent variable.
			*/
		    parsearray = elt.name.split('_');
		    side = parsearray[2];
		    t1 = elt.value;
		    if(parsearray[1] == "x"){
			    doc.writeln('<param name="'+indepvar+'.'+side+'" value="'+t1+'">');
		    }
		    else if(parsearray[1] == "y"){
			    doc.writeln('<param name="'+depvar+'.'+side+'" value="'+t1+'">');
		    }
			else if(parsearray[1] >= 0 && parsearray[1] < dependent_vars.length){
				var v_ind = parsearray[1];
			    doc.writeln('<param name="'+dependent_vars[v_ind]+'.'+side+'" value="'+t1+'">');
			}
		}
	}
}
/*
   This is the control function for all of the machines that write the HTML.
*/
function WriteAppletTags(){
	/* 
	** First, get a handle on the frames.
	*/
	message = '';
	eq_htmlstring = '';
	doc.open();
	/* 
	** Title and style information
	*/
	doc.writeln('<head>');
	doc.writeln('<title>IDEA Java Generator</title>');
	doc.writeln('<style>');
	doc.writeln('P{}');
	doc.writeln('BODY {font-family: Arial,Helvetica,sans-serif; background-color: #fffff0;}');
	doc.writeln('H1 {text-align: center;}');
	doc.writeln('HR {width: 80%; height: 10px; float: center;}');
	doc.writeln('.header {font-size: x-large; text-align: center;}');
	doc.writeln('.credits {font-size: small; text-align: center;}');
	doc.writeln('</style></head>');
	doc.writeln('<p class="header">IDEA Java Applet Window <img src="idealogo.png" alt="Created using the IDEA Project"></p>');
	doc.writeln('<hr>');
	doc.writeln(' ');
	doc.writeln('<table width="100%" border="1"><tr><td>');
	/*
	** The applet tag
	*/
	doc.writeln('<applet codebase="http://www.math.wsu.edu/idea/Jamba" code="IDEAapplet.class" width=600 height=500>');
	doc.writeln('<param name="applet.xspacers" value="9">');
	/* 
	   Get the number of tags, and then pass the lot to an element handler.
	*/
	var ntags=document.appletform.elements.length;
	ElementHandler(ntags,rightwin);
	setDisplayVariables();
	doc.writeln('</applet>');
	doc.writeln('</td></tr></table>');
	/* Write any error messages that might have accumulated */
	doc.writeln(eq_htmlstring);
	doc.writeln('<p style="color:red">'+message);
	doc.writeln('<hr><p class="credits">');
	doc.writeln('This page produced by the <a href="http://www.math.wsu.edu/idea">IDEA Project</a><br>');
	doc.writeln('Permission is given for you to modify this HTML as you see fit.<br>');
	doc.writeln('Comments and questions should be addressed to <a href="mailto:kcooper@math.wsu.edu">Kevin Cooper</a>');
	doc.close();
}

/* 
** This function parses the variable names out of the equation and writes curve tags
** for them.  It also looks for dependent and independent variables for trajectories.
*/
function writeCurveVars(eqstring,curveindex){
	/* If the string is empty, let's just leave */
	if(eqstring.length <= 1){return;}
	/* The name of the function is left of the parenthesis.  If it is not there
	** then we should return an error message
	*/
	var prime = eqstring.indexOf("'");
	var paren = eqstring.indexOf("(");
	if(paren < 0 && prime < 0){
		message = message+'Error: The function must be defined in the form e.g. f(x)=expression<br>';
		return;
	}
	if(paren >= 0 && paren < prime){
		message = message+'Error: this looks both like a function and a diff Eq.<br>';
		return;
	}
	if(prime < 0){
		/* the name of the independent variable is between the parentheses */
		var vars = eqstring.split("(");
		var indep = vars[1].split(")");
		/* certain specifications need appear only once */
		if(numcurves == 0){
			if(indepvar == 'none' || indepvar == 't'){
				indepvar = indep[0];
			}
			if(depvar == "none"){
				depvar = vars[0];
				dependent_vars[curveindex] = depvar;
			}
		}
		/* handle the curve */
		doc.writeln('<param name="curve('+numfunction+').xvariable" value="'+indep[0]+'">');
		doc.writeln('<param name="curve('+numfunction+').yvariable" value="'+depvar+'">');
		doc.writeln('<param name="curve('+numfunction+').function" value="'+vars[0]+'">');
		/*
		** If we got here, then this is considered a valid function definition.  Count it.
		*/
		numcurves++;
		numfunction++;
	}
	else{
		/* There is a differential equation.  In this case, the independent variable is t, unless we
		** are told otherwise later */
		if(indepvar == 'none'){
			indepvar = 't';
		}
		var vars = eqstring.split("'");
		depvar = vars[0];
		dependent_vars[curveindex] = depvar;
	}
}

/* This function parses the color specification for a curve, and writes the tags */
function writeCurveColor(listbox,curveindex){
	var num_items=listbox.length;
	var index=listbox.selectedIndex;
	var sel_color;
	/* If this there is no curve to go with this color, bail out. */
	if(curveindex >= numcurves){return;}
	if(index >= 0){colorspec = listbox.options[index].value;}
	else{colorspec = "1,0,0";}
	var colors = colorspec.split(",");
	sel_color = parseColorSpec(colorspec);
	doc.writeln('<param name="curve('+curveindex+').red" value="'+colors[0]+'">');
	doc.writeln('<param name="curve('+curveindex+').green" value="'+colors[1]+'">');
	doc.writeln('<param name="curve('+curveindex+').blue" value="'+colors[2]+'">');	
	eq_htmlstring = eq_htmlstring+'<font color="'+sel_color+'">'+sel_color+': '+eq_strings[curveindex]+'</font><br>';
}
/* This function parses the color specification for trajectories, and writes the tags */
function writeTrajColor(listbox,curveindex){
	var num_items=listbox.length;
	var index=listbox.selectedIndex;
	if(index >= 0){colorspec = listbox.options[index].value;}
	else{colorspec = "1,0,0";}
	var sel_color = parseColorSpec(colorspec);
	var colors = colorspec.split(",");
	doc.writeln('<param name="trajectory.red" value="'+colors[0]+'">');
	doc.writeln('<param name="trajectory.green" value="'+colors[1]+'">');
	doc.writeln('<param name="trajectory.blue" value="'+colors[2]+'">');
	eq_htmlstring = eq_htmlstring+'<font color="'+sel_color+'">'+sel_color+': trajectories</font><br>';
}

/*
** Manage the variables for the displays
*/
function setDisplayVariables(){
	var i,j,k;
	var numdisplays = displaytype.length;
	for(k=0;k<dependent_vars.length;k++){
		message = message+'<br>';
	}
	for(k=0;k<numdisplays;k++){
		if(displaytype[k] == "plain"){
			doc.writeln('<param name="display('+k+').xvariable" value="'+indepvar+'">');
			doc.writeln('<param name="display('+k+').yvariable" value="'+dependent_vars[0]+'">');
		}
		else{
			var indices = displaytype[k].split('_');
			if(indices[0] == "plain"){
				doc.writeln('<param name="display('+k+').xvariable" value="'+indepvar+'">');
			}
			else{
				doc.writeln('<param name="display('+k+').xvariable" value="'+dependent_vars[indices[0]]+'">');
			}
			doc.writeln('<param name="display('+k+').yvariable" value="'+dependent_vars[indices[1]]+'">');
		}
	}
	//doc.writeln('<param name="applet.independentvariable" value="'+indepvar+'">');
}

function parseColorSpec(colorspec){
	var sel_color;
	if(colorspec == "1,0,0"){sel_color="red";}
	if(colorspec == "0,1,0"){sel_color="lime";}
	if(colorspec == "0,0,1"){sel_color="blue";}
	if(colorspec == "0,0,.5"){sel_color="navy";}
	if(colorspec == "0,1,1"){sel_color="cyan";}
	if(colorspec == ".7,0,.7"){sel_color="purple";}
	if(colorspec == "1,1,0"){sel_color="yellow";}
	if(colorspec == "1,.5,0"){sel_color="orange";}
	if(colorspec == "0,.5,0"){sel_color="green";}
	if(colorspec == "1,.5,.31"){sel_color="coral";}
	if(colorspec == ".86,.08,.23"){sel_color="crimson";}
	return sel_color;
}
