
//##########################################################
//Funções de apoio ao respondimento de questões avulsas
//##########################################################

//Alterna entre o modo resumido e o modo full
function search_result_toggle (key,is_colapsed){
	div1 = 	'colapsed_question_' + key;
	div2 =  'expanded_question_' + key;
 	Effect.toggle(div1, 'blind', {duration: 0.0});
	Effect.toggle(div2, 'blind', {duration: 0.0});

	/*if (is_colapsed) {
		div_answer_status = "show_answer_status_" + key;
		show_answer_status_url = "/answers/hide_answer_status" + url_params;
		new Ajax.Updater (div_answer_status, show_answer_status_url, {asynchronous:true, evalScripts:true});
	}*/

}

/*
//Submete a resposta para uma determinada questão
function submit_answer (key) {
	 options = document.forms["options_" + key].elements['answer_id'];

	 for(var i = 0; i < options.length; i++) {
		 if(options[i].checked) { user_choice = options[i].value; }
	 }	 
	 url_params = "?key=" + key + "&user_choice=" + user_choice;
	 
	//Submete a resposta do usuário
	submit_answer_url =  "/answers/submit_answer" + url_params;
	new Ajax.Request(submit_answer_url, {asynchronous:false , evalScripts:true});

	//Atualiza o div indicando se o usuário errou ou acertou 
	div_answer_status = "show_answer_status_" + key;
	show_answer_status_url = "/answers/show_answer_status" + url_params;
	new Ajax.Updater (div_answer_status, show_answer_status_url, {asynchronous:true, evalScripts:true}); 

	//Desabilita a opção de responder 
	$('answer_'+ key).style.display = "none";
	$('answer_'+ key + '_answered').style.display = "inline";	

	return false;
}
*/

//Submete a resposta para uma determinada questão
function submit_answer (key,right_answer,last_search_term) {

	 options = document.forms["options_" + key].elements['answer_id'];
	 no_choice = true;
	 for(var i = 0; i < options.length; i++) {
		 if(options[i].checked) { 
		 	user_choice = options[i].value; 
		 	no_choice = false;
		 }
	 }	 

	if (!no_choice){ 
		url_params = "?key=" + key + "&user_choice=" + user_choice + "&last_search_term=" + last_search_term;
		//Submete a resposta do usuário
		submit_answer_url =  "/answers/submit_answer" + url_params;
		new Ajax.Request(submit_answer_url, {asynchronous:true , evalScripts:true});
		if (user_choice == right_answer){
			Element.show("right_answer_" + key);		
		}else{
			Element.show("wrong_answer_" + key);				
		}
		
		//Mostra o div de mensagens
		Element.show("answer_msgs_" + key);						
		
		//Desabilita a opção de responder 
		$('answer_'+ key).style.display = "none";
		$('answer_'+ key + '_answered').style.display = "inline";	
	}
		
	return false;
}


//###############################################################
//Funções de apoio a parte de Desempenho e histórico
//###############################################################

function open_qst (i,key){
	Effect.toggle('div_hide_' + i ,'blind', {duration: 0.0});
	Effect.toggle('div_show_' + i ,'blind', {duration: 0.0});
	new Ajax.Updater ('qst_' + i, "/questions/show_preview?key=" + key, {asynchronous:true, evalScripts:true}); 
	Element.show('qst_' + i);	
}
function close_qst (i,key){
	Effect.toggle('div_hide_' + i ,'blind', {duration: 0.0});
	Effect.toggle('div_show_' + i ,'blind', {duration: 0.0});
	Element.hide('qst_' + i);	
}

//###############################################################
//Funções de apoio à criação de simulados
//###############################################################

//Adiciona uma questão ao simulado
function add_question_to_exam (key) {
	add_question_to_exam_url = "/exams/add_question?key=" + key;
	new Ajax.Request(add_question_to_exam_url, {asynchronous:false, evalScripts:true}); 
	Element.hide ("add_question_to_exam_" + key);
	Element.show ("remove_question_from_exam_" + key);
	new Ajax.Updater ("exam_questions_list", "/exams/update_exam_questions_list_div", {asynchronous:true, evalScripts:true}); 
	return false;
}

