//name: EngPhonology.js
//Author: Norbert Rennert
//Date: March 7, 2006
//Purpose: provide english language support for English CALL pages
//includes functions for playing sound and the spellcheck

//STATIC ARRAYS of syllable shapes
//used to build regexp when no other sounds are selected by user
var wordInitial1C="b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,v,w,x,y,z"; //21 items
var wordInitial2C="bl,br,dr,dw,fl,fr,gl,gr,kl,cl,kr,cr,pl,pr,sk,sc,sl,sm,sn,sp,st,sw,tr,tw"; //24 items
var wordInitial3C="scr,spl,spr,str"; //4 items
var wordIDiC = "phr,chl,chr,sch,squ,shr,thr"; // wordinitial digraphs + consonant
var digrlett="ch,ck,ng,th,sh,qu,ph,tch,gn,mn,wr,gh";//12 items
var doublelett="bb,cc,dd,ff,gg,ll,mm,nn,pp,rr,ss,tt,zz";// 13 items
var vowel1="a,e,i,o,u,y"; //6 items includes y
var vowel2="ai,ay,au,ea,ee,ei,eigh,eu,ew,ey,ie,igh,iu,ou,ough,ow,oy,ui"; //18 items
var wordFinal1C="b,c,d,f,g,h,j,k,l,m,n,p,q,r,s,t,w,x,y,z"; // 20 items
var wordFinal2C="ct,ft,ld,lf,lk,lm,ln,lp,lt,mp,nd,nk,nt,pt,rb,rc,rd,rf,rg,rk,rl,rm,rn,rp,rt,sk,sm,sp,st"; // 29 items
var wordFDiC = "cht,ckt,thm"; //3 items wordfinal digraph + consonant sch,rrh,thmn
var wordFCDi = "dth,fth,lch,lph,lsh,lth,mph,mth,nch,nck,nth,pth,rch,rff,rph,rrh,rsh,rth,sch"; //19 items wordfinal consonant + digraph
var wordFinal3C="mpt,nct,nds,nks,nst,nts,nx,pts,rds,rld,rmth,rst,rtz,xt"; //14 items
var wordFinalDi="ld,lf,lk,mn"; //4 items
var wordFinalTri="ght"; //1 item

//naming convention of the consonant arrays is to be read as follows:
//a1Ci="array of single consonants word initial"
//a2Cf="array of double consonants word final" etc.
//*** define arrays here
var a1C=new Array; //single consonant array is populated by the function construct1CArray() from html checkbox values
var aEendV=new Array; //words with a final e
var sregexp2='';
var finalE=''; // final 'e' at end of the word
var aDt=new Array; //('qu,x'); //English consonant diphthongs (double sounds)
var aDg=new Array; //('ch,ck,ng,sh,th,ff,ll,ss'); //English consonant digraphs (double letters representing 1 sound) (should we distinguish between word initial and word final digraphs?)

//DYNAMIC CONTENT filled when user selects sounds from checkboxes
//used to build regexp to match vocabulary. results in restrictive matches
var a1Ci= new Array;//single phonemes at word initial position (can be digraphs or single letters: eg. voiced th)
var a2Ci= new Array;//('bl,br,dr,dw,fl,fr,gl,gr,kl,kr,pl,pr,sk,sl,sm,sn,sp,st,sw,tr,tw'); //English word initial double consonant clusters
var a3Ci= new Array;//('spl,spr,str,squ,shr,thr'); //English word initial triple consonant clusters
var a1V=  new Array;//vowel arrays are populated by the function toggleArray() from html checkbox values
var a2V=  new Array;
var a1Cf= new Array;//single phonemes at word final position (can be digraphs or single letters: eg. ng)
var a2Cf= new Array;//('ct,ft,ld,lf,lm,ln,lp,lt,mp,nd,nk,nt,pt,rb,rc,rd,rf,rg,rk,rl,rm,rn,rp,rt,sk,sm,sp,st,xt'); //English word final 2 consonant clusters
var a3Cf= new Array;//('dth,fth,lch,lge,lsh,lth,mph,mpt,nch,nct,nge,ntch,pth,rch,rge,rsh,rth,rve,ngth'); //English word final triple consonant clusters
var aiDigr=new Array;//word initial digraphs ('ch','sh','th','ph','qu')
var afDigr=new Array;//word final digraphs ('ch','ck','ng','th','ph','sh')
var aDouble=new Array;//double letters ('bb','cc','dd','ff','gg','ll','mm','nn','pp','rr','ss','tt','zz')
var aSyll=new Array;//types of syllable shapes (eg. cv, cvc, ccvc etc.) - generated from html checkboxes
var CVpattern='';
var arrayOfWordLists=new Array;
var charClassArray=new Array;
var realWordArray=new Array;
var selectedWordArray=new Array;
var nonsenseWordArray=new Array;
var finalWordArray=new Array;
var wordIndex=0;
var usedIndex=new Array;
var doRandom=0;
var identity='';
var currentFocus='';
var storyAreaContent='';

