

var _challengeObject;
var _challengePopup;

function Challenge()
{
}





Challenge.TilesLaidDown = function(words)
{
    var isBingo = ( tileLaidDown.length == 7 );

    _challengeObject = new Challenge();
    _challengeObject.play = currentPlayer.ScoreDetails( isBingo, words );

    // Build message, and list of raw words to be challenged.
    var str = "";
    var str2 = "";
    for (var inx = 0; inx < words.length; inx++)
    {
        var w = words[inx];
        if (inx > 0)
        {
            str+=", ";
            str2+="\n";
        }
        str += '"'+w.WordHTML+'"';
        str2 += w.WordText;
    }
    _challengeObject.wordsHTML = str;
    _challengeObject.wordsText = str2.toUpperCase();

    _challengeObject.wasMyPlay = Player.IsMyTurn();
    
    if ( !_challengePopup )
        _challengePopup = new PopUp({
            width: 400, 
            height: 200, 
            noCloseButton: true
        });

    _challengeObject.popUp = _challengePopup;
    _challengeObject.popUp.SetTitle( "Any Challenges?" );
    _challengeObject.popUp.SetPosition( PagePosition.Absolute( 200, 200 ) );
    _challengeObject.popUp.SetBody( 
currentPlayer.name+" played <span style='font-size:18pt;margin-left:25px'><xmp style='margin-left:25px'>\n"+_challengeObject.wordsText+"\n</xmp></span> Will score "+_challengeObject.play.totalScore+" ("+_challengeObject.wordsHTML+(isBingo?" BINGO!!!":"")+")<br>\n"+
"<table id=_tmp_ChallengeList style='margin-left:25px'></table>"
        );
    _challengeObject.popUp.Open();

    var tr = $("_tmp_ChallengeList").insertRow();
    tr.insertCell().innerHTML = "<B>Player&nbsp;&nbsp;&nbsp;</B>";
    tr.insertCell().innerHTML = "<B>Challenge?</B>";
    
    var choiceHash = {};
    for (var inx = 0; inx < Player._players.length; inx++)
    {
        var p = Player._players[inx];
        if ( p === currentPlayer )
            continue;

        var isMe = ( p === whoAmI );

        var tr = $("_tmp_ChallengeList").insertRow();
        tr.insertCell().innerHTML = p.name;
        var td = tr.insertCell();
        var yesSpan = AddNode( td, "SPAN" );
        yesSpan.innerHTML = "Yes&nbsp;";
        var yesRadio = AddNode( yesSpan, "<INPUT TYPE=RADIO NAME=_tmp_ChallengeList_"+inx+" VALUE='Y'>" );
        var noSpan = AddNode( td, "SPAN" );
        noSpan.innerHTML = "No&nbsp;";
        var noRadio = AddNode( noSpan, "<INPUT TYPE=RADIO NAME=_tmp_ChallengeList_"+inx+" VALUE='N'>" );
        
        if (isMe)
        {
            yesSpan.onclick = function()
            {
                yesRadio.disabled = true;
                noRadio.disabled = true;
                Action.Add("challengeChoice", "Y");
            };
            noSpan.onclick = function()
            {
                yesRadio.disabled = true;
                noRadio.disabled = true;
                Action.Add("challengeChoice", "N");
            };
        }
        else
        {
            yesRadio.disabled = true;
            noRadio.disabled = true;
        }
        
        choiceHash[ p.name ] = [ yesRadio, noRadio ];
    }

    _challengeObject.yesCount = 0;
    _challengeObject.noCount = 0;
    _challengeObject.choiceMade = false;
    _challengeObject.choiceHash = choiceHash;
    _challengeObject.challengers = {};

    if (_challengeObject.wasMyPlay)
    {
        // Give the other players 15 secs to respond.
        _challengeObject.intervalID = setInterval( function()  
            {
                _challengeObject._ChoiceMade();
            }, 15 * 1000 );
    }
}

