/**
 * Controlador de plataforma de pago por teléfono.
 * @author Modificado por ProPsycho
 */
var noPhone			= false;
var waitingCall		= false;
var checkInterval	= 3;  // IN SECONDS
var timerId			= 0;

function Log(_message)
{
	if(typeof(console) != 'undefined') console.log(_message);
}

$(document).ready
(
	function()
	{
		if ($("#p2e").length && !waitingCall)
			//getNumber();
			startCountDown(document.getElementById('countDownTime').value);
		else if ($("#ncc").length)
		{
			var iframeLoaded	= false;
			$("#iframe_ncc").hide();
			$('#loading').show();
			$('#if_ncc').load
			(
				function() 
				{
					$("#loading").fadeOut('2000');
					$("#iframe_ncc").fadeIn("3000");
					iframeLoaded = true;            
				}
			);
		}
		return false;
	}
);

function getNumber() 
{
	$('#noCall').hide();
	//$('#call').hide();
	$('#loading').hide();
	$.post("/scripts/getNumber.php?nc=" + Math.random(), {uid: $("#uid").val()}, cbGetNumber, 'json');
}

function cbGetNumber(_data) 
{
	$('#loading').hide();
	
	if ( _data.response.state == 'OK' ) 
	{
		$("#phoneNumber").html(_data.response.phonenumber);
		startCountDown(_data.response.remain);

		$('#noCall').hide();
		$('#call').show();

		noPhone = false;
		waitingCall = true;
		checkPhonecall();
	}
	else 
		$('#noCall').show();
}

function checkPhonecall() 
{
	$.post("/scripts/chkPhonecall.php?nc=" + Math.random(), {uid: $("#uid").val()}, cbCheckPhonecall, 'json');
	if ( noPhone == false ) timerId = setTimeout("checkPhonecall()", checkInterval * 1000);
}

function cbCheckPhonecall(_data) 
{
	if ( _data.response.state == 'OK' )
	{
		clearInterval(timerId);
		window.location = "/scripts/p2eLogin.php?uid=" + $("#uid").val() + "&nc=" + Math.random();
	}
}

function noCall() 
{
   noPhone = true;
   waitingCall = false;
   clearInterval(timerId);

   showRetry();
}

function startCountDown(_startNumber)
{
	document.getElementById('countDown').innerHTML = _startNumber + ' segundos';
	if(typeof(console) != 'undefined')
		console.log('Cuenta atrás = ' + _startNumber);
	
	if(_startNumber > 0)
		setTimeout('startCountDown(' + (_startNumber - 1) + ')', 1000);
	else
		noCall();
}

function showRetry()
{
	$('#noCall').show();
	$('#call').hide();
	document.getElementById('callCheckerIframe').src = '';
}
