function onlyNumbersDecimals(evt){
	evt = (evt) ? evt : window.event
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if ((charCode > 31 && (charCode < 48 || charCode > 57)) && (charCode != 46)) {
		return false
	}
	return true;
}

function onlyNumbers(evt){
	evt = (evt) ? evt : window.event
	var charCode = (evt.which) ? evt.which : evt.keyCode
	if ((charCode > 31 && (charCode < 48 || charCode > 57))) {
		return false
	}
	return true;
}

function calcTotal(){
	var total = 0;
	$('#tableQuestions').children().each( 
		function(){ 
			$(this).children().each( 
				function(){
					$(this).children().each( 
						function(){ 
							$(this).children().each(	
								function(){ 
									if (($(this).attr('id') == 'inPoints') && ($(this).val() != ''))
										total = total + parseFloat($(this).val());
								} 
							)
						} 
					)
				} 
			)
		}
	);	

	document.getElementById("totalPoints").innerHTML = total;
}

function addImageExam(value){
	document.getElementById("questionImg").src = "../cursos/images/exams/" + value;
	document.getElementById("questionImg").style.display = 'block';

	document.getElementById("imgName").value = value;
}


//--------- NEW EXAM --------------
function newExam(value){
	var AJ = new Ajax();
	try{
		AJ.setUrl("newExam.php");
		AJ.setVar("examType", value);
		AJ.setVar("cursoId", document.getElementById("idCurso").value);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(completeTab);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


//--------- SAVE EXAM --------------
function saveExam(value){
	var AJ = new Ajax();
	try{
		AJ.setUrl("newExam.php");

		AJ.setVar("saveExam", 1);

		var idClass = 0;
		try{
			idClass = document.getElementById("selIdClass").value;
		} catch (e){
		}

		try{
			var nameExam = document.getElementById("examName").value;
			if (nameExam == ''){
				blockErrorMsg('El nombre del examen no puede estar vacío.', 1);
				return;
			}
			AJ.setVar("name", nameExam);
		} catch (e){
		}

		AJ.setVar("classId", idClass);
		AJ.setVar("typeQuestion", value);
		AJ.setVar("cursoId", document.getElementById("idCurso").value);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);

		if (value == 1)
			AJ.setOnComplete(saveExamDesarrolloComplete);
		else
			AJ.setOnComplete(saveExamMultipleComplete);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


function saveExamDesarrolloComplete(httpRequest,AJ){
	var resp = httpRequest.responseText;

	var AJ = new Ajax();

	try{
		AJ.setUrl("newQuestionDesarrollo.php");
		AJ.setVar("examId", resp);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(showQuestionComplete);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}

function saveExamMultipleComplete(httpRequest,AJ){
	var resp = httpRequest.responseText;

	var AJ = new Ajax();

	try{
		AJ.setUrl("newQuestionMultiple.php");
		AJ.setVar("examId", resp);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(showQuestionComplete);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}

var newobject;
function showQuestionComplete(httpRequest,AJ){
	var activeTab = $('#container-tab').activeTab();
	var spanTabActive = document.getElementById("spanTab" + activeTab);

	var resp = httpRequest.responseText;

	spanTabActive.innerHTML = resp;

	try{
		newobject = document.getElementById('trOriginal').cloneNode(true);
	}catch(e){
	}

	try{
		var instance = CKEDITOR.instances['newQuestionEditor'];
		if (instance)
			CKEDITOR.remove(CKEDITOR.instances['newQuestionEditor']);
	}catch(e){
	}

	try{
	CKEDITOR.replace( 'newQuestionEditor',
		{
			toolbar :
			[
				['Cut','Copy','Paste','PasteText','PasteFromWord'],
				['Undo','Redo'],
				['TextColor','BGColor'],
				['Bold','Italic','Underline','-','Subscript','Superscript'],
				['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
				['Link','Unlink']
			],
			height: '70'
		});
	}
	catch(e){
		alert(e);}

}


//--------- SAVE QUESTION --------------
function saveQuestionDesarrollo(value){
	var AJ = new Ajax();
	try{
		var sText	= encodeURIComponent(CKEDITOR.instances.newQuestionEditor.getData());
	
		AJ.setUrl("newQuestionDesarrollo.php");
		AJ.setVar("saveQuestion", 1);
		AJ.setVar("sQuestion", sText);
		AJ.setVar("sIntructivo", document.getElementById("textInstructivo").innerHTML);
		AJ.setVar("sImageName", document.getElementById("imgName").value);
		AJ.setVar("examId", document.getElementById("examId").value);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);

		switch (value){
			case 1:	AJ.setOnComplete(saveExamDesarrolloComplete); break;
			case 2:	AJ.setOnComplete(saveExamMultipleComplete); break;
			case 3:	AJ.setOnComplete(saveExamLast); break;
		}

		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


function saveQuestionMultiple(value){
	var error = 0;
	var allParts = '';

	var part = '';
	var dontsave = 0;
	var correct = 0;
	$('#tableRespuestas').children().each( 
		function(){ 
			dontsave = 0;

			$(this).children().each( 
				function(){
					if (dontsave == 1)
						return;
				
					$(this).children().each( 
						function(){ 
							if (($(this).attr('id') == 'descriptionRespuesta') && ($(this).val() == ''))
								dontsave = 1;
							else{
								if (($(this).attr('id') == 'checkRespuesta') && ($(this).attr('checked'))){
									correct = 1;
								}
							}

							if (dontsave == 0){
								if ($(this).attr('id') == 'checkRespuesta'){
									var check = 0;
									if ($(this).attr('checked'))
										check = 1;

									part = part + check + '---';
								}
								else
									part = part + $(this).val() + '---';
							}
						} 
					)
				} 
			)

			if (dontsave == 0)
				allParts = allParts + part + '****';

			part = '';
		}
	);


	var sText	= encodeURIComponent(CKEDITOR.instances.newQuestionEditor.getData());

	if (sText != ''){
		if ((allParts == '****') || (correct == 0)){
			blockErrorMsg("La pregunta debe tener al menos una respuesta correcta.", 1);
			return;
		}
	}

	var AJ = new Ajax();

	try{
		AJ.setUrl("newQuestionMultiple.php");
		AJ.setVar("saveQuestion", 1);
		AJ.setVar("sResponse", sText);
		AJ.setVar("sImageName", document.getElementById("imgName").value);
		AJ.setVar("sRespuestas", allParts);
		AJ.setVar("examId", document.getElementById("examId").value);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);

		switch (value){
			case 1:	AJ.setOnComplete(saveExamDesarrolloComplete); break;
			case 2:	AJ.setOnComplete(saveExamMultipleComplete); break;
			case 3:	AJ.setOnComplete(saveExamLast); break;
		}

		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


//--------- NEW RESPONSE --------------
function newRespuesta(){
	var newNode = newobject.cloneNode(true);
	document.getElementById('tableRespuestas').appendChild(newNode); 
}


//--------- EXAM FINISH --------------
function showFinishExam(httpRequest,AJ){
	var resp = httpRequest.responseText;

	var AJ = new Ajax();

	try{
		AJ.setUrl("examFinish.php");
		AJ.setVar("examId", resp);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(completeTab);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


function savePointsExam(){
	var allParts = '';
	var question = '';
	zeroValue = 0;
	$('#tableQuestions').children().each( 
		function(){ 
			$(this).children().each( 
				function(){
					question = '';
					$(this).children().each( 
						function(){ 
							$(this).children().each(	
								function(){ 
									if ($(this).attr('id') == 'inId')
										question = $(this).val() + '-';
									else if ($(this).attr('id') == 'inExcluyente'){
										if ($(this).attr('checked'))
											question = question + '1-';
										else
											question = question + '0-';
									}
									else if ($(this).attr('id') == 'inPoints'){
										if (($(this).val() != '') && parseFloat($(this).val()) > 0)
											question = question + $(this).val();
										else
											zeroValue = 1;
									}
								} 
							)
						} 
					)
					allParts = allParts + question + '****';
				} 
			)
		}
	);	
		
	if (zeroValue == 1){
		blockErrorMsg('El puntaje de las preguntas no puede ser cero, verifique los valores ingresados.', 1);
		return;
	}

	if ((document.getElementById("pointsAprobacion").value == '') || (parseFloat(document.getElementById("pointsAprobacion").value) == 0)){
		blockErrorMsg('Ingrese un puntaje para la aprobación del examen.', 1);
		return;
	}

	if ((document.getElementById('totalPoints')) != null){
		if (parseFloat(document.getElementById('totalPoints').innerHTML) < parseFloat(document.getElementById('pointsAprobacion').value)){
			blockErrorMsg('La cantidad de puntos necesarios para aprobar no puede ser mayor a los puntos totales.', 1);
			return;
		}
	}

	var AJ = new Ajax();

	try{
		AJ.setUrl("examFinish.php");
		AJ.setVar("saveQuestion", 1);
		AJ.setVar("allQuestions", allParts);
		AJ.setVar("pointsAprobacion", document.getElementById("pointsAprobacion").value);
		AJ.setVar("examId", document.getElementById("examId").value);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(saveFinalExamComplete);

		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}



function saveFinalExamComplete(httpRequest,AJ){
	var resp = httpRequest.responseText;

	if ((resp == "1") || (resp == 1)){
		blockCustomMsg('<img src="../common/images/ok.gif" style="vertical-align: middle">&nbsp;&nbsp;&nbsp;' + 'Examen finalizado correctamente.<br><br><input type="button" value="Aceptar" class="inputButton" onclick="reloadTab()">');
	}
	else{
		blockDefaultErrorMsg(resp);
	}
}



function saveExamLast(httpRequest,AJ){
	var resp = httpRequest.responseText;

	var AJ = new Ajax();

	try{
		AJ.setUrl("examSaveLast.php");
		AJ.setVar("examId", resp);
		AJ.setMethod("POST");
		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(saveExamLastComplete);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


function saveExamLastComplete(httpRequest,AJ){
	var activeTab = $('#container-tab').activeTab();
	var spanTabActive = document.getElementById("spanTab" + activeTab);

	var resp = httpRequest.responseText;

	spanTabActive.innerHTML = resp;

	$(function() {
		$("#listQuestions").sortable();
	});
}


function toggleCheckOrder(){
	if (document.getElementById("cantPreguntas").value != 0){
		$('#checkOrder').attr('checked', false); 
		$('#spanCheck').hide('fast');
		$('#spanQuestion').hide('fast');
	}
	else
		$('#spanCheck').show('fast');
}



function saveFinalExam(){
	var veces			= document.getElementById("cantVeces").value;
	var cantPreguntas	= document.getElementById("cantPreguntas").value;
	var vIds			= $("#listQuestions").sortable( 'toArray'); 
	var selProfessor	= document.getElementById("selProfessor").value;

	var questionString = '';
	for (var i = 0; i < vIds.length; i++)
		questionString = questionString + vIds[i] + '-';

	if (document.getElementById("editHoras").value == '')
		document.getElementById("editHoras").value = 0;

	if (document.getElementById("editMinutos").value == '')
		document.getElementById("editMinutos").value = 0;

	var automatic = 0;
	try{
		if (document.getElementById("checkAutomatic").checked)
			automatic = 1;
	}catch (e){}
	
	var minutos			= (parseInt(document.getElementById("editHoras").value) * 60) + parseInt(document.getElementById("editMinutos").value);

	var AJ = new Ajax();
	try{
		AJ.setUrl("examSaveLast.php");
		AJ.setVar("saveExam", 1);
		AJ.setVar("examId", document.getElementById("examId").value);
		AJ.setVar("cantVeces", veces);
		AJ.setVar("cantPreguntas", cantPreguntas);
		AJ.setVar("automatic", automatic);
		AJ.setVar("questionString", questionString);
		AJ.setVar("minutos", minutos);
		AJ.setVar("professor", selProfessor);
		AJ.setMethod("POST");
//		AJ.setOnLoading(loadingTab);
		AJ.setOnComplete(showFinishExam);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}


function deleteExam(id){
	blockInfoMsg('¿Está seguro que desea eliminar el examen?<br><br><input type="button" value="Aceptar" class="inputButton" onclick="deleteExamAccept(' + id + ')">&nbsp;&nbsp;<input type="button" value="Cancelar" class="inputButton" onclick="myUnblockUI()">', 0);
}

function deleteExamAccept(value){
	var AJ = new Ajax();

	try{
		AJ.setUrl("newExam.php");
		AJ.setVar("examId", value);
		AJ.setVar("deleteExam", 1);
		AJ.setMethod("POST");
		AJ.setOnLoading(deleteExamLoading);
		AJ.setOnComplete(deleteExamComplete);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}

function deleteExamLoading(){
	blockLoadingMsg('Eliminando examen...', 1);
}

function deleteExamComplete(httpRequest,AJ){
	var resp = httpRequest.responseText;

	if ((resp == "1") || (resp == 1)){
		blockCustomMsg('<img src="../common/images/ok.gif" style="vertical-align: middle">&nbsp;&nbsp;&nbsp;' + 'Examen eliminado correctamente.<br><br><input type="button" value="Aceptar" class="inputButton" onclick="reloadTab()">');
	}
	else{
		blockDefaultErrorMsg(resp);
	}
}


function publishExam(id){
	blockInfoMsg('¿Está seguro que desea publicar el examen?<br><br><input type="button" value="Aceptar" class="inputButton" onclick="publishExamAccept(' + id + ')">&nbsp;&nbsp;<input type="button" value="Cancelar" class="inputButton" onclick="myUnblockUI()">', 0);
}


function publishExamAccept(value){
	var AJ = new Ajax();

	try{
		AJ.setUrl("newExam.php");
		AJ.setVar("examId", value);
		AJ.setVar("publishExam", 1);
		AJ.setMethod("POST");
		AJ.setOnLoading(publishExamLoading);
		AJ.setOnComplete(publishExamComplete);
		AJ.connect();
		AJ.getData();
	}catch(e){
	}
}

function publishExamLoading(){
	blockLoadingMsg('Publicando examen...', 1);
}

function publishExamComplete(httpRequest,AJ){
	var resp = httpRequest.responseText;

	if ((resp == "1") || (resp == 1)){
		blockCustomMsg('<img src="../common/images/ok.gif" style="vertical-align: middle">&nbsp;&nbsp;&nbsp;' + 'Examen publicado correctamente.<br><br><input type="button" value="Aceptar" class="inputButton" onclick="reloadTab()">');
	}
	else{
		blockDefaultErrorMsg(resp);
	}
}

