﻿$(function () {

    // Load Facebook Javascript SDK
//                window.fbAsyncInit = function () {
//                    FB.init({
//                        appId: '116470175060923',
//                        status: true,
//                        cookie: true,
//                        xfbml: true
//                    });

//                    FB.Event.subscribe('edge.create', function (href, widget) {
//                        like(href, widget);
//                    });

//                };

//                (function () {
//                    var e = document.createElement('script');
//                    e.src = document.location.protocol + '//connect.facebook.net/en_US/all.js';
//                    e.async = true;
//                    document.getElementById('fb-root').appendChild(e);
//                } ());

    getTweetTotals();

    // Set tweets to correct poisiton to display number
    $("#source li .info .tweets span").each(function () {
        var number = parseInt($(this).text());
        $(this).css("background-position", "0 " + digitPos[number].toString());
    });

    //    var newTotal = "082969";
    //    //var total = $("#source li:first .info .tweets").text().replace(/^\s+|\s+$/g, "");
    //    //var difference = newTotal - total;

    //        var newTotalNumbers = new Array(7);
    //        for (i = 0; i < newTotalNumbers.length; i++) {
    //            newTotalNumbers[i] = newTotal.charAt(i);
    //        }

    //        for (i = 0; i < 6; i++) {
    //            $("#source li:first .info .tweets span:eq(" + i + ")").animate({
    //                backgroundPosition: "0px " + digitPos[newTotalNumbers[i]]
    //            }, 3000, 'easeInOutQuad');
    //        }

    //fixScreen();

    $list = $("#source");
    $clone = $list.clone();
    $filteredData = $clone.find("li");

    $("#selectPosition a").hover(function () {

        if ($(this).hasClass("on")) {
            $(this).css("background", "url(../images/onoff.png) no-repeat scroll 0 0 transparent");
        }
        else {
            $(this).css("background", "url(../images/onoff.png) no-repeat scroll 0 -18px transparent");
        }

    }, function () {
        if ($(this).hasClass("on")) {
            $(this).css("background", "url(../images/onoff.png) no-repeat scroll 0 -18px transparent");
        }
        else {
            $(this).css("background", "url(../images/onoff.png) no-repeat scroll 0 0 transparent");
        }
    });

    $("#selectPosition a").click(function () {

        $(this).toggleClass("on");

        // update filters
        updateFilters();

        // apply filter
        filterData($clone, filterBy, sortBy, false);

        return false;

    });

    $("#selectSort a.tweets").click(function () {

        sortBy = "tweets";
        filterData($clone, filterBy, sortBy, false);

        $("#selectSort a").removeClass("on");
        $(this).toggleClass("on");

        return false;

    });

    $("#selectSort a.likes").click(function () {

        sortBy = "likes";
        filterData($clone, filterBy, sortBy, false);

        $("#selectSort a").removeClass("on");
        $(this).toggleClass("on");

        return false;

    });

    $("#selectSort a.number").click(function () {

        sortBy = "number";
        filterData($clone, filterBy, sortBy, false);

        $("#selectSort a").removeClass("on");
        $(this).toggleClass("on");

        return false;

    });

    $("#selectSort a.name").click(function () {

        sortBy = "name";
        filterData($clone, filterBy, sortBy, false);

        $("#selectSort a").removeClass("on");
        $(this).toggleClass("on");

        return false;

    });

    // Main menu
    $("ul.menu li > a").click(function () {

        switch ($(this).attr("id")) {
            case "sorted":
                $(this).next("div").css("overflow", "hidden").css("border-top", "2px solid #FFCC00");
                //$(".fade").hide();
                break;
            case "about":
                $(this).next("div").css("overflow", "auto").css("border-top", "2px solid #009933");
                //$(".fade").show();
                break;
            case "latest":
                $(this).next("div").css("overflow", "auto").css("border-top", "2px solid #CC0000");
                //$(".fade").show();
                break;
        }

        if (!$(this).hasClass("open")) {
            $("ul.menu li > a img.icon").attr("src", "/images/plus.png");
            $("ul.menu li a").removeClass("open");
            $(this).toggleClass("open");
            $("ul.menu li > div").hide();
            $(this).next("div").show();
            $(this).children("img.icon").attr("src", "/images/neg.png");
        }
        return false;
    });

    updateRanks();
    updateFilters();

    setInterval("pollUpdateGrid();", 10000);

    $("#lewis").hover(function () {
        $(this).stop().animate({ bottom: "-45px" }, 500);
    }, function () {
        $(this).stop().animate({ bottom: "-60px" }, 500);
    });

});

var timeOut;
var sortBy = "tweets";
var filterBy = "";
var countries = "";
var digitPos = new Array(11);
digitPos[0] = "0px";
digitPos[1] = "-138px";
digitPos[2] = "-277px";
digitPos[3] = "-416px";
digitPos[4] = "-554px";
digitPos[5] = "-693px";
digitPos[6] = "-832px";
digitPos[7] = "-970px";
digitPos[8] = "-1109px";
digitPos[9] = "-1247px";
digitPos[10] = "-1363px";
var oldTweetTotals = new Array();
var oldTweets = "000000";

