function survey() {
	this.title = "QuicKutz Survey";
	this.startDate = "";
	this.endDate = "";
	this.welcomemessage = "";
	this.thankyoumessage = "";
	this.firstQuestion = null;
	this.startAt = this.firstQuestion;
	this.qperpage = 10;
	
	this.addQuestion = addQuestion;
	this.writeSurvey = writeSurvey;
	this.thankYou = thankYou;
	this.recordSurvey = recordSurvey;
	this.saveAnswers = saveAnswers;
	this.getQuestionById = getQuestionById;
}

function addQuestion(qobj) {
	with (this) {
		if (firstQuestion == null) {
			firstQuestion = qobj;
			startAt = firstQuestion;
		}
		else {
			var que = firstQuestion;
			while (que.nextQuestion != null)
				que = que.nextQuestion;
			que.nextQuestion = qobj;
		}
	}
}

function writeSurvey() {
	with (this) {
		var header = document.getElementById('titleTd');
		header.innerHTML = title;
		
		var instr = document.getElementById('instrDiv');
		if (instr)
			instr.innerHTML = surveyObj.welcomemessage;
		
		var page = document.getElementById('surveyDiv');
		page.innerHTML = "";
		
		var que = startAt;
		var counter = 1;
		
		var part = document.createElement("DIV");
		part.id = "part"+counter;
		
		var el;
		
		var questionsWritten = 0;
		
	
	while (que != null) {
		// if there's a display condition...
		if (que.condition != "" && counter > 1) {
			startAt = que;
			break;
		}
		if (!que.testCondition()) {
			que = que.nextQuestion;
			continue;
		}
		
		var qdiv = document.createElement("DIV");
		qdiv.id = "qdiv"+que.id;

/*		el = document.createElement("DIV");
		el.className = "questionHead";
		if (counter > 1)
			el.style.display = "none";
		el.innerHTML = "Question:";
		part.appendChild(el);
*/		
		el = document.createElement("P");
		var questionBody = que.q;
		questionBody = questionBody.replace("\n\r", "<br>");
		el.innerHTML = questionBody;
		qdiv.appendChild(el);
		el = document.createElement("P");
		el.style.paddingLeft = "15";
		
		// Add each answer to the question
		var ansEl;
		if (que.qtype == QTEXT) {
			ansEl = document.createElement("INPUT");
			ansEl.type = "text";
			ansEl.id = "q"+que.id;
			ansEl.name = "q"+que.id;
			if (que.size > 0)
				ansEl.size = que.size;
			el.appendChild(ansEl);
		}
		else if (que.qtype == QTEXTAREA) {
			ansEl = document.createElement("TEXTAREA");
			ansEl.id = "q"+que.id;
			ansEl.name = "q"+que.id;
			ansEl.rows = "5";
			ansEl.cols = "35";
			el.appendChild(ansEl);
		}
		else if (que.qtype == QRADIO) {
			var ans = que.firstAnswer;
			var anum = 1;
			while (ans != null) {
				try {
					ansEl = document.createElement("<input type='radio' name='q"+que.id+"' value='"+ans.value+"'>");
				}
				catch (e) {
					ansEl = document.createElement("INPUT");
					ansEl.type = "radio";
					ansEl.name = "q"+que.id;
					ansEl.value = ans.value;
				}
				el.appendChild(ansEl);
				el.appendChild(document.createTextNode(ans.a + "  "));
				if (ans.value == "") {
					var other = document.createElement("INPUT");
					other.type = "text";
					other.id = "q"+que.id+"_other";
					other.name = other.id;
					other.onchange = new Function("var el = getRadio('"+que.id+"', '"+anum+"'); if (el) { el.value = this.value; if (el.value != '') el.checked = true; }");
					el.appendChild(other);
				}
				el.appendChild(document.createElement("BR"));
				ans = ans.nextAnswer;
				anum++;
			}
		}
		else if (que.qtype == QCHECKBOX) {
			var ans = que.firstAnswer;
			var counter2 = 1;
			while (ans != null) {
				ansEl = document.createElement("INPUT");
				ansEl.type = "checkbox";
				ansEl.name = "q"+que.id+"_"+counter2;
				ansEl.id = ansEl.name;
				ansEl.value = ans.value;
				if (ans.exclusive) // uncheck everything else
					ansEl.onclick = new Function("if (this.checked) exclusiveCheck('"+que.id+"', '"+counter2+"');");
				else // uncheck any exclusive ones
					ansEl.onclick = new Function("if (this.checked) exclusiveUnCheck('"+que.id+"', '"+counter2+"');");
				el.appendChild(ansEl);
				el.appendChild(document.createTextNode(ans.a + "  "));
				if (ans.value == "") {
					var other = document.createElement("INPUT");
					other.type = "text";
					other.id = "q"+que.id+"_"+counter2+"_other";
					other.name = other.id;
					other.onchange = new Function("var el = document.getElementById('q"+que.id+"_"+counter2+"'); if (el) { el.value = this.value; if (el.value != '') el.checked = true; }");
					el.appendChild(other);
				}
				el.appendChild(document.createElement("BR"));
				ans = ans.nextAnswer;
				counter2++;
			}
		}
		/*** end ***/
		
		qdiv.appendChild(el);
		part.appendChild(qdiv);
		questionsWritten++;
	
	
		// if the question we just added has potential skips, STOP
		if (que.hasPotentialSkip()) {
			startAt = que.nextQuestion;
			break;
		}
		
		que = que.nextQuestion;
		counter++;
		if (counter > qperpage) {
			startAt = que;
			break;
		}
		if (que == null)
			startAt = null;
	}
	
	if (questionsWritten == 0) {
		recordSurvey();
		return;
	}
	
		// Add a next button to the end of the part
		el = document.createElement("DIV");
		el.style.textAlign = "right";
		var subEl = document.createElement("SPAN");
		subEl.className = "nextLink";
		if (startAt == null) {
			subEl.onclick = new Function("if (surveyObj.saveAnswers()) surveyObj.recordSurvey(); else alert(errormsg);");
			subEl.innerHTML = "finish &gt;&gt;";
		}
		else {
			subEl.onclick = new Function("if (surveyObj.saveAnswers()) surveyObj.writeSurvey(); else alert(errormsg);");
			subEl.innerHTML = "next &gt;&gt;";
		}
		el.appendChild(subEl);
		part.appendChild(el);
		/*** end ***/
		
		page.appendChild(part);
		
	}
}

