<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name='viewport' content='width=device-width, initial-scale=1.0, user-scalable=yes'>
   <title>Video Poker</title>
   <style>
		@import url('https://fonts.googleapis.com/css?family=Luckiest+Guy');
      body { background-color:#0032b4; color:#fff; font-family:"Helvetica Neue",Helvetica,sans-serif; font-size:1vw; }
      #main { perspective:1000px; position:absolute; top:0px; right:0px; bottom:0px; left:0px; text-align:center; }
      #paytable { 
			display:none;
         width:90%;
         color:#ffffff;
         border: 4px outset #0df;
         margin:.5em auto 0px;
         background-color:#142850;
         border-collapse:collapse;
         line-height:1em;
         font-weight: 700; font-size:130%;text-transform: uppercase;  
      }
      #paybet { background-color:#0af; color:#ff0;border-bottom: 2px solid #fff;  }
      #paytable td#paybet1, #paytable td#paybet2,#paytable td#paybet3,#paytable td#paybet4,#paytable td#paybet5 { background-color:#0af; color:#ff0; text-align:center; border-bottom: 2px solid #fff; }
      table#paytable .paybet { background-color:#c00; color:#ff0; }
      #paytable td { text-align:left; border-left:3px solid #0af; white-space:nowrap; padding:.125em .25em .125em .25em;}
      #paytable td.right { text-align:right; }
      .paybet { background-color:#ff0; }
      #toolbar { display:inline-block; position:absolute; left:0px; bottom:0px; right:0px; height:15%; text-align:center; background-color:rgba(0,0,0,.5); }
      button { z-index:999; margin-top:1em; font-size:200%; color:#000; background-color:#cccc00; border:.25em outset #ffff00; width:7em; height 3em; text-transform:uppercase; height:3em; font-weight:bold;   position:relative; text-shadow: 2px 2px 1px rgba(255,255,255,.5);}
      button.disabled { color: #cccc00; text-shadow: none; }
      .right { text-align:right; }
      .left { text-align:left; }
      h2 { width:3.3vw; height:6.1vh; margin:0; padding:1.3vw 1.6vw 1.1vw 0.7vw; color:#fff; z-index:9999; border-radius:5vw; display:inline-block; border:0.6vw dashed #fff; font-size:3vw; top:-1vh; position:relative; letter-spacing:-4px; text-shadow:-1px -2px 0px #000; }
      .status { display:inline-block; }
      #bet { width:30%; color:#eee; position:absolute; left:2vw; height:8vh; font-size:3vw; top:5vh; text-align:left; }
      #bet:before { content: "BET: "; }
      #credit { width:30vw; color:#eef; position:absolute; right:2vw; height:8vh; font-size:3vw; top:5vh; text-align:right; }
      #credit:before { content: "CREDITS: "; }
      #win { width:33%; color:#eee; position:absolute; left:33%; height:9vh; top:5vh; font-size:3vw;z-index:9999;  }
		@keyframes bounce {
			0% { transform: rotate(0deg) scale(1); }
			10% { transform: rotate(-15deg) scale(1.5); }
			20% { transform: rotate(15deg) scale(1); }
			30% { transform: rotate(-10deg) scale(1.5); }
			40% { transform: rotate(10deg) scale(1); }
			50% { transform: rotate(-5deg) scale(1.5); }
			60% { transform: rotate(5deg) scale(1); }
			70% { transform: scale(1.5); }
			80% { transform: scale(1); }
			90% { transform: scale(1.5); }
			100% { transform: scale(1); }
		}
		.handresult {
			font-size:2em;
			background-color:rgba(174,84,231,1);
			color:#fff;
			border:.25vw solid rgba(107,36,154,1);
			border-bottom-left-radius:1vw;
			border-bottom-right-radius:1vw;
			font-weight:bold;
			text-shadow:2px 2px 2px #000;
			z-index:99999;
			width:100%;
			position:absolute;
			bottom:-0.2vh;
			left:0;
			display:none;
			overflow:hidden;
			transition:all 300ms cubic-bezier(.25, .99, .71, 1.23);
			height:5vh;
			text-transform:uppercase;
		}
		#cards .handresult {
			font-size:3vw;
			bottom:-1.5vh;
			height:7vh;
		}
      #won {
			position: absolute;
			display: inline-block;
			width:50vw;
			top: 22%;
			left: 20%;
			font-size: 1.5vw;
			color: #f9e945;
			text-shadow: 2px 2px 0px #000;
			font-weight: bold;
			background-color: rgba(0,0,0,.5);
			padding: 2vh 4vw 2vh;
			border-radius: 4vw;
			border: 1vw solid rgb(249, 233, 69);
			transform: scale(1);
			z-index: 99999;
			box-shadow: 0 0.5vw 0.5vw rgba(0,0,0,.4);
			animation: bounce 2s 2;
			display:none;
			animation: win 2000ms 2;
      }
		#won button { border-radius:4vw; }
		@keyframes win {
			0% { text-shadow:0 0 0 #fff; transform:scale(1); }
			10% { transform:scale(1.25); }
			20% { transform:scale(1.0); }
			30% { transform:scale(1.25); }
			40% { transform:scale(1.0); }
			50% { text-shadow:0 0 6vw #fff; }
			60% { text-shadow:0 0 0vw #fff; }
			70% { text-shadow:0 0 6vw #fff; }
			80% { text-shadow:0 0 0vw #fff; }
			90% { text-shadow:0 0 6vw #fff; transform:scale(1.25); }
			100% { text-shadow:0 0 0vw #fff; transform:scale(1.0); }
		}
      table#paytable tr.winner { background-color:#00d8ff; color:#000;}
      td.winner { background-color:#fff; transform:scale(1); text-align:center; animation: throb 2s; }
      #results { margin-top:-2em; display:none;}
      .status { height: 10vh; position: absolute; font-weight: bold; bottom:16vh; text-shadow: 2px 2px 1px rgba(0,0,0,.5); left: 0px; width:100%; z-index:99; }
      @keyframes throb {
         0% { transform: scale(2); }
        20% { transform: scale(1); }
        40% { transform: scale(2); }
        60% { transform: scale(1); }
        80% { transform: scale(2); }
        100% { transform: scale(1); }
      }
      th { border-bottom:3px solid #0df; border-right:3px solid #0df;  }
		#payleft, #payright {
			position:absolute;
			line-height:1.4vw;
			bottom:15vh;
			width:16vw;
			height:42vh;
		}
		#payleft { left:0px; }
		#payright { right:0px; }
.payline {
    background-color: #f00;
    margin: 0.2vh .5vw;
    font-size: 1.25vw;
    text-transform: uppercase;
    text-align: center;
    text-shadow: 1.5px 1.5px 0px #000;
    border-radius: 1.5vw;
    border: 0.2vw outset;
    font-weight: bold;
    padding-bottom: 0.3vh;
}
.pay {
    background-color: #000;
    display: block;
    width: 10vw;
    margin: 0 auto 0vh;
    border: 2px inset #ff0;
	 padding:0.4vh 2vw;
	 border-bottom-left-radius:1.2vw;
	 border-bottom-right-radius:1.2vw;
}
#gameselect {
	position:absolute;
	display:inline-block;
	bottom:11vh;
	left:18vw;
	width:24vw;
	height:0vh;
	background:linear-gradient(to top, #f4e130 0%,#fff460 100%);
   z-index:999;
	font-size:2.4vw;
	color:#000;
	text-shadow:1px 1px 0px #fff;
	box-shadow:.25vw -.25vw .25vw rgba(0,0,0,.4), -.25vw 0 .25vw rgba(0,0,0,.4);
	overflow:hidden;
	font-weight:500;
	text-transform:uppercase;
	transition:all 300ms cubic-bezier(.25, .99, .71, 1.23);
	text-align:left;
}
#handselect {
	position:absolute;
	display:inline-block;
	bottom:11vh;
	left:32.3vw;
	width:14vw;
	height:0vh;
	background:linear-gradient(to top, #f4e130 0%,#fff460 100%);
   z-index:999;
	text-align:center;
	font-size:3vw;
	color:#000;
	text-shadow:1px 1px 0px #fff;
	box-shadow:.25vw -.25vw .25vw rgba(0,0,0,.4), -.25vw 0 .25vw rgba(0,0,0,.4);
	overflow:hidden;
	font-weight:500;
	text-transform:uppercase;
	transition:all 300ms cubic-bezier(.25, .99, .71, 1.23);
}
div#handselect.open { height:33vh; }
div#gameselect.open { height:36vh; }
#handselect input { display:none; }
#handcount { margin:0; padding:0; }
#gameslist { margin:0; padding:0; }
#gameslist li { list-style-type:none; border-bottom:1px solid #660; cursor:pointer; padding:1vh;}
.gameslistSelected { background-color:#660; color:#fff; }
#handcount li {
	list-style-type:none;	
	border-bottom: 1px solid #660;
	cursor:pointer;
}
.handcountSelected {
	background-color:#660;
	color:#fff;
}
#doubleup {
	position:absolute;
	display:none;
	top:0;
	left:0;
	right:0;
	bottom:0;
	background-color:#0032b4;
	z-index:99999;
	width:100%;
}
#doubleup .cardwrap .card { width:90%; height:90%; }
#doubleup .cardwrap { padding-left:2.5vw; }
#doubleheader { font-size:2vw; font-family:"Luckiest Guy", cursive;  }
#doubleheader h1 { color:#c00; -webkit-text-stroke: .125vw #ff0; font-size:2em; }
#doubleheader button {font-size:1.5vw;margin-left:2vw;  }
.dealercardlabel { display: inline-block; position: relative; top: -2.2vh; background-color: #0032b4; color: #ff0; font-size: 1.5em; padding: 0px 0.25vw; left: -1.6vw; font-weight: bold; text-shadow: 2px 2px 0px #000; white-space: nowrap;}
#doubledealer { display: inline-block; width: 12vw; margin-right: 4vw; border: .25vw solid #ff0; border-radius: 1vw; padding-left: 3vw; height: 38vh; }
   </style>
   <link rel='manifest' href='manifest.json'>
   <link rel='stylesheet' type='text/css' href='poker5.css'>
   <script src="pokersolver.js"></script>
	<script src="https://www.gstatic.com/firebasejs/3.9.0/firebase.js"></script>
	<script>
	  // Initialize Firebase
	  var config = {
		 apiKey: "AIzaSyDxGzBuvFA2qrOZZPBdTmIjsXAgWpcrmcs",
		 authDomain: "crblackjack-9e220.firebaseapp.com",
		 databaseURL: "https://crblackjack-9e220.firebaseio.com",
		 projectId: "crblackjack-9e220",
		 storageBucket: "crblackjack-9e220.appspot.com",
		 messagingSenderId: "32143422101"
	  };
	  firebase.initializeApp(config);
	</script>

</head>
<body>
<div id='main'>
   <table id='paytable'>
      <colgroup>
         <col>
         <col id='bet1pay'>
         <col id='bet2pay'>
         <col id='bet3pay'>
         <col id='bet4pay'>
         <col id='bet5pay'>
      </colgroup>
   </table>
   <div id='holds'>
      <div id='card0-hold' class='hold'></div>
      <div id='card1-hold' class='hold'></div>
      <div id='card2-hold' class='hold'></div>
      <div id='card3-hold' class='hold'></div>
      <div id='card4-hold' class='hold'></div>
   </div>
	<div id='hands'>
   </div>
	<div id='payleft'></div>
   <div id='cards'>
		<div id='card0' class='cardwrap'><div class='card card1H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
		<div id='card1' class='cardwrap'><div class='card card13H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
		<div id='card2' class='cardwrap'><div class='card card12H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
		<div id='card3' class='cardwrap'><div class='card card11H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
		<div id='card4' class='cardwrap'><div class='card card10H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
		<div id='result' class='handresult'></div>
	</div>
	<div id='payright'></div>
   <div id='status' class='status'>
      <div id='bet'>0</div>
      <div id='win'></div>
      <div id='credit'></div>
   </div>
   <div id='won'></div>
   <div id='gameover'>PLAY 5 CREDITS</div>
	<div id='gameselect'>
		<ul id='gameslist'>
			<li id='game_poker'>Jacks or Better</li>
			<li id='game_bonus'>Bonus Poker</li>
			<li id='game_doublebonus'>Double Bonus</li>
			<li id='game_dueces'>Dueces Wild</li>
			<li id='game_joker'>Joker Poker</li>
		</ul>
	</div>
	<div id='handselect'>
		<ul id='handcount'>
			<li id='handcount5'>5</li>
			<li id='handcount10'>10</li>
			<li id='handcount25'>25</li>
			<li id='handcount50'>50</li>
			<li id='handcount100'>100</li>
		</ul>
	</div>
   <div id='toolbar'>
      <span class='left'>
         <button onclick='cdr.login()' class='leftButton' id='loginButton'>Login</button>
         <button onclick='cdr.changeGames()' id='gamesButton'>Games</button>
         <button onclick='cdr.changeHands()' id='handsButton'>Hands</button>
      </span>
      <h2 id='denom'>$1</h2>
      <span class='right'>
         <button onclick='cdr.betone()' id='betOne'>Bet 1</button>
         <button onclick='cdr.betmax()' id='betMax'>Bet 5</button>
         <button id='dealdrawButton' onclick='cdr.dealdraw()' disabled='true' class='rightButton disabled'>Deal</button>
      </span>
   </div>
	<div id='doubleup'>
		<div id='doubleheader'>
			<h1>Double Up?</h1>
			<p>YOU WON $<span id='doublewin'>0</span></p>
			<p>DOUBLE UP TO $<span id='doubledouble'>0</span></p>
			<p>
				<button id='doubleButton'>Double</button>
				<button id='collectButton'>Collect</button>
			</p>
		</div>
		<div id='doublecards'>
			<div id='doubledealer'><span class='dealercardlabel'>DEALERS CARD</span><br><div id='doublecard0' class='cardwrap flipped' ><div class='card card1S'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div></div>
			<div id='doublecard1' class='cardwrap flipped'><br><div class='card card3H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
			<div id='doublecard2' class='cardwrap flipped'><br><div class='card card8D'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
			<div id='doublecard3' class='cardwrap flipped'><br><div class='card card11C'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
			<div id='doublecard4' class='cardwrap flipped'><br><div class='card card10H'><figure class='pic'>&nbsp;</figure></div><div class='cardback'><figure class='pic'>&nbsp;</figure></div></div>
		</div>
	</div>
</div>
<script>
(function() {
   window.cdr = {
      game: {
			endpoint: "https://us-central1-crblackjack-9e220.cloudfunctions.net/",
			hands: 10,
			type: "poker",
			wilds: "",
			chipColors: ["#dd0", "#0c0", "#c00", "#c0c", "#000", "#0be", "#fa0", "#999", "#0a6", "#69a", "#333", "#000"],
			creditValues: [ 1, 2, 5, 10, 25, 100, 250, 500, 1000, 2000, 5000, 10000, 50000 ],
			creditValueIdx:0,
			creditValue:1,
         cards: [],
         discards: {},
         holds: {},
         bet: 0,
         credit: 1000,
			uid:"",
			stage:0
      },
      paytable: {
         "RoyalFlush": { hand: 'Royal Flush', win: [ 250, 500, 750, 1000, 4000]},
         "StraightFlush": { hand: 'Straight Flush', win: [ 50, 100, 150, 200, 250]},
         "FourOfAKind": { hand: 'Four of a Kind', win: [ 25, 50, 75, 100, 125]},
         "FullHouse": { hand: 'Full House', win: [ 9, 18, 27, 36, 45]},
         "Flush": { hand: 'Flush', win: [ 6, 12, 18, 24, 30]},
         "Straight": { hand: 'Straight', win: [ 4, 8, 12, 16, 20]},
         "ThreeOfAKind": { hand: 'Three of a Kind', win: [ 3, 6, 9, 12, 15]},
         "TwoPair": { hand: 'Two Pair', win: [ 2, 4, 6, 8, 10]},
         "OnePair": { hand: 'Jacks or Better', win: [ 1, 2, 3, 4, 5]}
      },
		games: {
			"poker": "Jacks or Better",
			"bonus": "Bonus Poker",
			"doublebonus": "Double Bonus Poker",
			"dueces": "Dueces Wild",
			"joker": "Joker Poker"
		},
      addListener: function(i) {
         $$("card" + i).addEventListener("click", function(e) { cdr.toggleCard("card" + i, 0); });

      },
		changeGames: function() {
			$$("game_"+cdr.game.type).classList.add('gameslistSelected');
			$$("gameselect").classList.toggle("open");
			$$("handselect").classList.remove("open");
		},
		changeHands: function() {
			$$("handcount"+cdr.game.hands).classList.add('handcountSelected');
			$$("handselect").classList.toggle("open");
			$$("gameselect").classList.remove("open");
		},
      betone: function() {
			$$("handselect").classList.remove("open");
			$$("gameselect").classList.remove("open");
         if (cdr.game.bet > 0) $(".paybet").classList.remove('paybet');
         cdr.game.bet++;
         
         if (cdr.game.bet > 5) { 
            cdr.game.bet = 0;
				$$("dealdrawButton").setAttribute("disabled", true);
				$$("dealdrawButton").classList.add("disabled");
         }
         if (cdr.game.bet > 0) {
				$$("dealdrawButton").removeAttribute("disabled");
				$$("dealdrawButton").classList.remove("disabled");
            $$("paytable").className = "paybet" + cdr.game.bet;
				if ($(".paybet")) $(".paybet").classList.remove('paybet');
            $$("bet"+cdr.game.bet+"pay").classList.add('paybet');
         }
         $$("bet").innerHTML = cdr.game.bet + "x"+cdr.game.hands;
			cdr.genPaytable();
      },
      betmax: function() {
			$$("handselect").classList.remove("open");
			$$("gameselect").classList.remove("open");
         cdr.game.bet = 5;
         if (cdr.game.bet > 0) {
				$$("dealdrawButton").removeAttribute("disabled");
				$$("dealdrawButton").classList.remove("disabled");
				$$("dealdrawButton").innerHTML = "DEAL";
            $$("paytable").className = "paybet" + cdr.game.bet;
				if ($(".paybet")) $(".paybet").classList.remove('paybet');
            $$("bet"+cdr.game.bet+"pay").classList.add('paybet');
         } else {
				$$("dealdrawButton").setAttribute("disabled");
				$$("dealdrawButton").classList.add("disabled");
			}
         $$("bet").innerHTML = cdr.game.bet + "x" + cdr.game.hands + "(" + (cdr.game.bet * cdr.game.hands) + ")";
			cdr.genPaytable();
         cdr.deal();
      },
		dealdraw: function() {
			$$("handselect").classList.remove("open");
			$$("gameselect").classList.remove("open");
			if (cdr.game.stage === 0) {
				cdr.deal();
			} else if (cdr.game.stage === 1) {
				cdr.draw();
			}
		},
		addListeners: function() {
		   $$("cards").addEventListener("mousedown", function(e) {
				var tgt = e.target;
				if (tgt.classList.contains('card')) {
					cdr.toggleCard(tgt.parentNode.id, 0, 0);
				} else if (tgt.classList.contains('cardwrap')) {
					cdr.toggleCard(tgt.id, 0, 0);
				}
			});
			$$("gameslist").addEventListener("click", function(e) {
				$(".gameslistSelected").classList.remove("gameslistSelected");
				var tgt = e.target;
				var matches = tgt.id.match(/game_(\w+)/);
				if (matches[1]) {
					cdr.game.type = matches[1];
					tgt.classList.add('gameslistSelected');
					var url = document.location.href.replace(/#.*/, '');
					document.location.href = url + "#" + cdr.game.type;
					$$("gameselect").classList.remove('open');
					cdr.init();
					$$('win').innerHTML = tgt.innerHTML;
					cdr.settings.type = matches[1];
					localStorage.setItem("settings", JSON.stringify(cdr.settings));
				}
			});

			$$("handcount").addEventListener("click", function(e) {
				var tgt = e.target;
				var matches = tgt.id.match(/handcount(\d+)/);
				if (matches[1]) {
					var newcount = parseInt(matches[1]);
					cdr.switchHands(newcount);
					cdr.settings.hands = newcount;
					localStorage.setItem("settings", JSON.stringify(cdr.settings));
				}
			});

			$$("denom").addEventListener("click", function(e) {
				cdr.game.creditValueIdx++;
				if (cdr.game.creditValueIdx > cdr.game.creditValues.length - 1) cdr.game.creditValueIdx = 0;
				if (cdr.game.balance / cdr.game.creditValues[cdr.game.creditValueIdx] < 0) cdr.game.creditValueIdx = 0;

				cdr.game.creditValue = cdr.game.creditValues[cdr.game.creditValueIdx];
				cdr.updateChip();
				cdr.updateCredits();
				cdr.settings.creditValue = cdr.game.creditValue;
				cdr.settings.creditValueIdx = cdr.game.creditValueIdx;

				localStorage.setItem("settings", JSON.stringify(cdr.settings));
			});

		},
      init: function() {
         if (document.location.hash) {
				cdr.game.type = document.location.hash.replace(/^#/, '');
				if (cdr.game.type==="dueces") {
					$$("main").classList.add('wilds');
					cdr.game.wilds = "wilds";
				} else {
					cdr.game.wilds = "";
				}
			}
			var savedJS = localStorage.getItem("settings");
			if (savedJS) {
				cdr.settings = JSON.parse(savedJS);

				for (var i in cdr.settings) {
					if (cdr.settings.hasOwnProperty(i)) {
						cdr.game[i] = cdr.settings[i];
					}
				}
			}
			cdr.updateChip();
         cdr.genPaytable();
			cdr.makeHands();
         //var cards = cdr.newDeck();
			$$("main").classList.add("hands"+cdr.game.hands);
         $$("gameover").style.transform = "scale(1)";
			$$("gameover").innerHTML = cdr.games[cdr.game.type];
			if (!cdr.game.listening) {
				cdr.addListeners();
				cdr.game.listening = true;
			}
      },
		switchHands: function(handcount) {
				$$("handcount"+cdr.game.hands).className = "";
				$$("handcount"+handcount).className = "handcountSelected";
				cdr.game.hands = handcount;
				setTimeout(function() { $$("handselect").classList.remove("open"); }, 250);
				setTimeout(function() { 
					cdr.makeHands(); 
					$$("main").className = "hands"+cdr.game.hands + " " + cdr.game.wilds;
				}, 250);
		},
		updateChip: function() {
			$$("denom").className = "chip" + cdr.game.creditValue;
			$$("denom").style.backgroundColor = cdr.game.chipColors[cdr.game.creditValueIdx];
			var show = (cdr.game.creditValue>999) ? (cdr.game.creditValue / 1000) + "K" : cdr.game.creditValue;
			$$("denom").innerHTML = "$" + show;
		},
		updateCredits: function() {
			var uid = cdr.game.uid;
			 firebase.database().ref("bank/"+uid+"/balance").on("value", function(snapshot) {
				  var balance = snapshot.val();
				  cdr.game.balance = balance;
				  cdr.game.credit = Math.floor(balance / cdr.game.creditValue);
				  var showCredit = cdr.game.credit;
				  if (showCredit > 1000000000) {
						showCredit = Math.floor(showCredit / 1000000) / 100 + "B";
				  } else if (showCredit > 1000000) {
						showCredit = Math.floor(showCredit / 1000) / 100 + "M";
				  } else if (showCredit > 1000) {
						showCredit = Math.floor(showCredit / 100) / 10 + "K";
				  }
				  $$("credit").innerHTML = showCredit;

				  if ((cdr.game.credit < 1) || cdr.game.active) {
					  cdr.disable("betOne");
					  cdr.disable("betMax");
				  } else if (cdr.game.credit < 5) {
					  cdr.enable("betOne");
					  cdr.disable("betMax");
				  } else {
					  cdr.enable("betOne");
					  cdr.enable("betMax");
				  }
			 });
		},
		disable: function(item) {
			  $$(item).setAttribute("disabled",true);
			  $$(item).classList.add('disabled');
		},
		enable: function(item) {
			  $$(item).removeAttribute("disabled");
			  $$(item).classList.remove('disabled');

		},
      toggleCard: function(card, delay) {
         // setTimeout(function() { $$(card).classList.toggle('flipped'); }, delay * 100);
         var current = $$(card + '-hold').style.visibility;
         if (current==="hidden") {
            $$(card + '-hold').style.visibility = "";
            cdr.game.holds[card] = true;

				for (var i=1; i < cdr.game.hands; i++) {
					$("#hand"+i+card+" .card").className = $("#"+card+" .card").className;
					// $$("hand"+i+card).classList.remove('flipped');
					cdr.showCard("hand"+i+card, 0, 0);
				}
         } else {
            $$(card + '-hold').style.visibility = "hidden";
				for (var i=1; i < cdr.game.hands; i++) {
					// $$("hand"+i+card).classList.add('flipped');
					cdr.hideCard("hand"+i+card, 0, 0);
				}
            delete cdr.game.holds[card];
         }
         // if (cdr.game.discards[card]) { delete cdr.game.discards[card]; } else { cdr.game.discards[card] = true; }
      },
      hideCard: function(card, delay) {
         setTimeout(function() { $$(card).classList.add('flipped'); setTimeout(function() { $("#"+card+" .card").style.visibility='hidden';}, 100); }, delay * 10);
      },
      showCard: function(card, delay, wait=500) {
         setTimeout(function() { $("#"+card+" .card").style.visibility='visible'; $$(card).classList.remove('flipped'); }, (delay * 10) + wait);
      },
      setCard: function(i, draw, delay) {
            setTimeout(function() { $("#card" + i + " .card").className = 'card card' + draw; }, (delay * 100));
      },
      clearHolds: function() {
         for (var i=0; i<5; i++) {
            $$("card"+i+"-hold").style.visibility = "hidden";
         }
         cdr.game.holds = [];
      },
      newCard: function(card, newcard, delay) {
         var match = card.match(/card(\d)/);
         cdr.game.cards[match[1]] = newcard;
         
         setTimeout(function() {
            $("#" + card + " .card").className = "card card" + newcard;
         }, delay * 75);

      },
      draw: function() {
         var cnt = 0;
			var needcards = [];
			$$("dealdrawButton").setAttribute("disabled", true);
			$$("dealdrawButton").classList.add('disabled');
			$$("dealdrawButton").innerHTML = "DEAL";

         for (var i=0; i<5; i++) {
            if (!cdr.game.holds["card"+i]) {
					cdr.hideCard('card' + i, cnt);
					cnt++;
               cdr.game.discards["card"+i] = true;
					needcards.push(i);
            }
         }
         var scr = document.createElement('script');
			scr.src = cdr.game.endpoint + "exchangeCards?game="+cdr.game.type+"&callback=cdr.newCards&hands=" + cdr.game.hands + "&uid=" + firebase.auth().currentUser.uid + "&discard=" + needcards.join(',');
			document.body.appendChild(scr);
		},
		newCards: function(cards) {
			console.log("cards: "+JSON.stringify(cards));
			console.dir(cards);
			cdr.game.results = cards;
		   cdr.game.resultCounts = {};
			cdr.game.stage = 2;

			var cnt = 0;
			var wintot = 0;
			var c = cards.hands[0];

			for (var j=0; j < c.length; j++) {
				if ($$("card"+j).classList.contains('flipped')) {
					$("#card"+j+" .card").className = "card card" + c[j];
					$("#card"+j+" .card").style.visibility = "visible";
					cdr.showCard("card"+j, cnt, 0);
					cnt++;
				}
			}
			if (cards.results[0]) {
				cdr.showResult(0, cards);
				wintot += cards.wins[0];
				if (!cdr.game.resultCounts[cards.results[0]]) cdr.game.resultCounts[cards.results[0]] = 0;
				cdr.game.resultCounts[cards.results[0]]++;
				cdr.genPaytable(cdr.game.resultCounts);
		   }
			var discards = 0;
         for (var i=1; i < cards.hands.length; i++) {
            var c = cards.hands[i];
				for (var j=0; j < c.length; j++) {
					if ($$("hand"+i+"card"+j).classList.contains('flipped')) {
						$("#hand"+i+"card"+j+" .card").className = "card card" + c[j];
						cdr.showCard("hand"+i+"card"+j, cnt, 0);
					}
				}
				cnt++;
				if (!discards) discards = cnt;
				if (cards.results[i]) {
					cdr.showResult(i, cards);
					wintot += cards.wins[i];
					if (!cdr.game.resultCounts[cards.results[i]]) cdr.game.resultCounts[cards.results[i]] = 0;
					cdr.updatePaytable(i, cards.results[i]);
				}
         }
			if (wintot > 0) {
				setTimeout(function() { 
					$$("won").innerHTML = "<h1>YOU'VE WON "+Math.floor(wintot / cdr.game.creditValue)+" CREDITS!</h1><h1>\"DOUBLE IT\" TO "+Math.floor(wintot / cdr.game.creditValue) * 2 +"?</h1><button onclick='cdr.doubleup()'>DOUBLE IT</button> <button onclick='$$(\"won\").style.display = \"none\"'>COLLECT</button>";
					$$("won").style.display = "inline-block";
					$$("win").innerHTML = "WIN: "+Math.floor(wintot / cdr.game.creditValue);
					cdr.resetButtons();
					cdr.game.active = false;
					cdr.game.stage = 0;
					/*setTimeout(function() { 
						$$("doublewin").innerHTML = Math.floor(wintot / cdr.game.creditValue);
						$$("doubledouble").innerHTML = Math.floor(wintot / cdr.game.creditValue) * 2;
						$$("doubleup").style.display = "inline-block";
					}, 2000);*/
				}, cnt * 25);
			} else {
				cdr.gameoverTimeout = setTimeout(function() { $$("gameover").innerHTML = "GAME OVER"; $$("gameover").style.transform = "scale(1)"; }, 1000);
				cdr.game.active = false;
				cdr.resetButtons();
				cdr.game.stage = 0;
			}
		},
		updatePaytable: function(cnt, hand) {
			setTimeout(function() {
				cdr.game.resultCounts[hand]++;
				cdr.genPaytable(cdr.game.resultCounts); 
			}, cnt * 10);
		},
		showResult: function(i, cards) {
			var el = (i > 0) ? $$("hand"+i+"result") : $$("result");
			setTimeout(function() {
				el.innerHTML = cards.results[i].replace(/([a-z0-9])([A-Z0-9])/g, '$1 $2').replace(/([A-Z])([A-Z])/g, '$1 $2');
				el.style.display = "inline-block";
				el.style.height = "";
			}, 10 * i);
			
		},
		checkWin: function() {
         var scr = document.createElement('script');
			scr.src = cdr.game.endpoint + "checkHand?callback=cdr.gotWin&game="+cdr.game.type+"&uid=" + firebase.auth().currentUser.uid;
			document.body.appendChild(scr); 
		},
		gotWin: function(hand, won) {
         if (hand && won) {
            var win = cdr.paytable[hand];
            if (win) {
               $$("win").innerHTML = win.hand;
               $$("won").style.display = "inline-block";
               $$("won").innerHTML = "WON " + win.win[cdr.game.bet - 1];
               cdr.clearWinners(); 
               $$(hand).classList.add('winner');
               $$(hand + (cdr.game.bet - 1)).classList.add('winner');
					cdr.gameoverTimeout = setTimeout(function() { $$("gameover").innerHTML = "GAME OVER"; $$("gameover").style.transform = "scale(1)"; }, 10000);
            }
         } else { 
				$$("gameover").innerHTML = "GAME OVER";
				$$("gameover").style.transform = "scale(1)";
			}
			cdr.resetButtons();
			cdr.game.active = false;
      },
		resetButtons: function() {
			$$("gamesButton").classList.remove('disabled');
			$$("gamesButton").removeAttribute('disabled');
			$$("handsButton").classList.remove('disabled');
			$$("handsButton").removeAttribute('disabled');
			$$("handselect").classList.remove("open");
			$$("gameselect").classList.remove("open");
			$$("betOne").classList.remove('disabled');
			$$("betOne").removeAttribute('disabled');
			$$("betMax").classList.remove('disabled');
			$$("betMax").removeAttribute('disabled');
			if (cdr.game.bet) {
				$$("dealdrawButton").classList.remove('disabled');
				$$("dealdrawButton").removeAttribute('disabled');
			} else {
				$$("dealdrawButton").classList.add('disabled');
				$$("dealdrawButton").setAttribute('disabled');
			}
			$$("dealdrawButton").innerHTML = "DEAL";
		},
      clearWinners: function() {
         var els = $$$('.winner');
         for (var i=0; i<els.length; i++) {
            els[i].classList.remove('winner');
         }
			
			$$("result").style.display = "none";
			for (var i=1; i<5; i++) {
				$$("hand"+i+"result").style.display = "none";
			}
      },
		resetCards: function() {
			for (var h=1; h < cdr.game.hands; h++) {
				for (var c=0; c < 5; c++) {
					$$("hand"+h+"card"+c).classList.add('flipped');
				}
				$$("hand"+h+"result").style.height = "0";
			}
			setTimeout(function() { 
				var els = $$$(".handresult"); 
				for (var i in els) { 
					if (els.hasOwnProperty(i)) {
						els[i].style.display = "none";
					}
				}
			}, 150);
		},
      deal: function() {
         if (cdr.game.bet == 0) {
            $$("gameover").innerHTML = "ADD CREDITS TO PLAY";
            return false;
         }
			if (cdr.gameoverTimeout) {
				clearTimeout(cdr.gameoverTimeout);
				cdr.gameoverTimeout = 0;
			}
			$$("gameover").style.transform = "scale(0)";
			$$("won").style.display = "none";
			
			cdr.game.active = true;
			cdr.game.stage = 1;
         cdr.clearHolds();
			cdr.clearWinners();
			cdr.resetCards();

         $$("win").innerHTML = "";
         $$("won").innerHTML = "";
         $$("won").style.display = "none";
         $$("gamesButton").classList.add("disabled");
         $$("gamesButton").setAttribute("disabled", true);
         $$("handsButton").classList.add("disabled");
         $$("handsButton").setAttribute("disabled", true);
         $$("dealdrawButton").innerHTML = "DRAW";
         $$("betOne").classList.add("disabled");
         $$("betOne").setAttribute("disabled", true);
         $$("betMax").classList.add("disabled");
         $$("betMax").setAttribute("disabled", true);
         
         cdr.game.cards = [];
         cdr.game.discards = [];
         cdr.newDeck();
         
			var func = document.createElement('script');
			func.src = cdr.game.endpoint + "newGame?game="+cdr.game.type+"&hands="+cdr.game.hands+"&callback=cdr.gotGame&uid=" + firebase.auth().currentUser.uid + "&bet=" + cdr.game.bet *  cdr.game.creditValue;
			document.body.appendChild(func);
		},
		gotGame: function(cards) {
         for (var i=0; i<5; i++) {
            draw = cards[i];
            cards.push(draw);
            cdr.hideCard("card" + i, i);
            cdr.setCard(i, draw, i);
            cdr.showCard("card" + i, i + 1);
         }
         cdr.game.cards = cards;
         cdr.game.active = true;
         cdr.game.draws = 1;
      },
      solve: function() {
         var hand = [];
         
         for (var i=0; i<cdr.game.cards.length; i++) {
            var card = cdr.game.cards[i].toLowerCase();
            var match = card.match(/(\d*)([cdsh])/i);
            var num = parseInt(match[1]);
            var suit = match[2];
            if ((num > 9) || (num==1)) {
               switch (num) {
                  case 1:
                     num = "A";
                     break;
                  case 10:
                     num = "T";
                     break;
                  case 11:
                     num = "J";
                     break;
                  case 12:
                     num = "Q";
                     break;
                  case 13:
                     num = "K";
                     break;
               }
            }
            hand.push(num + suit);
         }
         console.log("hand:");
         console.dir(hand);
         var result = Hand.solve(hand, "jacksbetter", true);
         cdr.game.result = result.constructor.name;

         console.dir(result);
         return result;
      },
      solveHand: function(hand) {
         var suits = [];
         var cards = [];
         var seen = {};
         var suit = '';
         var canFlush = 1;
			var haveAce = 0;
         for (var i=0; i<hand.length; i++) {
            var match = hand[i].match(/^(\d+)([HDSC])/i);
            if (match[1] && match[2]) {
               if (suit === '') suit = match[2];
               if (match[1] == 1) {
						haveAce++;
               }
               if (suit && (suit !== match[2])) {
                  canFlush = 0;
               }
               if (!seen[match[1]]) {
                  seen[match[1]] = 1;
               } else {
                  seen[match[1]]++;
               }
               cards.push(parseInt(match[1]));
               suits.push(match[2]);
            }
         }
         var isFlush = canFlush;
         cards = cards.sort(function(a, b) { return a - b; });
         var lastCard, isStraight = true;
         for (var i=0; i<cards.length - 1; i++) {
            if (!lastCard) {
               lastCard = parseInt(cards[i]);
            } else if ((lastCard + 1) !== parseInt(cards[i])) {
					if (isStraight!==false && (lastCard===1) && (cards[i]===10)) {
                  isStraight = true;
               } else {
                  isStraight = false;
               }
            }
            lastCard = parseInt(cards[i]);
         }
         var isPair = false;
			var isTwoPair = false;
         var isQualifiedPair = false;
         var isThreeOfAKind = false;
         var isFourOfAKind = false;

         for (var i in seen) {
            if (seen.hasOwnProperty(i)) {
               if (seen[i] > 1) {
                  switch (seen[i]) {
                     case 2:
                        if ((i > 10) || (i == 1)) {
                           isQualifiedPair = true;
                        }
								if (isPair===true) isTwoPair = true;
                        isPair = true;
                        break;
                     case 3:
                        isThreeOfAKind = true;
                        break;
                     case 4:
                        isFourOfAKind = true;
                        break;
                  }
               }
            }
         }
         if (isStraight && isFlush && (cards[0] === 10)) return "RoyalFlush"; 
         if (isStraight && isFlush) return "StraightFlush";
         if (isFourOfAKind) return "FourOfAKind";
         if (isThreeOfAKind && isPair) return "FullHouse";
         if (isFlush) return "Flush";
         if (isStraight) return "Straight";
         if (isThreeOfAKind) return "ThreeOfAKind";
         if (isTwoPair) return "TwoPair";
         if (isQualifiedPair) return "OnePair";

         return false;
      },
      shuffle: function(array) {
        var currentIndex = array.length, temporaryValue, randomIndex;

        // While there remain elements to shuffle...
        while (0 !== currentIndex) {

          // Pick a remaining element...
          randomIndex = Math.floor(Math.random() * currentIndex);
          currentIndex -= 1;

          // And swap it with the current element.
          temporaryValue = array[currentIndex];
          array[currentIndex] = array[randomIndex];
          array[randomIndex] = temporaryValue;
        }

        return array;
      },
      genPaytable: function(counts) {
			firebase.database().ref("payouts/"+cdr.game.type).once("value", function(snap) {
				var pt = snap.val();
				var hands = Object.keys(pt.hands);
				var newpaytable = {};
				var sortable = [];
				for (var i=0; i<hands.length; i++) {
					var name = hands[i];
					var displayName = name.replace(/([a-z0-9])([A-Z0-9])/g, "$1 $2").replace(/([A-Z0-9])([A-Z0-9])/g, "$1 $2");
					sortable.push([name, pt.hands[name]]);

					var pay = [];
					for (var j=1; j<6; j++) {
						pay.push(parseInt(pt.hands[name]) * j);
					}
					newpaytable[name] = { "hand": displayName, win: pay };
				}
				cdr.paytable = newpaytable;
				sortable.sort(function(a, b) {
					return b[1] - a[1];
				});
				cdr.paytable[sortable[0][0]].win[4] = parseInt(pt.jackpot);
				console.dir(newpaytable);
				console.log("New pay table: " + JSON.stringify(newpaytable));
				var payleft = $('#payleft');
				var payright = $('#payright');
				payleft.innerHTML = "";
				payright.innerHTML = "";
				var keys = Object.keys(cdr.paytable);
				var half = Math.floor(keys.length / 2);
				var entry, mypt, win, cnt;

				for (var i=0; i < half; i++) {
					mypt = cdr.paytable[sortable[i][0]];
					win = mypt.win[cdr.game.bet - 1] || 0;
					cnt = (counts && counts[sortable[i][0]]!=undefined) ? " X " + counts[sortable[i][0]] : "";
					if (counts && cnt==="") win = 0;
					entry = el('div', 'payline'+i, 'payline', mypt.hand + " <div class='pay'>" + win + cnt + "</"+"div>");
					payleft.appendChild(entry);
				}
				for (var i=half; i < sortable.length; i++) {
					mypt = cdr.paytable[sortable[i][0]];
					win = mypt.win[cdr.game.bet - 1] || 0;
					cnt = (counts && counts[sortable[i][0]]!=undefined) ? " X " + counts[sortable[i][0]] : "";
					if (counts && cnt==="") win = 0;
					entry = el('div', 'payline'+i, 'payline', mypt.hand + " <div class='pay'>"+win + cnt+"<"+"/div>");
					payright.appendChild(entry);
				}
			});
      },
      newDeck: function() {
         cdr.deck = [];
         var suits = ['S', 'C', 'D', 'H'];
         for (var s=0; s<4; s++) {
            for (var i=1; i<14; i++) {
               cdr.deck.push(i + suits[s]);
            }
         }
         var scnt = Math.floor(Math.random() * 10) + 4;
         for (var i=0; i<scnt; i++) {
            cdr.deck = cdr.shuffle(cdr.deck);
         }
         return cdr.deck;
      },
		login: function(who) {
			var provider;
			provider = new firebase.auth.FacebookAuthProvider();
			db = firebase.database();

			firebase.auth().signInWithPopup(provider).then(function(result) {
			  var token = result.credential.accessToken;
			  var user = result.user;
			  console.dir(user);
			  writeUserData(user.uid, user.displayName, user.email, user.photoURL);
			  db.ref("bank/" + firebase.auth().currentUser.uid).on("value", function(snapshot) {
					var bank = snapshot.val();
					$$("credit").innerHTML = bank.balance;
				});
			}).catch(function(error) {
			  var errorCode = error.code;
			  var errorMessage = error.message;
			  var email = error.email;
			  var credential = error.credential;
			});	
		},
		writeUserData: function(userId, name, email, imageUrl) {
			firebase.database().ref('users/' + userId).set({
				name: name,
				email: email,
				profile_picture : imageUrl
			});
			setCookie("uid", userId);
		},
		makeHands: function() {
			var hands = $$("hands");
			hands.innerHTML = "";
			for (var i=1; i<cdr.game.hands; i++) {
				hands.appendChild(cdr.makeHand(i));
			}
		},
		makeHand: function(id) {
			var suits = ['S', 'C', 'D', 'H'];
			var hand = el('div', 'hand'+id, 'hand');
			var nums = 1, snum = 0;
			for (var i=0; i<5; i++) {
				var cnum = i + 1;
				var suit = suits[3];
				var card = el('div', '', 'card card' + cnum + suit, '<figure class="pic">&nbsp;</figure>');
				var cardback = el('div', '', 'cardback', '<figure class="pic">&nbsp;</figure>');
				var cardwrap = el('div', 'hand'+id+'card'+i, 'cardwrap flipped');
				cardwrap.appendChild(card);
				cardwrap.appendChild(cardback);
				hand.appendChild(cardwrap);
				nums++;
				if (nums > 13) {
					nums = 1;
					snum++;
					if (snum > 3) {
						snum = 0;
					}
				}
			}
			hand.appendChild(el('div', 'hand'+id+'result', 'handresult'));
			return hand;
		}
   };
   cdr.init();
})();
function el(tag, id, classname, content) {
   var el = document.createElement(tag);
   if (id) el.id = id;
   if (classname) el.className = classname;
   if (content) el.innerHTML = content;

   return el;
}
function $(str) { return document.querySelector(str); }
function $$(str) { return document.getElementById(str); }
function $$$(str) { return document.querySelectorAll(str); }
firebase.auth().onAuthStateChanged(function(user) {
  if (user) {
	console.dir(user);
    // User is signed in.
    var displayName = user.displayName;
    var email = user.email;
    var emailVerified = user.emailVerified;
    var photoURL = user.photoURL;
    var isAnonymous = user.isAnonymous;
    var uid = user.uid;
    var providerData = user.providerData;
	 $$("loginButton").innerHTML = "LOGOUT";
	 
	 cdr.game.uid = user.uid;
	 
	 cdr.updateCredits();

  } else {
    // User is signed out.
    // ...
	 $$("loginButton").innerHTML = "LOGIN";
  }
});
</script>
</body>
</html>
