﻿// Lobby javascript file.
var reqwestHandler=null; // autoThrow handler.
var open_requests;
var room;
var me;
var page=1;
var page_shift=0;
var games_hnd = new Array();
var canCreateGame=false;
var temp,j;
var counter=0;
var total_games=0;
var game=0;
var isIE = (window.navigator.userAgent.indexOf("MSIE") > 0);
var mygame="";
var create_g = false;
var winW, winH ;
var xGames = true;
var dataBindHandler=null;

if (! isIE) {
  HTMLElement.prototype.__defineGetter__("innerText", 
              function () { return(this.textContent); });
  HTMLElement.prototype.__defineSetter__("innerText", 
              function (txt) { this.textContent = txt; });
}

window.onresize = on_resize;

// This function fills games table.
function dataBind()
{   
    // Get Games.
    BackGammonService.GetLobbyGames(room,me,page,OnGetLobbyGamesComplete,OnError,OnTimeout);
}

// Creates a new game request.
function CreateNewGame()
{
    create_g = true;
    if (room!=myRoom)
    {
        room=myRoom;
        if (canCreateGame)
        {
            document.getElementById("CreateRoom").value=room;
            document.getElementById("CreateGameForm").style.display="";
            document.getElementById("newGame").style.display="none";
            // Set CreateGameForm position.
            on_resize();
        }
        //LblRoom_click(1);
    }
    else
    {
        document.getElementById("CreateRoom").value=room;
        document.getElementById("CreateGameForm").style.display="";
        document.getElementById("newGame").style.display="none";
        create_g=false;
        on_resize();
    }
}

// Create game accept.
function BtnOk_click()
{
    // Create game.
    document.getElementById("CreateGameForm").style.display="none";
    document.getElementById("newGame").style.display="none";
    BackGammonService.CreateGame(me,document.getElementById("CreateRoom").value,document.getElementById("EnableGameDouble").checked,document.getElementById("EnableFastGame").checked,document.getElementById("NumberOfGames").value,function(){},OnError,OnTimeout);
    dataBind();
}

function BtnCancel_click()
{
    document.getElementById("CreateGameForm").style.display="none";
    document.getElementById("newGame").style.display="";
    on_resize();
}

// Handles buttonExit click.
function btnExit_Click(id)
{
    // Remove game.
    BackGammonService.RemoveGame(MyRoom,id,me,function(){},OnError,OnTimeout);
    dataBind();
}

// Handles NumberOfGames changed.
function NumberOfGames_changed()
{
    if (isNaN(document.getElementById("NumberOfGames").value))
        document.getElementById("NumberOfGames").value=1;
    if (document.getElementById("NumberOfGames").value > 9)
        document.getElementById("NumberOfGames").value=9;
    if (document.getElementById("NumberOfGames").value < 1)
        document.getElementById("NumberOfGames").value=1;
}

