/* Charles Chen 2003 */
/* the main data structure that contains user answers. 
a multi dimensional array with the form_names and an array of form elements.
structured with form_name as index and element with element_name, element_id, 
element_type, element_value */
var data;  
// data structure to hold pop up data for yes/no questions
var pop_up;
/* form data, for descriptions with the form name as the keys */
var form_data;
/* pop up window variable that allows for a single pop up window to be interfaced */
var popUpWin;
// constant indices variables
var ELEMENT_NAME = 0;
var ELEMENT_ID = 1;
var ELEMENT_TYPE = 2;
var ELEMENT_VALUE = 3;
// constants for pop up array structure
var ADDRESS = 0;
var TITLE = 1;
var LOWER_RANGE= 2;
var UPPER_RANGE= 3;

/* constructor for the FormLoader object */
function FormLoader(){
	// set it's available methods for calling outside
	this.parseForm = parseForm;
	this.buildForm = buildForm;
	this.checkForPopUp = checkForPopUp;
	this.printData = printData;
	this.createPopUpsArray = createPopUpsArray;
	this.addPopupElement = addPopupElement;
	this.checkYesPopUps = checkYesPopUps;
}

/* pops up array */
function createPopUpsArray(){
		pop_up = new Array();
}

// function that adds a pop up element into the pop up array
function addPopupElement(address, title, lower, upper){
	var index;
	if(pop_up != null){
		//alert("Adding pop up element:" + address + " " + title + " (" + lower + "-" + upper + ")");
		index = pop_up.length;
		pop_up[index] = new Array(address,title,lower,upper);		
	}
}

// function that checks and displays pop ups depending on how many answers were answered yes
// popups array contains other arrays with three variables [page_name, title,lower range, upper range]
// where lower and upper range represents the range of positive variables to trigger the pop up

function checkYesPopUps(document)
{
	var i, j,yes_count, upper, lower, page,title;
	yes_count = 0;
	if (pop_up != null){
		for(i=0;i<document.forms.length; i++){
		//	 utility function that checks if any values of a form is YES 
			for(j=0;j<document.forms[i].elements.length;j++){
				if(document.forms[i].elements[j].type == "radio" && 
					document.forms[i].elements[j].id == "YES" && 
					document.forms[i].elements[j].checked == true){
					yes_count += 1;
					}
			}
		}
		// now go through the pop ups array and pop up the window based on the range
		for(i=0;i<pop_up.length; i++){
			title = pop_up[i][TITLE];
			upper = pop_up[i][UPPER_RANGE];
			lower = pop_up[i][LOWER_RANGE];
			page = pop_up[i][ADDRESS];
			if(yes_count >= lower && yes_count <= upper){
				//alert("value(" + yes_count + "): " + page + " " + title + "(" + upper + "-" + lower + ")");
				var url;
				var index;
				// trim the string to get the relative length
				if(document.URL.indexOf("file",0) >= 0){
					index = document.URL.lastIndexOf("\\");
				}else{
					index = document.URL.lastIndexOf("/");
				}
				url = document.URL.substring(0,index + 1);
				// relative urls
				url += "popups/" + page;
				popUpWindow(url,title,300,200,300,250);
			}			
		}
	}
}

/* function that parses a documents form fields and then adds the elements into the document array */
function parseForm(document){
	/* for each form in the document, get its input elements and get their values and place 
	them into the data array */
	var i;
	for (i =0; i< document.forms.length; i++){
		loadForm(document.forms[i]);
	}
}

/* function that sets the form data based on the elements in the data array */
function buildForm(document)
{
	var i,j;
	// if the data array exists, parse through each form in the document and check if there is data
	// in the data array structure
	if(data != null){
		for(i=0; i< document.forms.length; i++){
			form_name = document.forms[i].name;
			if (document.forms[i].elements != null){
				for(j=0;j<document.forms[i].elements.length; j++){
					// if the data contains this element then set its value on the document
					if (document.forms[i].elements[j].type != "submit" &&
						document.forms[i].elements[j].type != "button"){
						var temparray;
						// use the elements id and name field to get the elements value
						temparray = getElementValue(form_name,document.forms[i].elements[j].name,
													document.forms[i].elements[j].id);
						// if this element is in the data array, then set the values for the document
						if (temparray != null){
							//alert("retrieved: [" + temparray[ELEMENT_NAME] + "] [" + temparray[ELEMENT_ID] + 
							//		"] [" + temparray[ELEMENT_TYPE] + "] [" + temparray[ELEMENT_VALUE] + "]");
							if (document.forms[i].elements[j].type == "radio" || document.forms[i].elements[j].type == "checkbox"){
								document.forms[i].elements[j].checked = temparray[ELEMENT_VALUE];
							}else
							document.forms[i].elements[j].value = temparray[ELEMENT_VALUE];
							document.forms[i].elements[j].id = temparray[ELEMENT_ID];
						}
					}
				}
			}
		}
	}
}

