//Register passby vars
var RegTournamentId = 0;
var RegRound = 0;
var RegBracket = 0;
var RegIsRebuy = false;
var RegRebuyAmount = "$0";
var RegIsFromLobby = false;

// provides access to querystring collection
function Widgets_QueryString(){var aQS;var sQS = window.location.search.toString();sQS = sQS.substring(1, sQS.length);if (sQS != null && sQS != ""){aQS = sQS.split("&");for (var i = 0; i < aQS.length; i++){aQS[i] = aQS[i].split("=");}}else{aQS = new Array(0);}this.Get = function (sKey){sKey = escape(sKey);for (var i = 0; i < aQS.length; i++){if (aQS[i][0] == sKey){return unescape(aQS[i][1]);}}return null;};this.Count = aQS.length;};
function Widgets_Request(){this.QueryString = new Widgets_QueryString;};
var Request = new Widgets_Request();

// deprecated syntax support
function CasinoGameOpenDemo() { CasinoGameOpen(arguments[0], -1); }
function CasinoGameOpenLogin() { CasinoGameOpen(arguments[0], 1); }
function OnGameClicked() { CasinoGameOpen(arguments[0]); }
function OnPlayClicked() { CasinoGameOpen(arguments[0],arguments[1]); }

// game launch
function CasinoGameOpen(nCasinoGameId, nAccountId, sGameCode)
{
   var LaunchForm = document.forms["LaunchForm"];
   var LobbyForm = document.forms["LobbyForm"];
   if (LaunchForm == null){alert("Launch Form not found"); return;}
   if (LobbyForm == null){alert("Lobby Form not found"); return;}
   
   if (nAccountId != null) LaunchForm["AccountId"].value = nAccountId;

   // verify login
   var token = LaunchForm["Token"].value;
   var nAccountId = LaunchForm["AccountId"].value;
   if (nAccountId == "1" && token == "") return;
   
   LaunchForm["CasinoGameId"].value = nCasinoGameId;
   if (LaunchForm["GameCode"] != null) LaunchForm["GameCode"].value = sGameCode;
   
   var wWindow = popupGame();
   if (wWindow == null)
   {
      alert("Unable to open game window. You may have a pop-up blocker enabled.");
      return;
   }
   try 
   {
      wWindow.moveTo(0,0);
   } 
   catch(e){}
   try 
   {
      wWindow.resizeTo(screen.width,screen.height);
      wWindow.focus();
   } 
   catch(e){}
   LaunchForm.submit();
}

// lobby functions
function OnLanguageClicked(Language)
{
   var LobbyForm = document.forms["LobbyForm"];
	LobbyForm["lang"].value = Language;
	LobbyForm.submit();
}

function OnCategoryClicked(CategoryId, IsContest, TabCode)
{
   var LobbyForm = document.forms["LobbyForm"];
   LobbyForm["catid"].value = CategoryId;
   LobbyForm["tabcode"].value = TabCode;
   LobbyForm.submit();
}

function RefreshLobby()
{
   document.forms["LobbyForm"].submit();
}

function OnLobbyLoad()
{
   if (document.location.search != null && document.location.search.length > 2)
   {
      if (Request.QueryString.Get("CasinoGameId") != null) 
      CasinoGameOpen(Request.QueryString.Get("CasinoGameId"));
      if (Request.QueryString.Get("GameCode") != null)
      CasinoGameOpen(0,null,Request.QueryString.Get("GameCode"));
      RefreshLobby();
   }
}

// contest functions
function OnRegisterClicked(TournamentId, Round, Bracket, Fee)
{
	if (confirm("This will debit " + Fee + " from your account"))
	{
	   var LobbyForm = document.forms["LobbyForm"];
		LobbyForm["tournamentid"].value = TournamentId;
		LobbyForm["round"].value = Round;
		LobbyForm["bracket"].value = Bracket;
		LobbyForm["action"].value = "REGISTER";
		LobbyForm["target"].value = "REGISTER_WND";
		LobbyForm.submit();
	}
	
}

function OnScoreboardClicked(TournamentId, Round, Bracket)
{   
   var LobbyForm = document.forms["LobbyForm"];
	LobbyForm["tournamentid"].value = TournamentId;
	LobbyForm["round"].value = Round;
	LobbyForm["bracket"].value = Bracket;
	LobbyForm["action"].value = "SCOREBOARD";
	LobbyForm.target = "SCOREBOARD_WND";
	LobbyForm.submit();
}

