/*
christhomas123.co.uk - owzthat

Copyright (c) 2009 Chris Thomas
 
The MIT License

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/


// Douglas Crockford's Module Pattern
var OWZTHAT = function() {    
    var weHaveBeenInitOnce = false;
    var players = ["Stress", "Cake", "Bull", "Patterson", "Colander", "Previous", "Flinstone", "Wide", "Goose", "Hoggy", "Frontbottom"];
    var batting = [1, 4, 3, 2, 6, 0];
    var bowling = ["Bowled", "Caught", "Not Out", "Stumped", "L.B.W.", "No Ball"];
    var inningsScore = 0;
    var batsmanScore = 0;
    var batsman = '';
    var extras = 0;
    var wicket = 0;
    var lastScore = [];
    var lastHowOut = [];
    var loopCounter = 0;
    
    var _init = function() {
        if (!weHaveBeenInitOnce) {
            Event.observe(window, 'load', function() {
                Event.observe('bowl', 'click', OWZTHAT.bowl);
                Event.observe('reset', 'click', OWZTHAT.init);
            });
            weHaveBeenInitOnce = true;
        }   
                
        inningsScore = 0;
        batsmanScore = 0;
        extras = 0;
        wicket = 0;
        lastScore = [];
        lastHowOut = [];        
        batsman = players[wicket];
        $('bowl').disabled = false;
        $('bowl').focus();
                
        $('theAction').innerHTML = "";
        $('batsman').innerHTML = batsman;
        $('inningsScore').innerHTML = inningsScore;
        $('batsmanScore').innerHTML = batsmanScore;
        $('scorecard').innerHTML = "Scorecard:<br>";
        $('extras').innerHTML = extras;
        $('wicket').innerHTML = wicket;        
        $('scorecard').innerHTML = _buildScorecard();
    }
    
    // play the game!
    var _bowl = function() {
        $('bowl').disabled = true;
        
        // if they're all out, return - game over.
        if (wicket > 9) {
            return;
        }
        
        $('theAction').hide();
        Effect.Appear('theAction');
        _selectBattingAtRandom();
    }
    
    // Do we need to roll the bowling dice?
    var _checkForBowling = function(selectedBatting) {    
        if (selectedBatting > 0) {
            _doScores(selectedBatting, "Not Out");
        }
        else {
            $('theAction').innerHTML = '<span style="color: #FF0000;">"OWZTHAT?!"</span>';
            Effect.Pulsate('theAction');
            setTimeout(_selectBowlingAtRandom, 1000);
        }
    }
    
    // work out what happened and update stuff accordingly
    var _doScores = function(selectedBatting, selectedBowling) {
        // if runs are scored - update the runs...
        if (selectedBatting > 0) {
            batsmanScore += selectedBatting;
            inningsScore += selectedBatting;
            $('inningsScore').innerHTML = inningsScore;
            $('batsmanScore').innerHTML = batsmanScore;
            $('theAction').innerHTML = selectedBatting;
        }
        else {
            // ...if we rolled for a wicket...
            if (selectedBowling === "Not Out") {
                $('theAction').innerHTML = selectedBowling;
            }
            else if (selectedBowling === "No Ball") {
                extras += 1;
                inningsScore += 1;
                $('extras').innerHTML = extras;
                $('inningsScore').innerHTML = inningsScore;
                $('theAction').innerHTML = selectedBowling;
            }
            else {
                // ...umpire raises his finger!  That's out...
                lastScore[wicket] = batsmanScore;
                lastHowOut[wicket] = selectedBowling;
                
                wicket += 1;
                batsman = players[wicket];
                batsmanScore = 0;
                
                if (wicket > 9) {
                    $('wicket').innerHTML = 'All Out';
                    $('batsman').innerHTML = ''
                    $('batsmanScore').innerHTML = '';
                    $('theAction').innerHTML = "Game Over";     
                }
                else {
                    $('wicket').innerHTML = wicket;
                    $('batsman').innerHTML = batsman;
                    $('batsmanScore').innerHTML = batsmanScore;
                $('theAction').innerHTML = selectedBowling;     
                }
                           
                $('scorecard').innerHTML = _buildScorecard();
            }
        }
        $('bowl').disabled = false;
        $('bowl').focus();          // this enables 'return' or 'space' to play
    }
        
    // roll the batting dice and give a visual representation of 'randomness'...
    var _selectBattingAtRandom = function() {
        var selectedBatting = batting[Math.floor(Math.random() * batting.length)];
        $('theAction').innerHTML = selectedBatting > 0 ? selectedBatting : '.';
        loopCounter++;
        
        // (...these loop and timeout settings seem to give nice results, no particular reason otherwise...)
        if (loopCounter > 20) {
            loopCounter = 0;
            _checkForBowling(selectedBatting);
        }
        else {
            setTimeout(_selectBattingAtRandom, 40);
        }
    }

    // roll the bowling dice and give a visual representation of 'randomness'...
    var _selectBowlingAtRandom = function() {
        var selectedBowling = bowling[Math.floor(Math.random() * bowling.length)];
        $('theAction').innerHTML = selectedBowling;
        loopCounter++;
        
        // (...these loop and timeout settings seem to give nice results, no particular reason otherwise...)
        if (loopCounter > 16) {
            loopCounter = 0;
            _doScores(0, selectedBowling);
        }
        else {
            setTimeout(_selectBowlingAtRandom, 60);
        }
    }
    
    var _buildScorecard = function() {
        var scorecard = 'Scorecard: <br>';
        for (var i = 0; i < players.length; i++) {
            if (lastHowOut[i]) {
                scorecard += '    ' + players[i] + ' '.times(12 - players[i].length);
                scorecard += lastHowOut[i] + ' '.times(9 - lastHowOut[i].length);
                scorecard += ' '.times(5 - (' ' + lastScore[i]).length) + lastScore[i];
                scorecard += '<br>';
            }
            else {
                scorecard += '    ' + players[i] + '<br>';
            }
        }
        return scorecard;
    }
    
    return {
        init: _init,
        bowl: _bowl
    };
}();

OWZTHAT.init();
