var maxQuestions = 20;
var currentQuestion = 2;
var fromKeyPress=false;

document.onkeypress=detectspecialkeys

function detectspecialkeys(e){
	var evtobj=window.event? event : e
	var unicode=evtobj.charCode? evtobj.charCode : evtobj.keyCode
	//var actualkey=String.fromCharCode(unicode)
	//if (evtobj.altKey || evtobj.ctrlKey || evtobj.shiftKey)

	if (evtobj.altKey && unicode==109){
		fromKeyPress=true;
		toggleNumberDetail(currentQuestion,8);
	}
}

function updatepage(str, location){
		if ( location == "") {
    	document.getElementById("result").innerHTML = str;
		} else {
			document.getElementById(location).innerHTML = str;
		}
}


// retrieve
function xmlhttpGet(strURL, location) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('GET', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText, location);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

// this function POSTS data to the server
function xmlhttpPost(strURL, location) {
    var xmlHttpReq = false;
    var self = this;
    // Mozilla/Safari
    if (window.XMLHttpRequest) {
        self.xmlHttpReq = new XMLHttpRequest();
    }
    // IE
    else if (window.ActiveXObject) {
        self.xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
    }
    self.xmlHttpReq.open('POST', strURL, true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    self.xmlHttpReq.onreadystatechange = function() {
        if (self.xmlHttpReq.readyState == 4) {
            updatepage(self.xmlHttpReq.responseText, location);
        }
    }
    self.xmlHttpReq.send(getquerystring());
}

function getquerystring() {
    return formData2QueryString(document.forms['quizForm']);
}

function formData2QueryString(docForm) {

	var strSubmitContent = '';
	var formElem;
	var strLastElemName = '';

	for (i = 0; i < docForm.elements.length; i++) {

		formElem = docForm.elements[i];
		switch (formElem.type) {
			// Text fields, hidden form elements
			case 'text':
			case 'hidden':
			case 'password':
			case 'textarea':
				//alert(encodeURI(formElem.value));
				strSubmitContent += formElem.name + '=' + encodeURI(formElem.value) + '&'
				break;

			// select box has to be done differently for IE to work properly
			case 'select-one':
				//alert(formElem[formElem.selectedIndex].text);
				strSubmitContent += formElem.name + '=' + encodeURI(formElem[formElem.selectedIndex].text) + '&'
				break;

			// Radio buttons
			case 'radio':
				if (formElem.checked) {
					strSubmitContent += formElem.name + '=' + encodeURI(formElem.value) + '&'
				}
				break;

			// Checkboxes
			case 'checkbox':
				if (formElem.checked) {
					// Continuing multiple, same-name checkboxes
					if (formElem.name == strLastElemName) {
						// Strip of end ampersand if there is one
						if (strSubmitContent.lastIndexOf('&') == strSubmitContent.length-1) {
							strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
						}
						// Append value as comma-delimited string
						strSubmitContent += ',' + encodeURI(formElem.value);
					}
					else {
						strSubmitContent += formElem.name + '=' + encodeURI(formElem.value);
					}
					strSubmitContent += '&';
					strLastElemName = formElem.name;
				}
				break;

		}
	}

	// Remove trailing separator
	strSubmitContent = strSubmitContent.substr(0, strSubmitContent.length - 1);
	strSubmitContent += '&preview=' + encodeURI("1");
	return strSubmitContent;
}

function toggleSingleDetail(id,number) {
  // toggle the display status of a single row of the quiz form table
  body=document.getElementById(id+"_"+number);
  if (body) {
    if (body.style.display == 'none') {
    	// To make tr tags disappear
    	// we set display to none, as usual
    	// to make them appear again
    	// we set style to block for IE
    	// but for firefox we use table-row
    	try {
    	  body.style.display='table-row';
    	} catch(e) {
    	  body.style.display = 'block';
    	}
    }
    else {
    	body.style.display = 'none';
    }
  }
}

function toggleRanks() {
  // toggle the display status of the custom rank fields
	for ( id=1; id<=5; id++ ) {
		body=document.getElementById("rank"+id+"row");
  	if (body) {
  	  if (body.style.display == 'none') {
  	  	// To make tr tags disappear
  	  	// we set display to none, as usual
  	  	// to make them appear again
  	  	// we set style to block for IE
  	  	// but for firefox we use table-row
  	  	try {
  	  	  body.style.display='table-row';
  	  	} catch(e) {
  	  	  body.style.display = 'block';
  	  	}
  	  }
  	  else {
  	  	body.style.display = 'none';
  	  }
  	} // end body
	} // end for loop
}

function toggleNumberDetail(id,number) {
	// determine type of quiz
	for (i=0;i<document.quizForm.quizType.length;i++){
		if (document.quizForm.quizType[i].checked==true)
		theone=i
	}

  // loop to process all the rows of the quiz form table for the add/remove buttons
  for (i=1;i<=number;i++) {
			// the foils get handled differently depending on type of quiz
			if  ((i>=4) && (i<=6) ) {
				if (document.quizForm.quizType[theone].value == "multiple") {
					toggleSingleDetail("row"+id,i);
				} else if (document.quizForm.quizType[theone].value == "truefalse") {
					if (4==i)	{ toggleSingleDetail("row"+id,i); }
				} else {
					// do nothing
				}
			} else {
				toggleSingleDetail("row"+id,i);
			}
			// handle the hints
			if ( 3==i ){
				if ((document.quizForm.hints.checked) && (document.getElementById("row"+id+"_1").style.display != 'none')) {
					turnONSingleDetail("row"+id+"_"+3);
				} else {
					turnOFFSingleDetail("row"+id+"_"+3);
				}
			}
  }
	toggleSingleDetail("row"+(id-1),7); // toggle the buttons

	// handle the extra row of space, can't toggle due to remove button using same function
	if (document.getElementById("row"+id+"_1").style.display == 'none') {
		turnOFFSingleDetail("row"+id+"_"+8);
 		currentQuestion=id;
		document.getElementById("Question"+(id-1)+"_1").focus();
	} else {
		turnONSingleDetail("row"+id+"_"+8);
		currentQuestion=id+1;
		if ( !fromKeyPress ) {
			document.getElementById("Question"+id+"_1").focus();
		}
		//
	}
	fromKeyPress=false;
}

function turnOFFSingleDetail(detail) {
  // doesn't toggle, just turns off a row, needs EXACT name passed
  body=document.getElementById(detail);
  if (body) {
    	body.style.display = 'none';
  }
}


function turnONSingleDetail(detail) {
  // doesn't toggle, just turns ON a row, needs EXACT name passed
  body=document.getElementById(detail);
  // To make tr tags disappear
  // we set display to none, as usual
  // to make them appear again
  // we set style to block for IE
  // but for firefox we use table-row
  try {
    body.style.display='table-row';
  } catch(e) {
    body.style.display = 'block';
  }
}

function togglequizType(){
	// depending on the status of the multiple choice checkbox, will either remove or add the FOIL answers
	// works by looping through all VISIBLE questions
	id=1;
	do {
		body=document.getElementById("row"+id+"_1");

		for (i=0;i<document.quizForm.quizType.length;i++){
			if (document.quizForm.quizType[i].checked==true)
			theone=i
		}

			if (document.quizForm.quizType[theone].value == "multiple") {
				turnONSingleDetail("row"+id+"_"+4);
				turnONSingleDetail("row"+id+"_"+5);
				turnONSingleDetail("row"+id+"_"+6);
			} else if (document.quizForm.quizType[theone].value == "truefalse") {
				turnONSingleDetail("row"+id+"_"+4);
				turnOFFSingleDetail("row"+id+"_"+5);
				turnOFFSingleDetail("row"+id+"_"+6);
			} else {
				turnOFFSingleDetail("row"+id+"_"+4);
				turnOFFSingleDetail("row"+id+"_"+5);
				turnOFFSingleDetail("row"+id+"_"+6);
			}

		// handle the hints
		if (document.quizForm.quizType[theone].value == "matching") {
			turnOFFSingleDetail("hintsAllowed");
		} else {
			turnONSingleDetail("hintsAllowed");
		}

		id++;
		if (id<=maxQuestions) {
			body=document.getElementById("row"+id+"_1");
			//alert(id);
		}
	} while ( (body.style.display != 'none') && (id<=maxQuestions) );
}

function toggleHints(){
	// depending on the status of the hints checkbox, will either remove or add the answers hints
	// works by looping through all VISIBLE questions
	id=1;
	do {
		body=document.getElementById("row"+id+"_1");

		if (body.style.display != 'none') {
			if (document.quizForm.hints.checked) {
				turnONSingleDetail("row"+id+"_"+3);
			} else {
				turnOFFSingleDetail("row"+id+"_"+3);
			}
		}
		id++;
		if (id<=maxQuestions) {
			body=document.getElementById("row"+id+"_1");
			//alert(id);
		}
	} while ( (body.style.display != 'none') && (id<=maxQuestions) );
}

function ValidateQuizForm(){
	// make sure all the fields in quizForm are filled in (except the multiple choice button)
	warn=0; emptyColor = "#ddaaaa"; lengthColor = "#99aaaa"; okColor="#ffffff";
	for (i=0;i<document.quizForm.quizType.length;i++){
		if (document.quizForm.quizType[i].checked==true)
		theone=i
	}

	// yeah, I could make a loop or function for the three standalone fields, but not worth the effort for 3 questions
	quizField = document.quizForm.author;
	if (quizField.value.length <=0) {
		warn=1; quizField.style.background=emptyColor;
	} else {
		quizField.style.background=okColor;
	}

	quizField = document.quizForm.title;
	if (quizField.value.length <=0) {
		warn=1; quizField.style.background=emptyColor;
	} else {
		quizField.style.background=okColor;
	}

	quizField = document.quizForm.description;
	if (quizField.value.length <=0) {
		warn=1; quizField.style.background=emptyColor;
	} else {
		quizField.style.background=okColor;
	}

	// do all the questions, this is why they are named with numbers, just loop it
	id=1;
	do {
		for ( loop=1; loop<7; loop++ ) {
			body=document.getElementById("row"+id+"_"+loop);

			if (body.style.display != 'none') {  // if we can see it, we need it!
				inputText=document.getElementById("Question"+id+"_"+loop);
				if (inputText.value.length <=0) {
 							inputText.style.background=emptyColor;
							warn=1;
				} else if ((document.quizForm.quizType[theone].value == "matching") && (inputText.value.length >50)) {
 							inputText.style.background=lengthColor;
							warn=1;
				} else {
					inputText.style.background=okColor;
				}
			} else {
				inputText=document.getElementById("Question"+id+"_"+loop);
				inputText.value="";
			}
		}
		body=document.getElementById("row"+id+"_1");
		if (body.style.display == 'none') {  // if we can't see it, BLANK IT
			document.getElementById("Question"+id+"_1").value="";
		}

		id++;
		if (id<=maxQuestions) {
			body=document.getElementById("row"+id+"_1");
			//alert(id);
		}
	} while (id<=maxQuestions);

	// oooh, css display, this is more WEB 2.0 than an alert box
	if ( warn ) {
		document.getElementById("validateResult").innerHTML = "<p style=\"color: red;\">There are incorrect fields. Please review textfields in red.</p>"+"<p style=\"color: "+emptyColor+";\">These fields are empty and need to be filled.</p>\n"+ "<p style=\"color: "+lengthColor+";\">These fields are too long and need to be shortened.</p>\n";
		document.getElementById("result").innerHTML = "";
		return false;
	} else {
		document.getElementById("validateResult").innerHTML = "<p style=\"color: blue;\">All fields are complete</p>";
		document.getElementById("result").innerHTML = "";
		return true;
	}
}

