﻿function syncServerTime() {
    $.ajax({
        type: "POST",
        url: "webconnector.asmx/GetServerTime",
        data: "",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            $('.FeedElement').each(function (i) {
                $(this).children('.FeedTime').html(getDifferenceString($(this).children('.FeedPostDate').html(), msg.d))
            });
        },
        error: function (e) {
            //optional error handling
        }
    });
}

function getFeedBody(obj) {

    var detail = $.parseJSON(obj.Detail);
    var score = " with a score of " + detail.Score;
    switch (obj.Type) {
        case 1:
            var bounty = "";
            if (detail.Bounty > 0) {
                bounty = " and claimed a bounty of " + detail.Bounty + " credits! A Value of $" + (detail.Bounty / 10) + " USD!";
            }
            return "Achieved King on " + detail.Level + " with a score of " + detail.Score + bounty;
        case 2:
            return "Achieved a new high score of " + detail.Score + " on " + detail.Level + getFriendsBeatString(detail);
        case 3:
            //dont check for 1 because that would be king.
            if (detail.Rank == 2)
                return "Achieved 2nd place on " + detail.Level + getFriendsBeatString(detail) + score;
            else if (detail.Rank == 3)
                return "Achieved 3rd place on " + detail.Level + getFriendsBeatString(detail) + score;
            else if (detail.Rank > 3)
                return "Achieved " + detail.Rank + "th place on " + detail.Level + getFriendsBeatString(detail) + score;

        case 4:
            return "Earned " + detail.DailyCredits + " daily credits for being king. A value of $" + (detail.DailyCredits / 10) + " USD!";
    }
}

function getFriendsBeatString(detail) {
    var Friends = "";
    if (detail.Friends.length == 1) {

        Friends = " and beat their friend: " + getFriendSocialLink(detail.Friends[0]);
    }
    else if (detail.Friends.length == 2) {
        Friends = " and beat their friends: " + getFriendSocialLink(detail.Friends[0]) + " and " + getFriendSocialLink(detail.Friends[1]);
    }
    else if (detail.Friends.length == 3) {
        Friends = " and beat their friends: " + getFriendSocialLink(detail.Friends[0]) + ", " + getFriendSocialLink(detail.Friends[1]) + " and " + getFriendSocialLink(detail.Friends[2]);
    }
    else if (detail.Friends.length == 4) {
        Friends = " and beat their friends: " + getFriendSocialLink(detail.Friends[0]) + ", " + getFriendSocialLink(detail.Friends[1]) + ", " + getFriendSocialLink(detail.Friends[2]) + " and 1 other friend";
    }
    else if (detail.Friends.length > 4) {
        Friends = " and beat their friends: " + getFriendSocialLink(detail.Friends[0]) + ", " + getFriendSocialLink(detail.Friends[1]) + ", " + getFriendSocialLink(detail.Friends[2]) + " and " + (detail.Friends.length - 3) + " other friends";
    }
    return Friends;
}

function getFriendSocialLink(friend) {
    return "<a href='http://www.facebook.com/profile.php?id=" + friend.ID + "' target='_blank'><img src='http://graph.facebook.com/" + friend.ID + "/picture' height=16 width=16 alt='profile'/><b> " + friend.Name + "</b></a>";
}

function getFeedIcon(obj) {
    var icon = "Images/EventIcons/";
    var detail = $.parseJSON(obj.Detail);

    switch (obj.Type) {
        case 1:
            if (detail.Bounty > 0)
                icon += "Bounty60Box.png";
            else
                icon += "King60Box.png";


            break;
        case 2:
            icon += "PersonalBest60Box.png";
            break;
        case 3:
            icon += "NewRank60Box.png";
            break;
        default:
            icon += "Daily60Box.png";
            break;
    }
    return icon;
}

