﻿/*jslint browser: true*/
/*global jQuery*/

jQuery.blockUI.defaults.message = 'Please wait ... <img alt="" src="/images/England/icons/loading-small-inverse.gif">';
jQuery.blockUI.defaults.css = {
    border: 'none',
    padding: '15px',
    backgroundColor: '#000',
    color: '#fff',
    opacity: 1,
    cursor: 'wait',
    '-moz-border-radius': '10px',
    '-webkit-border-radius': '10px'
};
jQuery.blockUI.defaults.overlayCSS = {
    backgroundColor: '#000',
    opacity: 0.33,
    cursor: 'wait',
    '-moz-border-radius': '5px',
    '-webkit-border-radius': '5px'
};

var EnglandModules = EnglandModules ? EnglandModules : function($) {
    var priv = {
        AjaxSpinnerInit: false
    };

    var pub = {
        AjaxSpinner: function() {
            if (!priv.AjaxSpinnerInit) {
                priv.AjaxSpinnerInit = true;

                try {
                    var prm = Sys.WebForms.PageRequestManager.getInstance();
                    prm.add_initializeRequest(function InitializeRequest(sender, args) {
                        try {
                            $(args._postBackElement.id).attr('disabled', true);
                            $("#" + args._postBackElement.id).closest('.ajax-container').block();
                        } catch (exception) {
                        }
                    });
                    /*
                    prm.add_endRequest(function EndRequest(sender, args) {
                        $("#" + sender._postBackSettings.sourceElement.id).closest('.ajax-container').unblock();
                    });
                    */
                } catch (exception) {
                }
            }
        },

        AjaxDefaults:
        {
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json"
        },

        Ajax: function(methodName, options) {
            var o = {};
            $.extend(o, this.AjaxDefaults, options,
                          { url: "/webservices/England/Modules.asmx/" + methodName });
            $.ajax(o);
        }
    };

    return pub;
} (jQuery);


EnglandCommentList = function(elid, itemid) { this.init(elid, itemid); };
EnglandCommentList.prototype = {
    _itemid: null,
    _currPage: 0,
    _lastPage: null,
    _pageCache: [],
    _commentList: null,
    _ul: null,
    _next: null,
    _prev: null,

    init: function(elid, itemid) {
        var _this = this;
        _this._itemid = itemid;
        _this._commentList = jQuery('#' + elid);
        _this._ul = jQuery('ul', _this._commentList);
        _this._next = jQuery('a.next', _this._commentList);
        _this._prev = jQuery('a.prev', _this._commentList);

        if (_this._commentList) {
            _this._pageCache[0] = jQuery('li', _this._ul);

            _this._prev.bind('click', function(e) {
                e.preventDefault();
                if (!(_this._prev.hasClass('disabled') || _this._currPage == 0)) {
                    _this._page(_this._currPage - 1, true, _this);
                }
            });

            _this._next.bind('click', function(e) {
                e.preventDefault();
                if (!_this._next.hasClass('disabled')) {
                    _this._page(_this._currPage + 1, false, _this);
                }
            });
        }
    },

    _loadPage: function(page, back, _this) {
        if (page > 0) {
            _this._prev.removeClass('disabled').removeAttr('disabled');
        } else {
            _this._prev.addClass('disabled').attr('disabled', 'disabled');
        }

        if (!_this._lastPage || _this._lastPage > page) {
            _this._next.removeClass('disabled').removeAttr('disabled');
        } else {
            _this._next.addClass('disabled').attr('disabled', 'disabled');
        }

        if (_this._commentList) {
            _this._currPage = page;
            _this._commentList.fadeOut('fast', function() {
                _this._ul.html(_this._pageCache[page]);
                j$(this).fadeIn('fast');
            });
        }
    },

    _page: function(page, back, _this) {
        if (_this._pageCache[page]) {
            _this._loadPage(page, back, _this);
        } else {
            EnglandModules.Ajax("GetComments", {
                data: "{id:'" + _this._itemid + "', page:" + page + "}",
                success: function(msg) {
                    if (msg.d.comments.length == 0) {
                        _this._ul.effect('bounce', { direction: 'up', distance: 25, times: 1 }, 200);
                        _this._pageCache[page] = "";
                    } else {
                        var newPage = "";
                        jQuery.each(msg.d.comments, function(idx, comment) {
                            var newLine = "<li><img class='quote-start' src='/images/England/icons/quote-start.gif' alt=''/><em>" + comment.comment + "</em><img class='quote-end' src='/images/England/icons/quote-end.gif' alt=''/><span class='author'>By <strong>" + comment.nickname + "</strong> " + comment.when + "</span></li>";
                            if (back) {
                                newPage = newLine + newPage;
                            } else {
                                newPage += newLine;
                            }
                        });
                        _this._pageCache[page] = newPage;
                        if (!msg.d.more) {
                            _this._lastPage = page;
                        }
                        _this._loadPage(page, back, _this);
                    }
                }
            });
        }
    }
};