function FillRow(i,params)
{
    // add command button.
    if (me==params.player1 || me==params.player2)
    {
        // command button is exit or enter.
        if (params.status==2)
        {
            document.getElementById("BtnCmd"+i).innerText=enterCaption;
            document.getElementById("BtnBg"+i).style.backgroundColor="#f46902";
        }
        else
        {
            document.getElementById("BtnBg"+i).style.backgroundColor="#c6ff1b";
            document.getElementById("BtnCmd"+i).innerText=exitCaption;
            mygame=params.id;
        }
    }
    else if (params.player2=="")
    {
        // join command.
        document.getElementById("BtnCmd"+i).innerText=joinCaption;
        document.getElementById("BtnBg"+i).style.backgroundColor="#f46902";
    }
    else
    {
        // view command.
        document.getElementById("BtnCmd"+i).innerText=viewCaption;
        document.getElementById("BtnBg"+i).style.backgroundColor="#4383b7";
    }
    document.getElementById("GameId" + i).innerText=params.id;
    document.getElementById("Player1Country" + i).src="Images/Flags/" + params.Player1country + ".jpg"; 
    document.getElementById("Player1Country" + i).style.display = "";
    document.getElementById("Player1Rank" + i).innerText=params.Player1rank;
    document.getElementById("Player1Name" + i).innerText=params.nick1;
    document.getElementById("Player1Link" + i).href="Member.aspx?code="+params.Player1Id;
    if (params.status<2)
    {
        // no oponent.
        document.getElementById("PanelPlayer2Game" + i).style.display = "none";
        document.getElementById("PanelParamsGame" + i).style.display = "";
        document.getElementById("Player2Rank" + i).innerText = "";
        document.getElementById("Player2Name" + i).innerText = "";
        document.getElementById("Player2Game" + i).innerText = strgames + " " + params.stages + " ";
        document.getElementById("Player2Star" + i).style.display = "";
        if (params.Player1stars==0)
        {
            document.getElementById("Player2Star" + i).style.display = "none";
            document.getElementById("Player2Star" + i).title = "";
        }
        else
        {
            document.getElementById("Player2Star" + i).src = "Images/stars/" + params.Player1stars + "starsmall.gif";
            document.getElementById("Player2Star" + i).title = strAband + ": " + params.Player1Abadonment + "%";
            //document.getElementById("Player2Star" + i).style.display = "none";
        }
//        if (params.doubleing)
//        {
//            document.getElementById("Player2Game" + i).innerText += strwithdoubleing;
//        }
//        else
//        {
//            document.getElementById("Player2Game" + i).innerText += strwithoutdoubleing;
//        }
    }
    else
    {
        // there is an oponent.
        document.getElementById("PanelPlayer2Game" + i).style.display = "";
        document.getElementById("PanelParamsGame" + i).style.display = "none";
         document.getElementById("Player2Game" + i).innerText = "";
        document.getElementById("Player2Rank" + i).style.display = "";
        document.getElementById("Player2Name" + i).style.display = "";
        document.getElementById("vs" + i).innerText = "-v.s-";
        document.getElementById("Player2Country" + i).src="Images/Flags/" + params.Player2country + ".jpg"; 
        document.getElementById("Player2Country" + i).style.display = "";
        document.getElementById("Player2Rank" + i).innerText=params.Player2rank;
        document.getElementById("Player2Name" + i).innerText=params.nick2;
        document.getElementById("Player2Link" + i).href="Member.aspx?code="+params.Player2Id;
    }
}

function ClearRow(i)
{
    // Clear row.
    document.getElementById("BtnCmd" + i).innerText=" ";
    document.getElementById("GameId" + i).innerText=" ";
    document.getElementById("Player1Country" + i).style.display = "none";
    document.getElementById("Player1Rank" + i).innerText=" ";
    document.getElementById("Player1Name" + i).innerText="";
    document.getElementById("Player1Link" + i).href="#";
    document.getElementById("vs" + i).innerText =" ";
    document.getElementById("Player2Country" + i).style.display = "none";
    document.getElementById("Player2Rank" + i).innerText=" ";
    document.getElementById("Player2Name" + i).innerText="";
    document.getElementById("Player2Link" + i).href="#";
    document.getElementById("BtnBg"+i).style.backgroundColor="#7592ba";
    document.getElementById("Player2Game" + i).innerText="";
    document.getElementById("Player2Game" + i).display="none";
    document.getElementById("Player2Star" + i).style.display = "none";
}



