var counter        = 0;
var telefono_no    = false;
var waiting_call   = false;
var time_limit     = 110; // IN SECONDS
var check_interval = 3;  // IN SECONDS
var timer_id       = 0;
var iframe_loaded  = false;

$(document).ready(function(){
   $('#join-telefono').bind("blur", function(e){

      if ( $("#p2e").length ) {
         if ( waiting_call == false ) {
            get_number();
            $("#no_call").click( get_number );
         }
      }

      if ( $("#ncc").length && iframe_loaded === false ) {
         var user_id    = $("#user_id").val();
         var alias      = $("#alias").val();
         var iframe_url = "http://scripts.nccgateway.com/Common/module.php?customid=2640&siteid=14061&brokerid=2009620";
             iframe_url+= "&extlogin=" + user_id + "|" + alias;
             iframe_url+= "&sid=15&mediaid=00600000";

         $("#if_ncc").attr("src", iframe_url);

         $('#if_ncc').load(function() {
            $("#iframe_loading").fadeOut();
            $("#iframe_ncc").fadeIn("3000");
            iframe_loaded = true;            
         });
      }

      return false;
   });
});

function ini_counter() {
   $('#counter').countdown({seconds: time_limit, callback: 'no_call()'});
}

function get_number() {
   $('#no_call').hide();
   $('#loading').show();
   $.post("/p2e/lib/get_number.php?nc="+Math.random(), {uid: $("#uid").val()}, cb_get_number);
}

function cb_get_number(xmlData) {
   $('#loading').hide();

   if ( $(xmlData).find('state').text() == 'OK' ) {
	   $("#phone_number").html($(xmlData).find('phonenumber').text());
	   time_limit = $(xmlData).find('remain').text();
	   ini_counter();
	   $('#no_call').hide();
	   $('#call_now').show();
	   telefono_no = false;
	   waiting_call = true;
	   check_phonecall();
   }
   else {
      $('#no_call').show();
   }
}

function check_phonecall() {
   $.post("/p2e/lib/chk_phonecall.php?nc="+Math.random(), {uid: $("#uid").val()}, cb_check_phonecall);
   if ( telefono_no == false ) timerId = setTimeout("check_phonecall()", check_interval*1000);
}

function cb_check_phonecall(xmlData) {
   if ( $(xmlData).find('state').text() == 'OK' ) {
	   location.href = "/p2e/lib/p2e_login.php?uid=" + $("#uid").val() + "&nc=" + Math.random();
   }
}

function no_call() {
   telefono_no = true;
   waiting_call = false;
   clearInterval(timer_id);
   $('#call_now').hide();
   $('#no_call').show();
}