var toPregunta = 1
var errMsj = 'ERROR: PROBLEMAS CON LA CONEXION AL SERVIDOR. INTENTELO NUEVAMENTE DENTRO DE ALGUNOS MINUTOS.'
var ajaxMsj = ''
var toAlerta = Array('', 'Es obligatorio rellenar los campos resaltados...', 'El email ingresado presenta errores...')

function toResponderPregunta(){
	toVelo(1)
	$('#toCalificacion').html('')
	$.ajax({
		type: 'POST',
		url: 'php/to_testAjax.php',
		data: 'tipo=test&preguntaNro=' + escape(toPregunta) + '&respuesta=' + escape($('input:checked').val()),
		success: function(msg){
			toPregunta++
			if (msg.substr(0,2) == 'OK'){
				$('.toTest').html(msg.substr(2))
				$('.toProcesando').hide()
				toEvaluarBotones()
				$('.toVelo').fadeOut(500)
			}
			else {
				$('.toOk').css('color', '#090')
				$('.toOk').children('img.toAcertado').show()
				$('input:checked').next('span').css('color', '#f30')
				$('input:checked').next('span').children('img.toError').show()
				$('#btnSiguiente, #btnVolver').addClass('toInactivo')
				$('#btnLoader').show()
				$('.toProcesando').hide()
				$('.toVelo').fadeOut(500, function(){
					ajaxMsj = msg.substr(2)
					var t = setTimeout('toMostrarSiguientePregunta()', 3000)
				})
			}
		},
		error: function(){
			alert(errMsj)
			toVelo(0)
		}
	})
}

function toVelo(num){
	switch (num){
		case 0:
			$('.toProcesando').hide()
			$('.toVelo').fadeOut(500)
			break
		case 1:
			$('.toProcesando').html('Procesando la respuesta ' + toPregunta + ' de 20')
			var h = $(document).height()
			var l = parseInt(($(document).width() - $('.toProcesando').width()) / 2)
			$('.toVelo').css('height', h).fadeIn(500, function(){
				$('.toProcesando').css('left', l).show()
			})
			break
		case 2:
			$('.toHistorial').html('<div class="toEspaciador"></div><iframe width="800" height="350" frameborder="0" src="php/frame/to_historial.php"></iframe><div class="toEspaciador"><span onclick="toVelo(3)">Cerrar</span></div>')
			var h = $(document).height()
			var l = parseInt(($(document).width() - $('.toHistorial').width()) / 2)
			$('.toVelo').css('height', h).fadeIn(500, function(){
				$('.toHistorial').css('left', l).show()
			})
			break
		case 3:
			$('.toHistorial').html('').hide()
			$('.toVelo').fadeOut(500)
			break
		case 4:
			var h = $(document).height()
			$('.toVeloTrans').css('height', h).show()
			break
		case 5:
			$('.toVeloTrans').hide()
			break
	}
}

function toMostrarSiguientePregunta(msg){
	$('.toTest').fadeOut(500, function(){
		$('#btnSiguiente, #btnVolver').removeClass('toInactivo')
		$('#btnLoader').hide()
		toEvaluarBotones()
		$(this).html(ajaxMsj).fadeIn(500)
	})
}

function toEvaluarBotones(){
	if (toPregunta > 1){
		$('#btnVolver, #btnEstado').removeClass('toInactivo')
	}
	if (toPregunta >= 21){
		$('#btnSiguiente').addClass('toInactivo')
		$('#btnPuntaje').removeClass('toInactivo')
	}
}

function toRegistro(){
	var h = -1 * ($('#toCompRegistro').height() + 4)
	var l = parseInt(($(document).width() - 800) / 2)
	$('#toCompRegistro').css({'top': h, 'left': l}).show()
	toVelo(4)
	$('#toCompRegistro').animate({top: 0}, 1000)
}

function toMostrarRegistro(){
	var a = toPregunta - 1
	toVelo(2)
}

function toValidarEmail(str){
	var regex = /^[-_.a-z0-9]+@(([-a-z0-9]+\.)+(ad|ae|aero|af|ag|ai|al|am|an|ao|aq|ar|arpa|as|at|au|aw|az|ba|bb|bd|be|bf|bg|bh|bi|biz|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|com|coop|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|edu|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gh|gi|gl|gm|gn|gov|gob|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|in|info|int|io|iq|ir|is|it|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mil|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|museum|mv|mw|mx|my|mz|na|name|nc|ne|net|nf|ng|ni|nl|no|np|nr|nt|nu|nz|om|org|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|pro|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|su|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)|(([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5])\.){3}([0-9][0-9]?|[0-1][0-9][0-9]|[2][0-4][0-9]|[2][5][0-5]))$/i
	return regex.test(str)
}

