
/* 	
	------------------------------------------------------------------------------
	/project/apps/submissiontypes/js/app.js
	
	admin submissiontypes
	
   	------------------------------------------------------------------------------
*/
var appName = "SubmissionReview";
var appType = "P";

function SubmissionReview_onload() {
	dgConferenceSubmissions.dataSource = "getSubmissions";
	dgConferenceSubmissions.dataBind();
}


function dgConferenceSubmissions_onmouseover(ev, el, row, col) {
	dgConferenceSubmissions.setRowClass("over", row);
}

function dgConferenceSubmissions_onmouseout(ev, el, row, col) {
	dgConferenceSubmissions.setRowClass("", row);
}

var SubmissionID = 0;
function dgConferenceSubmissions_oneditclick(ev, el, row) {
	SubmissionID = row;
	initEditConferenceSubmission();
	
}



function dgSubmissionFiles_oneditclick(ev, el, row) {
	var str = webroot + "/rpc.php?format_type=file&app_name=SubmissionReview&app_type=P&function_name=getConferenceSubmissionFile&";
	str    += "paramSubmissionGUID=" + SubmissionGUID + "&paramFileName=" + row;
	document.location = str;
}


function initEditConferenceSubmissionAttachments() {
	
	var params = new Array();
	params["SubmissionGUID"] = SubmissionGUID;
	dgFiles.dataSource = "getConferenceSubmissionFiles";
	dgFiles.dataParams = params;
//	dgFiles.ondataBind = files_loaded();
	dgFiles.dataBind();
	
}