function thankYou() {
	with (this) {
		var page = document.getElementById('surveyDiv');
		page.innerHTML = thankyoumessage;
		needToConfirm = false;
	}
}

function recordSurvey() {
	var record = "";
	with (this) {
		// post the answers
		var que = firstQuestion;
		if (que == null)
			return false;
		
		var counter = 1;
		while (que != null) {
			if (counter > 1)
				record += ",";
			if (que.qtype == QCHECKBOX) {
				// checkboxes already have quotes because they are inherently a comma-separated userAnswer
				// unless the user skipped that question.  then we just have to fill in some commas
				if (que.userAnswer == "") {
					var ans = que.firstAnswer;
					while (ans.nextAnswer != null) {
						que.userAnswer += ",";
						ans = ans.nextAnswer;
					}
				}
				record += que.userAnswer;
			}
			else
				record += "\"" + (que.userAnswer.replace(/\r\n/mg, ' ')).replace(/"/mg, "\"\"") + "\"";
			que = que.nextQuestion;
			counter++;
		}
	}
	sendPost(surveyObj.title.replace(/\s/g, ''), record);
}		

function sendPost(surveyId, str) {
	// simple ajax post - pass one string containing whole record
	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', "saveResponse.aspx", true);
    self.xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	self.xmlHttpReq.onreadystatechange = function() {
		if (self.xmlHttpReq.readyState == 4) {
			surveyObj.thankYou();
		}
	}
	self.xmlHttpReq.send("id=" + surveyId + "&record=" + str);
}