function Command_click(id)
{
    if (document.getElementById("BtnCmd"+id).innerText==joinCaption)
    {
        // Joining game.
        for (i=0;i<games_hnd.length;i++)
        {
            if (games_hnd[i]!=null && games_hnd[i].closed)
                games_hnd[i]=null;
            if (games_hnd[i]!=null && games_hnd[i].id==document.getElementById("GameId" + id).innerText)
            {
                // already exist.
                return;
            }
        }
        
        var ga=document.getElementById("GameId" + id).innerText;
        
        if(xGames)
        {
            // Open agreement window.
            games_hnd[games_hnd.length]=window.open('Agreement.aspx?code=' + document.getElementById("GameId" + id).innerText + '&player=' + me + '&room=' + room,"_blank","height=585,width=800,top=10,left=10,status=yes,toolbar=no,menubar=no,titlebar=no,location=no");
            BackGammonService.CreateGameRequest(myId,room,document.getElementById("GameId" + id).innerText,myRoom,mygame,me,function(){},OnError,OnTimeout);
            //BackGammonService.chkCountTurs(document.getElementById("GameId" + id).innerText,myId,GetTurs)
        }
    }
    else if (document.getElementById("BtnCmd"+id).innerText==exitCaption)
    {
        // Removing game.
        BackGammonService.RemoveGame(myRoom,document.getElementById("GameId" + id).innerText,me,function(){},OnError,OnTimeout);
        mygame="";
        game=0;
    }
    else if (document.getElementById("BtnCmd"+id).innerText==enterCaption)
    {
        // Entering open game.
        // Check if not opened.
        for (i=0;i<games_hnd.length;i++)
        {
            if (games_hnd[i]!=null && games_hnd[i].closed)
                games_hnd[i]=null;
            if (games_hnd[i]!=null && games_hnd[i].gameId==document.getElementById("GameId" + id).innerText)
            {
                // already exist.
                return;
            }
        }
        games_hnd[games_hnd.length] = window.open('Game.aspx?code=' + document.getElementById("GameId" + id).innerText + '&room=' + room,"_blank","height=585,width=800,top=10,left=10,status=yes,toolbar=no,menubar=no,titlebar=no,location=no");
    }
    else if (document.getElementById("BtnCmd"+id).innerText==viewCaption)
    {
        // Check if not opened.
        for (i=0;i<games_hnd.length;i++)
        {
            if (games_hnd[i]!=null && games_hnd[i].closed)
                games_hnd[i]=null;
            if (games_hnd[i]!=null && games_hnd[i].gameId==document.getElementById("GameId" + id).innerText)
            {
                // already exist.
                return;
            }
        }
        games_hnd[games_hnd.length] = window.open('Game.aspx?code=' + document.getElementById("GameId" + id).innerText + '&room=' + room,"_blank","height=585,width=800,top=10,left=10,status=yes,toolbar=no,menubar=no,titlebar=no,location=no");
    }
    else
    {
       // No command.
       // alert (document.getElementById("GameId" + id).innerText);
    }
    dataBind();
}

function BtnAccept_click()
{
    // Open new window.
    BackGammonService.AcceptRequest(myRoom,document.getElementById("RequestGame").value,document.getElementById("RequestKey").value,me,document.getElementById("RequesterId").value,function(){},OnError,OnTimeout);
    document.getElementById("Request").style.display="none";
    clearInterval(reqwestHandler);
    // Check if not opened.
    for (i=0;i<games_hnd.length;i++)
    {
        if (games_hnd[i]!=null && games_hnd[i].closed)
            games_hnd[i]=null;
        if (games_hnd[i]!=null && games_hnd[i].id==document.getElementById("GameId" + document.getElementById("GameId" + id).innerText).innerText)
        {
            // already exist.
            return;
        }
    }
    games_hnd[games_hnd.length] = window.open('Game.aspx?code=' + document.getElementById("RequestGame").value,"_blank","height=585,width=800,top=10,left=10,status=yes,toolbar=no,menubar=no,titlebar=no,location=no");
}

function BtnDecline_click()
{
    // Decline request.
    BackGammonService.DeclineRequest(myRoom,document.getElementById("RequestGame").value,document.getElementById("RequestKey").value,me,function(){},OnError,OnTimeout);
    document.getElementById("Request").style.display="none";
    clearInterval(reqwestHandler);
    BackGammonService.chkCountTurs(document.getElementById("RequestGame").value,'1',GetTurs)  
}

function LblRoom_click(id)
{
    if (room==6)
    {
        room=1;
    }
    document.getElementById("RoomBckGrndLeft1").style.backgroundImage="url(Images/TAGS_LEFT.jpg)";
    document.getElementById("RoomBckGrndMid1").style.backgroundImage="url(Images/TAGS_MIDLE.jpg)";
    document.getElementById("RoomBckGrndRight1").style.backgroundImage="url(Images/TAGS_RIGHT.jpg)";
    document.getElementById("RoomBckGrndLeft" + (room+1)).style.backgroundImage="url(Images/TAGS_LEFT.jpg)";
    document.getElementById("RoomBckGrndLeft" + id).style.backgroundImage="url(Images/TAGS_DN_LEFT.jpg)";
    document.getElementById("RoomBckGrndMid" + (room+1)).style.backgroundImage="url(Images/TAGS_MIDLE.jpg)";
    document.getElementById("RoomBckGrndMid" + id).style.backgroundImage="url(Images/TAGS_DN_MIDLE.jpg)";
    document.getElementById("RoomBckGrndRight" + (room+1)).style.backgroundImage="url(Images/TAGS_RIGHT.jpg)";
    document.getElementById("RoomBckGrndRight" + id).style.backgroundImage="url(Images/TAGS_DN_RIGHT.jpg)";
    if (id==1)
    {
        room=6;
    }
    else
    {
        room=(id-1);
    }
    document.getElementById("newGame").style.display="none";
    dataBind();
}