function initEditConferenceSubmission() {
	//alert("you want to edit element on row " + row);
	pnlMain.hide();
	pnlEdit.show();
	
	var params = new Array();
	params["SubmissionID"] = SubmissionID;
	oXmlRequest = new XmlRequest();
	oXmlRequest.functionName	= "getConferenceSubmission";
	oXmlRequest.params 			= params;	
	oXmlRequest.onsuccess 		= getConferenceSubmission_success;
	oXmlRequest.start();
	
	
		
	function getConferenceSubmission_success(oXmlResponse) {
		debug.write("getConferenceSubmission_success: " + oXmlResponse.responseText);
		
		var cs = oXmlResponse.data[0];
		lblConferenceSubmissionType.setValue(cs["SubmissionType"]);
		lblConferenceSubmissionChair.setValue(cs["Chair"]);
		lblConferenceSubmissionFacilitator.setValue(cs["Facilitator"]);
		lblConferenceSubmissionTitle.setValue(cs["Title"]);
		lblConferenceSubmissionAnswers.setValue(cs["Answers"]);
		//cboConferenceSubmissionStatus.setSelectedValue(cs["Status"]);
		lblConferenceSubmissionAdminRemark.setValue(cs["AdminRemark"]);
		
	
		
		var params = new Array();
		params["SubmissionTypeID"] = cs["SubmissionTypeID"];
		params["SubmissionID"] = SubmissionID;
		oXmlRequest = new XmlRequest();
		oXmlRequest.functionName	= "getSubmissionTypeReviewQuestions";
		oXmlRequest.params 			= params;	
		oXmlRequest.onsuccess 		= getSubmissionTypeReviewQuestions_success;
		oXmlRequest.start();
		
		
		var params2 = new Array();
		params2["SubmissionID"] = SubmissionID;
		params2["SubmissionTypeID"] = cs["SubmissionTypeID"];
		oXmlRequest2 = new XmlRequest();
		oXmlRequest2.functionName = "getConferenceSubmissionThemes";
		oXmlRequest2.params = params2;
		oXmlRequest2.onsuccess = getConferenceSubmissionThemes_success;
		oXmlRequest2.start();
		
		SubmissionGUID = cs["SubmissionGUID"];
		
		initEditConferenceSubmissionAttachments();
	
	}
	
	
	function getConferenceSubmissionThemes_success(oXmlResponse) {
		//alert(oXmlResponse.responseText);
		var str = "";
		if (oXmlResponse.numDataRows > 0) {
			str += "Found " + oXmlResponse.numDataRows + " theme(s):";
			str += "<ul>";
			for (i=0; i<oXmlResponse.numDataRows; i++) {
				var st = oXmlResponse.data[i];
				str += "<li>" + st["Name"] + "</li>";
			}
			str += "</ul>";
		}
		else {
			str = "No themes found";
		}
		
		
		lblConferenceSubmissionThemes.setValue(str);
	}
	
	function getSubmissionTypeReviewQuestions_success(oXmlResponse) {
		
		
		//alert(oXmlResponse.responseText);
		var tbl = document.getElementById("tableReviewQuestions");
		var tbody = tbl.tBodies[0];
		
		// eerst leegmaken
	
		
		debug.write("page.controls.length is now " + page.numControls + "-" + page.controls.length);
		var str = "";
		for (i=0; i<page.controls.length; i++) 
		{
			obj = page.controls[i];
			if (obj) {
				str = str + "-" + obj.id;
			}
			else {
				str = str + "-undefined_object";
			}
		}
		debug.write("alle controls: " + str);

		var elementsToDestroy = new Array();
		var destroyIndex = 0;
		
		for (i=0;i<page.controls.length; i++) {
			obj = page.controls[i];
			debug.write("object #" + i + " = " + obj.id);
			if (obj.getType() == "TextBox" && obj.id.indexOf("txtSubmissionTypeReviewQuestion_") >= 0) {
				debug.write("planning to destroy " + obj.id);
				elementsToDestroy[destroyIndex] = obj;
				destroyIndex++;
			}
			if (obj.getType() == "TextBox" && obj.id.indexOf("txtRemarks") >= 0) {
				debug.write("planning to destroy " + obj.id);
				elementsToDestroy[destroyIndex] = obj;
				destroyIndex++;
			}
			else if (obj.getType() == "DropDownBox" && obj.id.indexOf("cboWouldYouApprove") >= 0) {
				debug.write("planning to destroy " + obj.id);
				elementsToDestroy[destroyIndex] = obj;
				destroyIndex++;
			}
		}	
		
		debug.write("page.controls.length before destroy round is now " + page.numControls + "-" + page.controls.length);
		
		for (k=0; k<destroyIndex; k++) {
			obj = elementsToDestroy[k];
			debug.write("Now destroying " + obj.id);
			obj.destroy();
		}
		
		debug.write("page.controls.length is now " + page.numControls + "-" + page.controls.length);
		var str = "";
		for (i=0; i<page.controls.length; i++) 
		{
			obj = page.controls[i];
			if (obj) {
				str = str + "-" + obj.id;
			}
			else {
				str = str + "-undefined_object";
			}
			
		}
		debug.write("alle controls: " + str);

		var numrows = tbody.rows.length;
		for (i=numrows-1; i>=0; i--) {
			//debug.write("Row " + i);
			tbody.deleteRow(i);
			//tr = obj.rows[i];
			//obj.removeChild(tr);
		}
		
		
		
		var startIndex = 0;
		var stopIndex = oXmlResponse.data.length-1;
					
		var firstQuestion;
		var alreadySubmitted = false;	
		for (i=startIndex; i<=stopIndex; i++) {
		
						
			var reviewQuestion = oXmlResponse.data[i];
			
			var tr = document.createElement("tr");
			var td = document.createElement("td");
			td.innerHTML = reviewQuestion["DisplayName"];
			tr.appendChild(td);
								
			//td.style.textAlign = oDataColumn.textAlign;
			
			var td = document.createElement("td");
			
			var id = reviewQuestion["SubmissionTypeReviewQuestionID"];
			
			
			elementName = "txtSubmissionTypeReviewQuestion_" + id;
			// om goed te zijn mogen we niet de innerHTML van het targetElement nemen om als value te dienen
			// eigenlijk moeten we de dataSource gaan opzoeken van de datagrid en kijken wat deze kolom als waarde heeft op deze row
			// hiervoor moet een extra functie gebruikt worden!
			//debug.write("getvalue = " + frameworkElement.getValue(row, col));
			
			eval(elementName + " = new TextBox(elementName, '');");
			//eval(elementName + ".onkeyup = 'calculateScore';");
			eval(elementName + ".onblur= 'txtQuestion_onblur';");
			eval(elementName + ".tag = id;");
			eval(elementName + ".editorType = 'none'");
			eval(elementName + ".parentElement = td;");
			eval(elementName + ".width = '50px';");
			eval(elementName + ".render();");
			eval(elementName + ".show();");
			//eval(elementName + ".focus();");
			
			if (parseInt(reviewQuestion["Score"]) > 0) {
				eval(elementName + ".setValue('" + reviewQuestion["Score"] + "');");
				eval(elementName + ".setDisabled();");
				alreadySubmitted = true;
			}
			
			
			/*txt = new TextBox("txtSubmissionTypeReviewQuestionID_" + id, "");
			//txt.onclick = 'DataGrid_handle_txtInstantEdit_onclick';
			//txt.onkeyup = 'DataGrid_handle_txtInstantEdit_onkeyup';
			txt.onblur= 'calculateScore';
			txt.tag = "SubmissionTypeReviewQuestionID_" + id;
			txt.width = "50px";
			txt.editorType = 'none';
			txt.parentElement = td;
			txt.render();
			txt.show();*/
			
			if (i==0) {
				eval("firstQuestion = " + elementName + ";");
				//firstQuestion = txt;
			}
			
			
			tr.appendChild(td);
			tbody.appendChild(tr);
			
			
		}
		
		/*if (firstQuestion) {
			firstQuestion.focus();
		}*/
	
		
		// rij voor de resultaten
		var tr = document.createElement("tr");
		var td = document.createElement("td");
		td.style.textAlign = "right";
		td.style.backgroundColor = "#EEEEEE";
		td.innerHTML = "Total score";
		tr.appendChild(td);
		
		var td = document.createElement("td");
		td.style.backgroundColor = "#EEEEEE";
		td.innerHTML = "";
		td.id = "tdScore";
		tr.appendChild(td);
		tbody.appendChild(tr);
		
				
		
		
		// approve??
		
		var tr = document.createElement("tr");
		var td = document.createElement("td");
		td.innerHTML = "Would you approve this submission?";
		tr.appendChild(td);
							
		//td.style.textAlign = oDataColumn.textAlign;
		
		var td = document.createElement("td");
		
		// would you approve question
		cboWouldYouApprove = new DropDownBox("cboWouldYouApprove");
		//cbo.onchange = 'DataGrid_handle_cboInstantEdit_onchange';
		//cbo.onblur = 'DataGrid_handle_cboInstantEdit_onblur';
		//cboWouldYouApprove.tag = "cboWouldYouApprove_WouldYouApprove";
		var ds = new Array();
		ds["1"] = "Yes";
		ds["0"] = "No";
		cboWouldYouApprove.dataSource = ds;
		cboWouldYouApprove.parentElement = td;
		cboWouldYouApprove.width = "60px";
		cboWouldYouApprove.render();
		cboWouldYouApprove.show();
		if (alreadySubmitted) {
			cboWouldYouApprove.setSelectedValue(reviewQuestion["WouldYouApprove"]);
			cboWouldYouApprove.setDisabled();
		}
		else {
			cboWouldYouApprove.setSelectedValue(1);
			cboWouldYouApprove.setEnabled();
		}
		
		//cboWouldYouApprove.focus();
		
		tr.appendChild(td);
		tbody.appendChild(tr);
		
		
		// rij voor tekst: your remarks
		var tr = document.createElement("tr");
		var td = document.createElement("td");
		td.colSpan = 2;
		//td.style.backgroundColor = "#EEEEEE";
		td.innerHTML = "Your remarks:";
		tr.appendChild(td);
		
		txtRemarks = new TextBox();
		txtRemarks.type = "multiline";
		txtRemarks.id = "txtRemarks";
		txtRemarks.parentElement = td;
		txtRemarks.value = "";
		//txtRemarks.tag = question["SubmissionTypeQuestionID"];
		txtRemarks.render();
		txtRemarks.formElement.style.width = "99%";
		txtRemarks.formElement.style.height = "100px";
		//txtRemarks.formElement.style.marginBottom = "20px";
		txtRemarks.formElement.style.clear = "both";
		txtRemarks.show();
		if (alreadySubmitted) {
			txtRemarks.setValue(reviewQuestion["Remarks"]);
			txtRemarks.setDisabled();
		}
		else {
			txtRemarks.setValue("");
			txtRemarks.setEnabled();
		}
		
		
		tbody.appendChild(tr);
		
		
			
		
		if (alreadySubmitted == true) {
			lblMessage.setValue("You already have reviewed this submission. You can view the results below.");
			txtQuestion_onblur();
		}
		else {
			lblMessage.setValue("Please answer open questions with a score from 0 to 10.");
		}
								
	}
	
	
	
}