//basic consonant array is built by function toggleArray() from html checkbox values
//basic vowel array is built by function toggleArray() from html checkbox values

var n=new Array;
var useRealWords;
var WordListIsUpToDate=0;
var allArraysProcessed=0;
var sregexpPRE='';
var sregexpC='';
var sregexpFOL='';
var PRE=''; //string used to build word initial regexp
var FOL=''; //string used to build word final regexp
var C=''; //string used to build vowel portion of regexp
var Vowels=''; //string used to build vowel portion of regexp

function toggleArray(destinationArray1,destinationArray2,Char,ListOfWords) {
// sample: toggleArray(a1V,'','i','ie_i'); type order (if not empty): variable, variable, string, string
// sample: toggleArray(a1Ci,a1Cf,'b','b_b');
// destinationArray1 and destinationArary2 are dynamic arrays which get used in ...
// Char is the letter or letters which get added to the destination arrays
// ListOfWords is the name of the Eng[ListOfWords] array which contains vocabulary */
	toggleArrayStepTwo(destinationArray1,Char);
	if(typeof destinationArray2=="object" && destinationArray2 !=null) {
		toggleArrayStepTwo(destinationArray2,Char);
	}
//	if(typeof ListOfWords =="string" && ListOfWords !='')  //(typeof words=="string" && words !='') // old array names
	if(typeof Eng[ListOfWords] =="string" && Eng[ListOfWords] !='') {  //typeof words=="string" && words !='')
		//addToSubtractFromArray(arrayOfWordLists,ListOfWords); // old array name
		addToSubtractFromArray(arrayOfWordLists,Eng[ListOfWords]);
		//addItemToArray(arrayOfWordLists,Eng[ListOfWords]);
		realWordArray.length =0;
		//alert('realWordArray.length: #1 '+realWordArray.length);
		//alert('arrayOfWordLists.length: '+arrayOfWordLists.length+'\nContent of array: '+arrayOfWordLists);
		for(var i=0; i < arrayOfWordLists.length; i++){
			var aTemp = new Array;
			aTemp = arrayOfWordLists[i].split(',');
			realWordArray = realWordArray.concat(aTemp);
			realWordArray[0].split(',');
			//alert('realWordArray.length #2: '+realWordArray[0].length);
		}
	}
	//alert('realWordArray contains: '+realWordArray+'\nrealWordArray is '+realWordArray.length+' long.');
	refreshVariables();
}

function toggleArrayStepTwo(destinationArray,Item) { //Item can be a string only 1 char long or a comma separated string
	var aItem=new Array;
	var found=0;
	aItem=Item.split(',');
	for(var i=0; i<destinationArray.length; i++) {
		for(var j=0; j<aItem.length; j++) {
			if(destinationArray[i]==aItem[j]) { //if the Item is in the Array
				destinationArray.splice(i,1); //then take it out
				found=1;
			}
		}
	}
	if(found==0){	//alert('@toggleArrayStepTwo(); found==0; Content of aItem is: '+aItem+'\nlength of aItem is: '+aItem.length+'\n realWordArray length is: '+realWordArray.length);
		addItemToArray(destinationArray,Item);
	}
}

function addToSubtractFromArray(destinationArray,NewItem){
	var found=0;
	for(var i=0; i<destinationArray.length; i++) {
		if(destinationArray[i]==NewItem) { //if the Item is in the Array
			destinationArray.splice(i,1); //then take it out
			found=1;
		}
	}
	if(found ==0){
		destinationArray.push(NewItem); //add it to the array
	}
}

function removeDuplicates(arrayOfWords){
	var tempArray=new Array;
	for(var i=0; i< arrayOfWords.length; i++) {
		for(var j=0; j<tempArray.length; j++) {
			if(arrayOfWords[i] != tempArray[j]) { //if the Item is not in the tempArray
				tempArray[j]=arrayOfWords[i]; //add item to tempArray
			}
		}
	}
	return tempArray;
}

function addItemToArray(destinationArray,Item) {
	var aItem=new Array;
	var found=0;
	aItem=Item.split(',');
	for(var j in aItem) {
		for(var i in destinationArray) {
			if(aItem[j]==destinationArray[i]) { // old version
			//if(aItem[j].match(destinationArray[i])){// new attempt using match for case insensitivity
			//if(/aItem[j]/i.test(destinationArray[i])){// new attempt using test for case insensitivity
				found=1;
				break;
			}
		}
		if(found==0) {
			destinationArray.push(aItem[j]);
		}
	}
}