// function that loads a form object into the data structure
function loadForm(form){
	var form_name;
	var j;
	form_name = form.name;
	// add this form into the form_data structure
	addFormElement(form_name,form.id);
	// for each input element in the form, add an entry into the data array
	for (j=0; j< form.elements.length; j++){
		// if the form element is a button or a submit button then do nothing
		if (form.elements[j].type != "button" &&
			form.elements[j].type != "submit"){
			var element_name,element_type,element_id,element_value = "";
			if(form.elements[j].name != null)
				element_name = form.elements[j].name;
			if(form.elements[j].id != null)
				element_id = form.elements[j].id;
			if(form.elements[j].type != null)
				element_type = form.elements[j].type;
			// if the element is a radio button type then get the value based on the checked property
			if(element_type == "radio" ||  element_type =="checkbox"){
				if(form.elements[j].checked == true)
					element_value = true;
				else 
					element_value = false;
			}else{
				if(form.elements[j].value != null)
					element_value = form.elements[j].value;
			}
		addElement(form_name,element_name,element_id,element_type,element_value);
		}
	}
}
/* function that checks if document needs a pop up */
function checkForPopUp(document){
	var i;
	// for each of the forms in this document 
	for(i=0;i<document.forms.length;i++){
		// check if the form exists, and if a pop up is needed
		if (hasForm(document.forms[i].name) == false){
			// load the data for this form into the data stucture
			loadForm(document.forms[i]);
			// if there are yes values, then open the pop up page for this form
			if(checkForYes(document.forms[i].name) == true){
				var url,title,left,top,width,height;
				var index;
				// trim the string to get the relative length
				if(document.URL.indexOf("file",0) >= 0){
					index = document.URL.lastIndexOf("\\");
				}else{
					index = document.URL.lastIndexOf("/");
				}
				url = document.URL.substring(0,index + 1);
				// relative urls
				url += "popups/" + document.forms[i].name + ".htm";
				title = document.forms[i].name;
				// hard coded position and size values;
				popUpWindow(url,title,300,200,300,250);
			}
		}else loadForm(document.forms[i]);
	}
}

/* add form item */
function addFormElement(form_name, form_description){
	// form_data is a key value pair structure
	if (form_data != null){
		form_data[form_name] = form_description;
	}else{
		form_data = new Array();
		form_data[form_name] = form_description;
	}
}

/* get form element */
function getFormElement(form_name){
	if(form_data != null && form_data[form_name] != null){
		return form_data[form_name];
	}else return null;
}
		
/* function that adds an element into the data array using the form name as the index */
function addElement(form_name,element_name, element_id,element_type,element_value){
	/* create a triplet array with the value of the added element */
	var temparray = new Array(element_name,element_id,element_type,element_value);
	var array_index = 0;
	/* if the data object does not exist, then build the structure */
	if (data == null) data = new Array();
	// if the form does not exists then build the array
	if (data[form_name] == null){
		data[form_name] = new Array();
	}else{ 
		/* add the entry to the structure. if the structure exist, overwrite the existing entry */
		var i;
		// overwrite if exists
		for(i=0; i< data[form_name].length;i++){
			if(data[form_name][i][ELEMENT_ID] == element_id && 
			   data[form_name][i][ELEMENT_NAME] == element_name){
				array_index = i;
				break;
			}else array_index = data[form_name].length // gets the next elements index
		}
	}
	// set the value
	data[form_name][array_index] = temparray;
	//alert("element added/overwritten (" + form_name + ", " + array_index + "): [" + data[form_name][array_index][ELEMENT_NAME] + "]  [" 
		//				+ data[form_name][array_index][ELEMENT_ID] + "]  [" + data[form_name][array_index][ELEMENT_TYPE] + "] [" 
			//		+ data[form_name][array_index][ELEMENT_VALUE] + "]");
}

/* function that retrieves values of an element if it is contained in the data array */
function getElementValue(form_name,element_name,element_id){
	if (data[form_name] != null){
		var i;
		for(i=0;i<data[form_name].length;i++){
			if (data[form_name][i][ELEMENT_NAME] == element_name && data[form_name][i][ELEMENT_ID] == element_id){
				//alert("element found: [" + data[form_name][i][0] + "] [" + data[form_name][i][1] + "] [" + 
				//		data[form_name][i][2] + "]");	
				return new Array(data[form_name][i][ELEMENT_NAME],data[form_name][i][ELEMENT_ID],
								data[form_name][i][ELEMENT_TYPE],data[form_name][i][ELEMENT_VALUE]);
			}
		}
	}
	return null;
}

