var redownloadDelay = 1000;
var growDelay = 10;
var growSize = 40;
var activeQuestion = null;
var heightOvershoot = 20;

function WindowResize() {
	var imagedlg = document.getElementById('image-dialog');
	var imagediv = document.getElementById('imagediv');
	
	imagediv.style.left = getLeft(imagedlg);
	imagediv.style.top = getTop(imagedlg);
}

function reloadQuestions() {
	var status = document.getElementById('status');
	var tbl = document.getElementById('questions');
	var lastRow = tbl.rows.length-2;
	
	for(i=lastRow;i>=1;i--)
		tbl.deleteRow(i);
	status.innerHTML = "<IMG SRC='"+survey_path+"/loading.gif'> Please Wait, Attempting to Download Questions...";
	requestData(url_path+account+'/questions/', loadQuestions);
}

function checkForUpdates(timestamp) {
	requestDataExt(url_path+account+'/timestamp/', 'timestamp='+timestamp, checkUpdateResponse);
}

function checkUpdateResponse(request) {
	var status = document.getElementById('status');
	
	if(request.status != 200) {
		status.innerHTML = "Error updating question list.";
		return;
	}
	var xmldoc = request.responseXML;
	var root = xmldoc.getElementsByTagName('root').item(0);
	var cnt=0;
	
	var timestamp = xmlGetChildNode(root, 'timestamp').data;
	var oldtimestamp = xmlGetChildNode(root, 'oldtimestamp').data;
	if(oldtimestamp != timestamp) {
		reloadQuestions();
	} else {
		setTimeout("checkForUpdates('"+timestamp+"')", redownloadDelay);
	}
}

function loadQuestions(request) {
	var status = document.getElementById('status');
	
	if(request.status != 200) {
		status.innerHTML = "Error obtaining question list.";
		return;
	}
	status.innerHTML = "Loading Questions File...";
	var xmldoc = request.responseXML;
	var root = xmldoc.getElementsByTagName('root')[0];
	var cnt=0;
	
	var timestamp = xmlGetChildNode(root, 'timestamp').data;
	setTimeout("checkForUpdates('"+timestamp+"')", redownloadDelay);
	for(var iNode = 0; iNode < root.childNodes.length; iNode++) {
		var node = root.childNodes.item(iNode);
		for (i = 0; i < node.childNodes.length; i++) {
			var sibl = node.childNodes.item(i);
			var arr = new Array();
			
			if(!sibl.childNodes.length)
				continue;
			if(xmlGetChildNode(sibl, 'active').data == '1')
			{
				id = xmlGetChildNode(sibl, 'id').data;
				arr[0] = xmlGetChildNode(sibl, 'title').data;
				arr[1] = "<INPUT TYPE=\"SUBMIT\" VALUE=\"Select\" ONCLICK=\"JavaScript:selectQuestion('"+id+"');\"></INPUT>";
				addQuestion(id, arr);
				cnt++;
			}
		}
	}
	if(cnt == 0)
		status.innerHTML = "There are no questions at this time.";
	else if(cnt == 1)
		status.innerHTML = "One Question Downloaded.";
	else
		status.innerHTML = cnt+" Questions Downloaded.";
}

function selectQuestion(id)
{
	var tbl = document.getElementById('questions');
	var rows = tbl.getElementsByTagName("tr");   
	var lastRow = tbl.rows.length-2;
	
	/* Deselect All Rows */
	for(i=lastRow;i>=1;i--)
		rows[i].className = '';
	/* Select Requested Row */
	for(i=lastRow;i>=1;i--)
	{
		if(rows[i].id == id)
		{
			var q = document.getElementById('qstatus');
			
			rows[i].className = 'question-active';
			q.innerHTML = "<IMG SRC='"+survey_path+"/loading.gif'> Downloading Question...";
			requestDataExt(url_path+account+'/questions/', 'command=getquestion&id='+id, loadQuestion);
			return;
		}
	}
	alert('Row/Question mismatch!');
}

function loadQuestion(request)
{
	var q = document.getElementById('qstatus');
	var titlerow = document.getElementById('titlerow');
	var textrow = document.getElementById('textrow');
	var imagerow = document.getElementById('imagerow');
	var answer = document.getElementById('answer');
	var answerrow = document.getElementById('answerrow');
	var c = document.getElementsByName('confidence');
	var confidencerow = document.getElementById('confidencerow');
	var answerbutton = document.getElementById('answerbutton');
	var cancelbutton = document.getElementById('cancelbutton');
	
	if(request.status != 200) {
		q.innerHTML = "Error obtaining question list.";
		return;
	}
	q.innerHTML = "Loading Question File...";
	var xmldoc = request.responseXML;
	var root = xmldoc.getElementsByTagName('root')[0];
	
	for(var iNode = 0; iNode < root.childNodes.length; iNode++)
	{
		var node = root.childNodes.item(iNode);
		for (i = 0; i < node.childNodes.length; i++)
		{
			var id, title, text, textinput, freehand, confidence;
			var sibl = node.childNodes.item(i);
			var arr = new Array();
			
			if(!sibl.childNodes.length)
				continue;
			id = xmlGetChildNode(sibl, 'id').data;
			title = xmlGetChildNode(sibl, 'title').data;
			text = xmlGetChildNode(sibl, 'text').data;
			textinput = (xmlGetChildNode(sibl, 'textinput').data == '1');
			freehand = (xmlGetChildNode(sibl, 'freehand').data == '1');
			confidence = (xmlGetChildNode(sibl, 'confidence').data == '1');
			titlerow.innerHTML = '<B>'+title+'</B>';
			textrow.innerHTML = text;
			imagerow.className = freehand ? 'visible' : 'hidden';
			answer.value = "";
			answerrow.className = textinput ? 'visible' : 'hidden';
			for(i=0;i<10;i++) {
				c[i].checked = false;
			}
			confidencerow.className = confidence ? 'visible' : 'hidden';
			activeQuestion = id;
			answerbutton.onclick = function(){submitAnswer(activeQuestion);}
			cancelbutton.onclick = function(){deselectQuestion(activeQuestion);}
			setTimeout("showQuestion(0,"+freehand+");", 0);
			q.innerHTML = "Question Loaded.";
			return;
		}
	}
	q.innerHTML = "<CENTER>Unable to load question!</CENTER>";
}