function elementExists(id) {
//checks to see if an element exists in the document
	if(document.getElementById != null){
		return document.getElementById(id);
	}
	if(document.all != null){
		return document.all[id];
	}
	if(document.layers != null){
		return document.layers[id];
	}
	return null;
}

function refreshVariables() {
	doRandom=getButton(document.wordControls.random);
	//useWholeWords=getButton(document.wordControls.whole);
	//collect syllable types into an array
	aSyll.length=0;
	if(doNonsense == true){
	var syllShapes=document.wordControls.syllshape;
		for(var i=0; i < syllShapes.length; i++){
			if(syllShapes[i].checked==true){
				// csv string are handled later
				aSyll.push(syllShapes[i].value);
			}
		}
	}
	if(doNonsense == false){
		if(document.wordControls.syllPRE1 && document.wordControls.syllPRE1.checked==true){
			aSyll.push(document.wordControls.syllPRE1.value);
		}
		if(document.wordControls.syllPRE2 && document.wordControls.syllPRE2.checked==true){
			aSyll.push(document.wordControls.syllPRE2.value)
		}
		if(document.wordControls.syllPRE3 && document.wordControls.syllPRE3.checked==true){
			aSyll.push(document.wordControls.syllPRE3.value);
		}
		if(document.wordControls.syllC1 && document.wordControls.syllC1.checked==true){
			aSyll.push(document.wordControls.syllC1.value);
		}
		if(document.wordControls.syllFOL1 && document.wordControls.syllFOL1.checked==true){
			aSyll.push(document.wordControls.syllFOL1.value);
		}
		if(document.wordControls.syllFOL2 && document.wordControls.syllFOL2.checked==true){
			aSyll.push(document.wordControls.syllFOL2.value);
		}
		if(document.wordControls.syllFOL3 && document.wordControls.syllFOL3.checked==true){
			aSyll.push(document.wordControls.syllFOL3.value);
		}
	}
	//alert('@refreshVariables; The length of aSyll is: '+aSyll.length+'\nThe contents of aSyll is: '+aSyll);
	if(aSyll.length==0) {
		finalWordArray.length=0; //reset the array to 0
		document.getElementById('TotalWords').innerHTML="Total words available: <b>"+finalWordArray.length+'</b>';
		document.getElementById('storyArea').innerHTML='<div class="noContent">No words available. Click on another sound or try changing the syllable elements.</div>';
		return;
	}
	startWordList();
}