function getFeedGameDiv(obj) {
    var detail = $.parseJSON(obj.Detail);

    var div = "<div class='GameIcon'><a href='";
    var imgStart = "<img src='";
    var imgEnd = "'height=64 width=64 alt='gameIcon'/>";
    var instanceUrl = "";

    if (detail.InstanceID)
        instanceUrl = "?InstanceID=" + detail.InstanceID;
    switch (obj.GameID) {
        case "2c68c2c9-0d87-4752-adb7-51f93ea38fb7":
            //Brick Breaker King
            div += "BrickBreakerKingPlay.aspx'>" + imgStart + "Images/GameButtons/brickBreakerKing_icon.png" + imgEnd;
            break;
        case "c72ced34-3182-4655-83f9-7b2e42041784":
            //Block Drop
            div += "ReActionPlay.aspx" + instanceUrl + "'>" + imgStart + "Images/GameButtons/reaction_icon.png" + imgEnd;
            break;
        case "5ef3eb8f-9fb6-4451-ad46-2de5d877491f":
            //Block Drop
            div += "DungeonFighterPlay.aspx" + instanceUrl + "'>" + imgStart + "Images/GameButtons/dungeonFighter_icon.png" + imgEnd;
            break;
        default:
            div += "/'>" + imgStart + "Images/boxBlue_80.png" + imgEnd;
            break;
    }
    div += "</a></div>"
    return div;
}

function sendFeedRequest(type) {
    var funcCall = "GetGamesFeed";
    var sendData = "";

    if (type == "new") {
        funcCall = "GetGamesFeedNewer";
        sendData = "{'FeedID':'" + $('.FeedId:first').html() + "'}";
    }
    $.ajax({
        type: "POST",
        url: "webconnector.asmx/" + funcCall,
        data: sendData,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
            recieveFeed(msg.d, type);
            syncServerTime();
        },
        error: function (e) {
            //optional error handling
        }
    });


    function recieveFeed(data, type) {
        var obj = $.parseJSON(data);

        //Icon
        var design = "";
        var icon = "";
        var name = "";
        var pic = "";
        var title = "";
        var time = "";
        var ids = new Array();

        var hidden = "";

        $.each(obj, function (i) {
            try {
                icon = "<div class='FeedIcon'><img src='" + getFeedIcon(obj[i]) + "' alt='post'></img></div>";

                pic = "<div class='FeedPic'><a href='http://www.facebook.com/profile.php?id=" + obj[i].PlatformUserId + "' target='blank'><img src='http://graph.facebook.com/" + obj[i].PlatformUserId + "/picture' height=45 width=45 alt='profile'/></a></div>";

                var username = obj[i].FirstName;
                if (obj[i].LastName != null) {
                    username += " " + obj[i].LastName;
                }

                name = "<div class='FeedName'><a href='http://www.facebook.com/profile.php?id=" + obj[i].PlatformUserId + "' target='blank'><b>" + username + "</b></a></div>";

                time = "<div class='FeedTime'></div><div class='FeedId'>" + obj[i].Id + "</div><div class='FeedPostDate'>" + obj[i].PostDate + "</div>";

                title = "<div class='FeedTitle'>" + getFeedBody(obj[i]) + "</div>";

                if (type == "new")
                    hidden = "display:none";
                else
                    hidden = "";

                design += "<div class='FeedElement' style='" + hidden + "'><div style='float:left; width:600px;'>" + icon + name + pic + title + "</div>" + getFeedGameDiv(obj[i]) + time;

                design += "</div>";
            }
            catch (err) {
                return true;
            }

        });
        if (type == "new") {

            if (design) {
                $('#feed').prepend(design);
                fadeIn(obj.length);
            }
        }
        else {
            $('#feed').html();
            $('#feed').append(design);
        }

    };
}

function fadeIn(count) {
    $('.FeedElement').each(function (i) {
        $(this).fadeIn(3000, function () {
            // Animation complete
        });
        if (i == (count - 1)) {
            return false;
        }
    });
}


function getDifferenceString(itemDate, currServerTime) {
    var datetimeRow = new Date(itemDate);
    var timeServer = new Date(currServerTime);
    var minDiff = (timeServer - datetimeRow) / 60000;
    if (minDiff < 1) {
        return 'a few seconds ago';
    }
    else if (minDiff <= 59) {
        return formatDateDifferenceCaption('Minute', minDiff);
    }
    else if (minDiff > 59 && minDiff < 1340) {
        return formatDateDifferenceCaption('Hour', minDiff / 60);
    }
    else if (minDiff >= 1340) {
        return formatDateDifferenceCaption('Day', minDiff / 1440);
    }
}

function formatDateDifferenceCaption(type, amount) {
    var roundedamt = Math.round(amount);
    if (roundedamt > 1) {
        return roundedamt + ' ' + type + 's ago';
    }
    else {
        return roundedamt + ' ' + type + ' ago';
    }
}