function showQuestion(h, freehand)
{
	var answerbutton = document.getElementById('answerbutton');
	var rollout = document.getElementById('rollout');
	var height = parseInt(h);
	var maxHeight;
	
	if(height == 0) {
		var question = document.getElementById('question');
		
		if(rollout.style.height != "") {
			height = parseInt(rollout.style.height);
		} else {
			question.className = 'visible';
		}
		clearImage();
	} else {
		rollout.style.height = height+'px';
	}
	maxHeight = getTop(answerbutton)+getHeight(answerbutton)-heightOvershoot;
	if(height+growSize < maxHeight)
	{
		setTimeout("showQuestion('"+(height+growSize)+"',"+freehand+");", growDelay);
	}
	else
	{
		var imagediv = document.getElementById('imagediv');
		
		rollout.style.height = maxHeight+'px';
		if(freehand)
		{
			if(SVG_OK() != 0)
			{
				var imagedlg = document.getElementById('image-dialog');
				
				imagediv.style.left = getLeft(imagedlg);
				imagediv.style.top = getTop(imagedlg);
				imagediv.style.visibility = 'visible';
			}
			else
			{
				var status = document.getElementById('image-status');
				
				status.innerHTML = "You must <A HREF=\"http://www.mozilla.com\">use Firefox</A> or <A HREF=\"http://www.adobe.com/svg/viewer/install/main.html\">install the Adobe SVG plugin</A> before you may use InkSurvey.";
			}
		}
		else
		{
			imagediv.style.visibility = 'hidden';
		}
	}
}

function hideQuestion(h)
{
	var rollout = document.getElementById('rollout');
	var height = parseInt(h);
	
	if(height != height) {
		var imagediv = document.getElementById('imagediv');
		
		imagediv.style.visibility = 'hidden';
		height = parseInt(rollout.style.height);
	} else if(height <= 1) {
		height = 1;
	}
	rollout.style.height = height+'px';
	if(height > 1) {
		setTimeout("hideQuestion('"+(height-growSize)+"');", growDelay);
	}
}

function deselectQuestion(id)
{
	var q = document.getElementById('qstatus');
	var qrow = document.getElementById(id);
	
	if(qrow) {
		qrow.className = '';
	}
	setTimeout("hideQuestion(NaN);", 0);
	q.innerHTML = "No Question Selected";
}

function submitAnswer(id)
{
	var q = document.getElementById('qstatus');
	var tr = (document.getElementById('answerrow').className == 'visible');
	var ir = (document.getElementById('imagerow').className == 'visible');
	var cr = (document.getElementById('confidencerow').className == 'visible');
	var data = 'command=submitanswer&id='+id;
	
	if(tr)
	{
		var t = document.getElementById('answer');
		var answer = t.value;
		
		data = data + '&answer='+answer;
	}
	if(ir)
	{
		var svg = svgDocument();
		data = data+'&image='+svg;
	}
	if(cr)
	{
		var c = document.getElementsByName('confidence');
		var confidence = 0;
		for(i=0;i<c.length;i++)
		{
			if(c[i].checked)
				confidence = c[i].value;
		}
		data = data + '&confidence='+confidence;
	}
	deselectQuestion(id);
	q.innerHTML = "<CENTER>Submitting Answer, Please Wait...</CENTER>";
	pushDataExt(url_path+'/'+account+'/questions/', data, answerSubmitted);
}

function answerSubmitted(request)
{
	var q = document.getElementById('qstatus');
	
	if(request.status != 200) {
		q.innerHTML = 'Error submitting answer, server error code '+request.status+'!';
		return;
	}
	if(request.responseText == '1')
		q.innerHTML = "No Question Selected";
	else
		q.innerHTML = 'Error submitting answer: '+request.responseText+'!';
}

function addQuestion(id, arr)
{
	var tbl = document.getElementById('questions');
	var lastRow = tbl.rows.length-1;
	var row = tbl.insertRow(lastRow);
	
	row.name = id;
	row.id = id;
	for (r = 0; r < arr.length; r++) {
		var cell = row.insertCell(r);
		cell.innerHTML = arr[r];
	}
}
