////////////////////////////////////////////////////////
// poker.js
// copyright Chris Johnson chriso@people.net.au
// JavaScript
///////////////////////////////////////////////////////

var hand = new Array(5)             // Current Hand
var noBet = false;                  // No Bet Flag
var gamestatus;                     //  Tells whether new deal or not
var bet        = 0;                 //  Holds the amount to bet
var winnings   = 100;               //  Holds winnings
var maxbet     = 50;                // Maximin Bet
var cardvals   = new Array(5);      //  Holds values of dealt cards
var src = "Cards/cardSkin.png";     //  Store image for back of cards
var won = 0;
//  Compare function for sorting the cards

function compare(a, b) {
    return a-b;
}

    
//  Checks for winnings

function checkwin() {
    var suits = new Array(4);         //  To check for a flush
    var matched = new Array(13);      //  To check for pairs, threes, fours
    var pairs = 0, threes = 0, fours = 0;
    var flush = false, straight = false;
    var info;
  won=0;


    cardvals.sort(compare);           //  Sort the cards

    for ( var i = 0; i < 4; i++ ) {
        suits[i] = 0;                 //  Initialise suits array to zero
    }

    for ( var i = 0; i < 13; i++ ) {
        matched[i] = 0;               //  Initialise matched array to zero  
    }

    for ( var i = 0; i < 5; i++ ) {
        matched[cardvals[i] % 13]++;            //  Update matched for cards
        suits[Math.floor(cardvals[i]/13)]++;    //  Update suits for cards
    }


    //  Check for pairs, threes and fours

    for ( var i = 0; i < 13; i++ ) {
        if ( matched[i] == 2 ) {
            pairs++;
        }
        else if ( matched[i] == 3 ) {
            threes++;
        }
        else if ( matched[i] == 4 ) {
            fours++;
        }
    }


    //  Check for a flush

    for ( var i = 0; i < 4; i++ ) {
        if ( suits[i] == 5 ) {
            flush = true;
        }
    }

    if ( cardvals[4] - cardvals[1] == 3  &&              //  Consistent with 
         cardvals[4] - cardvals[0] == 12 &&              //  A, T, J, Q, K...
         flush ) {        //  If we also have a flush, then its a royal flush
        info= "Royal flush!";
        won = bet * 2500;
    }
    else if ( cardvals[4] - cardvals[0] == 4 && flush ) {
        info = "Straight flush!";
        won = bet * 250;
    }


    //  Sort cards by face value (necessary to check for a straight)

    for ( var i = 0; i < 5; i++ )
        cardvals[i] = cardvals[i] % 13;
    cardvals.sort(compare);


    if ( won == 0 ) {           // Don't check further if we've already won
        if ( fours > 0 ) {
            info= "Four of a kind!";
         won = bet * 100;
        }
        else if ( threes == 1 && pairs == 1 ) {
            info = "Full house!";
            won = bet * 50;
        }
        else if ( flush ) {
            info = "A flush!";
            won = bet * 20;
        }
        else if ( cardvals[4] - cardvals[0] == 4 && pairs == 0) {
            info = "A straight!";
            won = bet * 15;
        }
        else if ( threes > 0 ) {
            info = "Three of a kind!";
            won = bet * 4;
        }
        else if ( pairs == 2 ) {
            info = "Two pair!";
            won = bet * 3;
        }
        else if ( matched[0]  == 2 ||
                  matched[10] == 2 ||             
                  matched[11] == 2 ||             
                  matched[12] == 2 ) {
            info = "Jacks or better!";
            won = bet * 2;
        }
        else {
            info = "No win! Bad luck!";
        }
    }


    //  Update winnings if we've won

    if ( won > 0 ) {
        winnings += won;
        info += " You win $" + won + "!";
    }   
     noBet=false;
     return info;
}




//**** Silverlight Functions****

//***Events
function onPokerLoaded(sender,e)
{
    Shuffle();
    gamestatus='a';
   // var mp = sender.findName("introSnd")
    //mp.Play()

}


// Arrow button on the bet control
function onarrowMouseDown(sender, e)
{
  if(sender.Name == "uparrow")
  
  {
    sender.Source="Cards/upArrowY.png";
  }
  else
  {
    sender.Source="Cards/downArrowY.png";
  }
  
   
}

function onMouseArrowUp(sender, e)
{
  if(sender.Name == "uparrow")
  
  {
    sender.Source="Cards/upArrow.png";
    if ((winnings > 10), (bet < maxbet))
        {
        var snd=sender.findName("cashsound")
            snd.Stop();
            snd.Play();
            winnings = winnings-10; //Take 10 of the winnings
            bet= bet+10; // Add it to the bet
            var BetText = sender.findName("BetText");
            BetText.Text= '$' + bet + '.00';
            var WinText= sender.findName("WinText");
            WinText.Text= "Winnings $" + winnings + '.00';
            noBet= true;
        }
      else
      {
        alert("You have made a maximin bet or no more money to bet with.")
      }
  }
  else
  {
    sender.Source="Cards/downArrow.png";
     if (bet >10)
        {
          var snd=sender.findName("cashsound")
            snd.Stop();
            snd.Play();
            winnings = winnings+10; //Take 10 of the winnings
            bet= bet-10; // Add it to the bet
            var BetText = sender.findName("BetText");
            BetText.Text= '$' + bet + '.00';
            var WinText= sender.findName("WinText");
            WinText.Text= "Winnings $" + winnings + '.00';
            
            if (bet == 0) {
            noBet=true;
            alert("You must make a bet to play")
            }
        }
      else
      {
        alert("No Bet")
      }
  }
}


