﻿function DataContext() {
    this.getAllBetMarkets = function(betMarkets) {
        return object;
    };
    this.getFirstScorer = function() {
        return JSLINQ(object).Where(function(item) {
            return item.BetType == "First Goalscorer";
        }).Select(function(item) {
            return item;
        });
    };
    this.getAnytimeScorer = function() {
        return JSLINQ(object).Where(function(item) {
            return item.BetType == "Anytime Goalscorer";
        }).Select(function(item) {
            return item;
        });
    };
    this.get90Minutes = function() {
        return JSLINQ(object).Where(function(item) {
            return item.BetType == "Match Betting";
        }).Select(function(item) {
            return item;
        });
    };
    this.getMarketByHomeTeamAndAwayTeam = function(hometeam, awayteam, markets) {
        return JSLINQ(markets).Where(function(item) {
            return (((item.HomeTeam.ClientTeamName == hometeam) && (item.AwayTeam.ClientTeamName == awayteam)) 
			|| ((item.HomeTeam.FantasyLeagueResultsAndFixturesName == hometeam) && (item.AwayTeam.FantasyLeagueResultsAndFixturesName == awayteam))
			|| ((item.HomeTeam.FantasyLeagueTeamScreenName == hometeam) && (item.AwayTeam.FantasyLeagueTeamScreenName == awayteam)));
        }).Select(function(item) {
            return item;
        });
    };
    this.getMarketByHomeOrAwayTeam = function(playerClub, markets) {
        return JSLINQ(markets).Where(function(item) {
            return (item.HomeTeam.FantasyLeagueTeamScreenName == playerClub) || (item.AwayTeam.FantasyLeagueTeamScreenName == playerClub || item.HomeTeam.FantasyLeagueResultsAndFixturesName == playerClub) || (item.AwayTeam.FantasyLeagueResultsAndFixturesName == playerClub);
        }).Select(function(item) {
            return item;
        });
    };
    this.getPlayerByFirstNameAndSurname = function(firstname, surname, participants) {
        return JSLINQ(participants).Where(function(item) {
            return (item.FirstName == firstname) && (item.Surname == surname);
        }).Select(function(item) {
            return item;
        });
    };
    this.getPlayerByInitialAndSurname = function(initial, surname, participants) {
        return JSLINQ(participants).Where(function(item) {
            return (item.FirstInitial == initial) && (item.Surname == surname);
        }).Select(function(item) {
            return item;
        });
    };
    this.getTeamFromMarket = function(teamname, participants) {
        return JSLINQ(participants).Where(function(item) {
            return item.FullName == teamname;
        }).Select(function(item) {
            return item;
        });
    };
    this.getMarketByPlayerClub = function(club, markets) {
        return JSLINQ(markets).Where(function(item) {
            return (item.HomeTeam.FantasyLeagueTeamScreenName == club) || (item.AwayTeam.FantasyLeagueTeamScreenName == club || item.HomeTeam.FantasyLeagueResultsAndFixturesName == club) || (item.AwayTeam.FantasyLeagueResultsAndFixturesName == club);
        }).Select(function(item) {
            return item;
        });
    };
}
var object;

function initBettingInt() {
    var controller = new BettingIntAppController();
    this.init = function() {
        $.ajax({
            type: "GET",
            url: "OddsJson.aspx",
            dataType: "application/json",
            success: function(data) {
                var pathname = window.location.pathname;

                if (data != "") {
                    object = eval('(' + data + ')');
                }
				
				controller.BettingIntWidget();

                if (pathname == "/resultsandfixtures.aspx" || pathname == "/ResultsAndFixtures.aspx") {
                    controller.ResultsAndFixturesWidget();
                }
                if (pathname == "/Playerlist.aspx") {
                    controller.PlayerListWidget();
                }
                if (pathname == "/Team.aspx") {
                    controller.TeamScreenWidget();
                }
            },
            error: function() { }
        });
    };
}

