<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<%@ taglib prefix="js" uri="net.sourceforge.jsurveyor.jsurveyorlib" %>
<%@ page import="java.util.*" %>
<%@ page import="net.sourceforge.jsurveyor.*" %>
<js:noCache />
<js:login access="admin" />
<%
int questionnaireID = Integer.parseInt(request.getParameter("questionnaireID"));
int questionPageID = Integer.parseInt(request.getParameter("questionPageID"));
int questionID = Integer.parseInt(request.getParameter("questionID"));

if ( request.getParameter("reload") != null && ((String) request.getParameter("reload")).equals("true") && request.getParameter("Depend") != null ) {
	int Depend = Integer.parseInt(request.getParameter("Depend"));
	response.sendRedirect("admin_freetext.jsp?QuestionnaireID="+questionnaireID+"&QuestionPageID="+questionPageID+"&Question="+questionID+"&reload="+Depend);
} else {
	%>
	<c:if test="${param.button == 'Save'}">
		<%
		QuestionFreeText editQuestion = (QuestionFreeText)DataAccess.retrieveQuestion(questionID);
		int depend = Integer.parseInt(request.getParameter("Depend"));
		if(depend != -1) {
			String choices = "";
			%>
			<c:forEach items="${paramValues.Answers}" var="current">
				<%
				choices = choices + (String)pageContext.getAttribute("current") + ":";
				%>
			</c:forEach>
			<%
			String[] convertMe = (choices.substring(0,choices.length()-1)).split(":");
			int[] choicesInt = new int[convertMe.length];
			for(int i = 0; i < convertMe.length; i++) {
				choicesInt[i] = Integer.parseInt(convertMe[i]);
			}
			QuestionMultipleChoice dependQ = (QuestionMultipleChoice)DataAccess.retrieveQuestion(depend);	
			try {
				editQuestion.setDependency(dependQ, choicesInt);
			} catch(IllegalAccessException e) {
				response.sendRedirect("logout.jsp"); // wont happen if the user behaves, so lets log the user out.
			}	
		} else {
			try {
				editQuestion.removeDependency();
			} catch(IllegalAccessException e) {
				response.sendRedirect("logout.jsp"); // wont happen if the user behaves, so lets log the user out.
			}
		}
		try { 
			editQuestion.setText(request.getParameter("text"));
		} catch(IllegalAccessException e) {
			response.sendRedirect("logout.jsp"); // wont happen if the user behaves, so lets log the user out.
		}
		DataAccess.storeQuestion(editQuestion);
		%>
	</c:if>
	<%
	response.sendRedirect("admin_questionnaire.jsp?QuestionnaireID=" + questionnaireID);
}
%>