// Video Poker JavaScript example
//
// Copyright 2004 -- MKSoft Development
// All rights reserved -- http://www.sinz.org/
//
// This is just for some fun and games with JavaScript
// and HTML 4
//

var MaxDraws = 1; // Number of draws per hand

var Payout = [
              ['Royal Flush',     250, 500,1000,2000,4000],
              ['Straight Flush',   50, 100, 200, 400, 800],
              ['Four of a Kind',   25,  50,  75, 100, 125],
              ['Full House',        9,  18,  27,  36,  45],
              ['Flush',             6,  12,  18,  24,  30],
              ['Straight',          4,   8,  12,  16,  20],
              ['Three of a Kind',   3,   6,   9,  12,  15],
              ['Two Pair',          2,   4,   6,   8,  10],
              ['Jacks or better',   1,   2,   3,   4,   5]
             ];

var MaxBet = Payout[0].length - 1;

var Styles = ["standard","small"];
var Suites = ['Spades','Hearts','Clubs','Diamonds'];
var CardID = ['','A','2','3','4','5','6','7','8','9','T','J','Q','K'];
var Cards = null;

var PayoutTable = document.getElementById('payout');
var CardArea = document.getElementById('cardarea');
var PlayCards = null;
var Deck = null;
var DeckPos = 0;
var InPlay = false;
var Expires = new Date();
Expires.setYear(Expires.getYear() + 1901);
var CookieExpires = '; expires=' + Expires.toGMTString();
var Bank = GetBank();
var Bet = 0;

InitDeck();         // Initialize the deck
InitStyles();       // Initialize the style
InitCards();        // Initialize the card playing area
InitPayoutTable();  // Initialize the payout table

// Show the card backs (initial display)
ShowCards();

// Start a new hand
DoHand();

function SetBetBank()
{
    SetBank(Bank);
    document.getElementById('bank').innerHTML = Bank;
    document.getElementById('bet').innerHTML = Bet;
}

function AddBet(num)
{
    for (bets = 0; bets < num; bets++)
    {
        if ((Bet < MaxBet) && (Bank > 0))
        {
            Bet++;
            Bank--;

            if (Bet == 1)
            {
                document.getElementById('action-deal').innerHTML = '<input type=button value="Deal" onclick="DoDeal()" />';
            }
        }
    }

    SetBetBank();

    if (!((Bet < MaxBet) && (Bank > 0)))
    {
        document.getElementById('action-bet').innerHTML = '<input type=button value="Bet" disabled /><input type=button value="Max" disabled />';
    }
}

function DoDeal()
{
    document.getElementById('action-bet').innerHTML = '';
    document.getElementById('action-deal').innerHTML = '';
    ShuffleDeck();
    DealDraw('DoDealDone(' + MaxDraws + ');');
}

function DoDealDone(count)
{
	count--;
    document.getElementById('action-bet').innerHTML = '<input type=button value="Stand" onclick="DoStand()" />';
    document.getElementById('action-deal').innerHTML = '<input type=button value="Draw" onclick="DoDraw(' + count + ')" />';
    InPlay = true;
}

function DoStand()
{
    // You can only stand if you have not thrown out any cards
    for (x=0; x < PlayCards.length; x++)
    {
        if (PlayCards[x].showback)
        {
            alert('You can not stand with less than 5 cards showing.');
            return;
        }
    }
    DoDraw1();
}

function DoDraw(count)
{
    // You can only draw if you have thrown out a card
    for (x=0; x < PlayCards.length; x++)
    {
        if (PlayCards[x].showback)
        {
            DoDraw1(count);
            return;
        }
    }
    alert('You must throw out at least 1 card to draw.');
}

function DoDraw1(count)
{
    InPlay = false;
    document.getElementById('action-bet').innerHTML = '';
    document.getElementById('action-deal').innerHTML = '';

	if (count > 0)
	{
		DealDraw('DoDealDone(' + count + ');');
	}
	else
	{
		DealDraw('DoPayout();');
	}
}

function SetPayout(hand)
{
    Bank += Payout[hand][Bet];
    document.getElementById('bankarea').innerHTML = '<span id="results">' + Payout[hand][0] + '&nbsp;-&nbsp;payed&nbsp;' + Payout[hand][Bet] + '</span>';
}

function cardSort(a,b)
{
    if (a == b)
    {
        return 0;
    }
    if ((a-0) < (b-0))
    {
        return -1
    }
    return 1;
}

function DoHand()
{
    // Flush the bet and the hand
    Bet = 0;
    FlushHand();

	// If you ran out of money...
	if (Bank < 1)
	{
		alert('You have run out of chips!  We are giving you a fresh set of 100 chips.');
		Bank = 100;
	}

    document.getElementById('bankarea').innerHTML = 'Bank:<span id="bank">-</span>&nbsp;&nbsp;&nbsp;&nbsp;Bet:<span id="bet">-</span>';
    document.getElementById('action-bet').innerHTML = '<input type=button value="Bet" onclick="AddBet(1)" /><input type=button value="Max" onclick="AddBet(' + MaxBet + ')" />';
    document.getElementById('action-deal').innerHTML = '<input type=button value="Deal" disabled />';
    SetBetBank();
}