Challenge.prototype.ChallengeChoice = function( playerName, yesNo )
{
    var radioButtons = this.choiceHash[playerName];
    if (yesNo == "Y")
    {
        this.yesCount++;
        this.challengers[ playerName ] = true;
        radioButtons[0].checked = true;
        radioButtons[1].checked = false;
    }
    else
    {
        this.noCount++;
        radioButtons[0].checked = false;
        radioButtons[1].checked = true;
    }

    // If all choices are in (i.e. every player, except the guy who just laid down, have responded)...
    if ( (this.yesCount+this.noCount)+1 == Player._players.length )
        this._ChoiceMade();
}
Challenge.prototype._ChoiceMade = function()
{
    if (this.choiceMade)
        return;

    clearInterval( this.intervalID );
    
    var isChallenge = (this.yesCount > 0);

    // Freeze choice-making now.  The choice-maker (the player that laid down) could get a late
    // choice from the network.  The only possibly affect of that would be for the player to get his
    // name added to an already existing list of challengers.  But if there were no challengers,
    // and the late choice is a challenge, it does not affect us.  We've assumed no-challenge at 
    // this point.
    this.choiceMade = true;
    var playerName;
    for ( playerName in this.choiceHash )
    {
        var radioButtons = this.choiceHash[playerName];
        radioButtons[0].disabled = true;
        radioButtons[1].disabled = true;
    }

    // Take Action
    if ( this.wasMyPlay )
    {
        if (isChallenge)
        {   
            // A Challenge
            CallbackText(root+"ServerBus.aspx", "checkWordList\n"+this.wordsText, function (rspTxt)
            {
                if (rspTxt == "true") // all words okay
                    Action.Add("challengeOutcome", "FAILED");
                else
                    Action.Add("challengeOutcome", "SUCCESS");
            });
        }
        else
        {   // No Challenge

            // It is important for the 1 decider (the player that laid down) to be the only
            // one with a timeout.  In the event that he did timeout, he'll make a decision,
            // which could be "no-challenge".  Late "challenge" choices might arrive to the
            // other players, so they will not close themselves (because they think the decision was
            // to challenge).  In this event, the decider must send out an explicit "no-challenge" outcome.
            var allVotesCounted = ((this.yesCount+this.noCount)+1 == Player._players.length);
            if (allVotesCounted)
                this._PlaySuccess();
            else
                Action.Add("challengeOutcome", "NONE");
        }
    }
    else
    {
        if (isChallenge)
        {   
            // Challenge.  Wait for the "challengeOutcome" action (which comes from the player who laid down).
        }
        else
        {   // No Challenge.  Pause 1 sec, to show last person's click.
            var _this = this;
            setTimeout( function()
                {
                    _this._PlaySuccess();
                }, 1000 );
        }
    }
}

Challenge.prototype.ChallengeOutcome = function( status )
{
    if ( status == "FAILED" )
    {
        // Challengers are penalized.
        var challengersTxt = "";
        var challenger;
        for ( challenger in this.challengers )
        {
            if (challengersTxt.length > 0)
                challengersTxt += ", ";
            challengersTxt += challenger;
            var p = Player.Get( challenger );
            p.LoseNextTurn();
        }
        this.popUp.SetBody("Challenge fails!  (i.e. all words played are valid according to OWL2).  "+challengersTxt+" "+(this.challengers==1?"":"each ")+"lose a turn.");

        var _this = this;
        setTimeout( function()
            {
                _this._PlaySuccess();
            }, 1500 );
    }
    else if ( status == "SUCCESS" ) 
    {
        // Current Player had a bad word.  Misses next turn.
        this.popUp.SetBody("Challenge succeeds!  "+currentPlayer.name+" loses a turn.");
        currentPlayer.LoseNextTurn();
        var _this = this;
        setTimeout( function()
            {
                _this._PlayFailed();
            }, 1500 );
    }
    else if ( status == "NONE" ) 
    {
        this._PlaySuccess();
    }
    else
        debugger;
}
Challenge.prototype._PlaySuccess = function() // either no-challenge, or words are okay
{
    Board.Lay(tileLaidDown);
    tileLaidDown = [];
    scorelessTurnCount = 0;

    this.popUp.Close();
    currentPlayer.SuccessfulPlay( this.play );
    currentPlayer.ShowMessage( "Played "+this.wordsHTML+" for "+this.play.totalScore+"."+(this.play.isBingo?"  BINGO!!!":"") );
    _challengeObject = null;
    currentPlayer.EndTurn();
}
Challenge.prototype._PlayFailed = function() // words were bad, and someone challenged
{
    Action.UndoAllTiles();

    this.popUp.Close();
    currentPlayer.ShowMessage( "Was challenged." );
    _challengeObject = null;
    currentPlayer.EndTurn();
}