function saveAnswers() {
	with (this) {
		var validates = true;
		errormsg = "";

		// save answers in questions objects
		var que = surveyObj.firstQuestion;
		while (que != null) {
			var contDiv = document.getElementById('qdiv'+que.id);
			if (!contDiv) {
				que = que.nextQuestion;
				continue;
			}
				
			if (que.qtype == QTEXT) {
				if (document.getElementById('q'+que.id)) {
					que.userAnswer = document.getElementById('q'+que.id).value;
					if (que.required && document.getElementById('q'+que.id).value == "")
						validates = false;
					if (que.mask != "") {
						var regE = new RegExp(que.mask, "gi");
						if (!regE.test(document.getElementById('q'+que.id).value)) {
							validates = false;
							if (que.errormessage != "")
								errormsg += que.errormessage + "\n";
						}
					}
				}
			}
			else if (que.qtype == QTEXTAREA) {
				if (document.getElementById('q'+que.id)) {
					que.userAnswer = "";
					if (document.getElementById('q'+que.id).innerText)
						que.userAnswer = document.getElementById('q'+que.id).innerText.replace(/[\n\r]/g, " ");
					else if (document.getElementById('q'+que.id).textContent)
						que.userAnswer = document.getElementById('q'+que.id).textContent.replace(/[\n\r]/g, " ");
					if (que.required && document.getElementById('q'+que.id).value == "")
						validates = false;
					if (que.mask != "") {
						var regE = new RegExp(que.mask, "gi");
						if (!regE.test(document.getElementById('q'+que.id).value)) {
							validates = false;
							if (que.errormessage != "")
								errormsg += que.errormessage + "\n";
						}
					}
				}
			}
			else if (que.qtype == QRADIO) { // darn radios
				var radioBoxes = contDiv.getElementsByTagName("INPUT");
				var isValid = false;
				var a;
				for (a=0; a<radioBoxes.length; a++) {
					if (radioBoxes[a].name == 'q'+que.id && radioBoxes[a].checked) {
						isValid = true;
						que.userAnswer = radioBoxes[a].value;
						var ans = que.firstAnswer;
						while (ans != null) {
							if ((ans.value == que.userAnswer || ans.atype == AOTHER) && ans.skipTo != 0) {
								if (ans.skipTo == "END")
									startAt = null;
								else {
									var nextQ = surveyObj.getQuestionById(ans.skipTo);
									if (nextQ)
										startAt = nextQ;
								}
								break;
							}
							ans = ans.nextAnswer;
						}
						break;
					}
				}
				if (que.required)
					validates &= isValid;
				if (!isValid && que.errormessage != "")
					errormsg += que.errormessage + "\n";
			}
			else { // darn checkboxes
				var checkBoxes = contDiv.getElementsByTagName("INPUT");
				var isValid = false;
				var a;
				var ans = que.firstAnswer;
				var nextQ = null;
				que.userAnswer = "";
				for (a=0; a<checkBoxes.length; a++) {
					if (checkBoxes[a].type == "checkbox") {
						var nm = checkBoxes[a].name.substring(0, checkBoxes[a].name.indexOf("_"));
						if (nm == 'q'+que.id) {
							if (a > 0)
								que.userAnswer += ","
							if (checkBoxes[a].checked) {
								isValid = true;
								que.userAnswer += "\"" + checkBoxes[a].value + "\"";
								if (ans.skipTo == "END")
									startAt = null;
								else if (ans.skipTo != 0)
									nextQ = surveyObj.getQuestionById(ans.skipTo)
							}
						}
						ans = ans.nextAnswer;
					}
				}
				if (nextQ)
					startAt = nextQ;
				if (que.required)
					validates &= isValid;
				if (!isValid && que.errormessage != "")
					errormsg += que.errormessage + "\n";
			}
			que = que.nextQuestion;
		}
	}
	
	if (errormsg == "")
		errormsg = "You have either left a required question blank, or have not provided a sufficient answer.  Please check your answers and try again.";
	return validates;
}

function getQuestionById(id) {
	with (this) {
		var que = firstQuestion;
		while (que != null) {
			if (que.id == id)
				return que;
			que = que.nextQuestion;
		}
		
		return null;
	}
}


var surveyObj = new survey();
var errormsg = "";