/* utility function to check if a for exists */
function hasForm(form_name){
	if (data != null && data[form_name] != null) return true;
	return false;
}

/* utility function that checks if any values of a form is YES */
function checkForYes(form_name){
	if (data[form_name] != null){
		for(i=0; i<data[form_name].length; i++){
			if(data[form_name][i][ELEMENT_TYPE] == "radio" 
				&& data[form_name][i][ELEMENT_ID].toUpperCase() == "YES" 
				&& data[form_name][i][ELEMENT_VALUE] == true)
				return true;
			}
	}
	return false;
}

/* function that pops up a new window with the specified url address */
function popUpWindow(URLStr, title, left, top, width, height)
{ // closes the pop up window exists, then create a new window with the default settings
  if(popUpWin)
  {
    if(!popUpWin.closed) popUpWin.close();
  }
  popUpWin = open(URLStr, title,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
}

// returns the element array, that includes the element name, value, type, id, etc
function getFormElementValue(form_name, element_name)
{
	var i;
	if(data[form_name] != null){
		for(i=0;i< data[form_name].length;i++){
			if (data[form_name][i][ELEMENT_NAME] == element_name){
				return data[form_name][i];
			}
		}
	}return null;
}

// helper function that gets the value of radio buttons
function getRadioButtonValues(form_name,element_name)
{
	var i;
	if (data[form_name] != null){
		for(i=0;i<data[form_name].length;i++){
			if((data[form_name][i][ELEMENT_NAME] == element_name) && 
			   (data[form_name][i][ELEMENT_TYPE] == "radio") && 
			   (data[form_name][i][ELEMENT_VALUE] == true)){
			   		return data[form_name][i];
			}
		}
	}return null;
}

// helper function that checks if the form exists in the data structure
function hasAnswers(form_name)
{
	var i;
	if(data[form_name] != null){
		for(i=0;i<data[form_name].length;i++){
			if(data[form_name][i][ELEMENT_VALUE] != "") return true;
		}
	}return false;
}

/* function that prints out the data in a window */
function printData(document)
{
	if(data != null){
		var title,left,top,height,width;
		var value;
		var name;
		var date = new Date();
		left = 150;
		top =50;
		width = 600;
		height = 600;
		title = "Result";
		name = getFormElementValue("section3_2","section3_2_3");
		//'toolbar=yes,location=no,directories=no,status=no,menubar=no,scrollbar=yes,resizable=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
		// hard coded position and size values;
		if (popUpWin != null) popUpWin.close();
		popUpWin = open('', title,'toolbar=yes,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,copyhistory=yes,width='+width+',height='+height+',left='+left+', top='+top+',screenX='+left+',screenY='+top+'');
		value = "<html><head><title>First Step To Change</title><link href='../sitestyle.css' rel='stylesheet' type='text/css'>";
		value += "</head><body>";
		value += "<table width='100%' border='0'><tr><td width='50'><img src='../images/logo.gif' align='top'></td>";
		value += "<td width='*'><p class='headers'>Your First Step To Change</p></td></tr></table>";
		value += "<p class='regulartext'>Date:";
		value += " " + date.toString();
		if ((name != null) && (name[ELEMENT_VALUE] != "")){
			value += "<br>Name: " + name[ELEMENT_VALUE];
		}
		value += "</p>";
		value += "<table width ='95%' align='center' border='0'><tr>";
		value += "<td class='textbox'>You may print your results by pressing the printer button on the status bar.</td></tr></table>"
		value += "<br><b>Here are your goals for change:</b><hr>";
		// go through each entry in the data data structure and build a page up and display it
		for(var i in data){
			if(hasAnswers(i)){
				// use the form description as the section header
				value += "<table width='90%' border='0' cellpadding='5'><tr><td colspan='2'><div align='center'>";
				value += "<p class='textstyle'>" + getFormElement(i) + "</p></div></td></tr>";
				// check which form has been selected in the list
				switch(i){
					// section three one has a different style a four sectioned table based on user input 
					case "section3_1":
						var tmp1,tmp2,tmp3,tmp4;
						var ans1,ans2,ans3;
						tmp = getFormElementValue(i,"section3_1_1");
						tmp2 = getFormElementValue(i,"section3_1_2");
						tmp3 = getFormElementValue(i,"section3_1_3");
						tmp4 = getFormElementValue(i,"section3_1_4");
						// print out the table for benefits and costs
						if ((tmp[ELEMENT_VALUE] != "") || (tmp2[ELEMENT_VALUE] != "")){
							value += "<tr><td width='50%' height='20'>";
							value += "<div align='center'><p class='sectionstyle'>" + tmp[ELEMENT_ID] + "</p></div></td>";
							value += "<td width='50%' height='20'><div align='center'><p class='sectionstyle'>" + tmp2[ELEMENT_ID] + "</p></div></td></tr>";
							value += "<tr><td width='50%' class='tableanswer'>" + tmp[ELEMENT_VALUE] + "</td>";
							value += "<td width='50%' class='tableanswer'>" + tmp2[ELEMENT_VALUE] + "</td></tr>";
						}
						if ((tmp3[ELEMENT_VALUE] != "") || (tmp4[ELEMENT_VALUE] != "")){
							value += "<tr><td width='50%' height='20'>";
							value += "<div align='center'><p class='sectionstyle'>" + tmp3[ELEMENT_ID] + "</p></div></td>";
							value += "<td width ='50%' height='20'><div align='center'><p class='sectionstyle'>" + tmp4[ELEMENT_ID] + "</p></div></td></tr>";
							value += "<tr><td width='50%' class='tableanswer'>" + tmp3[ELEMENT_VALUE] + "</td>";
							value += "<td width='50%' class='tableanswer'>" + tmp4[ELEMENT_VALUE] + "</td></tr>";
						}
						// now do the answers:
						ans1 = getRadioButtonValues(i,"section3_1_5");
						if (ans1 != null){
							value += "<tr><td class='answer'>Which box has the most answers?</td>";
							value += "<td class='answer'>" + ans1[ELEMENT_ID] + "</td></tr>";
						}
						ans2 = getFormElementValue(i,"section3_1_6");
						if ((ans2 != null) && (ans2[ELEMENT_VALUE] != "")){
							value += "<tr><td colspan='2' align ='center' class='sectionstyle'>" + ans2[ELEMENT_ID] + "</td></tr>";
							value += "<tr><td colspan='2' class='answer'>" + ans2[ELEMENT_VALUE] + "</td></tr>";
						}
						ans3 = getRadioButtonValues(i,"section3_1_7");
						if (ans3 != null){
							value += "<tr><td class='answer'>Do the benefits of continuing to gamble outweigh the costs?</td>";
							value += "<td class='answer'>" + ans3[ELEMENT_ID] + "</td></tr>";
						}									
						break;
					case "section3_2":
						var tmp1,tmp2;
						var ans1,ans2,ans3;
						tmp = getRadioButtonValues(i,"section3_2_1");
						if (tmp != null){
							// print out the table for benefits and costs
							value += "<tr><td class='answer'>Which option did you choose?</td>";
							value += "<td class='answer'>" + tmp[ELEMENT_ID] + "</td></tr>";
						}
						tmp2 = getFormElementValue(i,"section3_2_2");
						if ((tmp2 != null) && (tmp2[ELEMENT_VALUE] != "")){
							value += "<tr><td colspan='2' align='center' class='sectionstyle'>" + tmp2[ELEMENT_ID] + "</td></tr>";
							value += "<tr><td colspan='2' class='answer'>" + tmp2[ELEMENT_VALUE] + "</td></tr>";
						}
						break;
					case "section3_3":
						var tmp;
						tmp = getFormElementValue(i,"section3_3_1");
						if ((tmp != null) && (tmp[ELEMENT_VALUE] != "")){
							value += "<tr><td colspan='2' align='center' class='sectionstyle'>" + tmp[ELEMENT_ID] + "</td></tr>";
							value += "<tr><td colspan='2' class='answer'>" + tmp[ELEMENT_VALUE] + "</td></tr>";
						}
						break;
					// the default section is the list of YES/NO questions
					default:
						value += "<tr><td><div align='center'><p class='sectionstyle'>Question</p></div></td>";
						value += "<td><div align='center'><p class='sectionstyle'> Answer</p></div></td>";
						value += "</tr><tr>";
						// get the answers for each item
						for(j=0;j<data[i].length;j++){
							if (data[i][j][ELEMENT_TYPE] != "radio"){
								value += "<td width='60%' class='answer'>" + data[i][j][ELEMENT_ID] + "</td>";
								value += "<td width='40%' class='answer'>" + data[i][j][ELEMENT_VALUE] + "</td>";
								value += "</tr>";
							}else{
								if(data[i][j][ELEMENT_ID] == "YES")
								{
									value += "<td width='90%' class='answer'>" + data[i][j][ELEMENT_NAME] + "</td>";
									if(data[i][j][ELEMENT_VALUE] == true)
										value += "<td width='10%' class='answer'>YES</td>";
									else
										value += "<td width='10%' class='answer'>NO</td>";
								value += "</tr>";
								}
							}
						}
				}		
				// end all sections with the table closing value
				value += "</table><br>";
			}
		}

		// finish up the page and write the value to the document
		value += "</body></html>";
		popUpWin.document.write(value);
	  }
}
			
	
	
	