function startWordList() { //starts the process of creating an array of words
	wordIndex=0;
	charClassArray.length=0;
	nonsenseWordArray.length=0;
	selectedWordArray.length=0;
	finalWordArray.length=0;
	sregexpPRE='';
	sregexpC='';
	sregexpFOL='';
	var tempArray=new Array;
	//alert('aSyll.length is: '+aSyll.length+'\nContent of aSyll is: '+aSyll);
//	if(a2Ci != ''){ // word initial double consonant clusters
//		PRE=PRE.concat(a2Ci); //add dynamic string of cc to proto-regexp
//	} else {
//		PRE=PRE.concat(wordInitial2C); //add predefined string of cc to proto-regexp
//	}
	for(var s=0; s < aSyll.length; s++) {
		tempArray=aSyll[s].split(',');
		//alert('aSyll['+s+'] content is: '+aSyll[s]);
		for(var t=0; t < tempArray.length; t++){
			//alert('tempArray['+t+'] is: '+ tempArray[t]);
			switch (tempArray[t]) {
				case '1Ci': //word initial single sound consonants (can be digraphs such as 'th')
					charClassArray[t]=a1Ci;
					//alert('@startWordList() this is a1Ci: '+a1Ci+'\ntempArray['+t+'] is: '+ tempArray[t]);
					break;
				case '2Ci': //word initial double consonant clusters
					charClassArray[t]=a2Ci;
					break;
				case '3Ci': //word initial triple consonant clusters
					charClassArray[t]=a3Ci;
					break;
				case '1Cf': //word final single sound consonants (can be digraphs such as 'th')
					charClassArray[t]=a1Cf;
					//alert('@startWordList() this is a1Cf: '+a1Cf+
					//'\ntempArray['+t+'] is: '+ tempArray[t]);
					break;
				case '2Cf': //word final double consonant clusters
					charClassArray[t]=a2Cf;
					break;
				case '3Cf': //word final triple consonant clusters
					charClassArray[t]=a3Cf;
					break;
				case '4Cf': //word final quadruple consonant clusters
					charClassArray[t]=a4Cf;
					break;
				case 'c': //single consonants
					charClassArray[t]=a1Ci;
					//alert('@startWordList() this is a1Ci: '+a1Ci);
					break;
				case 'v': //single vowels
					charClassArray[t]=a1V;
					break;
				case 'vv': //double vowels
					charClassArray[t]=a2V;
					break;
				case '1V': //single vowels
					charClassArray[t]=a1V;
					break;
				case '2V': //double vowels
					charClassArray[t]=a2V;
					break;
				case 'aEendV': //final e on words
					charClassArray[t]=aEendV;
					finalE='e?';
					if(document.getElementById('finalE')) {
						document.getElementById('finalE').checked=true;
					}
					break;
				case 'iDigr': // word initial digraphs
					charClassArray[t]=aiDigr;
					break;
				case 'fDigr': // word initial digraphs
					charClassArray[t]=afDigr;
					break;
				case 'Double': // word initial digraphs
					charClassArray[t]=aDouble;
					break;
				//*** add any new syllable categories here following the format above
				//vowel types: 1V,2V,aEendV
			}
		}
	}
	//alert('The length of finalWordArray before nonsense function is: '+finalWordArray.length);
	if(doNonsense == true) {
		createNonsenseWords('',0, tempArray.length);
		//alert('nonsense words in array: '+nonsenseWordArray+'\nwords in finalWordArray: '+finalWordArray);
		finalWordArray=finalWordArray.concat(nonsenseWordArray);
		wordIndex=0;
	} else {
		finalWordArray.length=0;
	}
	//alert('The length of finalWordArray after nonsense function is: '+finalWordArray.length);
	if(doNonsense == false) {
		createRealWordList();
		finalWordArray=finalWordArray.concat(selectedWordArray);
		wordIndex=0;
		//alert('real words in final array: '+finalWordArray);
	} else {
		realWordArray.length=0;
	}
	document.getElementById('TotalWords').innerHTML="Total words available: <b>"+finalWordArray.length+'</b>';
	if(finalWordArray.length==0){
		document.getElementById('storyArea').innerHTML='<div class="noContent">No words available. Click on another sound or try changing the syllable elements.</div>';
	} else {
		writeLines();
	}
	//alert which displays contents of various arrays
	//alert('@function startWordList();\nin Array: a1V: '+a1V+'\n in Array: a1Ci: '+a1Ci+'\n in Array: a1Cf: '+ a1Cf+'\n in Array: aSyll: '+aSyll+'\n realWordArray length is: '+realWordArray.length+'\n Content of realWordArray is: '+realWordArray+'\n length of nonsenseWordArray is: '+nonsenseWordArray.length+'\n length of finalWordArray is: '+finalWordArray.length+'\n sregexp2: '+sregexp2+'\n sregexpPRE: '+sregexpPRE+'\n sregexpC: '+sregexpC+'\n sregexpFOL: '+sregexpFOL);
}

function createNonsenseWords(base,depth,bottom) { //generates all possible letter variations based on syllable shape and v + c inventory to make one 'word'
	//alert('Number of words in array so far: '+finalWordArray.length+'\nbase: '+base+', depth: '+depth+', bottom: '+bottom);
	if(document.wordControls.finalE.checked==true) { //nonsenseSyllForm was the form name
		finalE='e';
	} else {
		finalE='';
	}
	var charClass=charClassArray[depth];
	var i;
	//alert('charClass assignment: ' + charClass);
	if(depth==bottom-1) {
		for(var i=0; i<charClass.length; i++) {
			nonsenseWordArray[wordIndex]=base+charClass[i]+finalE;
			//alert("nonsenseWordArray contains: "+nonsenseWordArray);
			wordIndex ++;
		}
	} else {
		//alert(charClass.value);
		for(var i=0; i<charClass.length; i++) {
			createNonsenseWords(base+charClass[i], depth+1, bottom);
		}
	}
}