//Remove uma questão do simulado
function remove_question_from_exam (key) {
	remove_question_from_exam_url = "/exams/remove_question?key=" + key;
	new Ajax.Request(remove_question_from_exam_url, {asynchronous:false, evalScripts:true}); 
	Element.show ("add_question_to_exam_" + key);
	Element.hide ("remove_question_from_exam_" + key);
	new Ajax.Updater ("exam_questions_list", "/exams/update_exam_questions_list_div", {asynchronous:true, evalScripts:true}); 
	return false;
}

function remove_question_from_exam_2 (key) {

	remove_question_from_exam_url = "/exams/remove_question?key=" + key;
	new Ajax.Request(remove_question_from_exam_url, {asynchronous:false, evalScripts:true}); 
	Element.hide ("question_preview_div");
	new Ajax.Updater ("exam_questions_list", "/exams/update_exam_questions_list_div", {asynchronous:true, evalScripts:true}); 

	if ( $("remove_question_from_exam_" + key) != null ) {
		$("remove_question_from_exam_" + key).style.display = "none";
		$("add_question_to_exam_" + key).style.display = "inline";		
	}
	return false;

}

function toggle_exam_control_panel () {
	new Ajax.Updater ("exam_questions_list", "/exams/update_exam_questions_list_div", {asynchronous:false, evalScripts:true}); 
	Effect.toggle("exam_creation_info",'blind', {duration: 0.0})
	Effect.toggle("open_exam_cp", 'blind', {duration: 0.0});
	Effect.toggle("close_exam_cp", 'blind', {duration: 0.0});
	return false;
}

function toggle_exam_comment () {
	Effect.toggle("add_question_comment_box",'blind', {duration: 0.0})
	Effect.toggle("open_exam_comment",'blind', {duration: 0.0})
	Effect.toggle("close_exam_comment", 'blind', {duration: 0.0});
	return false;
}

function update_exam_question_list (){
	exam_questions_list_div = "exam_questions_list";
	exam_questions_list_url = "/exams/update_exam_questions_list_div";
	new Ajax.Updater (exam_questions_list, exam_questions_list_url, {asynchronous:true, evalScripts:true}); 
	return false;
}

function show_question_preview (key){
	new Ajax.Updater ("question_preview_div", "/questions/show_preview?key=" + key, {asynchronous:false, evalScripts:true}); 
	Element.show ("question_preview_div");
	return false;
}

function hide_question_preview () {
	Element.hide ("question_preview_div");
	return false;
}


//Salva o simulado
function create_exam (){
	
	exam_name = $('name').value;
	exam_description = $('description').value;	
	exam_send_to_list = $('send_to_list').value;	
	exam_time_hours = $('time_hours').value
	exam_time_minutes = $('time_minutes').value;	

	if ( exam_time_hours.match(/^[\s\n]*$/)) {exam_time_hours = "0";}
	if ( exam_time_minutes.match(/^[\s\n]*$/)) {exam_time_minutes = "0";}

	if ( exam_name.match(/^[\s\n]*$/) || exam_description.match(/^[\s\n]*$/) ) {
		alert ("Os campos Título, Descrição e Tempo são obrigatórios.");
		return false;
	}

	if ( !exam_time_hours.match(/^\d+$/) || !exam_time_minutes.match(/^\d+$/) ) {
		alert ("Os campos de tempo são obrigatórios, devem conter somente \n números e pelo menos um deles diferente de 0.");
		return false;
	}

	if ( exam_time_hours.match(/^[1-9]+$/) || exam_time_minutes.match(/^[1-9]+[0-9]*$/) ) {

		//Envia a requisição de criação do simulado
		url_params = "name=" + exam_name + "&description=" + exam_description + "&send_to_list=" + exam_send_to_list + "&time_minutes=" + exam_time_minutes + "&time_hours=" + exam_time_hours;
		create_exam_url = "/exams/create_exam?" + url_params;
		new Ajax.Request(create_exam_url,{asynchronous:false, evalScripts:true});

		//Limpa o campos do formulário
		$('name').value = "";
		$('description').value = "";	
		$('send_to_list').value = "";	
		$('time_hours').value = "";
		$('time_minutes').value = "";

		alert ("O simulado foi criado com sucesso.");
		window.location = "/exams/list";
		
	}else{
		alert ("O tempo sugerido deve ser diferente de 0");
	}

}