function txtQuestion_onblur() {
	var total = calculateScore();
	document.getElementById("tdScore").innerHTML = total + " %";
	
	new Effect.Highlight("tdScore");	
}

function calculateScore() {
	totalScore = 0;
	numberOfQuestions = 0;
	for (i=0;i<page.controls.length; i++) {
		obj = page.controls[i];
		if (obj.getType() == "TextBox" && obj.id.indexOf("txtSubmissionTypeReviewQuestion_") >= 0) {
			debug.write("calculating score: " + obj.id + " - " + obj.getValue());
			obj.clearError();

			score = parseInt(obj.getValue());
			res = isScoreValid(obj.getValue());
			if (res == "" || res == "no_value") {
				if (score >= 0) 
					totalScore += score;
			}
			else {
				obj.setError(res);
			}
			
			numberOfQuestions++;
		}
	}
			
	res = totalScore/numberOfQuestions * 10;
	return Math.round(res*100)/100;
	
}

function isScoreValid(strScore) {
	score = parseInt(strScore);
	floatedScore = parseFloat(strScore);
			
	//debug.write("score: " + score + " - " + floatedScore);
		
	if (score > 10) {
		return "Invalid value";
	}
	else if(score >= 0) {
		if (parseFloat(score) != floatedScore) {
			return "Invalid value";
		}
		else {
			return "";
		}
	}
	else if (strScore != "") {
		return "Invalid value";
	}
	else {
		return "no_value";
	}
	
			
}