function createRealWordList() { //creates a wordlist based on various criteria from an array of potentially mixed words
	var Begin='';
	var End='';
	var PRE1='';
	var PRE2='';
	var PRE3='';
	var PRE4='';
	var FOL1='';
	var FOL2='';
	var FOL3='';
	var FOL4='';
	var FOL5='';
	var C1='';
	var C2='';
	var sregexpPRE='';
	var sregexpFOL='';
	var sregexpC='';
	var sregexp2='';
	if(document.wordControls.whole.checked==true) {
		End='\\b'; //regexp flag for matching whole words
		Begin='\\b';
	} //else {
		//wholeWords='';
	//}
	if(document.getElementById('finalE') && document.getElementById('finalE').checked==true) {
		finalE='e?'; //regexp flag for matching final 'e'
	} else {
		finalE='';
	}
//checks syllable structure controls and letter arrays
//word initial consonants
	if(document.wordControls.syllPRE1){
		if(a1Ci == '' && document.wordControls.syllPRE1.checked == false) {
			PRE1=''; //nothing in regexp
			//alert("1: a1Ci == '' && document.wordControls.syllPRE1.checked == false");
		} else if(a1Ci == '' && document.wordControls.syllPRE1.checked == true) {
			PRE1=wordInitial1C; //predetermined values in regexp
			Begin='\\b';
			//alert("2: a1Ci == '' && document.wordControls.syllPRE1.checked == true");
		} else if(a1Ci != '' && document.wordControls.syllPRE1.checked == true) {
			PRE1=a1Ci.join(','); //selected values in regexp
			Begin='\\b';
			//document.wordControls.syllPRE1.checked=true;
			//alert("3: a1Ci != '' && document.wordControls.syllPRE1.checked == true");
		} else {
			PRE1='';
			//document.wordControls.syllPRE1.checked=true;
			//alert("else this is #4");
		}
	}

	if(document.wordControls.syllPRE2){
		if(a2Ci == '' && document.wordControls.syllPRE2.checked == false) {
			PRE2='';
		} else if(a2Ci == '' && document.wordControls.syllPRE2.checked == true) {
			PRE2=wordInitial2C;
			Begin='\\b';
		} else if(a2Ci != '' && document.wordControls.syllPRE2.checked == true){
			PRE2=a2Ci.join(',');
			Begin='\\b';
		} else {
			PRE2='';
		}
	}

	if(document.wordControls.syllPRE3){
		if(a3Ci == '' && document.wordControls.syllPRE3.checked == false) {
			PRE3='';
		} else if(a3Ci == '' && document.wordControls.syllPRE3.checked == true) {
			PRE3=wordInitial3C;
			Begin='\\b';
		} else if(a3Ci != '' && document.wordControls.syllPRE3.checked == true){
			PRE3=a3Ci.join(',');
			Begin='\\b';
		} else {
			PRE3='';
		}
	}

	if(document.wordControls.syllPRE4){
		if(aiDigr == '' && document.wordControls.syllPRE4.checked == false) {
			PRE4='';
		} else if(aiDigr == '' && document.wordControls.syllPRE4.checked == true) {
			PRE4=digrlett;
			Begin='\\b';
		} else if(aiDigr != '' && document.wordControls.syllPRE4.checked == true){
			PRE4=aiDigr.join(',');
			Begin='\\b';
		} else {
			PRE4='';
		}
	}

//word final consonants
	if(document.wordControls.syllFOL1){
		if(a1Cf == '' && document.wordControls.syllFOL1.checked == false) {
			FOL1='';
		} else if(a1Cf == '' && document.wordControls.syllFOL1.checked == true) {
			FOL1=wordFinal1C;
			End='\\b';
		} else if(a1Cf != '' && document.wordControls.syllFOL1.checked == true){
			FOL1=a1Cf.join(',');
			End='\\b';
		} else {
			FOL1='';
		}
	}

	if(document.wordControls.syllFOL2){
		if(a2Cf == '' && document.wordControls.syllFOL2.checked == false) {
			FOL2='';
		} else if(a2Cf == '' && document.wordControls.syllFOL2.checked == true) {
			FOL2=wordFinal2C;
			End='\\b';
		} else if(a2Cf != '' && document.wordControls.syllFOL2.checked == true) {
			FOL2=a2Cf.join(',');
			End='\\b';
		} else {
			FOL2='';
		}
	}

	if(document.wordControls.syllFOL3){
		if(a3Cf == '' && document.wordControls.syllFOL3.checked == false) {
			FOL3='';
		} else if(a3Cf == '' && document.wordControls.syllFOL3.checked == true) {
			FOL3=wordFinal3C;
			End='\\b';
		} else if(a3Cf != '' && document.wordControls.syllFOL3.checked == true) {
			FOL3=a3Cf.join(',');
			End='\\b';
		} else {
			FOL3='';
		}
	}

	if(document.wordControls.syllFOL4){
		if(afDigr == '' && document.wordControls.syllFOL4.checked == false) {
			FOL4='';
		} else if(afDigr == '' && document.wordControls.syllFOL4.checked == true) {
			FOL4=digrlett;
			End='\\b';
		} else if(afDigr != '' && document.wordControls.syllFOL4.checked == true) {
			FOL4=afDigr.join(',');
			End='\\b';
		} else {
			FOL4='';
		}
	}

	if(document.wordControls.syllFOL5){
		if(aDouble == '' && document.wordControls.syllFOL5.checked == false) {
			FOL5='';
		} else if(aDouble == '' && document.wordControls.syllFOL5.checked == true) {
			FOL5=doublelett;
			End='\\b';
		} else if(aDouble != '' && document.wordControls.syllFOL5.checked == true) {
			FOL5=aDouble.join(',');
			End='\\b';
		} else {
			FOL5='';
		}
	}
//vowels
	if(document.wordControls.syllC1){
		if(a1V =='' && document.wordControls.syllC1.checked == false) {
			C1='';
		} else if(a1V =='' && document.wordControls.syllC1.checked == true){
			C1=vowel1;
		} else if(a1V != '' && document.wordControls.syllC1.checked == true) {
			C1=a1V.join(',');
		} else {
			C1='';
			//alert('#3 single vowel');
		}
	}

	if(document.wordControls.syllC2){
		if(a2V == '' && document.wordControls.syllC2.checked == false) {
			C2='';
		} else if(a2V == '' && document.wordControls.syllC2.checked == true) {
			C2=vowel2;
		} else if(a2V != '' && document.wordControls.syllC2.checked == true) {
			C2=a2V.join(',');
		} else {
			C2='';
			//alert('#3 double vowel');
		}
		//alert('a1V= '+a1V+'\nC1= '+C1+'\nvowel1= '+vowel1+'\ntype of C1: '+typeof C1+'\ntype of vowel1: '+typeof vowel1+'\ntype of a1V: '+typeof a1V);
	}

//prepare regular expression components from above strings
	PRE=PRE1+','+PRE2+','+PRE3+','+PRE4;
	PRE=PRE.replace(/\,\,/g,'').replace(/^\,/,'').replace(/\,$/,''); //replace double commas, commas at beginning and end of string
	if(PRE != '') {
		sregexpPRE='(' + PRE.split(',').join("|") + ')';
	} else {
		 sregexpPRE='';
	}
	//alert('content of PRE is: '+PRE+'\nPRE.replace: ' +PRE.replace(/\,\,/,''));
	//alert("Content of PRE is: "+PRE+'\nType of PRE is: '+typeof PRE+
	//"'\nContent of C is: "+C+'\nType of C is: '+typeof C+
	//"'\nContent of FOL is: "+FOL +'\nType of FOL is: '+typeof FOL);
	C=C1+','+C2;
	C=C.replace(/\,\,/g,'').replace(/^\,/,'').replace(/\,$/,'');
	if(C != '') {
		sregexpC='(' + C.split(',').join("|") + ')';
	} else {
		sregexpC='';
	}
	FOL=FOL1+','+FOL2+','+FOL3+','+FOL4+','+FOL5;
	FOL=FOL.replace(/\,\,/g,'').replace(/^\,/,'').replace(/\,$/,''); //replace double commas, commas at beginning and end of string
	if(FOL != '') {
		sregexpFOL='(' + FOL.split(',').join("|") + ')';
	} else {
		sregexpFOL='';
	}
	sregexp2=new RegExp('(?:' + Begin + sregexpPRE + sregexpC + sregexpFOL + finalE + End + ')','i');// took out g before i at end; took out ?: after RegExp('(?:' = passive subexpression only groups its contents
	//alert("The realWordArray length is: "+realWordArray.length);
	if(document.wordControls.regexp) { //displays regexp in a textbox for debugging purposes
		document.wordControls.regexp.value = 'P: '+ Begin + sregexpPRE + '\nC: '+ sregexpC + '\nF: ' + sregexpFOL+ '\n'+sregexp2;
	}

	for(var i=0; i<realWordArray.length; i++){
		if(realWordArray[i].match(sregexp2)) {
			addItemToArray(selectedWordArray,realWordArray[i]);
		}
	}
	//alert("length of realWordArray is: "+realWordArray.length+"\nContent: "+realWordArray+"\nMatch found! "+ realWordArray[i]);
	//alert('a1Ci='+a1Ci+'\na1V ='+a1V+'\na1Cf=' +a1Cf+ '\nPRE1= '+PRE1+'\nPRE2= '+PRE2+'\nPRE3= '+PRE3+'\nPRE= '+PRE+'\nFOL1= '+FOL1+'\nFOL2= '+FOL2+'\nFOL3= '+FOL3+'\nFOL= '+FOL+'\nsregexpPRE= '+sregexpPRE+'\nsregexpC= '+sregexpC+'\nsregexpFOL='+sregexpFOL+'\nRegExpression: '+sregexp2+'\nselectedWordArray.length is: '+selectedWordArray.length+'\nContent: '+selectedWordArray);
	//alert('selectedWordArray.length is: '+selectedWordArray.length+'\nContent: '+selectedWordArray);
	//wordArray=wordArray.match(sregexp2);
	//alert('in Array: a1C:'+a1C+'\nin Array: a1Cf: '+ a1Cf+'\nin Array: a1V: '+a1V+'\nin Array: a1Ci: '+a1Ci+'\nin Array: aSyll: '+aSyll);
}

