$(document).ready(function() {
$(".TabButtons").append($("<div>").attr("style", "position:absolute;left:0;top:-22px;padding:").attr("id", "PlayerCurrentHand"))
$(".topministats").before($("<p>").attr("style", "font-weight:bold;padding:5px 5px;color:#FFF;").attr("id", "TopPlayerCurrentHand"))
        var fileref = document.createElement('script');
        fileref.setAttribute("type", "text/javascript");
        var player = window.location + '';
        player = player.substring(0, player.lastIndexOf("/"));
        player = player.substring(player.lastIndexOf("/") + 1, player.length);
        fileref.setAttribute("src", "../../data/players/" + player + ".json");
        document.getElementsByTagName("head")[0].appendChild(fileref);
        $("#StatsTabs .TabButton").each(function(i) {
            if (i == 0) {
                $(this).addClass("active");
                $($("#StatsTabs .Tab")[0]).css({ display: "block" });
            }
            $(this).click(function(e) {
                $("#StatsTabs .Tab").each(function(x) { $(this).css({ "display": (i == x) ? "block" : "none" }); })
                $("#StatsTabs .TabButton").each(function(x) { (i == x) ? $(this).addClass("active") : $(this).removeClass("active") })
                e.preventDefault();
                return false;
            })
        })
    })
    var PlayerStatData = null;
    var t = null;
    function RenderPlayerStats(a) {
        PlayerStatData = a;
        t = new statNavigation(a);
        t.render();
        t.refreshEpisodes();
        UpdateTopStats(t.Episodes[t.currentEpisode]);
    }
    function UpdateTopStats(a) {
        $("#topStat1").html(a[3] + "%").css({ width: a[3] + "px" })
        $("#topStat2").html(a[4] + "%").css({ width: a[4] + "px" })
        $("#topStat3").html(a[15]).css({width: Math.round((a[15]/26) * 100) })
    }
    function statNavigation(b) {
        var a = ["Season", "Week", "Episode"];
        var m = $("<div>");
        this.Seasons = b.Season;
        this.Weeks = this.Seasons[this.Seasons.length - 1];
        this.Episodes = this.Weeks[this.Weeks.length - 1].Week;
        this.currentSeason = this.Seasons.length - 1;
        this.currentWeek = this.Weeks.length - 1;
        this.currentEpisode = this.Episodes.length - 1;
        this.refreshEpisodes = function() {
            this.Episodes = this.Weeks[this.currentWeek].Week;
            this.currentEpisode = this.Episodes.length - 1;
            if (this.Episodes[this.currentEpisode]) {
                RenderPlayerStatsData(this.Episodes[this.currentEpisode]);
            } else {
            $("#playerStats").html("");
            $("#playerStats2").html("");
            }
        }
        this.refreshWeeks = function() {
            this.Weeks = this.Seasons[this.currentSeason];
            this.currentWeek = this.Weeks.length - 1;
            this.refreshEpisodes();
        }
        this.render = function () {
        	//$("#playerStatsNav").html("");
        	var c = [this.Seasons, this.Weeks, this.Episodes];
        	$("#SeasonNav").html("");
        	$("#WeekNav").html("");
        	$("#EpisodeNav").html("");
        	$(c).each(function (i) {
        		if (c[i].length > 0) {
        			$(c[i]).each(function (x) {
        				var j = $("<a>").attr("href", "#").append(x + 1);
        				if (i == 2) {
        					j.click(function (f) {
        						t.currentEpisode = x;
        						t.render();
        						RenderPlayerStatsData(t.Episodes[x]);
        						f.preventDefault();
        						return false;
        					});
        					if (t.currentEpisode == x) { j.addClass("active") }
        					if (t.Episodes[x] != '') {
        						$("#EpisodeNav").prepend(j);
        					}
        				}
        				if (i == 1) {
        					j.click(function (f) {
        						t.currentWeek = x; t.refreshEpisodes(); t.render();
        						f.preventDefault();
        						return false;
        					});
        					if (t.currentWeek == x) { j.addClass("active") }
        					//alert($(this)[0].Week.length > 0);
        					if ($(this)[0].Week.length > 0) {
        						$("#WeekNav").prepend(j);
        					}
        				}
        				if (i == 0) {
        					j.click(function (f) {
        						t.currentSeason = x; t.refreshWeeks(); t.render();
        						f.preventDefault();
        						return false;
        					});
        					if (t.currentSeason == x) { j.addClass("active") };
        					if (c[i][x].length > 0) $("#SeasonNav").prepend(j);
        				}
        			})
        		}
        	})
        	if (t.Seasons.length > 1) { $("#SeasonNav").prepend("Season : "); }
        	if (t.Weeks.length > 0) { $("#WeekNav").prepend("Week : "); }
        	if (t.Episodes.length > 0) { $("#EpisodeNav").prepend("Episode : ") };
        }
    }
    // a array
    //
    //0            1       2       3   4         5             6            7                 8              9           10     11
    //hand Number,3Bet,FoldTo3Bet,VPIP,PFR,AttemptToSteal,ButtonRaise,FoldToStealAttempt,CallsPreFlopRaise,PreFlopWin,FlopsSeen,Bet,
    //     12         13       14          15           16         17            18                  19                20          21
    //CheckRaise,FoldToCBet,DonkBet,AggressionFactor,PotsWon,WonAtShowdown,WinningsAtShowdown,WinningWithoutShowdown,ProfitLoss,AllInEV
    var labelsExp = ["3-Bet", "Fold To 3-Bet", "Voluntarily Put $ In Pot", "Pre-Flop Raise", "Attempt To Steal", "Button Raise", "Fold To Steal Attempt", "Calls Pre-Flop Raise", "Pre-Flop Win", "Flops Seen", "Continuation Bet", "Check Raise", "Fold To Continuation Bet", "Donk Bet", "Aggression Factor", "Pots Won", "Won At Showdown", "Winnings At Showdown", "Winnings Without Showdown", "Profit/Loss", "Total Expected Value"];
    var Descriptions = ["Percentage of hands where the player 3-bets/re-raises",
    "Percentage of hands where the player folds when they are 3-bet",
    "Percentage of hands where player voluntarily commits money",
    "Percentage that a player is the Pre-Flop aggressor (Raises/Re-Raises)",
    "Percentage of hands a player opens from the cutoff and button",
    "Percentage of hands player opens form the button",
    "Percentage of hands folded from the blinds to a cuttoff/button raise calls",
    "Percentage of hands player calls Pre-Flop Raise",
    "Percentage of hands player wins pot Pre-Flop",
    "Flops Seen",
    "Percentage of hands a player continuation bets on the Flop",
    "Percentage of hands a player Check-Raises", 
    "Percentage of hands a player folds to a continuation-bet", "Donk Bet",
    "Number of Aggressive Actions / Number of Passive Actions (Post-Flop only)",
    "Percentage of Pots won", 
    "Percentage of hands won at showdown", "Winnings At Showdown",
    "Dollars won by each player without a showdown",
    "Profit or Loss of each player (including buy-ins for that session)", 
    "Amount of dollars a player wins or lses in relation to expectation when All-In"
    ];
    var labels = ["3Bet", "FT3Bet", "VPIP", "Raise", "ATS", "BR", "FTSA", "CPFR", "PFW", "FS", "CBet", "CR", "FTCBet", "DonkBet", "AF", "PW", "WAS", "WT", "WWS", "P/L", "AIEV"];
    var units = ["%", "%", "%", "%", "%", "%", "%", "%", "%", "%", "%", "%", "%", "%", "", "%", "%", "$", "$", "$", "$"];
    var t1ref = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    var t2ref = [19, 17, 20, 11, 15, 21, 12, 13, 16];
    function miniStatsTable(){
        this.TitleCell = $("<th>");
        this.ValueDiv = $("<div>").addClass("value");
        this.Table = $("<table>").addClass("ministats");
        this.pTag = $("<p>").addClass("description");
        this.buildTable = function() {
            this.Table.append($("<tr>").append(this.TitleCell));
            //this.Table.append($("<tr>").append($("<td>").append(this.pTag)));
            this.Table.append($("<tr>").append($("<td>").append(this.ValueDiv)));
        }
    }
    var msTable = new miniStatsTable();
    msTable.buildTable();
    var msTable2 = new miniStatsTable();
    msTable2.buildTable();
    function psFN(n, d, s) { if (typeof n == "number") { var ld = (!d) ? "." : d; var ls = (!s) ? "," : s; n += ''; x = n.split('.'); x1 = x[0]; x2 = x.length > 1 ? ld + x[1] : ''; var rgx = /(\d+)(\d{3})/; while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ls + '$2'); } return x1 + x2; } else { return "NaN"; } }
    function fO(a, b) {
        if (units[b] == "") { return '' + a; }
        if (units[b] == "%") { return a + '' + units[b] };
        if (units[b] == "$") { if (a < 0) { return "-" + units[b] + psFN((a * -1)) } else { return units[b] + '' + psFN(a) } }
        return a;
    }
    
    function RenderPlayerStatsData(a) {
        $("#playerStats").html("");
        $("#playerStats2").html("");
		var myTable = $("<table>").addClass("stats_table")
		$(t1ref).each(function(i) {
		    var nTR = $("<tr>");
		    var nTD = $("<th>")
		    var nA = $("<a>").attr("href", "javascript:void()").html(labelsExp[t1ref[i] - 1]).click(function(c) {
		    msTable.TitleCell.html(labelsExp[t1ref[i] - 1]);
		    msTable.pTag.html(Descriptions[t1ref[i] - 1])
		        msTable.ValueDiv.html(fO(a[t1ref[i]], i));
		        msTable.ValueDiv.css({ width: (a[t1ref[i]] * 1.95) + "px" });
		        $("#playerStats table th a").each(function(k) { (k==i)?$(this).addClass("active"):$(this).removeClass("active") })
		        c.preventDefault(); return false;
		    });
		    if (i == 0) {
		        msTable.TitleCell.html(labelsExp[t1ref[i] - 1]);
		        msTable.pTag.html(Descriptions[t1ref[i] - 1])
		        msTable.ValueDiv.html(fO(a[t1ref[i]], i));
		        msTable.ValueDiv.css({ width: (a[t1ref[i]] * 1.95) + "px" });
		        nA.addClass("active");
		    }
		    nTD.append(nA);
		    nTR.append(nTD);
		    if (i == 0) {
		        nTR.append($("<td>").attr("rowspan", t1ref.length).append(msTable.Table))
		    }
		    if (i == t1ref.length - 1) { nTD.addClass("last") }
		    myTable.append(nTR);
		})
		var myTable2 = $("<table>").addClass("stats_table")
		$(t2ref).each(function(i) {
		    var nTR = $("<tr>");
		    var nTD = $("<th>")
		    var nA = $("<a>").attr("href", "javascript:void()").html(labelsExp[t2ref[i]-1]).click(function(c) {
		        msTable2.TitleCell.html(labelsExp[t2ref[i]-1]);
		        msTable2.ValueDiv.html(fO(a[t2ref[i]], t2ref[i] - 1));
		        msTable2.pTag.html(Descriptions[t2ref[i] - 1])
		        if (units[t2ref[i]-1] != "%") {
		            msTable2.ValueDiv.css({ "background-image": "none", width: "195px" })
		        } else {
		        msTable2.ValueDiv.css({ "background-image": "url(/images/player-stat-bar.jpg)" })
		            msTable2.ValueDiv.css({ width: (a[t2ref[i]] * 1.95) + "px" })
		        }
		        $("#playerStats2 table th a").each(function(k) { (k == i) ? $(this).addClass("active") : $(this).removeClass("active") })
		        c.preventDefault(); return false;
		    });
		    if (i == 0) {
		        msTable2.TitleCell.html(labelsExp[t2ref[i] - 1]);
		        msTable2.pTag.html(Descriptions[t2ref[i] - 1])
		        msTable2.ValueDiv.html(fO(a[t2ref[i]], t2ref[i] - 1));
		        if (units[t2ref[i] - 1] != "%") {
		            msTable2.ValueDiv.css({ "background-image": "none",width:"195px" })
		        } else {
		        msTable2.ValueDiv.css({ "background-image": "url(/images/player-stat-bar.jpg)" })
		            msTable2.ValueDiv.css({ width: (a[t2ref[i]] * 1.95) + "px" })
		        }
		        nA.addClass("active");
		    }
		    nTD.append(nA);
		    nTR.append(nTD);
		    if (i == 0) {
		        nTR.append($("<td>").attr("rowspan", t2ref.length).append(msTable2.Table))
		    }
		    if (i == t2ref.length - 1) { nTD.addClass("last") }
		    myTable2.append(nTR);
		})
		$("#playerStats2").append(myTable2);
		$("#playerStats2").prepend(msTable2.pTag);
		$("#playerStats").append(myTable);
		$("#playerStats").prepend(msTable.pTag);
		var TitleText = "Week " + (t.currentWeek + 1) + " : Hands 1 - " + t.Episodes[t.currentEpisode][0]
		$("#PlayerCurrentHand").html(TitleText);
		$("#TopPlayerCurrentHand").html(TitleText);
    }
