currSubmission = null; // {'id':..., 'code':..., 'subject':...}
currQuestionGroups = null; // [{'id':..., 'questions':[{'id':..., 'question':..., 'response':..., 'choice':..., 'num':...},...]},...]
currQuestionGroupIdx = null;
currQuestionGroup = null;

// called to goto prev question
function previousQuestionGroup (btn) {
  loadQuestionGroup (currQuestionGroupIdx - 1);
}

// called to goto next question
function nextQuestionGroup (btn) {
	loadQuestionGroup (currQuestionGroupIdx + 1);
}

// finds a question with the given id
function findByQuestionId (questionid) {
	for (var i in currQuestionGroups) {
		var group = currQuestionGroups[i];
		var questions = group['questions'];
		for (var j in questions) {
			var question = questions[j];
			if (question['id'] == questionid)
				return {'group':group, 'questions':questions, 'question':question};
		}
	}
	return null;
}

// called to set the answer on a question
function setResponse (questionid, response) {
//	setHtml ('content', encodeURIComponent (response));
	issueAsyncRequest ('setresponse.php?questionid=' + questionid + '&response=' + encodeURIComponent (response), function (req, url) {
		var json = defaultJsonRequestHandler (req, url);
		if (!json)
			return;
		var info = findByQuestionId (questionid);
		if (!info)
			return;
		info['question']['response'] = response;
	});
}

// called to commit submit of submission
function commitSubmission () {
	issueAsyncRequest ('finsubmission.php?submissionid=' + currSubmission['id'], function (req, url) {
		var json = defaultJsonRequestHandler (req, url);
		if (!json)
			return;
		loadHtml ('content', 'completed.html');
		eraseCookie ('submissionId');
	});
}

// called to submit submission
function submitSubmission () {
  issueAsyncRequest ('loadsubmission.php?submissionid=' + currSubmission.id, function (req, url) {
    var json = defaultJsonRequestHandler (req, url);
    if (!json)
      return;
    currSubmission = {'code':json.code, 'subject':json.subject, 'id': currSubmission.id};
    currQuestionGroups = json['questiongroups'];
		var html = [];
		var htmli = 0;
		html[htmli++] = '<div id="surveyTitle"> ' + htmlEncode (currSubmission.subject) + ' </div><br />';
    html[htmli++] = '<p> ' + htmlEncode (json.sinstructions).replace(/\n/g, '</p><p>') + ' </p>';
    /*
		var groupidx = 0;
		for (var i in currQuestionGroups) {
			var group = currQuestionGroups[i];
			var questions = group['questions'];
			for (var j in questions) {
				var question = questions[j];
				html[htmli++] = '<h3> ' + question['num'] + '. ' + htmlEncode (question['question']) + ' </h3>';
				if (question['choices'] == '*')
					html[htmli++] = '<p><a href="javascript:loadQuestionGroup(' + groupidx + ');"> ' + htmlEncode (question['response']) + ' </a></p>';
				else {
			    var choices = question['choices'].split('\n');
			    var response = question['response'];
			    for (var i = 0, imax = choices.length; i < imax; i++) {
						var choice = splitByEquals (choices[i]);
			      if (response == choice[0]) {
							html[htmli++] = '<p><a href="javascript:loadQuestionGroup(' + groupidx + ');"> ' + htmlEncode (choice[1]) + ' </a></p>';
							break;
						}
			    }
				}
			}
			groupidx++;
		}*/
    html[htmli++] = '<input class="button" type="button" value="Review" onclick="loadQuestionGroup(0);" />';
		html[htmli++] = '<input class="button" type="button" value="Submit" onclick="commitSubmission();" />';
		setHtml ('content', html.join('\n'));
  });
}

// split by =, always return array of two strings
function splitByEquals (val) {
  var val = val.split('=', 2);
  if (val.length == 1)
    val[1] = '';
  return val;
}

