//copyright 2006
//05-06-08 added alerts when clicking next,finish,back at the wrong time, added link to last explanation

	//setup variables
	var ddImagePrefix='ddCalcImages/';
	var ddPaperWidth;
	var ddPaperHeight;
	var ddPaper = new Array();
	var ddSteps = new Array();
	var ddLS;
	var ddS;
	
	//start button
	function ddStart(dontlogifzero){

		//record button click in log file
		//if(dontlogifzero!=0) document.all.buttonclick.src='_ddStart.gif?=' + Math.random();
		
		//check inputs
		var dividend, divisor, quotient, remainder, morehelp;
		dividend = document.all.ddcalculator.dividend.value;
		divisor = document.all.ddcalculator.divisor.value;
		quotient = document.all.ddcalculator.quotient.value;
		remainder = document.all.ddcalculator.remainder.value;
		
		//record inputs in log file
		//if(dontlogifzero!=0) document.all.buttonclick.src='_ddStart_'+escape(divisor)+'_'+escape(dividend)+"_"+escape(quotient)+'_'+escape(remainder)+'.gif?=' + Math.random();
		if(dontlogifzero!=0) document.all.buttonclick.src='_ddSTART.GIF?Divisor='+escape(divisor)+'_Dividend='+escape(dividend)+"_Quotient="+escape(quotient)+'_Remainder='+escape(remainder)+'_random=' + (Math.random()+'').substr(2,5);
		
		var nums = /^[0-9]*$/;
		if(!nums.test(dividend + divisor + quotient + remainder)) {alert('You must use only the digits 0-9');return;}
		
		if(dividend!="" && divisor!="" && quotient=="" && remainder==""){
			dividend *= 1; divisor *= 1;
			quotient = Math.floor(dividend/divisor)
			remainder = dividend-(divisor*quotient) }
		else if(dividend=="" && divisor!="" && quotient!="" && remainder!=""){
			divisor *= 1; quotient *=1; remainder *=1;
			dividend = divisor * quotient + remainder }
		else { 
			alert('You must supply these and\nleave the others blank:\n\ndivisor and dividend\n-or-\ndivisor, quotient and remainder');
			return;
		}
		
		if(divisor>dividend){alert('The divisor must be less than the dividend.'); return;}
		
		//determine total width and column positions
		var divisorLEN = (divisor+'').length;
		var dividendLEN = (dividend+'').length;
		var quotientLEN = (quotient+'').length;
		var totalWidth = divisorLEN + dividendLEN + quotientLEN + 7;
		var colA = Math.floor((ddPaperWidth - totalWidth) / 2);
		if (colA < 0) {alert('This paper is not wide enough.\nTry a smaller problem.'); return;}
		var colB = colA + 3 + divisorLEN;
		var colC = colB + 1 + dividendLEN;
		var colD = colC + 2 + quotientLEN;
		
		//setup paper
		ddClearPaper();
		ddInitPaperArray();
		
		//============================== START DOUBLE DIVIDING =====================================
		
		//write down the problem
		ddCreateNextStep();
		ddRecordChange(-1,0,'Write down the problem as usual.  Leave some space on the left and right.<br>&nbsp;<br>&nbsp;Click <b>Next Step</b>, <b>Next Step</b> ,,,')
		ddRecordNumberBackward(3,colB,divisor,false,false);
		ddRecordNumberBackward(3,colC,dividend,false,false);
		ddRecordChange(3,colB+1,"vline.gif");
		ddRecordChange(2,colB+1,"corner.gif");
		for(var i=1; i<=dividendLEN ; i++) ddRecordChange(2,colB+1+i,"hline.gif");
		
		//write down the 1x
		ddCreateNextStep();
		ddRecordChange(-1,0,"Write down '1x=' to the left of the divisor.  Leave two spaces inbetween.");
		ddRecordDigit(3,colA,1,false,true);
		ddRecordChange(3,colA+1,'_xequals.gif');
		
		//write down the 2x
		ddCreateNextStep();
		ddRecordChange(-1,0,"Write down '2x=' right below the '1x='.");
		ddRecordNoHighLighting();
		ddRecordDigit(4,colA,2,false,true);
		ddRecordChange(4,colA+1,'_xequals.gif');
		
		//double the divisor
		ddCreateNextStep();
		ddRecordChange(-1,0,"Double the divisor and write it underneath - keeping the ones column lined up.  Doubling "+divisor+" gets you "+(divisor*2)+".");
		ddRecordNoHighLighting();
		ddRecordNumberBackward(4,colB,divisor*2,false,true);
		
		//write down the 4x
		ddCreateNextStep();
		ddRecordChange(-1,0,"Write down '4x=' right below the '2x='.&nbsp;&nbsp;&nbsp;(It would be easy to write three X instead, but remember you are doubling.  An alternate name for this method is 1-2-4-8 Divsion in order to pound home this point.)");
		ddRecordNoHighLighting();
		ddRecordDigit(5,colA,4,false,true);
		ddRecordChange(5,colA+1,'_xequals.gif');
		
		//double the double
		ddCreateNextStep();
		ddRecordChange(-1,0,"Double the divisor again and write it underneath - keeping the ones column lined up.  Doubling "+(divisor*2)+" gets you "+(divisor*4)+".");
		ddRecordNoHighLighting();
		ddRecordNumberBackward(5,colB,divisor*4,false,true);
		
		//write down the 8x
		ddCreateNextStep();
		ddRecordChange(-1,0,"Write down '8x=' right below the '4x='.");
		ddRecordNoHighLighting();
		ddRecordDigit(6,colA,8,false,true);
		ddRecordChange(6,colA+1,'_xequals.gif');
		
		//double the double
		ddCreateNextStep();
		ddRecordChange(-1,0,"Double the divisor again and write it underneath - keeping the ones column lined up.  Doubling "+(divisor*4)+" gets you "+(divisor*8)+".");
		ddRecordNoHighLighting();
		ddRecordNumberBackward(6,colB,divisor*8,false,true);
		
		//start subtracting
		var bottomRow = 3;
		var whatsLeft = dividend;
		var firstDigit, multiple, zeros, zerosStr, toSubtract, startAtFirst;
		while(whatsLeft>=divisor){
		
			//check if out of room
			if(bottomRow+2>ddPaperHeight-1) {alert('This paper is not tall enough.\nTry a smaller problem.'); return;}
			
			//choose best multiple
			firstDigit = (((whatsLeft/divisor)+'').substr(0,1));
			if(firstDigit>=1) multiple=1;
			if(firstDigit>=2) multiple=2;
			if(firstDigit>=4) multiple=4;
			if(firstDigit>=8) multiple=8;
			zeros = (Math.floor(whatsLeft/divisor)+'').length-1;
			startAtFirst = ((divisor*multiple)+'').length+zeros == (whatsLeft+'').length;
			ddCreateNextStep();
			morehelp =  "CHOOSING THE BEST NUMBER:\\n \\n";
			morehelp += "The idea is to pick the best number from " + divisor*1 + ", " + divisor*2 + ", " + divisor*4 + ", and " + divisor*8 + "\\n";
			morehelp += "in order to subtract as much as possible from" + (bottomRow!=3 ? " whats left of" : "") + " the dividend.\\n \\n";
			morehelp += "You can write the number starting right below the first digit of " + whatsLeft + ",\\n";
			morehelp += "or you can write it starting right below the second digit of " + whatsLeft + ".\\n \\n";
			morehelp += "In this case the best choice is to write " + divisor*multiple + " starting under\\n";
			morehelp += "the " + ( startAtFirst ? "first" : "second") + " digit of " +  + whatsLeft + ".";
			ddRecordChange(-1,0,"Choose the best number from the divisor column to write under" + (bottomRow!=3 ? " what's left of" : "") + " the dividend.  You can slide the number over one if you need to. <a href='.' onClick='alert(\"" + morehelp + "\");return false;'>more help</a>");
			ddRecordNoHighLighting();
			ddRecordNumberBackward(bottomRow+1,colC-zeros,divisor*multiple,false,true);
			
			//file in zeros
			if(zeros){
				ddCreateNextStep();
				zerosStr="ZERO"; for(var i=1; i<zeros; i++) zerosStr += ', ZERO';
				ddRecordChange(-1,0,'Fill in to the right with zeros.  Say to yourself, "' + zerosStr + '."');
				ddRecordNoHighLighting();
				for(var i=0; i<zeros; i++) ddRecordDigit(bottomRow+1,colC-i,0,false,true);
			}
			
			//write the partial quotient
			ddCreateNextStep();
			if(zeros) ddRecordChange(-1,0,'Write the multiplier you used (1, 2, 4, or 8) on the right, followed by the same number of zeros you just wrote.  Say to yourself, "' + zerosStr + '."');
			else  ddRecordChange(-1,0,'Write the multiplier you used (1, 2, 4, or 8) on the right. No need to write any zeros afterwards.');
			ddRecordNoHighLighting();
			for(var i=0; i<zeros; i++) ddRecordDigit(bottomRow+1,colD-i,0,false,true);
			ddRecordDigit(bottomRow+1,colD-zeros,multiple,false,true);
			if(multiple==1) ddRecordDigit(3,colA,1,false,true);
			if(multiple==2) ddRecordDigit(4,colA,2,false,true);
			if(multiple==4) ddRecordDigit(5,colA,4,false,true);
			if(multiple==8) ddRecordDigit(6,colA,8,false,true);
			
			//subtract
			toSubtract = divisor*multiple*Math.pow(10,zeros);
			whatsLeft = whatsLeft -= toSubtract;
			ddCreateNextStep();
			ddRecordChange(-1,0,"Subtract." + (whatsLeft<divisor ? " ==&gt; Notice that the amount left over is less than the divisor - so you're done." : ""));
			ddRecordNoHighLighting();
			ddRecordNumberBackward(bottomRow+1,colC,toSubtract,true,false,true);
			ddRecordNumberBackward(bottomRow+2,colC,whatsLeft,false,true);
			
			//again
			bottomRow +=2;
		}
		
		//add up the answer
		ddCreateNextStep();
		ddRecordChange(-1,0,"Add up your answer on the right.  The remainder is " + whatsLeft + ".");
		ddRecordNoHighLighting();
		for(var i=0; i<zeros; i++) ddRecordDigit(bottomRow-1,colD-i,0,true,false);
		ddRecordDigit(bottomRow-1,colD-zeros,multiple,true,false);
		for(var i=zeros+1; i<quotientLEN; i++) ddRecordChange(bottomRow-1,colD-i,'blanku.gif');
		ddRecordChange(bottomRow-1,colD-quotientLEN,'plus.gif')
		ddRecordNumberBackward(bottomRow,colD,quotient,false,true);
		
		//write the answer on the top
		ddCreateNextStep();
		ddRecordChange(-1,0,'Write the answer on the top.<br>&nbsp;<br>&nbsp;Enter a new problem on the left<br>&nbsp;and then and click <b>Step 1</b>.<br>&nbsp;<br>&nbsp;<a href="images/Double-Division-Example-With-Remainder.html" target="example" onclick="newwindow=window.open(\'images/Double-Division-Example-With-Remainder.jpg\',\'popup\',\'height=440,width=475\'); if (window.focus) newwindow.focus(); return false;">hand written example</a>');
		ddRecordNoHighLighting();
		ddRecordNumberBackward(1,colC,quotient,false,true);
		ddRecordChange(1,colC+2,'_R.gif');
		ddRecordNumberForward(1,colC+3,remainder,false,true);
		
		//show first step
		ddS=0;
		ddDoStep(0);		
	}
	
	function ddNext(dontlogifzero){
		if(dontlogifzero!=0) document.all.buttonclick.src='_ddNext.gif?random=' + (Math.random()+'').substr(2,5);
		if(ddS==ddLS) alert('This problem is done.\nClick "Step 1."');
		else ddDoStep(++ddS);
	}
	
	function ddBack(dontlogifzero){
		if(dontlogifzero!=0) document.all.buttonclick.src='_ddBack.gif?random=' + (Math.random()+'').substr(2,5);
		if(ddS==0) alert('Cannot go back.\nClick "Next Step."');
		if(ddS > 0) ddUndoStep(ddS--);
	}
	
	function ddFinish(dontlogifzero){
		if(dontlogifzero!=0) document.all.buttonclick.src='_ddFinish.gif?random=' + (Math.random()+'').substr(2,5);
		if(ddS==ddLS) alert('This problem is done.\nClick "Step 1."');		
		else {
			ddS=ddLS;
			ddDisplayPaperArray();
		}
	}

	
	//draw paper (display)
	function ddDrawPaper(height,width){
		ddPaperWidth=width;
		ddPaperHeight=height;
		for(var r=0; r<ddPaperHeight; r++) {
			for(var c=0; c<ddPaperWidth; c++)
				document.write('<img name="r' + r + 'c' + c + '" src="'+ddImagePrefix+(r==2 ? 'hlineblank.gif' : 'blank.gif')+'">');
			document.write('<br>');
		} document.all.ddExplanation.innerHTML = ''
	}
	
	//clear paper
	function ddClearPaper(){
		for(var r=0; r<ddPaperHeight; r++) {
			for(var c=0; c<ddPaperWidth; c++)
				document['r'+r+'c'+c].src=ddImagePrefix+(r==2 ? 'hlineblank.gif' : 'blank.gif');
		} document.all.ddExplanation.innerHTML = ''
	}
	
	//initialize paper array, clear steps
	function ddInitPaperArray(){
		for(var r=0; r<ddPaperHeight; r++) {
			ddPaper[r] = new Array(ddPaperWidth);
			for(var c=0; c<ddPaperWidth; c++) ddPaper[r][c]=(r==2 ? 'hlineblank.gif' : 'blank.gif');
		} ddPaper[ddPaperHeight]='';
		ddLS=-1;
	}
	
	//display paper array
	function ddDisplayPaperArray(){
		for(var r=0; r<ddPaperHeight; r++) {
			for(var c=0; c<ddPaperWidth; c++) {
				if (document['r'+r+'c'+c].src != ddImagePrefix+ddPaper[r][c]) document['r'+r+'c'+c].src=ddImagePrefix+ddPaper[r][c];
			} document.all.ddExplanation.innerHTML = ddPaper[ddPaperHeight];
		}
	}
	
	//create next step at end of ddSteps[]
	function ddCreateNextStep(){
		ddSteps[++ddLS] = new Array();
		ddSteps[ddLS][0] = 0 //number of changes for this step
	}
	
	//record change of image in paper array and record change in steps array
	function ddRecordChange(row,column,newimage){
		if (row==-1) row=ddPaperHeight;
		var chg = ++ddSteps[ddLS][0];
		ddSteps[ddLS][chg]=new Object;
		ddSteps[ddLS][chg].row = row;
		ddSteps[ddLS][chg].column = column;
		ddSteps[ddLS][chg].after = newimage;
		if (row == ddPaperHeight) {
			ddSteps[ddLS][chg].before = ddPaper[row];
			ddPaper[row] = newimage;
		} else {
			ddSteps[ddLS][chg].before = ddPaper[row][column];
			ddPaper[row][column] = newimage;
		}
	}
	
	//apply step to display
	function ddDoStep(n){
		for(var chg=1; chg<=ddSteps[n][0]; chg++) {
			with(ddSteps[n][chg]) {
				if(row==ddPaperHeight) document.all.ddExplanation.innerHTML = after;
				else document['r'+row+'c'+column].src=ddImagePrefix+after
			}
		}
	}
	
	//un-apply step to display
	function ddUndoStep(n){
		for(var chg=1; chg<=ddSteps[n][0]; chg++) {
			with(ddSteps[n][chg]) {
				if(row==ddPaperHeight) document.all.ddExplanation.innerHTML = before;
				else document['r'+row+'c'+column].src=ddImagePrefix+before;
			}
		}
	}

	
	// record adding a digit to the paper
	function ddRecordDigit(row,column,digit,underline,highlighted){
		ddRecordChange(row, column, (highlighted?'_':'') + digit + (underline?'u':'') + '.gif'); }
	
	//record a number on the paper - forward	
	function ddRecordNumberForward(row,column,number,underline,highlighted){
		var numstr=new String(number);
		for(var d=0; d<numstr.length; d++)
			ddRecordChange(row, column+d, (highlighted?'_':'') + numstr.charAt(d) + (underline?'u':'') + '.gif'); }
	
	//record a number on the paper - backward	
	function ddRecordNumberBackward(row,column,number,underline,highlighted,minus){
		var numstr=new String(number);
		for(var d=0; d<numstr.length; d++)
			ddRecordChange(row, column-d, (highlighted?'_':'') + numstr.charAt(numstr.length-d-1) + (underline?'u':'') + '.gif');
		if (minus) ddRecordChange(row, column-numstr.length, (highlighted?'_':'')+'minus.gif'); }
		
	//remove all hightlighting
	function ddRecordNoHighLighting(){
		for(var r=0; r<ddPaperHeight; r++)
			for(var c=0; c<ddPaperWidth; c++)
				if (ddPaper[r][c].substr(0,1) == '_') ddRecordChange(r,c,ddPaper[r][c].substr(1)); }
	
	
	
	//direct manipulation of display (no longer used)
	function imageAtDirect(row,column,imagename){document['r'+row+'c'+column].src=ddImagePrefix+imagename;}
	function digitAtDirect(row,column,digit,underline){document['r'+row+'c'+column].src=ddImagePrefix+digit+(underline?'u':'')+'.gif';}
	function numberAtForwardDirect(row,column,number,underline){
		var numstr=new String(number);
		for(var d=0; d<numstr.length; d++)
			document['r'+row+'c'+(column+d)].src=imagePrefix+numstr.charAt(d)+(underline?'u':'')+'.gif'; }
	function numberAtBackwardDirect(row,column,number,underline){
		var numstr=new String(number);
		for(var d=0; d<numstr.length; d++)
			document['r'+row+'c'+(column-d)].src=ddImagePrefix+numstr.charAt(numstr.length-d-1)+(underline?'u':'')+'.gif'; }

	
//test