// England Did You Know

function DidYouKnow(id) { this.init(id); };
DidYouKnow.prototype = {
    _dykId: "",
    _btnDYKNext: null,
    _btnDYKReveal: null,
    _dykAnswer: null,

    init: function(id) {
        var _this = this;
        _this._dykId = id;
        _this._btnDYKNext = jQuery('#btnDYKNext');
        _this._btnDYKReveal = jQuery('#btnDYKReveal');
        _this._dykAnswer = jQuery('#dykAnswer');
        _this._dykQuestion = jQuery('#dykQuestion');
        _this._dykArea = jQuery('#dykArea');

        _this._btnDYKNext.bind('click', function(e) {

            e.preventDefault();
            _this._dykAnswer.hide();
            _this._getDidYouKnow(_this);
        });

        _this._btnDYKReveal.bind('click', function(e) {

            e.preventDefault();
            _this._dykAnswer.show("slow");
        });

    },


    _getDidYouKnow: function(_this) {
        _this._dykArea.hide("slow");
        EnglandModules.Ajax("GetDidYouKnow", {
            data: "{guid:'" + _this._dykId + "'}",
            success: function(msg) {
                var dykHtml = "";
                var i = 0;
                _this._dykId = msg.d.ItemId;
                _this._dykQuestion.html(msg.d.Question);
                _this._dykAnswer.html(msg.d.Answer);
                _this._dykArea.show("slow");
            },
            error: function(msg) {
                _this._dykQuestion.html("Sorry, but a problem has occured. Please try again later.<br/>TheFA.com Team.");
                _this._dykAnswer.html("");
                _this._dykArea.show("slow");
            }

        });
    }
};

//Stats Head To Head
function StatsHeadToHead() { this.statsHeadToHeadInit(); };

var lastLeftId = 0;
var lastRightId = 0;
var lastCompareFlags = "";

StatsHeadToHead.prototype = {
    statsHeadToHeadInit: function() {
        j$("div.module-stats-head-to-head").bind("keydown", function(event) {
            // track enter key
            var keycode = (event.keyCode ? event.keyCode : (event.which ? event.which : event.charCode));
            if (keycode == 13) { // keycode for enter key
                // force the 'Enter Key' to implicitly click the compare button
                j$("#stats-module .compares .versus .button").click();
                return false;
            } else {
                return true;
            } //End if/else
        }); //End bind


        j$("#stats-module .compares .versus .button").attr("href", "javascript:").click(function(e) {
            var compareFlags = j$("#stats-checkboxes .stat-friendlies").is(':checked') ? "1" : "0";
            compareFlags += j$("#stats-checkboxes .stat-competitions").is(':checked') ? "1" : "0";
            compareFlags += j$("#stats-checkboxes .stat-home").is(':checked') ? "1" : "0";
            compareFlags += j$("#stats-checkboxes .stat-away").is(':checked') ? "1" : "0";

            var compare = j$("div.module-stats-head-to-head .compare-id").val();
            var leftId = j$("div.compare1").find(".hiddenId").val();
            var rightId = j$("div.compare2").find(".hiddenId").val();
            if (lastLeftId == leftId && lastRightId == rightId && lastCompareFlags == compareFlags) {//Do not refresh same id's
                return;
            } //End if
            if (leftId == rightId) {
                return;
            } //End if


            lastLeftId = leftId;
            lastRightId = rightId;
            lastCompareFlags = compareFlags;
            var teamId = j$("#stats-module .team-id").val();
            var statF = j$("#stats-checkboxes .stat-friendlies").is(':checked');
            var statC = j$("#stats-checkboxes .stat-competitions").is(':checked');
            var statH = j$("#stats-checkboxes .stat-home").is(':checked');
            var statA = j$("#stats-checkboxes .stat-away").is(':checked');

            j$("#stats-module").block({ overlayCSS: { paddingBottom: '7px'} });
            j$.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "/webservices/England/Modules.asmx/GetHeadToHeadDetail",
                data: '{teamId:' + teamId + ', leftId:' + leftId + ', rightId:' + rightId + ', compare:"' + compare + '", friendlies:' + statF + ', competitions:' + statC + ', homeGames:' + statH + ', awayGames:' + statA + '}',
                dataType: "json",
                success: function(msg) {
                    if (msg.d.chartHasData) {
                        j$("#chart-no-data").hide("fast");
                        j$("#chart-html").fadeTo("fast", 0.01, function() {
                            j$(this).html(msg.d.chartHtml).show("fast").fadeTo("slow", 1);
                        } //End function
                        ); //End fadeTo
                    } //End if
                    else {
                        j$("#chart-html").hide("fast");
                        j$("#chart-no-data").show("slow");
                    } //End else
                    j$("#stats-module").unblock();
                }, //End success function
                failure: function(msg) {
                    j$("#stats-module").unblock();
                }
            }); //End ajax
        }); //End j$

        j$("div.module-stats-head-to-head .auto_complete").autocomplete("/webservices/England/Modules.asmx/FindTeamsOrIndividualsByFilter",
        {
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            httpMethod: "post",
            max: 100,
            scroll: true,
            minChars: 3,
            formatRequest: function(data) { return jQuery.toJSON(jQuery.extend(data, { type: j$("div.module-stats-head-to-head .compare-id").val(), team: j$("div.module-stats-head-to-head .team-id").val() })); },
            parse: function(data) {
                var parsed = [];
                var pIndex = 0;
                var rows = data.d;
                var leftId = j$("div.compare1").find(".hiddenId").val();
                var rightId = j$("div.compare2").find(".hiddenId").val();
                for (var i = 0; i < rows.length; i++) {
                    if ((rows[i].Id != leftId) && (rows[i].Id != rightId)) //ignore rows that have been selected
                    {
                        parsed[pIndex] = { data: rows[i], value: rows[i].DisplayName, result: rows[i].DisplayName };
                        pIndex++;
                    } //End if
                } //End for
                return parsed;
            } //End function
}//End autocomplete
      ).result(function(event, value) {
          var t = j$(event.target).closest("div.compare");
          t.find(".hiddenId").val(value.Id);
          t.find(".stat-photo").fadeOut("fast", function() { j$(this).attr('src', value.ImageUrl).attr('alt', value.DisplayName).fadeIn("slow"); });
      } //End function
        ); //End result
        } //End function statsHeadToHeadInit
    };  //End prototype