function writeLines() {
	var tabIndex = '0';
	if(doRandom==1) {
		finalWordArray.sort(randOrd); //randomize the list
	}
	storyAreaContent="<table width='100%' border='0'  bgcolor='#A5D0F7'>\n\t<tbody>\n"; // table open tags
	for(var l=0; l<document.form1.Lines.value; l++ ) { //checks for number of lines to write
		CVpattern=finalWordArray[wordIndex];
		wordIndex ++;
		tabIndex++;
		if(wordIndex >=finalWordArray.length) {
			wordIndex=0;
		}
		var ReadSpell = getButton(document.form1.Read);
		if(ReadSpell == 'read') {
			displayRead(CVpattern);
		} else {
			displaySpell(CVpattern,tabIndex);  //note: 2 variables being passed
		}
		storyAreaContent=storyAreaContent+"\t\t</tr>\n"; // row close tag
	}
	storyAreaContent = storyAreaContent+"\t</tbody>\n</table>\n";//table close tags
	document.getElementById('storyArea').innerHTML=storyAreaContent;
}

function callRead(){
	writeLines();
}
function callSpell(){
	writeLines();
}

function displayRead(Item){
//displays words only
	storyAreaContent= storyAreaContent+"\t\t<tr><td class='word'><a>"+Item+"</a></td>";
	//"<a href='http://dict.leo.org/ende?lang=en&lp=ende&search="+CVpattern+"'>"+CVpattern+"</a>" //CVpattern
}

