var nAttempt=1;
var ContextMessage='\n<class>\n\t<school>CMU</school>\n\t<period>09-106</period>\n'
		+'\t<description>Spring 2008</description>\n</class>\n'
		+'<dataset>\n\t<name>Online Vlab Homeworks</name>\n\t<leveltype="Assigned Homeworks">\n'
		+'\t\t<name>Stoichiometry Assignment</name>\n\t<problem>\n'
		+'\t\t<name>Determine stoichiometric coefficients</name>\n\t\t<context>Stoichiometry </context>\n'
		+'\t</problem>\n\t</level>\n</dataset>\n';
/**
* Enters name and date and starts the problem
*/
function check_intro() {
	//check if filled
	if(document.step0.studentName.value=="" || document.step0.studentId.value=="") {
		alert("Please enter your name and university ID to start the problem.");
	} else {
		//a1.deactivate();
		var stuName=document.step0.studentName.value;
		var stuId=document.step0.studentId.value;
		stuName=stuName.replace(/<.*>/g,"");
		stuId=stuId.replace(/<.*>/g,"");		
		//document.getElementById("intro").style.display="none";
		
		//document.getElementById("identification").style.display="block";
		document.getElementById("description").style.display="block";
		document.getElementById("vlab").style.display="block";
		//setInnerHTMLById("identification_date",'Loaded at '+full_time());
		//setInnerHTMLById("identification_name",stuName+", ID: "+stuId);

		logLogIn();
	}
	return false;
}

/**
* Enters name and date and starts the problem on PHP-enabled
*/
function check_data() {
	//check if filled
	if(isPHPworking) {
		//a1.deactivate();
		var stuName=userName;
		var stuId=userID;
		stuName=stuName.replace(/<.*>/g,"");
		stuId=stuId.replace(/<.*>/g,"");		
		//document.getElementById("intro").style.display="none";

		//document.getElementById("identification").style.display="block";
		document.getElementById("description").style.display="block";
		document.getElementById("vlab").style.display="block";
		//setInnerHTMLById("identification_date",'Loaded at '+full_time());
		//setInnerHTMLById("identification_name",stuName+", ID: "+stuId);
		
		logLogIn();
	}
}

/**
* Problem object
*/
function Problem() {
	this.compounds=new Array();
	for (i=0;i<4;i++) {
		this.compounds[i]=new Object();
	}
	this.compounds[0].name="A";
	this.compounds[1].name="B";
	this.compounds[2].name="C";
	this.compounds[3].name="D";


	//generate the four coefficients
	for (i=0;i<4;i++) {
		this.compounds[i].coeff=intRandom(1,2);
	}
	
	//perhaps, eliminate one compound 
	var inerts=intRandom(0,1);
	if (inerts==1) this.compounds[intRandom(0,3)].coeff=0;

	//reduce
	for (i=2;i<6;i++) {
		var divisible=true;
		for (j=0;j<4;j++) {
			if (this.compounds[j].coeff%i!=0) {
				divisible=false;
			}
		}
		if (divisible) {
			for (j=0;j<4;j++) {
				this.compounds[j].coeff=this.compounds[j].coeff/i;
			}
			i--;
		}
	}

	var reactants=intRandom(2,3-inerts);

	//decide reactants and assign entropies
	var tBAReactants=reactants;
	var pendingInerts=inerts;
	for (i=0;i<4;i++) {
		this.compounds[i].entropy=300;
		if (this.compounds[i].coeff!=0 && tBAReactants!=0) {
			if (doubleRandom(0,1)<(tBAReactants/(4-i-pendingInerts))) {
				this.compounds[i].coeff=-this.compounds[i].coeff;
				this.compounds[i].entropy=-300;
				tBAReactants--;
			}
		} else {
			if (this.compounds[i].coeff==0) pendingInerts--;
		}
	}
	
	//generate unknown String
	//u1,"+ unknowns[0].coeff+",u2,"+unknowns[1].coeff+",u3,"+unknowns[2].coeff+",u4,"+unknowns[3].coeff+",u5,"+unknowns[0].entropy+",u6,"+unknowns[1].entropy+",u7,"+unknowns[2].entropy+",u8,"+unknowns[3].entropy+"'
	this.unknownString="";
	for (i=0;i<4;i++) {
		this.unknownString+="u"+(i+1)+","+this.compounds[i].coeff+",";
	}
	for (i=0;i<4;i++) {
		this.unknownString+="u"+(i+5)+","+this.compounds[i].entropy+",";
	}
	this.unknownString=this.unknownString.substring(0,this.unknownString.length-1);
	
	//generate solution String
	this.solutionString=""
	for (i=0;i<4;i++) {
		if (this.compounds[i].coeff<0) this.solutionString+=(-this.compounds[i].coeff)+" "+this.compounds[i].name+" + ";
	}
	this.solutionString=this.solutionString.substring(0,this.solutionString.length-3)+" --> ";
	
	for (i=0;i<4;i++) {
		if (this.compounds[i].coeff>0) this.solutionString+=this.compounds[i].coeff+" "+this.compounds[i].name+" + ";
	}
	this.solutionString=this.solutionString.substring(0,this.solutionString.length-3);
}