function UpdateStats(obj, leftVal, rightVal, leftTotal, rightTotal, showPer) {
    var per = Math.round((leftVal / leftTotal) * 100);
    var text = showPer ? per + "%" : leftVal;
    obj.find(".left-number").text(text);
    obj.find(".left-bar div").attr("style", function() { return "width:" + per + "%"; });
    per = Math.round((rightVal / rightTotal) * 100);
    text = showPer ? per + "%" : rightVal;
    obj.find(".right-number").text(text);
    obj.find(".right-bar div").attr("style", function() { return "width:" + per + "%"; });
} //End function 


//Stats Table Explorer

function StatsTable() { this.statsInit(); };

function StartStatsAjax() {
    //debugger;
    var startYear = j$("select.ddlStartYear").val();
    var endYear = j$("select.ddlEndYear").val();
    j$("#stats-slider .start-year").val(startYear);
    j$("#stats-slider .end-year").val(endYear);
};

StatsTable.prototype = {
    _startYear: 0,
    _endYear: 0,
    _teamId: 0,
    _home: 0,
    _away: 0,
    _friend: 0,
    _compare: "",
    _comp: 0,
    _refreshr: null,
    _resultsSlider: null,
    statsInit: function() {
        j$("select.ddlStartYear, select.ddlEndYear").selectToUISlider({
            sliderOptions: { change: StartStatsAjax }
        });
        j$(".accessibleSlider").css("display", "none");
        j$("#stats-table").tablesorter(
                {
                    headers: //Fix issue
                        {1: { sorter: 'digit' },
                        2: { sorter: 'digit' },
                        3: { sorter: 'digit' },
                        4: { sorter: 'digit' },
                        5: { sorter: 'digit' },
                        6: { sorter: 'digit' },
                        7: { sorter: 'digit' }
                    }
                    , widgets: ["zebra"]

                });

        var _this = this;
        _this._statsSlider = j$("results-slider");
        _this._refresh = j$('#btnRefresh');
        _this._refresh.bind('click', function(e) {
            e.preventDefault();
            j$(this).fadeTo("slow", 0.01);
            RefreshStats();
        });

    },


    _getStats: function(_this) {

        _this._teamId = j$("div.styled-table .team-id").val();
        _this._compare = j$("div.styled-table .compare-id").val();
        _this._startYear = j$("#stats-slider .start-year").val();
        _this._endYear = j$("#stats-slider .end-year").val();
        _this._friend = j$("#stats-slider-checkboxes .stat-friendlies").is(':checked');
        _this._comp = j$("#stats-slider-checkboxes .stat-competitions").is(':checked');
        _this._home = j$("#stats-slider-checkboxes .stat-home").is(':checked');
        _this._away = j$("#stats-slider-checkboxes .stat-away").is(':checked');
        jQuery.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: "/webservices/England/Modules.asmx/GetStatsTableDetail",
            data: '{teamId:' + _this._teamId + ', compare:"' + _this._compare + '", startYear:' + _this._startYear + ', endYear:' + _this._endYear + ', friendlies:' + _this._friend + ', competitions:' + _this._comp + ', homeGames:' + _this._home + ', awayGames:' + _this._away + '}',
            dataType: "json",
            success: function(msg) {
                var newHtml = "";
                var i = 0;
                var lineCss = "";
                var homeTeamCss = "";
                var awayTeamCss = "";
                jQuery.each(msg.d.stats, function(idx, stat) {
                    if (i % 2 == 0) {
                        lineCss = "odd";
                    }
                    else {
                        lineCss = "even";
                    }
                    var goalsRatio = stat.GoalsFor / stat.Games;
                    var winRatio = stat.Wins / stat.Games;
                    // Because of a TableSorter bug when refreshing the table all numrics need to be padded with 0's so as the sort thinks they are strings.
                    //The ratios are fine as they have leading zeros anyway.
                    var row = "<tr class='" + lineCss + "'><td class='first'><span style='display:none'>" + stat.Name2 + " " + stat.Name1 + "</span>" + stat.DisplayName + "</td>" +
                        "<td>" + stat.Games + "</td>" +
                        "<td>" + stat.GoalsFor + "</td>" +
                        "<td>" + goalsRatio.toFixed(2) + "</td>" +
                        "<td>" + winRatio.toFixed(2) + "</td>" +
                        "<td>" + stat.CleanSheets + "</td>" +
                        "<td>" + stat.Yellow + "</td>" +
                        "<td>" + stat.Red + "</td></tr>";
                    newHtml = newHtml + row;
                    i++;

                });
                j$('#outer-stats-table').fadeTo("fast", 0.01, function() {
                    if (newHtml.length > 0) {
                        j$("#stats-table-body").html(newHtml);
                    }
                    else {
                        j$("#stats-table-body").html("<tr class='odd'><td colspan='7' class='first'>No matches. Please adjust your filter above.<td></tr>");
                    }
                    j$(this).show("fast").fadeTo("slow", 1);
                    j$("#stats-table").trigger("update");
                    j$("#btnRefresh").fadeTo("slow", 1);
                });
            }
        });
    }
};