// Flush out the cards in the hand...
function FlushHand()
{
    for (x=0; x < PlayCards.length; x++)
    {
        PlayCards[x].showback = true;
        PlayCards[x].face = 0;
        PlayCards[x].suite = 0;
        ShowCard(PlayCards[x]);
    }
}

// Deal new cards into the hand
function DealDraw(nextFunction)
{
    for (x=0; x < PlayCards.length; x++)
    {
        if (PlayCards[x].showback)
        {
            PlayCards[x].face = Deck[DeckPos].face;
            PlayCards[x].suite = Deck[DeckPos].suite;
            PlayCards[x].showback = false;
            ShowCard(PlayCards[x]);

            DeckPos++;
            if (DeckPos >= Deck.length)
            {
                DeckPos = 0;
            }

            // We did one card, so in a bit do another...
            if (nextFunction == undefined)
            {
                setTimeout('DealDraw();',200);
            }
            else
            {
                setTimeout('DealDraw("' + nextFunction + '");',200);
            }
            return;
        }
    }

    if (nextFunction != undefined)
    {
        setTimeout(nextFunction,200);
    }
}

// Initialize the deck (unshuffled)
function InitDeck()
{
    Deck = new Array();
    var x = 0;
    for (suite = 0; suite < Suites.length; suite++)
    {
        for (face = 1; face < CardID.length; face++)
        {
            Deck[x] = new Object();
            Deck[x].suite = suite;
            Deck[x].face = face;
            x++;
        }
    }
}

// This shuffles the deck - or at least tries to
function ShuffleDeck()
{
    var decksize = Deck.length;
    DeckPos = 0;

    for (loop = 0; loop < 7; loop++)
    {
        for (x = 0; x < decksize; x++)
        {
            var y = Math.floor(Math.random() * decksize);

            if (x != y)
            {
                var t = Deck[x];
                Deck[x] = Deck[y];
                Deck[y] = t;
            }
        }
    }
}

function InitStyles()
{
    style = GetCookie('CardStyle') - 0;
    if ((style >= Styles.length) || (style < 0))
    {
        style = 0;
    }

    loadCards(style);

    var tmp = 'Card&nbsp;Style:&nbsp;<select size=1 onchange="NewStyle(this.value)">';
    for (x=0; x < Styles.length; x++)
    {
        tmp += '<option value=' + x;
        if (x == style)
        {
            tmp += ' selected';
        }
        tmp += '>' + Styles[x] + '</option>';
    }
    tmp += '</select>';
    document.getElementById('styleselect').innerHTML = tmp;
}

function NewStyle(style)
{
    SetCookie('CardStyle',style);
    loadCards(style);
    ShowCards();
}

function OverCell(e)
{
    if (InPlay)
    {
        e.style.backgroundColor = "yellow";
    }
}

function DownCell(e)
{
    if (InPlay)
    {
        e.style.backgroundColor = "red";
    }
}

function UpCell(e)
{
    if (InPlay)
    {
        e.style.backgroundColor = "yellow";
    }
}

function OutCell(e)
{
    e.style.backgroundColor = "transparent";
}

function InitCards()
{
    var tmp = '<table cellspacing=0><tr>';
    for (x = 0; x < 5; x++)
    {
        tmp += '<td onmouseover="OverCell(this)" onmousedown="DownCell(this); CardClick(' + x + ')" onmouseup="UpCell(this)" onmouseout="OutCell(this)">';
        tmp += '<img id="card-' + x + '" src="blank.gif" />';
        tmp += '</td>';
    }
    tmp += '</tr></table>';
    CardArea.innerHTML = tmp;

    PlayCards = new Array();
    for (x=0; x<5; x++)
    {
        PlayCards[x] = document.getElementById('card-' + x);
    }

    FlushHand();
}

function ShowCard(card)
{
    card.src = ((card.showback) ? Cards[0][0].src : Cards[card.suite][card.face].src);
}

function CardClick(e)
{
    if (InPlay)
    {
        var card = PlayCards[e];
        card.showback = !card.showback;
        ShowCard(card);
    }
}

function ShowCards()
{
    for (i = 0; i < PlayCards.length; i++)
    {
        ShowCard(PlayCards[i]);
    }
}

function loadCards(style)
{
    var base = Styles[style] + '/';
    var back = new Image();

    back.src=base + 'back.gif';

    Cards = new Array();

    for (suite = 0; suite < Suites.length; suite++)
    {
        Cards[suite] = new Array();

        for (card = 0; card < CardID.length; card++)
        {
            if (CardID[card] == '')
            {
                Cards[suite][card] = back;
            }
            else
            {
                Cards[suite][card] = new Image();
                Cards[suite][card].src = base + Suites[suite] + '/' + CardID[card] + '.gif';
            }
        }
    }
}