//Limpa o simulado em construção
function clear_exam (){

	//Limpa o campos do formulário
	$('name').value = "";
	$('description').value = "";	
	$('send_to_list').value = "";	
	$('time_hours').value = "";
	$('time_minutes').value = "";
	new Ajax.Request("/exams/clear_exam",{asynchronous:false, evalScripts:true});
	window.location.reload(true);

}



//###############################################################
//Funções de apoio a realização de simulados
//###############################################################

//Inicia a participação em um simulado
function start_exam (exam_key){
	//Muda os estados dos DIVs
	$('exam_started').style.display = "inline";
	$('exam_start').style.display = "none";	
	$('exam_page_1').style.display = "inline";

	//Inicia o simulado
	url_params = "?exam_key=" + exam_key; 
	start_exam_url = "/exams/start_answering_exam" + url_params;
	new Ajax.Request(start_exam_url, {asynchronous:true , evalScripts:true});	

	return false;
}

//Controle de paginação do simulado corrente
function show_exam_page (page){
	i = 1;
	max_number_of_pages = 50;
	while (i < max_number_of_pages){
		page_div = 'exam_page_' + i;
		if ($('exam_page_' + i) != null) {
			if (page == i){ 
				$('exam_page_' + i).style.display = "inline";
			}else{
				$('exam_page_' + i).style.display = "none";			
			}
		}else{
			break;		
		}
		i++;
	}
	return false;
}

//Submete uma resposta para uma determinada questão do simulado corrente
function submit_answer_exam (key,user_choice){
	//Muda formatação para indicar que a questão já foi respondida
	$('exam_question_' + key).style.background = "#eeeeee";
	
	//Submete a resposta do usuário 
	url_params = "?key=" + key + "&user_choice=" + user_choice;
	submit_answer_exam_url =  "/exams/answer_exam_question" + url_params;
	new Ajax.Request(submit_answer_exam_url, {asynchronous:true , evalScripts:true});

	//Atualiza o DIV de número de questões respondidas
	//div_exam_question_counter = "exam_question_counter";
	//exam_question_counter_url = "/exams/update_answered_questions_div";
	//new Ajax.Updater (div_exam_question_counter, exam_question_counter_url, {asynchronous:true, evalScripts:true}); 

	return false;
}


//Cancela a participação no simulado corrente	
function cancel_exam (){
	confirmation = confirm("Deseja realmente cancelar sua participação no simulado?");
	if (confirmation == true){	
		new Ajax.Request("/exams/cancel_exam", {asynchronous:false , evalScripts:true});
		window.location = "/exams/list";
	}
}

//Submete o simulado
function submit_exam(exam_key) {
	submit_exam_url =  "/exams/submit_exam";
	confirmation = confirm("Confirmar envio do simulado?");
	if (confirmation == true){
		new Ajax.Request(submit_exam_url, {asynchronous:false , evalScripts:true});
		alert("/statistics/exam_stats?exam_key=" + exam_key);	
		window.location = "/statistics/exam_stats?exam_key=" + exam_key;
	}else{
		alert ("Uma boa conferida nunca vai mal. Boa sorte candidato!");	
	}
}




//####################################################################
//Funções de envio de comentários, votos, denuncias, emails, tags ...
//####################################################################

//Envio de comentários para questão
function send_comment (key,type) {

	//comment_text =  $("comment_text").value; (pau no IE)
	comment_text =  document.form.comment_text.value;	

	if (comment_text.length > 2000) {
		alert("O comentário possui mais que 2000 caracteres");
		return false;
	}
	
	if ( comment_text.match(/^[\s\n]*$/) ) {
		alert("Você não digitou seu comentário");	
		
	}else{

		url_params = "?key=" + key + "&opinion=" + comment_text;

		if (type == "question"){
			Element.hide ("question_comment_box");
			url = "/comments/add_question_comment" + url_params;
			show_comments_url = "/comments/show_question_comments?key=" + key;
		}else if (type == "exam") {
			Element.hide ("exam_comment_box");
			url = "/comments/add_exam_comment" + url_params;
			show_comments_url = "/comments/show_exam_comments?key=" + key;
		}

		//new Ajax.Request(url, {contentType:"xml", asynchronous:false , evalScripts:true});
		new Ajax.Request(url, {asynchronous:false , evalScripts:true});						

		$('comment_text').value = "";
		alert("Seu comentário foi enviado com sucesso!");
		new Ajax.Updater ("comments_div", show_comments_url, {asynchronous:true, evalScripts:true});		
		
	}
	return false;


}