//////////////////////////////// A J A X   F U N C T I O N S ///////////////////////////////////////////

// GetRequests handler.
function OnGetRequestsComplete(users)
{
    // users - array of requests.
    if (users)
    {
        if (document.getElementById("Request").style.display=="none")
        {
            // Agreement is not opened.
            document.getElementById("RequestName").innerText=users[0].playerName + "\n";
            document.getElementById("RequestLink").href="Member.aspx?code=" + users[0].player;
            document.getElementById("Gamemessage").innerText = requestMsgStr +"\n" + requestRankStr + " " + users[0].oponentRank;
            //document.getElementById("Quality").innerText = requestStarStr + " ";
            document.getElementById("QualityStars").style.display="";
            document.getElementById("QualityStars").title = strAband + ": " + users[0].oponentAbandonment + "%";
            document.getElementById("QualityStars").src="Images/stars/" + users[0].oponentStars + "star.gif";
            document.getElementById("RequestRoom").value=room;
            document.getElementById("RequestGame").value=users[0].id;
            document.getElementById("RequestKey").value=users[0].key;
            document.getElementById("RequesterId").value=users[0].player;
            document.getElementById("Request").style.top="120px";
            document.getElementById("Request").style.left="220px";
            document.getElementById("Request").style.display="";
            on_resize();
             //yossi close game reqwest after 1 minut
            reqwestHandler=setInterval(this.BtnDecline_click,60000);
            //BackGammonService.chkCountTurs(users[0].id,users[0].player,GetTurs)  
        }
    }
}
//Check if the turs<10 then allow the send req. else close the game.
function GetTurs(rcount)
{
   if(rcount.split(";")[0]=='0')
   {
    try
    {
        //this.BtnDecline_click()
        BackGammonService.RemoveGame(myRoom,rcount.split(";")[1],me,function(){},OnError,OnTimeout);
        canCreateGame=true;
    }catch(e){};
    mygame="";
    game=0;
    xGames = false;
    return false;
   } 
   else
   {
    xGames = true;
    return true;
   }
}

// GetLobbyGames CallBack.
function OnGetLobbyGamesComplete(result)
{
    counter++;
    if(result.games)
    {
        //document.getElementById("debug").innerText=counter+" "+result.length;
        for (i=0;i<result.games.length;i++)
        {
            if (!result.games[i].player2 && me==result.games[i].player1)
            {
                // Hide create new game button.
                canCreateGame=false;
            }  
            if (result.games[i].status==1 && me==result.games[i].player1)
            {
                // There are requests for the game.
                //BackGammonService.GetRequests(room,result[i].id,OnGetRequestsComplete,OnError,OnTimeout);
                game=result.games[i].id;
            }           
        }
    }
    else
    {   
        //document.getElementById("debug").innerText=counter+" 0";
    }
    
    if (game!=0)
    {
        BackGammonService.GetRequests(myRoom,game,OnGetRequestsComplete,OnError,OnTimeout);
    }    
    if (!document.getElementById("newGame")) return;  
    create_paging(result.tabs);
    
        
    // Bind to the games table.
    if (result.games && result.games.length)
    {
        // sort games.
//        for (i=0;i<result.games.length;i++)
//        {  
//           for (j=0;j<result.games.length-1;j++)
//            {
//                //alert(result[j+1].player1);
//                if (result.games[j+1].status==1 || result.games[j+1].status==0)
//                {
//                    // swap.
//                    temp=result.games[j];
//                    result.games[j]=result.games[j+1];
//                    result.games[j+1]=temp;
//                }
//                if ((result.games[j+1].player1==me || (!result.games[j+1].player2 && result.games[j+1].player2==me)) &&  result.games[j].player1!=me &&  result.games[j].player2!=me)
//                {
//                    // swap
//                    temp=result.games[j];
//                    result.games[j]=result.games[j+1];
//                    result.games[j+1]=temp;
//                }
//                if (result.games[j+1].player1==me && (result.games[j+1].status==1 || result.games[j+1].status==0))
//                {
//                    // swap
//                    temp=result.games[j];
//                    result.games[j]=result.games[j+1];
//                    result.games[j+1]=temp;
//                }
//            }
//        }
        
        total_games=0;
        for (i=0;i<result.games.length;i++)
        {
            if (result.games[i].room==room)
            {
                total_games++;
            }
        }
        
//        if ((page-1)>parseInt((total_games-1)/15))
//            page=parseInt((total_games-1)/15)+1;
        
       
        for (i=0;i<16;i++)
        {
            //addRow(result[i]);
            if (result.games && i<result.games.length && result.games[i].room==room)
            {
                // Fill row.
                FillRow(i+1,result.games[i]);
            }
            else
            {
                // Clear row.
                ClearRow(i+1);
            }
        }
        
        //if (room==myRoom)
            canCreateGame=true;  
//        else
//            canCreateGame=false;
        
        
    }
    else
    {
        // Clear room.
        for (i=0;i<16;i++)
            ClearRow(i+1);
        //if (room==myRoom)
            canCreateGame=true;  
//        else
//            canCreateGame=false;
    }
    
    if (result.has_game)
    {
        canCreateGame=false;
    }
    
    if (canCreateGame)
    {
        //if (canCreateGame)
        //{
//            document.getElementById("CreateRoom").value=room;
//            document.getElementById("CreateGameForm").style.display="";
//           document.getElementById("newGame").style.display="none";
            create_g=false;
        //}
        //else
        //{
            document.getElementById("newGame").style.display="";
        //}
    }
    else
    {
        document.getElementById("newGame").style.display="none";
    }
    
}