function RefreshStats() {
    StatsTable.prototype._getStats(StatsTable.prototype);
}

var EnglandVideo = EnglandVideo || function($) {
    var priv = {
        isPlayerAdded: false,
        playerDefaults: {
            autoStart: false,
            isVid: true,
            isUI: true,
            wmode: "transparent",
            cacheAMFURL: "http://services.brightcove.com/services/messagebroker/amf"
        }
    };

    var pub = {
        addPlayer: function(playerID, parent, id, params) {
            if (priv.isPlayerAdded) {
                removePlayer(id);
            }

            var ps = {};
            jQuery.extend(ps, priv.playerDefaults, params, { playerID: playerID });

            var player = brightcove.createElement("object");
            player.id = id;
            var pe;
            for (var p in ps) {
                pe = brightcove.createElement("param");
                pe.name = p;
                pe.value = ps[p];
                player.appendChild(pe);
            }

            brightcove.createExperience(player, parent, true);
            priv.isPlayerAdded = true;

            return false;
        },

        removePlayer: function(id) {
            if (priv.isPlayerAdded == true) {
                priv.isPlayerAdded = false;
                brightcove.removeExperience(id);
            }
        },

        addDeferredPlayer: function(playerID, link, id, params) {
            var div = document.createElement("div");
            div.id = id;
            $(link).replaceWith(div);
            return this.addPlayer(playerID, div, id + "-player", params);
        }
    };

    return pub;
} (jQuery);

/* Legacy Functions */

// opens new window
function NewWin(url) {
    var newWindow = window.open(url);
    newWindow.focus();
}

// opens new window of specified size
function NewWinSized(url, x, y) {
    var newWindow = window.open(url, 'popupwindow', 'width=' + x + ',height=' + y + ',toolbar=0,location=0,menubar=0,scrollbars=0,status=0');
    newWindow.focus();
}

// opens new window of specified size, with scrollbars
function NewWinSizedScroll(url, x, y) {
    var newWindow = window.open(url, 'popupwindow', 'width=' + x + ',height=' + y + ',toolbar=0,location=0,menubar=0,scrollbars=1,status=0');
    newWindow.focus();
}