//Envia a questão para uma lista de emails.
function send_question2friends (key){

	email_list = $('email_list_' + key).value;
	if ( email_list.match(/^[\s\n]*$/) ){
		alert ("Você pecisa indicar pelo menos um endereço de email.");
	}else {
		//send_question_url = 
		//new Ajax.Request(send_question_url, {asynchronous:true , evalScripts:true});			
	}

	return false;
}

//Envia a questão para uma lista de emails.
function send_exam2friends (key){

	email_list = $('emails').value;
	if ( email_list.match(/^[\s\n]*$/) ){
		alert ("Você pecisa indicar pelo menos um endereço de email.");
	}else {
		send_question_url = "/exams/invite_friends_to_solve_exam?key=" + key + "&emails=" + email_list;
		//new Ajax.Request(send_question_url, {asynchronous:true , evalScripts:true});			
		alert ("O convite para o simulado foi enviado com sucesso");
	}

	return false;
}

//Adiciona uma lista de tags à questão
function add_tag2question (key){

	tag_list = $('tag_list_' + key).value;
	if ( tag_list.match(/^[\s\n]*$/) ){
		alert ("Você pecisa indicar pelo menos uma tag.");		
	}else {
		//add_tag_url = 
		//new Ajax.Request(add_tag_url, {asynchronous:true , evalScripts:true});			
	}
	return false;
}

function rate_comment (id,rate){

	url_params = "?id=" + id + "&positive_or_negative=" + rate; 
	url_rate_comment = "/comments/snitch_comment";
	url_rate_comment = url_rate_comment + url_params;

	new Ajax.Request(url_rate_comment, {asynchronous:true , evalScripts:true});			
	Element.hide('allow_rate_comment_' + id);
	Element.show('thanks_rate_comment_' + id);
	
}



//##########################################################
//Funções de suporte à paginação
//##########################################################

function paginate_question_comments (){
	
	div_show_question_comments = "show_question_comments";
	show_question_comments_url = "/questions/show_question_comments";
	new Ajax.Updater (div_show_question_comments, show_question_comments_url, {asynchronous:true, evalScripts:true});
	return false;
}


//##########################################################
//Funções de suporte à manipulação da pag de stats
//##########################################################

function showQuestionComments() {
	Element.hide('diagnostic');
	Element.hide('references');
	Element.show('comments');	
}

function showQuestionReferences() {
	Element.hide('diagnostic');
	Element.hide('comments');
	Element.show('references');	
}

function showQuestionDiagnostic() {
	Element.hide('comments');
	Element.hide('references');	
	Element.show('diagnostic');
}

//##########################################################
//Funções de suporte à impressão de simulados
//##########################################################

function generate_pdf_exam (id) {
	url_params = "?id=" + id;
	submit_answer_exam_url =  "/exams/generate_pdf" + url_params;
	new Ajax.Request(submit_answer_exam_url, {asynchronous:false , evalScripts:true});
	return false;
}

//##########################################################
//Funções de suporte aos Rankings
//##########################################################

function deleteRanking (id){
	confirmation = confirm("Deseja realmente excluir o ranking?");
	if (confirmation == true){	
		window.location = "/rankings/delete?id="+id;
	}
}

function leaveRanking (id){
	confirmation = confirm("Deseja realmente sair do ranking?");
	if (confirmation == true){		
		window.location = "/rankings/leave?id="+id;
	}
}


//##########################################################
//Funções de suporte aos Bookmarks
//##########################################################
function add2bookmark (question_key) {
	form = document.forms["ac_" + question_key];
	new Ajax.Updater(
		"bookmark_msg_" + question_key,
		"/bookmarks/add_question_to_bookmark?question_key=" + question_key,
		{asynchronous:true, evalScripts:true, parameters:Form.serialize(form)}
	); 
	return false;	
}

function deleteBookmark (id) {
	confirmation = confirm("Deseja realmente excluir esse Bookmark?");
	if (confirmation == true){		
		window.location = "/bookmarks/delete?id="+id;
	}
}