function OnError()
{
    alert("Server request error.");
}

function OnTimeout()
{
    alert("Server request timeout.");
}

////////////////////////////////////////////////////////////////////////////////////////////////////////


function create_paging(count)
{
    var i;
    var tr = document.getElementById("pages");
    clear_row(tr);
    //if (parseInt((total_games-1)/15)==0) return;
   
      
    if (page>count+1)
    {
        page=count+1;
    }
    if (count>20 && page_shift>count-19)
    {
        page_shift=count-18;
    }
    if (count==0) return;
    var td = tr.insertCell(0);
    td.style.height="20px"
    if (page_shift>0)
    {
        td.innerHTML = "<span style='cursor: hand; cursor: pointer;' onclick='page_shift_back_click(" + count + ");'><<</span>";
    }
    for (i=page_shift;i<=count && i<(20+page_shift);i++)
    {
        td = tr.insertCell(i+1-page_shift);
        td.style.height="20px"
        if ((i+1)==page)
        {
            td.innerHTML = "<u><span style='cursor: hand; cursor: pointer;' onclick='page_click(" + (i+1) + ");'>" + (i+1) + "</span></u>";
        }
        else
        {
            td.innerHTML = "<span style='cursor: hand; cursor: pointer;' onclick='page_click(" + (i+1) + ");'>" + (i+1) + "</span>";
        }
        
    }
    if (count>20 && i<count)
    {
        td = tr.insertCell(21);
        td.style.height="20px"
        td.innerHTML = "<span style='cursor: hand; cursor: pointer;' onclick='page_forward_back_click(" + count + ");'>>></span>";
    }
  
}

function page_click(id)
{
    page=id;
    page_shift=0;
    dataBind();
}

function page_shift_back_click(count)
{
    page_shift--;
    create_paging(count);
}

function page_forward_back_click(count)
{
    page_shift++;
    create_paging(count);
}

function clear_row(obj)
{
    var i;
    while (obj.cells.length>0)
    {
        obj.deleteCell(0);
    }
}

function get_window_size()
{
    if (parseInt(navigator.appVersion)>3) 
    {
        if (navigator.appName=="Netscape") 
        {
            winW = window.innerWidth;
            winH = window.innerHeight;
        }
        if (navigator.appName.indexOf("Microsoft")!=-1) 
        {
            winW = document.body.offsetWidth;
            winH = document.body.offsetHeight;
        }
    }
}

function on_resize()
{
    get_window_size();
    var l;
    if (document.getElementById("CreateGameForm"))
    {
        l= parseInt(document.getElementById("CreateGameForm").style.width) ;
        document.getElementById("CreateGameForm").style.left = (winW / 2 - l / 2) + "px";
    }
    l= parseInt(document.getElementById("Request").style.width) ;
    document.getElementById("Request").style.left = (winW / 2 - l / 2) + "px";
}