//Play Button
function onPlayButtonDown(sender , eventArgs)
    {
        sender.Fill="Red";
        var betTxt = sender.findName("BetText")
        if (betTxt.Text == '$0.00')
        {
        alert("you must place a bet first")
        noBet=false;
        
        }
        else
        { 
            noBet=true;
        }
    }
    
function onPlayButtonUp(sender, e)
{
        sender.Fill="DarkGray";
    //    currentSilverLight=sender;
        if (noBet)
        {
        var snd=sender.findName("dealsound")
        snd.Stop();
        snd.Play();
        deal(sender);
        }
  if (!gamestatus == 1)
  {      
    var msg = sender.findName("message")
    
    msg.Text="Click on cards to  discard and hit play to redeal";
    }
}
//****Cards cicked****
function onCardMousedown(sender,e)
{
   
    
}

/// card click
function onCardMouseUp(sender,e)
{
 var snd=sender.findName("cardsound")
     snd.Stop();
     snd.Play();
    var k = parseInt(sender.Name.substr(4,1))
    var cName = sender.findName('c' +k)
      
    if( hand[k].IsFaceUp && gamestatus=="b")
    {
       cName.ImageSource = src;
       hand[k].IsFaceUp = !hand[k].IsFaceUp;  
    }
    else if(! hand[k].IsFaceUp  && gamestatus=="b")
    {
        flipCard(k,sender)
    }  
}


///*** Methods
function flipCard(idx, sender)
{
   
    var cd=sender.findName("c" + idx);
    
    if( hand[idx].IsFaceUp){
    cd.ImageSource=src
    hand[idx].IsFaceUp=false;
    }
    else
    {
    cd.ImageSource = hand[idx].Image;
    hand[idx].IsFaceUp=true;
    }
}

function deal(sender)
{
    var c;
   var gs = gamestatus;
   
   // first deal
   if (gs=="a")
    {
       if (!noBet)
        {
            alert("You must make a bet first");
            return;
        }
        for (var i = 0; i <5; i++)  
           {
            c = RemoveAt();                     //Draw a card from the pack
            hand[i]=c;                          // add the card to the hand
            flipCard(i,sender);                 // show the card
            cardvals[i]= c.deckValue;           // add to results array for win function
            gamestatus="b";                     // flag the status
            }
      }
      var tWinner=sender.findName("tbWinner")
        tWinner.Visibility="Collapsed";
        tWinner=null;
       var mText= sender.findName("message");       //update the message
        mText.Text="Best of Luck"; 
          // second deal
    if (gs=="b")                                // If its the redraw
        {                           
         for (var i = 0; i <5; i++)
            {
                if(! hand[i].IsFaceUp)
                {
                    c = RemoveAt();
                    hand[i]=c;
                    flipCard(i,sender);
                    cardvals[i]= c.deckValue;
                } 
             }
             // Update the display
             var mText= sender.findName("message");
             mText.Text=checkwin();
             showSplash(sender); 
             bet=0;
             mText=sender.findName("BetText");
             mText.Text="$0.00";
             mText=sender.findName("WinText");
             mText.Text= "Winnings $" + winnings + '.00';
            //reset the game 
             noBet=false;
             gamestatus='a';
        }
              // game over
          
}
function showSplash(sender)
{
var txt;
var tbWinner=sender.findName("tbWinner")
if(won>0)
{
    txt="Winner"
    var applause=sender.findName("applause")
    applause.Stop();
    applause.Play();
    
}
else
{
    txt="looser"
}

tbWinner.Text=txt;
tbWinner.Visibility="Visible"
}


//Media Events
function IntroOpened(sender,e)
{
//sender.Volume="1";
//alert("intro Opened" + sender.Name);

}
function IntroFailed(sender,e)
{
//alert("intro failed " + sender.Name);
}
function intobufferchanged(sender,e)
{
//alert("Buffer changed " + sender.Name)
}
function stateChanged(sender,e)
{

//alert("state changed " + sender.Name + " state: " + sender.CurrentState)
}
function CashSoundEnded(sender,e)
{
   
    if (sender.CurrentState=="Paused")
    {
    sender.stop;
    alert(sender.Name + ",  " + sender.CurrentState)
    }
}

function HideSplashScreen(sender,e)
{
 var splashscreen=sender.findName("SplashScreen")
 var Host= sender.getHost();
 var root=Host.content.Root;
root.children.remove(splashscreen)
}