function OnBackClicked()
{
   var LobbyForm = document.forms["LobbyForm"];
	LobbyForm["round"].value = "";
	LobbyForm["bracket"].value = "";
   LobbyForm["action"].value = "";
	LobbyForm.submit();
}

function Logout()
{
   var LobbyForm = document.forms["LobbyForm"];
   LobbyForm["token"].value = "";
	LobbyForm["action"].value = "LOGOUT";
	LobbyForm.submit();
}

function popupNews(url, width, height)
{
   var settings="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width="+width+",height="+height;
   winpops=window.open(url,"",settings);
}

function popupGame()
{
   var settings="toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,width="+screen.width+",height="+screen.height;
   return window.open("","casinogamingflashwindow",settings);
}

function doRegister(TournamentId, Round, Bracket, Fee, isFromLobby)
{
   if(confirm("This will debit " + Fee + " from your account"))
   {
      RegTournamentId = TournamentId;
      RegRound = Round;
      RegBracket = Bracket;
      RegIsRebuy = false;
      RegRebuyAmount = Fee;
      RegIsFromLobby = isFromLobby;
      
      jQuery.ajax({
	      type: "GET",
	      url: "/images/newsite1024/feed/new-casino-lobby-feed.aspx",
	      data: "action=REGISTER&tournamentid=" + TournamentId + "&round=" + Round + "&bracket=" + Bracket,
	      cache: false,
         success: registerResponse
	   });
	}
	
	return false;
}

function doRebuy(TournamentId, Round, Bracket, Fee)
{
   if(confirm("This will debit " + Fee + " from your account"))
   {
      RegTournamentId = TournamentId;
      RegRound = Round;
      RegBracket = Bracket;
      RegIsRebuy = true;
      RegRebuyAmount = Fee;
      
      jQuery.ajax({
	      type: "GET",
	      url: "/images/newsite1024/feed/new-casino-lobby-feed.aspx",
	      data: "action=REGISTER&tournamentid=" + TournamentId + "&round=" + Round + "&bracket=" + Bracket,
	      cache: false,
         success: registerResponse
	   });
	}
	
	return false;
}

function registerResponse(resp)  {

   var nofunds = resp.match(/You have insufficient funds to enter the contest./ig);
   var periodclosed = resp.match(/Registration period has closed./ig);
   
   if(nofunds && nofunds[0])
   {
      alert("You have insufficient funds to enter the contest.");
   }
   else
   {
      if(periodclosed && periodclosed[0])
      {
         alert("Registration period has closed.");
      }
      else
      {
         if(RegIsRebuy)
         {
            alert("You've successfully rebought for " + RegRebuyAmount  + ".");
         }
         else
         {
            //By default trigger the default option...
            //var LobbyForm = document.forms["LobbyForm"];
   		   //LobbyForm["tournamentid"].value = RegTournamentId;
   		   //LobbyForm["round"].value = RegRound;
   		   //LobbyForm["bracket"].value = RegBracket;
   		   //LobbyForm["action"].value = "REGISTER";
   		   //LobbyForm["target"].value = "REGISTER_WND";
   		   //LobbyForm.submit();
   		   
   		   //Default is supposed to be a register call...
   		   //We should either reload the page or reload the tab 
   		   //depending on where are we at !!!
   		   
   		   //Lets just reload the page for now....
   		   if(RegIsFromLobby)
   		      loadTab(4,3,"LOBBYCAT_CONTEST");
   		   else
   		      self.location = self.location;
   		}
      }
   }
}

function showScoreboard(TournamentId, Round, Bracket)
{
   var width = jQuery('.jScrollPaneContainer').width();
   var height = jQuery('.jScrollPaneContainer').height();
   
   jQuery('.jScrollPaneContainer').prepend(
      // '<div id="scoreboardDIV1" style="width: '+width+'px; height: '+height+'px; background-color: white; filter:alpha(opacity=25);opacity:0.25; position: absolute; top: 0px; left: 0px; z-index: 50000;"></div>' +
      '<div id="scoreboardDIV2" style="width: '+(width-2)+'px; height: '+(height-2)+'px; filter:alpha(opacity=100);opacity:1.0; border: 1px solid #ced6e3; background-color: white; position: absolute; top: 0px; left: 0px; z-index: 50001; padding: 0px;">' +
         '<p style="margin: 10px 10px;">Loading scoreboard...</p>' +
      '</div>');
      
   jQuery.ajax({
	   type: "GET",
	   url: "/images/newsite1024/feed/new-casino-lobby-feed.aspx",
	   data: "action=SCOREBOARD&tournamentid=" + TournamentId + "&round=" + Round + "&bracket=" + Bracket,
      cache: false,
      success: scoreboardResponse
	 });
	 
	 return false;
}