/**
* Checks coeff text for digits and updates the reaction string
*/
function check_coeff(boxName) {
	eval("isNaturalNumber(document.step1."+boxName+".value)");
	updateEquation();
	return true;
}

/**
* Updates the equation in the instant feedback
*/
function updateEquation () {
	a2.setInstantFeedback(getEnteredEquation());
}

/*
* Converts the entered equation to a string
*/
function getEnteredEquation() {
	var toSubmitEquation="";
	for (i=0;i<4;i++) {
		var coeff=eval("document.step1.rcoeff"+i+".value");
		if (coeff!="" && parseInt(coeff)!=0)
			toSubmitEquation+=coeff+" "+thisProblem.compounds[i].name+" + ";
	}
	toSubmitEquation=toSubmitEquation.substring(0,toSubmitEquation.length-3)+" --> ";
	
	for (i=0;i<4;i++) {
		var coeff=eval("document.step1.pcoeff"+i+".value");
		if (coeff!="" && parseInt(coeff)!=0)
			toSubmitEquation+=coeff+" "+thisProblem.compounds[i].name+" + ";
	}
	if (toSubmitEquation.charAt(toSubmitEquation.length-2)=="+")
		toSubmitEquation=toSubmitEquation.substring(0,toSubmitEquation.length-3);
	
	return toSubmitEquation;
}