// called to loads a question group
function loadQuestionGroup (questionGroupIdx) {
	currQuestionGroupIdx = questionGroupIdx;
  currQuestionGroup = currQuestionGroups[questionGroupIdx];
  if (currQuestionGroups == null || currQuestionGroups.length == 0) {
    setHtml ('content', 'No survey questions!');
		alert (currQuestionGroups);
    return;
  }
  var html = new Array();
  var htmli = 0;
  html[htmli++] = '<div id="surveyTitle">' + htmlEncode(currSubmission['subject']) + '</div><br /><br />';
  html[htmli++] = '<div id="instructions"> ' + htmlEncode(currQuestionGroup.instructions).replace(/\n/g, '</p><p>') + ' </div>';
	html[htmli++] = '<form>';
	var currQuestions = currQuestionGroup['questions'];
	for (var questioni in currQuestions) {
		var question = currQuestions[questioni];
	  if (question['choices'] == '*') {
      html[htmli++] = '<br /><strong> ' + /*question['num'] + '. ' + */ htmlEncode(question['question']) + ' </strong><br/ ><br />';
	    var response = question['response'];
	    html[htmli++] = '<textarea class="text" name="' + question['id'] + '" onchange="setResponse(' + question['id'] + ',this.value);">' + htmlEncode(response) + '</textarea><br />';
	  }
	  else {
      html[htmli++] = '<br />' + /*question['num'] + '. ' + */ htmlEncode(question['question']) + '<br/ ><br />';
	    var choices = question['choices'].split('\n');
	    var response = question['response'];
	    for (var i = 0, imax = choices.length; i < imax; i++) {
	      var choice = choices[i];
	      if (choice == '')
	        continue;
	      choice = splitByEquals (choice); // code=choice
	      if (response == choice[0])
					checked = ' checked="checked"';
				else
					checked = '';
	      html[htmli++] = '<input class="button" type="radio" name="' + question['id'] + '" onclick="setResponse(' + question['id'] + ',\'' + choice[0] + '\');"' + checked + ' />';
	      html[htmli++] = choice[1] + '<br />';
	    }
		}
	}
  html[htmli++] = '<br /><br />';
  if (currQuestionGroupIdx < currQuestionGroups.length - 1)
    html[htmli++] = '<input class="button" type="button" value="Next" onclick="nextQuestionGroup(this);" />';
  else
    html[htmli++] = '<input class="button" type="button" value="Finish" onclick="submitSubmission(this);" />';
  if (currQuestionGroupIdx > 0)
    html[htmli++] = '<input class="button" type="button" value="Previous" onclick="previousQuestionGroup(this);" />';
  html[htmli++] = '</form>';
  setHtml ('content', html.join('\n'));
}

// called to load a survey's submission
function loadSubmission (submissionId) {
  issueAsyncRequest ('loadsubmission.php?submissionid=' + submissionId, function (req, url) {
    var json = defaultJsonRequestHandler (req, url);
    if (!json)
      return;
    currSubmission = {'code':json['code'], 'subject':json['subject'], 'id': submissionId};
    currQuestionGroups = json['questiongroups'];
    loadQuestionGroup (0);
  });
}

// called when a new submission to a survey is requested
function addSubmission (btn) {
  issueAsyncFormRequest (btn.form, 'addsubmission.php', function (req, url) {
    var json = defaultJsonRequestHandler (req, url);
    if (!json)
      return;
    createCookie ('submissionId', json['submissionid'], 7);
    loadSubmission (json['submissionid']);
  });
}

// shows form whereby user can enter the survey code
function showCodeEntry () {
  loadHtml ('content', 'codeentry.html');
}

// kicks off initialization of the page used for issuing the survey to user
function initialize () {
	var params = getParamsAsArray();
	if (!params['nohttps'] && location.protocol == 'http:') {
		location = 'https:' + new String(location).substring(5);
		return;
	}
  var submissionId = readCookie ('submissionId');
  if (submissionId == null)
    showCodeEntry ();
  else
    loadSubmission (submissionId);
}