function toAlertas(num){
	alert(toAlerta[num])
}

function toRegistrar(){
	toLoader(1)
	$.ajax({
		type: 'POST',
		url: 'php/to_accionesAjax.php',
		data: 'tipo=registrar&nombre=' + escape($('#toNombre').val()) + '&email=' + escape($('#toEmail').val()) + '&cursoInteres=' + escape($('#toInteres').val()),
		success: function(msg){
			alert(msg.substr(2))
			if (msg.substr(0,2) == 'OK')
				toLoader(0)
			else
				toLoader(2)
		},
		error: function(){
			alert(errMsj)
			toLoader(0)
		}
	})
}

function toLoader(num){
	if (num == 0){
		$('.toObligatorio, #toInteres').attr('disabled', '').val('')
		$('#toBtnEnviar').removeClass('toDeshabilitado')
		$('#toLoader').hide()
	}
	else if (num == 1){
		$('.toObligatorio').attr('disabled', 'disabled')
		$('#toBtnEnviar').addClass('toDeshabilitado')
		$('#toLoader').show()
	}
	else if (num == 2){
		$('.toObligatorio, #toInteres').attr('disabled', '')
		$('#toBtnEnviar').removeClass('toDeshabilitado')
		$('#toLoader').hide()
	}
}

function toVerEstado(tipo){
	var toDiv = '#toCalificacion'
	if (tipo == 'puntaje')
		toDiv = '#toPuntaje'
	$.ajax({
		type: 'POST',
		url: 'php/to_accionesAjax.php',
		data: 'tipo=' + escape(tipo) + '&email=to&cursoInteres=pl&mensaje=esc&nombre=oscar',
		success: function(msg){
			$(toDiv).html(msg)
		}
	})	
}

$(function(){
	$('#btnSiguiente').click(function(){
		if (!$(this).hasClass('toInactivo')){
			toResponderPregunta()
		}
	})

	$('#btnVolver').click(function(){
		if (!$(this).hasClass('toInactivo')){
			toMostrarRegistro()
		}
	})

	$('#toQue_es').click(function(){
		var h = -1 * ($('#toCompQue_es').height() + 4)
		var l = parseInt(($(document).width() - 800) / 2)
		$('#toCompQue_es').css({'top': h, 'left': l}).show()
		toVelo(4)
		$('#toCompQue_es').animate({top: 0}, 1000)
	})

	$('#toRegistro').click(function(){
		toRegistro()
	})

	$('#toCerrarQue_es').click(function(){
		var t = -1 * ($('#toCompQue_es').height() + 4)
		$('#toCompQue_es').animate({top: t}, 800)
		toVelo(5)
	})

	$('#toLogin').click(function(){
		window.open('usuarios', '_self')
	})

	$('#toLogin, #toRegistro, #toQue_es').hover(
		function(){
			$(this).fadeTo(200, 0)
		},
		function(){
			$(this).fadeTo(200, 1)
		}
	)

	$('#toCerrarRegistro').click(function(){
		var t = -1 * ($('#toCompRegistro').height() + 4)
		$('#toCompRegistro').animate({top: t}, 800, function(){
			$('.toObligatorio').removeClass('toIncompleto').val('')
			$('#toInteres').val('')
		})
		toVelo(5)
	})

	$('#toBtnEnviar').click(function(){
		if (!$(this).hasClass('toDeshabilitado')){
			var x = 0
			var y = 0
			$('.toObligatorio').each(function(i){
				if (jQuery.trim($(this).val()) == ''){
					$(this).addClass('toIncompleto')
					x++
					y = 1
				}
				else
					$(this).removeClass('toIncompleto')
			})
			if (!toValidarEmail(jQuery.trim($('#toEmail').val()))){
				if (x == 0)
					y = 2
				x++
				$('#toEmail').addClass('toIncompleto')
			}
			if (x > 0)
				toAlertas(y)
			else
				toRegistrar()
		}
	})

	$('#btnEstado').hover(
		function(){
			if (!$(this).hasClass('toInactivo')){
				var l = parseInt(($(document).width() - 604) / 2)
				$('#toCalificacion').css('left', l).fadeIn(200, function(){
					toVerEstado('estado')
				})
			}
		},
		function(){
			$('#toCalificacion').fadeOut(200)
		}
	)

	$('#btnPuntaje').hover(
		function(){
			if (!$(this).hasClass('toInactivo')){
				var l = parseInt(($(document).width() - 604) / 2)
				$('#toPuntaje').css('left', l).fadeIn(200, function(){
					toVerEstado('puntaje')
				})
			}
		},
		function(){
			$('#toPuntaje').fadeOut(200)
		}
	)
})