function scoreboardResponse(resp)  { 
   var title = jQuery('table:eq(0)',resp).html();
   var table = jQuery('table:eq(1)',resp).html();
    
    jQuery("#scoreboardDIV2").html('<div style="line-height: 25px; text-align: right; padding-right: 10px;"><a href="#" onclick="return removeScoreboard();">Close</a></div><div style="padding-left: 5px; padding-right: 5px;"><table class="header-table">' + title + '</table><table>' + table + '</table></div>');
}

function removeScoreboard() {
   jQuery("#scoreboardDIV1,#scoreboardDIV2").remove();
   return false;
}

function processHeadFeed(msg,success) {
   
   if(msg.indexOf("<!--NOTLOGGEDIN-->") == 0)
   {
	  //Also change our header...
	  jQuery("#casino-content .casino-lobby-header-feed1,#casino-content .casino-lobby-header-feed2").hide();
	  jQuery("#casino-content .casino-lobby-header-banner").css("background-image","url(/images/newsite1024/images/casino/lobby-header-background-vi.jpg)");
   }
   
   jQuery("table",msg).each(function(){

      if(this.className == "contest")
      {
         jQuery("tbody tr:eq(0),tbody tr:eq(1)",this).each(function(){

            if(jQuery(this).children().length > 2 && jQuery("td:eq(2)",this).html() != "Finished")
            {
               var fst = jQuery("td:eq(1)",this).html();
               fst = fst.split(/<br>/i); 
               var dt = fst[0]
               var desc = fst[1];
               var stat = jQuery("td:eq(2)",this).html();
               var time = jQuery("td:eq(3)",this).html();
                           
               if(jQuery('.casino-lobby-header-feed1 .title').html() == "" && 
                  jQuery('.casino-lobby-header-feed1 .description').html() == "" && 
                  jQuery('.casino-lobby-header-feed1 .extra').html() == "")
               {
                  //Update 1 DIV
                  jQuery('.casino-lobby-header-feed1 .title').html(stat);
                  jQuery('.casino-lobby-header-feed1 .description').html(dt);
                  jQuery('.casino-lobby-header-feed1 .extra').html(time);
                  
                  jQuery('.casino-lobby-header-feed1').css("cursor","pointer");
                  jQuery('.casino-lobby-header-feed1').click(function(){ self.location = '/casino/casino-tournaments.aspx'; });                                    
               }
            }
            else
            {
               var fst = jQuery("td:eq(0)",this).html();
               fst = fst.split(/<br>/i);
               var game = fst[0];
               var desc = fst[1];
                        
               if(jQuery('.casino-lobby-header-feed2 .title').html() == "" && 
                  jQuery('.casino-lobby-header-feed2 .description').html() == "" && 
                  jQuery('.casino-lobby-header-feed2 .extra').html() == "")
               {
                  //Update 2 DIV
                  jQuery('.casino-lobby-header-feed2 .title').html(game);
                  jQuery('.casino-lobby-header-feed2 .description').html(desc);
                  jQuery('.casino-lobby-header-feed2 .extra').html("");
                  
                  jQuery('.casino-lobby-header-feed2').css("cursor","pointer");
                  jQuery('.casino-lobby-header-feed2').click(function(){ self.location = '/casino/casino-tournaments.aspx'; });                                    
               }
            }

         });                
      }

   });

}

jQuery(document).ready(function(){
   
   //Grab the first 2 tournaments....
   jQuery.ajax({
	   type: "GET",
	   url: "/images/newsite1024/feed/new-casino-lobby-feed.aspx",
	   data: "catid=3&tabcode=LOBBYCAT_CONTEST",
	  cache: false,
	  success: processHeadFeed
	 }); 
   
});