function DoPayout()
{
    // Calculate any payout and display the results (updating the bank/etc
    var cards = new Array();
    var flushFlag = true;
    for (x = 0; x < PlayCards.length; x++)
    {
        flushFlag = flushFlag && (PlayCards[0].suite == PlayCards[x].suite);
        cards[x] = PlayCards[x].face;
    }
    cards.sort(cardSort);   // Sort the cards just to make things easier...

    // First, lets see if we have a Royal Straight
    if ((cards[0] == 1) &&
        (cards[1] == 10) &&
        (cards[2] == 11) &&
        (cards[3] == 12) &&
        (cards[4] == 13))
    {
        if (flushFlag)
        {
            SetPayout(0);   // 0 = royal flush
        }
        else
        {
            SetPayout(5);   // Just a straight
        }
    }
    else if ((cards[0] == (cards[1]-1)) &&
             (cards[1] == (cards[2]-1)) &&
             (cards[2] == (cards[3]-1)) &&
             (cards[3] == (cards[4]-1)))
    {
        if (flushFlag)
        {
            SetPayout(1);   // 0 = royal flush
        }
        else
        {
            SetPayout(5);   // Just a straight
        }
    }
    else if (flushFlag)
    {
        SetPayout(4);   // Just a flush
    }
    else if ((cards[1] == cards[2]) &&
             (cards[1] == cards[3]) &&
             ((cards[1] == cards[4]) || (cards[1] == cards[0])))
    {
        SetPayout(2);   // Four of a kind
    }
    else if ((cards[0] == cards[1]) &&
             (cards[3] == cards[4]) &&
             ((cards[2] == cards[1]) || (cards[2] == cards[3])))
    {
        SetPayout(3);   // Full House
    }
    else if (((cards[0] == cards[1]) && (cards[1] == cards[2])) ||
             ((cards[1] == cards[2]) && (cards[2] == cards[3])) ||
             ((cards[2] == cards[3]) && (cards[3] == cards[4])))
    {
        SetPayout(6);   // Three of a kind
    }
    else if (((cards[0] == cards[1]) && (cards[2] == cards[3])) ||
             ((cards[0] == cards[1]) && (cards[3] == cards[4])) ||
             ((cards[1] == cards[2]) && (cards[3] == cards[4])))
    {
        SetPayout(7);   // Two Pair
    }
    else if (((cards[0] == cards[1]) && ((cards[0] == 1) || (cards[0] > 10))) ||
             ((cards[1] == cards[2]) && ((cards[1] == 1) || (cards[1] > 10))) ||
             ((cards[2] == cards[3]) && ((cards[2] == 1) || (cards[2] > 10))) ||
             ((cards[3] == cards[4]) && ((cards[3] == 1) || (cards[3] > 10))))
    {
        SetPayout(8);   // Jacks or better
    }
    else
    {
        document.getElementById('bankarea').innerHTML = '<span id="results">Bust</span>';
    }

    document.getElementById('action-deal').innerHTML = '<input type=button value="Next Hand" onclick="DoHand()" />';
}

function InitPayoutTable()
{
    var tmp = '<table cellspacing=0><tr><th>Payout Table</th>';
    for (cols = 1; cols < Payout[0].length; cols++)
    {
        tmp += '<th>' + cols + '</th>';
    }
    tmp += '</tr>';

    for (rows = 0; rows < Payout.length; rows++)
    {
        tmp += '<tr onmouseover="this.style.background=\'maroon\'" onmouseout="this.style.background=\'orange\'">';
        tmp += '<th>' + Payout[rows][0] + '</th>';
        for (cols=1; cols<Payout[rows].length; cols++)
        {
            tmp += '<td>' + Payout[rows][cols] + '</td>';
        }
        tmp += '</tr>';
    }
    tmp += '</table>';
    PayoutTable.innerHTML = tmp;
}

function GetBank()
{
    var t = GetCookie('Bank');
    if ((t - 0) < 1)
    {
        t = 100;
        SetBank(t);
    }
    return(t);
}

function SetBank(money)
{
    SetCookie('Bank',money);
}

function GetCookie(name)
{
    var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;

    while (i < clen)
    {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg)
        {
            var endstr = document.cookie.indexOf (";", j);
            if (endstr == -1)
            {
                endstr = document.cookie.length;
            }
            return unescape(document.cookie.substring(j, endstr));
        }

        i = document.cookie.indexOf(" ", i) + 1;

        if (i == 0)
        {
            return null;
        }
    }
    return null;
}

function SetCookie(name, value)
{
    document.cookie = name + '=' + escape(value) + CookieExpires;
}