function EventsLibrary() {
    this.popup = function() {
        $('.bubbleInfo').each(function() {
            var distance = 10;
            var time = 250;
            var hideDelay = 500;
            var hideDelayTimer = null;
            var beingShown = false;
            var shown = false;
            var trigger = $(this);
            var info = $('.popup', this).css('opacity', 0);
            if (info.length > 0) {
                $([trigger.get(0), info.get(0)]).mouseover(function() {
                    if (hideDelayTimer) clearTimeout(hideDelayTimer);
                    if (beingShown || shown) {
                        return;
                    } else {
                        beingShown = true;
                        info.css({
                            top: -93,
                            left: 0,
                            display: 'block'
                        }).animate({
                            top: '-=' + distance + 'px',
                            opacity: 1
                        }, time, 'swing', function() {
                            beingShown = false;
                            shown = true;
                        });
                    }
                    return false;
                }).mouseout(function() {
                    if (hideDelayTimer) clearTimeout(hideDelayTimer);
                    hideDelayTimer = setTimeout(function() {
                        hideDelayTimer = null;
                        info.animate({
                            top: '-=' + distance + 'px',
                            opacity: 0
                        }, time, 'swing', function() {
                            shown = false;
                            info.css('display', 'none');
                        });
                    }, hideDelay);
                    return false;
                });
            }
        });
    };
    this.initUrl = function() {
        $(".betInfo").click(function() {
            window.open($("span.url", this).text(), '_blank');
            return false;
        });
/* 		$(".odds").click(function() {
            window.open($("span.url", this).text(), "");
            return false;
        }); */
    };
    this.initWidgetAccordion = function() {
        $("#bettingIntWidget").addClass('ui-accordion');
        $("#bettingIntWidget").addClass('ui-widget');
        $("#bettingIntWidget").addClass('ui-helper-reset');
        $("#bettingIntWidget").addClass('ui-accordion-icons');
        $("#bettingIntWidget > span:first").next(".betcontent").slideDown('slow');
        $("#bettingIntWidget > span:first").addClass('ui-accordion-content-active');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-accordion-header');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-helper-reset');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-state-default');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-state-active');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-corner-top');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-corner-bottom');
        $("#bettingIntWidget > span.bet-widget-market").addClass('ui-state-hover');
        $(".betcontent").addClass('ui-accordion-content');
        $(".betcontent").addClass('ui-helper-reset');
        $(".betcontent").addClass('ui-widget-content');
        $(".betcontent").addClass('ui-corner-bottom');
        $("#bettingIntWidget >span.bet-widget-market").click(function() {
            if ($(this).hasClass('ui-accordion-content-active') == false) {
                $(".betcontent").slideUp('slow');
                $("#bettingIntWidget > span.bet-widget-market").removeClass('ui-accordion-content-active');
                $(this).next(".betcontent").slideDown('slow');
                $(this).addClass('ui-accordion-content-active');
            }
        });
        var toggle = true;
        $(".messagebody").hide();
        $(".messagehead").click(function() {
            $(this).next("div").children(".messagebody").slideToggle(500);
            return false;
        });
        $(".participants > li > a").click(function() {
            window.open($(this).attr('href'), '_blank');
            return false;
        });
        $("a.betLink").click(function() {
            window.open($(this).attr('href'), '_blank');
            return false;
        });
        $(".loading").hide();
    };
}

function BettingIntAppController() {
    var view;
    this.BettingIntWidget = function() {
        view = new WidgetAppView();
        view.render();
        view.uiEvents();
    };
    this.TeamScreenWidget = function() {
        view = new TeamScreenAppView();
        view.render();
        view.uiEvents();
    };
    this.PlayerListWidget = function() {
        view = new PlayerListAppView();
        view.render();
    };
    this.ResultsAndFixturesWidget = function() {
        view = new ResultsAndFixturesAppView();
        view.render();
    };
}

function WidgetAppView() {
    this.dataContext = new DataContext();
    this.eventsLib = new EventsLibrary();
    this.render = function() {
        var markets = this.dataContext.getAllBetMarkets();
        if (markets != undefined) {
            $('#betmarket-template').tmpl(this.dataContext.getAllBetMarkets()).appendTo('#bettingIntWidget');
        }
        else {
            $('#bettingIntWidget').append('<p>No Bet Data Available</p>');
        }
    };
    this.uiEvents = function() {
        this.eventsLib.initWidgetAccordion();
    };
}