//function displaySpell(TextItem,boxNumber){
////displays a text area in which the user types the word he hears and it gets checked for correct spelling
//	storyAreaContent= storyAreaContent+"\t\t<tr><td class='word'>"+
//	"<a href='javascript:playSound(\"sound/bps40.wav\");'><img title='Click me to hear this word' onclick='playSound(\"sound/bps40.wav\");' src='graphics/arrowr.gif' border='0'></a>\n"+
//	"<input type='text' class='wordItem' onblur='validateBox(\"box"+boxNumber+"\",\"sound/bps40.wav\",\""+TextItem+"\");' "+
//	"tabindex='"+1+boxNumber+"' id='box"+boxNumber+"' value='"+TextItem+"'></td>";
//	//add url as: "<a href='http://dict.leo.org/ende?lang=en&lp=ende&search="+TextItem+"'>"+TextItem+"</a>"
//}

function displaySpell(TextItem,boxNumber){ // calls the play() function for flash integration
//displays a text area in which the user types the word he hears and it gets checked for correct spelling
	storyAreaContent= storyAreaContent+"\t\t<tr><td class='word'>"+
	"<a href='javascript:play(\"sound/bad.mp3\");'><img title='Click me to hear this word' onclick='play(\"sound/bad.mp3\");' src='graphics/arrowr.gif' border='0'></a>\n"+
	"<input type='text' class='wordItem' onblur='validateBox(\"box"+boxNumber+"\",\"sound/bad.mp3\",\""+TextItem+"\");' "+
	"tabindex='"+1+boxNumber+"' id='box"+boxNumber+"' value='"+TextItem+"'></td>";
	//add url as: "<a href='http://dict.leo.org/ende?lang=en&lp=ende&search="+TextItem+"'>"+TextItem+"</a>"
}

function changeCSS(obj, bgColor, bdColor, ftColor) {
   	if(document.getElementById) {
		document.getElementById(obj).style.backgroundColor=bgColor;
		document.getElementById(obj).style.borderColor=bdColor;
		document.getElementById(obj).style.color=ftColor;
	}
}
function validateBox(box,url,text){
	if(document.getElementById(box).value==text){
		changeCSS(box,"#BFFF9F","#000000","#000000");
	} else {
		changeCSS(box,"#FF9F9F","#000000","#000000");
		playSound(url);
		document.getElementById(box).value="";
	}
}

function playSound(surl) {
	document.getElementById("dummyspan").innerHTML="<embed src='"+surl+"' hidden=true autostart=true loop=false />";
}

function playMetronome(surl) {
	document.getElementById("dummyspan").innerHTML="<embed src='"+ surl +"' hidden='true' autostart='true' loop='true' />";
}

function doPopUp(url) {
	doPopUpWindow=window.open(url,"The Sounds of English Tutorials","menubar=yes,resizable=yes,width=870,height=575,left=0,top=0,screenX=150,screenY=150,scrollbars=yes");
}

function inArray(item,arrayName) {
	for(var i=0; i<arrayName.length; i++) {
		if(item==arrayName[i])
			return 1;
	}
	return 0;
}

function randOrd(a,b) {
	return (Math.round(Math.random())-0.5);
}

function getButton(Button) {
	for(var i=0; i< Button.length; i ++ ) {
		if(Button[i].checked){
			return Button[i].value;
		}
	}
}

function clearAllNamedCheckboxes(el){ //checks for the 'name' attribute of a checkbox
// variable 'el' is a single word, not a csv string
	var namedEl= document.getElementsByName(el);
	for(var i=0; i<namedEl.length; i++){
		if(namedEl[i].checked == true) {
			namedEl[i].click();
		}
	}
}