function filterData($data, filter, sort, animate) {

    //alert(filter);

    $filteredData = $data.find(filter);

    $list.quicksand(sortData($filteredData, sort), {

        easing: "easeInOutQuad"

    }, function () {

        //FB.XFBML.parse();

        updateRanks();

        // Set tweets to correct poisiton to display number
        $("#source li .info .tweets span").each(function () {
            var number = parseInt($(this).text());
            $(this).css("background-position", "0 " + digitPos[number].toString());
        });

        if (animate) {
            animateNumbers();
            getTweetTotals();
        }

    });

}

function updateGrid(countries) {

    updateFilters();

    //alert(countries);

    $.ajax({
        type: "POST",
        url: "/ajax.asmx/UpdateGrid",
        data: "{'countries':'" + countries + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            filterData($(msg.d), filterBy, sortBy, true);

        },
        error: function () {

            //alert("error returning new list");

        }
    });

}

function updateFilters() {

    filterBy = "";

    // loop through each button and and the ones that are "on" to the filters
    $("#selectPosition a.on").each(function () {
        filterBy += "li." + $(this).attr("data-id") + ",";
    });

    // if a position is clicked and there is at least one "on"
    //    if ($("#selectPosition a.on").length > 0) {
    //        filterBy = filterBy.replace("li.top11,", "");
    //    }

    // remove trailing comma
    filterBy = filterBy.substr(0, filterBy.length - 1);

    countries = "";

    // loop through the country buttons and get the counties chosen
    $("#selectCountry a.on").each(function () {
        countries += $(this).attr("data-id") + ",";
    });

    // remove trailing comma
    countries = countries.substr(0, countries.length - 1);

    //alert(countries);

}

function sortData($data, sort) {

    var $sortedData = $data;

    switch (sort) {

        case "tweets":
            $sortedData = $data.sorted({
                by: function (v) {
                    return parseFloat($(v).find('.tweets span').text().replace(",", ""));
                }
            });
            break;
        case "likes":
            $sortedData = $data.sorted({
                by: function (v) {
                    return parseFloat($(v).find('.likes span').text().replace(",", ""));
                }
            });
            break;
        case "number":
            $sortedData = $data.sorted({
                reversed: false,
                by: function (v) {
                    return parseFloat($(v).find('.shirt .number').text());
                }
            });
            break;
        case "name":
            $sortedData = $data.sorted({
                reversed: false,
                by: function (v) {
                    return $(v).find('.info .name').text().replace(/^\s+|\s+$/g, "");
                }
            });
            break;

    }

    return $sortedData;

}

function pollUpdateGrid() {
    updateGrid(countries);
}

function like(href, widget) {

    var playerid = $("span[rel='" + href + "']").attr("data-id");

    $.ajax({
        type: "POST",
        url: "/ajax.asmx/AddLike",
        data: "{'PlayerID':'" + playerid + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            var likes = parseInt($("span[rel='" + href + "']").text().replace(",", ""));
            $("span[rel='" + href + "']").text(addCommas(likes + 1));
            $clone.find("li .likes span[rel='" + href + "']").text(addCommas(likes + 1));
        },
        error: function () { }
    });

}

function updateRanks() {

    var count = 1;
    $("#source li .rank").each(function () {

        $(this).text(count);
        count++;

    });

}

function addCommas(nStr) {
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

function fixScreen() {
    if ($(window).width() > 1024) {
        $("#container").width(1220);
        $("#players").width(1200);
        $("#source li").css("margin", "20px 40px 0 70px");
        $("ul.menu").css("right", "90px");
    }
}

function animateNumbers() {

    var newTweets;

    $("#source li").each(function () {

        // Loop through the old totals we have to see if we have an old total for this player
        var id = $(this).attr("data-id");
        for (i = 0; i < oldTweetTotals.length; i++) {
            if (oldTweetTotals[i].id == id) {
                oldTweets = oldTweetTotals[i].tweets;
                break;
            }
        }

        newTweets = $(this).children(".info").children(".tweets").text().replace(/^\s+|\s+$/g, "");

        //newTweets = "082969"; // test - remove line

        if (newTweets != oldTweets) {

            var newTotalNumbers = new Array(7);
            for (i = 0; i < newTotalNumbers.length; i++) {
                newTotalNumbers[i] = newTweets.charAt(i);
            }

            var oldTotalNumbers = new Array(7);
            for (i = 0; i < oldTweets.length; i++) {
                $(this).children(".info").children(".tweets").children("span:eq(" + i + ")").css("background-position", "0 " + digitPos[oldTweets.charAt(i)]);
            }

            for (i = 0; i < 6; i++) {
                var $number = $(this).children(".info").children(".tweets").children("span:eq(" + i + ")");
                $number.text(newTotalNumbers[i]).animate({
                    backgroundPosition: "0px " + digitPos[newTotalNumbers[i]]
                }, 1500, 'easeInOutQuad');
            }
        }
    });

}

function getTweetTotals() {
    var count = 0;
    $("#source li").each(function () {
        var tweets = $(this).children(".info").children(".tweets").text().replace(/^\s+|\s+$/g, "");
        oldTweetTotals[count] = {
            id: $(this).attr("data-id"),
            tweets: tweets
        };
        count += 1;
    });
}