function btnSave_onclick() {
	strScores = "";
	errorsFound = false;
	
	for (i=0;i<page.controls.length; i++) {
		obj = page.controls[i];
		if (obj.getType() == "TextBox" && obj.id.indexOf("txtSubmissionTypeReviewQuestion_") >= 0) {
			obj.clearError();
			
			score = parseInt(obj.getValue());
			res = isScoreValid(obj.getValue());
			if (res == "") {
				if (score >= 0) {
					strScores += obj.tag + "-" + score + ","
				}
			}
			else {
				errorsFound = true;
				obj.setError(res);
			}
			
			numberOfQuestions++;
		}
	}
	
	if (errorsFound) {
		alert("Cannot proceed your request. Did you fill in all questions? Decimal values are not allowed, only values from 0 to 10");
	}
	else {
		//alert(strScores);
		
		var params = new Array();
		params["Scores"] = strScores;
		params["WouldYouApprove"] = cboWouldYouApprove.getSelectedValue();
		params["SubmissionID"] = SubmissionID;
		params["Remarks"] = txtRemarks.getValue();
		oXmlRequest = new XmlRequest();
		oXmlRequest.functionName	= "saveReview";
		oXmlRequest.params 			= params;	
		oXmlRequest.onsuccess 		= saveReview_success;
		oXmlRequest.start();
		
		
	}
	
	
	function saveReview_success(oXmlResponse) {
		if (oXmlResponse.statusCode == 2000) {
			pnlEdit.hide();
			pnlMain.show();
			dgConferenceSubmissions.dataBind();
		}
		else {
			alert(oXmlResponse.message["en"]);
			pnlEdit.hide();
			pnlMain.show();
		}
	}
	
	
	
}
	
function btnCancel_onclick() {
	pnlEdit.hide();
	pnlMain.show();
}