/**
* Finish the lab
*/
function check_lab() {
	//check if complete reaction submitted
	var isReactionComplete=true;
	var countReactants=0;
	var countProducts=0;
	var countRepetitions=0;
	
	for(i=0;i<4;i++) {
		if (eval("document.step1.rcoeff"+i+".value")!="" && parseInt(eval("document.step1.rcoeff"+i+".value"))>0)
			countReactants++;
		if (eval("document.step1.pcoeff"+i+".value")!="" && parseInt(eval("document.step1.pcoeff"+i+".value"))>0)
			countProducts++;
		if (eval("document.step1.rcoeff"+i+".value")!="" && parseInt(eval("document.step1.rcoeff"+i+".value"))>0
				&& eval("document.step1.pcoeff"+i+".value")!="" && parseInt(eval("document.step1.pcoeff"+i+".value"))>0)
			countRepetitions++;
	}
	
	if (countReactants==0 || countProducts==0) {
		alert("Please enter a complete reaction before submitting");
	} else {
		var message="";
    	if (nAttempt<=3) {                      
		
			var correct=new Array();
			var enteredReactant=new Array();
			var enteredProduct=new Array();
			var userAnswer=new Array();
			for(i=0;i<4;i++) {
				correct[i]=thisProblem.compounds[i].coeff;
				enteredReactant[i]=parseInt("0"+eval("document.step1.rcoeff"+i+".value"));
				enteredProduct[i]=parseInt("0"+eval("document.step1.pcoeff"+i+".value"));
				userAnswer[i]=enteredProduct[i]-enteredReactant[i];
			}
			
			//entered in both sides?
			//correct?
			//reactants correct?
			//products correct?
			//unbalanced?
			//unreduced?
			var isCorrect=true;
			var countCorrects=0;
			var anyEnteredInBothSides=false;
			var areReactantCoeffsCorrect=true;
			var areProductCoeffsCorrect=true;
			var areReactantsAndProductsCorrect=true;
			var isUnreduced=true;
			var ratio=(correct[0]==0)?(parseFloat(userAnswer[1])/correct[1]):(parseFloat(userAnswer[0])/correct[0]);
			for(i=0;i<4;i++) {
				if (enteredReactant[i]!=0 && enteredProduct[i])
					anyEnteredInBothSides=true;
				
				if (correct[i]!=userAnswer[i])
					isCorrect=false;
				else
					countCorrects++;
					
				if (correct[i]<0 && correct[i]!=userAnswer[i])
					areReactantCoeffsCorrect=false;
				
				if (correct[i]>0 && correct[i]!=userAnswer[i])
					areProductCoeffsCorrect=false;
				
				if ((correct[i]==0 && userAnswer!=0) || (correct[i]!=0 && userAnswer==0) || correct[i]*userAnswer[i]<0)
					areReactantsAndProductsCorrect=false;
				
				if ((correct[i]==0 && userAnswer!=0) || (correct[i]!=0 && userAnswer==0)
						|| correct[i]*userAnswer[i]<0 || (correct[i]!=0 && !relativeError(userAnswer[i]/correct[i],ratio,0.001))) {
					isUnreduced=false;
					}
			}
			if (!anyEnteredInBothSides && isCorrect) {
       			logFormCheck('lab',nAttempt,getEnteredEquation(),thisProblem.solutionString,"Well done! You did a good job!",true,"CORRECT");
				problemCompleted();
			}            
			else {
				var errorType="UNKNOWN_ERROR";
				if(anyEnteredInBothSides) {
					message+="Remember that a chemical reaction describes a transformation from one\/some compound\/s to another. ";
					message+="Note that no compound should appear in both sides of the equation. Please correct the equation and try again.";
					errorType="EXCEDENT_AS_PRODUCT_ERROR";
			 	} else if(isUnreduced && areReactantsAndProductsCorrect) {
				 	message+="You're pretty close! You have the equation correct but reactions are usually written in the lowest multiples.\r\n";	
				 	errorType="UNREDUCED_EQUATION_ERROR";
				} else if(areProductCoeffsCorrect) {
				 	message+="You're on the right track! You have the products right, but your reactants are wrong. ";
				 	errorType="INCORRECT_REACTANTS_ERROR";
				} else if(areReactantCoeffsCorrect) {
				 	message+="You're on the right track! You have the reactants right, but your products are wrong. ";					
				 	errorType="INCORRECT_PRODUCTS_ERROR";
				} else if(areReactantsAndProductsCorrect) {
				    message+="You're pretty close! You seem to know what the reactants and products are, but the reaction still needs to be balanced correctly. ";
   				 	errorType="UNBALANCED_EQUATION_ERROR";
				} else {
    	         	message+="Try again and take a closer look at how the species react.";
				}
				
   				if (nAttempt==3) {
    	    		message="This was your third attempt and your guess wasn't right. ";
    	    		message+="The correct equation was "+thisProblem.solutionString+". ";
    	    		message+="Use the Virtual Lab to make sense of this result and hit the RELOAD/REFRESH button ";
	   	    		message+="to start over with a new problem. Keep going!";
	   	    		a2.deactivate();
    			}
		
				logFormCheck('lab',nAttempt,getEnteredEquation(),thisProblem.solutionString,message,false,errorType);
			    a2.setFeedback(message,nAttempt);
			    nAttempt++;
			}
		}
	}
	return false;		
}

/*
* Finishes the problem
*/
function problemCompleted() {
	a2.deactivate();
	document.getElementById("vlab").style.display="none";
	document.getElementById("done").style.display="block";
	setInnerHTMLById("done_answer1",getEnteredEquation());
}