function TeamScreenAppView() {
    var dataContext = new DataContext();
    var eventsLib = new EventsLibrary();
    this.render = function() {
        $("div.players > ul > li").each(function() {
            var playerCssClass = $(this).attr('class');
            var playerCssClassSplit = playerCssClass.split(" ");
            var playerClub = playerCssClassSplit[0];
            var playerName = $.trim($("a", this).text());
            playerName = playerName.split(" ");
            var the_length = playerName[0].length;
            var playerInitial = 0;
            if (isNaN(playerName[0].charAt(the_length - 1))) {
                playerInitial = playerName[0].charAt(the_length - 1);
            }
            var i = 1;
            var surname = "";
            for (i; i < playerName.length; i++) {
                surname += playerName[i];
                if (i >= 1 && (i + 1) != playerName.length) {
                    surname += " ";
                }
            }
            var type = dataContext.getFirstScorer();
            if (type.items.length == 1) {
                var market = dataContext.getMarketByHomeOrAwayTeam(playerClub, type.items[0].Markets);
                if (market.items.length == 1) {
                    var player = dataContext.getPlayerByInitialAndSurname(playerInitial, surname, market.items[0].Participants);
                    if (player.items.length == 1) {
                        if (market.items[0].HomeTeam.FantasyLeagueTeamScreenName != playerClub && market.items[0].AwayTeam.FantasyLeagueTeamScreenName == playerClub) {
                            player.items[0].RivalTeam = market.items[0].HomeTeam.ClientTeamName;
                        } else if (market.items[0].AwayTeam.FantasyLeagueTeamScreenName != playerClub && market.items[0].HomeTeam.FantasyLeagueTeamScreenName == playerClub) {
                            player.items[0].RivalTeam = market.items[0].AwayTeam.ClientTeamName;
                        }
                        var append = $("a", this);
                        $('#teamscreen-odds-template').tmpl(player.items[0]).appendTo(this);
                        $('#playerodds-template').tmpl(player.items[0]).appendTo(append);
                        $(this).addClass("bubbleInfo");
                        $("a", this).addClass("trigger");
                    }
                }
            }
        });
    };
    this.uiEvents = function() {
        eventsLib.popup();
        eventsLib.initUrl();
    };
}

function ResultsAndFixturesAppView() {
    var dataContext = new DataContext();
    this.render = function() {
        $("div.selected_players > table.tabbed > tbody > tr:nth-child(2)").each(function() {
            var hometeam = $.trim($("td:nth-child(2)", this).text());
            var awayteam = $.trim($("td:nth-child(4)", this).text());
            var type = dataContext.get90Minutes();
            if (type.items.length == 1) {
                var market = dataContext.getMarketByHomeTeamAndAwayTeam(hometeam, awayteam, type.items[0].Markets);
                if (market.items.length == 1) {
                    var hteam = dataContext.getTeamFromMarket(hometeam, market.items[0].Participants);
                    var ateam = dataContext.getTeamFromMarket(awayteam, market.items[0].Participants);
                    if (hteam != null) {
                        var append = $("td:nth-child(2)", this);
                        $("#hometeam-template").tmpl(hteam.items[0]).appendTo(append);
                    }
                    if (ateam != null) {
                        var append = $("td:nth-child(4)", this);
                        $("#hometeam-template").tmpl(ateam.items[0]).appendTo(append);
                    }
                }
            }
        });
    };
}

function PlayerListAppView() {
    var dataContext = new DataContext();
    this.render = function() {
        $("#playerlist > thead > tr > th:nth-child(1)").after("<th class='header'>Odds</th>");
        $("#playerlist > tbody > tr").each(function() {
            var playerClub = $.trim($("td:nth-child(4)", this).text()).toLowerCase();
            var playerName = $.trim($("td:nth-child(1)", this).text());
            $("td:nth-child(1)", this).after("<td></td>");
            var playername = playerName.split(" ");
            var firstname;
            var surname = "";
            if (playername.length > 1) {
                firstname = playername[0];
                var i = 1;
                for (i; i < playername.length; i++) {
                    surname += playername[i];
                    if (i >= 1 && (i + 1) != playername.length) {
                        surname += " ";
                    }
                }
            } else {
                firstname = "";
                surname = playername[0];
            }
            var type = dataContext.getFirstScorer();
            if (type.items.length == 1) {
                var market = dataContext.getMarketByHomeOrAwayTeam(playerClub, type.items[0].Markets);
                if (market.items.length == 1) {
                    var player = dataContext.getPlayerByFirstNameAndSurname(firstname, surname, market.items[0].Participants);
                    if (player.items.length == 1) {
                        if (market.items[0].HomeTeam.FantasyLeagueTeamScreenName != playerClub && market.items[0].AwayTeam.FantasyLeagueTeamScreenName == playerClub) {
                            player.items[0].RivalTeam = market.items[0].HomeTeam.ClientTeamName;
                        } else if (market.items[0].AwayTeam.FantasyLeagueTeamScreenName != playerClub && market.items[0].HomeTeam.FantasyLeagueTeamScreenName == playerClub) {
                            player.items[0].RivalTeam = market.items[0].AwayTeam.ClientTeamName;
                        }
                        var append = $("td:nth-child(2)", this);
                        $('#playerodds-template').tmpl(player.items[0]).appendTo(append);
                    }
                }
            }
        });
    };
}
