var encuesta_id = '';

$(document).ready(function() {
	verEncuesta(encuesta_id);
});

validarEncuesta = function(){

	encuesta_id = $('#frmEncuesta > #encuesta_id').val();

	var f = document.getElementById("frmEncuesta");
	var voto = 0;

	for(i=0; i<f.opcion_id.length; i++){
		if (f.opcion_id[i].checked) voto = 1;
	}

	if (voto == 1) { 
		enviarEncuesta(encuesta_id);
	} else {
		alert("Debe seleccionar alguna opción de voto.");
	}
}


verResultadosEncuesta = function(id){
	var qs = '';
	if (id != '' && id != undefined && id != null) qs = '?encuesta_id='+id;
	$('#ajax_encuesta').load('inc_encuesta_resultados.php'+qs);
}

verEncuesta = function(id) {
	var qs = '';
	if (id != '' && id != undefined && id != null) qs = '?encuesta_id='+id;

	$('#ajax_encuesta').load('inc_encuesta.php'+qs, function(response) {
		if (response == '') {
			$("#encuesta").css("display", "none");
		}
	});
}

enviarEncuesta = function(id) {

	var qs = $("#frmEncuesta").serialize();

	$.ajax({  
		type: "POST",  
		url: "web/ajax_encuesta_votar.php",  
		data: qs,
		async: false,
		cache: false,
		timeout: 30000,
		dataTypeString: "text",
		beforeSend: function() {
			$("#ajax_encuesta").html('<img src="images/spinner_16x16.gif" />');
		},
		success: function (response) {

//			$("#ajax_encuesta").html('&nbsp;');

			try {
				var json = jQuery.parseJSON(response);
			}
			catch (e) {
				alert(response);
				return -1;
			}

			if (json.status == 'error') {
				if (json.error == 'ya_voto'){
					alert('Ud. ya voto en esta encuesta.');
					verResultadosEncuesta(id);
				}
			} else {
				alert('Gracias por su voto.');
				verResultadosEncuesta(id);
			}
		}
	});  
}