function clickCheckboxes(el){ // checks the 'id' attribute of a checkbox
	//variable 'el' can be a csv string
	var aTemp = new Array;
	aTemp = el.split(',');
	//alert(el);
	//alert(aTemp.length);
	for(var i=0; i<aTemp.length; i++){
		document.getElementById(aTemp[i]).click();
	}
}
function checkCheckboxes(el){ // checks the 'id' attribute of a checkbox
	//variable 'el' can be a csv string
	var aTemp = new Array;
	aTemp = el.split(',');
	//alert(el.length);
	//alert(aTemp.length);
	for(var i=0; i<aTemp.length; i++){
		document.getElementById(aTemp[i]).click();//checked=true;
	}
}

/*
Made by Martial Boissonneault © 2002-2003 http://getElementById.com/
May be used and changed freely as long as this msg is intact
Visit http://getElementById.com/ for more free scripts and tutorials.
*/
var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ns6 = (!document.all && document.getElementById);

function show(id){
//takes a comma separated string as argument
	var temp=id.split(',');
	for(var i=0; i<temp.length; i++){
		// Netscape 4
		if(ns4){
			document.layers[id].visibility = "show";
		}
		// Explorer 4
		else if(ie4){
			document.all[id].style.visibility = "visible";
		}
		// W3C - Explorer 5+ and Netscape 6+
		else if(ns6 || ie5){
			document.getElementById(temp[i]).style.display= "inline";
		}
	}
}

function hide(id){
//takes a comma separated string as argument
	var temp=id.split(',');
	for(var i=0; i<temp.length; i++){
		// Netscape 4
		if(ns4){
			document.layers[id].visibility = "hide";
		}
		// Explorer 4
		else if(ie4){
			document.all[id].style.visibility = "hidden";
		}
		// W3C Netscape 6+
		else if(ns6 || ie5){
			document.getElementById(temp[i]).style.display = "none";
			//document.getElementById(temp[i]).style.visibility = "collapse";
		}
	}
}

function pageForPrintLayout(aList,row) {
//parameters: wordlist array name, row number
//ideas for improvement: use pts or px for table height, width, line-height, font-size etc.
//make the code calculate how many words per column automatically based on font-size and line-height
//add a script to the page to adjust the font-size and number of columns, sort randomly or sequentially from the html source page; make it a self-contained page. will need to include the word arrays in the page as variables as well.
var htmlTop="<html>\n<head>\n<title>Sounds of English Wordlist</title>\n<style>\n table {page-break-after: always;}\n .content{\n  font-size:18pt;\n  font-family: Verdana,Arial,Helvetica,sans-serif;\n  vertical-align:top;\n}\n h3 {\n  font: 18pt;\n  line-height: 22pt; padding-bottom: 0px; margin-bottom: 0px;}\n</style>\n<body>\n";
var htmlBottom="</div>\n</body>\n</html>";
var tableTop="\n<table cellpadding='2' cellspacing='5' border='0' style='width:700px; height:900px;'>\n";
var tableBottom="</table>\n";
var ro="\t<tr>\n";
var rc="\t</tr>\n";
var page; //this variable contains the html code for the whole page
var num_of_rows=0; //number of rows per column
var col=document.getElementById('print_columns').value;
var pageTitle="<tr><th colspan='"+col+"' style='border-bottom: 2px solid black;'>Focus on the letter:</th></tr>\n";
page=htmlTop;
	if(aList.length !=0){//if the wordlist is not empty
		for(var p=0; p < Math.ceil(aList.length/(col*30)); p++){ // this line calculates how many pages you need to print out all the words in aList. Each page is a whole table
			page+=tableTop+pageTitle;
			for(var r=0;r<row; r++){
				page+=ro; //outputs a new row <tr>
				for(var c=0;c<col;c++){
					var w = num_of_rows;
					if(w<aList.length){//add only as many cells (columns) as needed
						page+='\t\t<td class="content">';
						while(w<num_of_rows+30){
							if(aList[w] != undefined){
								page+=aList[w]+'<br>'; //word only (note only 1 line break)
								w++;
							} else {
								break;
							}
						}
					page+='</td>\n';
					num_of_rows+=30;
					}
				}
			page+=rc;
			}
		page+=tableBottom;
		}
	page+=htmlBottom
	dopopup(page);
	} else {//if the wordlist is empty
		alert('You must first select a sound to create a wordlist.');
	}
}

function dopopup(page) {
  var generator=window.open('','hello','menubar=yes,resizable=yes,height=600,toolbars=1,width=750,scrollbars=1');
  generator.document.write(page);
  generator.document.close();
}


