﻿GameString = {
    Page: {
        FBSession: null,
        FBUser: null,
        Controls: {
    }
},
JavaScriptStringEncode: function (sString) {
    return (sString + "").replace(/[\0-\x1F\"\\\x7F-\xA0\u0100-\uFFFF]/g, function (sChar) {
        switch (sChar) {
            case "\b": return "\\b";
            case "\t": return "\\t";
            case "\n": return "\\n";
            case "\f": return "\\f";
            case "\r": return "\\r";
            case "\\": return "\\\\";
            case "\"": return "\\\"";
        }
        var iChar = sChar.charCodeAt(0);
        if (iChar < 0x10) return "\\x0" + iChar.toString(16);
        if (iChar < 0x100) return "\\x" + iChar.toString(16);
        if (iChar < 0x1000) return "\\u0" + iChar.toString(16);
        return "\\u" + iChar.toString(16);
    });
},
Serialize: function (xValue) {
    switch (typeof (xValue)) {
        case "undefined": return "void(0)";
        case "boolean": return xValue.toString();
        case "number": return xValue.toString();
        case "string": return "\"" + GameString.JavaScriptStringEncode(xValue) + "\"";
        case "function": return "eval(\"" + GameString.JavaScriptStringEncode(xValue.toString()) + "\")";
        case "object":
            if (xValue == null) return "null";
            var bArray = true;
            var asObjectValues = [], asArrayValues = [], iCounter = 0, iLength = null;
            for (var i in xValue) {
                if (bArray) switch (i) {
                    case "length":
                        // Part of an array but not stored, keep so we can check
                        // if the length is correct
                        break;
                    case iCounter.toString():
                        // Part of an array and stored, but he index must be sequential starting at 0.
                        iCounter++;
                        asArrayValues.push(GameString.Serialize(xValue[i]));
                        break;
                    default:
                        // Not an array
                        bArray = false;
                }
                asObjectValues.push(GameString.Serialize(i) + ":" + GameString.Serialize(xValue[i]));
            }
            if (bArray) {
                try {
                    bArray &= (xValue.length == iCounter);
                } catch (e) {
                    bArray = false;
                }
            }
            return (bArray ?
        				"[" + asArrayValues.join(",") + "]" :
        				"{" + asObjectValues.join(",") + "}"
        			);
        default:
            throw new Error("Objects of type " + typeof (xValue) + " cannot be serialized.");
    }
},
addLoadEvent: function (func) {
    var oldonload = window.onload;
    if (typeof window.onload != 'function') {
        window.onload = func;
    }
    else {
        window.onload = function () {
            oldonload();
            func();
        }
    }
},
Utils: {
    parseDate: function (date) {
        var dSplit = date.split('/');
        var m = parseInt(dSplit[0]) - 1;
        var d = parseInt(dSplit[1]);
        var y = parseInt(dSplit[2]);
        date = new Date(y, m, d);
        var da = new Date();
        var gmtHours = da.getTimezoneOffset() / 60;
        date.setTime(date.getTime() - (gmtHours * 60 * 60 * 1000));
        return date;
    },
    toLocalTime: function (date) {
        if (typeof (date) == "string") {
            // parse string ex: '6/30/2010 10:17:11 PM'
            var dt = date.substr(0, date.indexOf(' '));
            var tt = date.substr(date.indexOf(' ') + 1);
            var dSplit = dt.split('/');
            var m = parseInt(dSplit[0]) - 1;
            var d = parseInt(dSplit[1]);
            var y = parseInt(dSplit[2]);
            var tSplit = tt.split(':');
            var hh = parseInt(tSplit[0]);
            var mm = parseInt(tSplit[1]);
            var ss = parseInt(tSplit[2]);
            if (tSplit[2].indexOf('PM') > 0) {
                hh = hh + 12;
            }
            date = new Date(y, m, d, hh, mm, ss);
        }
        var daa = new Date();
        var gmtHours = daa.getTimezoneOffset() / 60;
        date.setTime(date.getTime() - (gmtHours * 60 * 60 * 1000));
        return date;
    },
    toTimeAgoString: function (date) {
        var today = new Date();
        date = GameString.Utils.toLocalTime(date);
        //    date.add('m', -(date.getTimezoneOffset()));
        var diff = today.getTime() - date.getTime();
        var days = diff / (1000 * 60 * 60 * 24);
        if (days < 1) {
            var hours = (days - Math.floor(days)) * 24;
            if (hours < 1) {
                var min = (hours - Math.floor(hours)) * 60;
                if (min < 1) {
                    var sec = (min - Math.floor(min)) * 60;
                    return Math.floor(sec) + " seconds ago";
                }
                return Math.floor(min) + " minutes ago";
            }
            return Math.floor(hours) + " hours ago";
        }
        return Math.floor(days) + " days ago";

    },
    toDurationString: function (dur) {
        // duration is in millis
        var hh = dur / (60 * 60 * 1000);
        var th = Math.floor(hh);
        var mm = (hh - th) * 60;
        var tm = Math.floor(mm);
        var ss = (mm - tm) * 60;
        var ts = Math.round(ss);
        var ret = "";
        ret += (th < 10 ? "0" + th : th) + ":";
        ret += (tm < 10 ? "0" + tm : tm) + ":";
        ret += (ts < 10 ? "0" + ts : ts);
        return ret;
    },
    createElement: function (type, attrs) {
        var elm = document.createElement(type);
        if (attrs) {
            for (var aname in attrs) {
                elm.setAttribute(aname, attrs[aname]);
            }
        }
        return elm;
    },
    removeChildren: function (parent) {
        if (parent.hasChildNodes()) {
            while (parent.childNodes.length >= 1) {
                parent.removeChild(parent.firstChild);
            }
        }
    },
    getWinDims: function () {
        if (self.innerWidth) {
            _ac_winWidth = self.innerWidth;
            _ac_winHeight = self.innerHeight;
        }
        else if (document.documentElement && document.documentElement.clientWidth) {
            _ac_winWidth = document.documentElement.clientWidth;
            _ac_winHeight = document.documentElement.clientHeight;
        }
        else if (document.body) {
            _ac_winWidth = document.body.clientWidth;
            _ac_winHeight = document.body.clientHeight;
        }
        return [_ac_winWidth, _ac_winHeight];
    },
    findPos: function (obj) {
        var curleft = curtop = 0;
        if (obj.offsetParent) {
            curleft = obj.offsetLeft
            curtop = obj.offsetTop
            while (obj == obj.offsetParent) {
                curleft += obj.offsetLeft
                curtop += obj.offsetTop
            }
        }
        return [curleft, curtop];
    },
    round: function (val, places) {
        val = val * (10 * places);
        val = Math.round(val);
        return val / (10 * places);
    }
},
createCookie: function (name, value, days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    document.cookie = name + "=" + value + expires + "; path=/";
}, readCookie: function (name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
},
eraseCookie: function (name) {
    GameString.createCookie(name, "", -1);
},
Const: {
    GssDownloadLink: ''
},
Stream: {
    NONE: 0,
    GAMEFEED: 1,
    NOTIFICATION: 2
},
GameSession: {
    Permission: {
        PUBLIC: 0,
        PRIVATE: 1,
        PROTECTED: 2
    }
},
Permission: {
    OWNER: 0,
    FRIEND: 1,
    USER: 3,
    PUBLIC: 2
},
Windows: {
},
Facebook: {
    init: function () {
        var FB_APP_ID = "138617756203837";
        var FB_REDIRECT_URI = "http://apps.facebook.com/gamestring/";
        //var FB_PERMS = "email,publish_stream,offline_access,read_stream"; //comma separated list of extended permissions
        var FB_PERMS = "publish_stream"; //comma separated list of extended permissions

        FB.init({ appId: FB_APP_ID, status: true, cookie: true, xfbml: true });
        FB.getLoginStatus(function (response) {
            if (response.session) {
                GameString.Page.FBSession = response.session;
                FB.api('/me', function (response) {
                    alert(response.name);
                    GameString.Page.FBUser = response;
                });
            } else {
                var params = window.location.toString().slice(window.location.toString().indexOf('?'));
                top.location = 'https://graph.facebook.com/oauth/authorize?client_id=' + FB_APP_ID + '&scope=' + FB_PERMS + '&redirect_uri=' + FB_REDIRECT_URI + params;
            }
        });
    }
}
};







/////////////////////////////////////////////////////
//          START FriendList Script
/////////////////////////////////////////////////////


GameString.Page.Controls.gsFriendList = function (id, control, mode, isOwner, loadImgSrc, checkImgSrc, errImgSrc, title) { // New object constructor
    this.id = id;
    this.controlId = '#' + control;
    this.mode = mode;
    this.acceptFriendAction = null;
    this.denyFriendAction = null;
    this.sendFriendRequest = null;
    this.isOwner = isOwner;
    this.loadingImgSrc = loadImgSrc;
    this.errImgSrc = errImgSrc;
    this.checkImgSrc = checkImgSrc;
    this.json = null;
    this.list = null;
    this.title = title;
    this.bottomPager = null;
    this.topPager = null;
    this.pinfo = null;
    this.onDataNeeded = null;
    this.onRemoveMember = null;
};


GameString.Page.Controls.gsFriendList.prototype = {
    generateStreamItem: function (sd, prepend) {
        var html = '<li id="' + this.id + 'atiStreamItem' + sd["Id"] + '">' +
                        '<div class="friendWrapper' + (sd["RequestStatus"] == 1 ? ' unread' : '') + '">' +
                            '<ul class="hList friendAvatar">' +
                                '<li class="checkboxCell" style="margin-left: 16px;">' +
                                '<input type="checkbox" id="' + this.id + 'atiMessageCheck' + sd["Id"] + '" />' +
                                '</li>' +
                                '<li>' +
                                    (this.mode == "GROUP_LIST" ?
                                    '<a href="' + GameString.Page.PageBase + 'Account?us=' + sd["Id"] + '"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + sd["Id"] + '" /></a>'
                                    :
                                    '<a href="javascript: ;" onclick="top.location.href=\'' + GameString.Page.PageBase + 'Account?us=' + sd["Id"] + '\'"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + sd["Id"] + '" /></a>'
                                    ) +
                                '</li>' +
                            '</ul>' +
                            '<ul class="hList friendInfo">' +
                                '<li>' +
                                    (this.mode == "GROUP_LIST" ?
                                    '<a class="username" href="' + GameString.Page.PageBase + 'Account?u=' + sd["Id"] + '">' + sd["UserName"] + '</a><br />'
                                    :
                                    '<a class="username" href="javascript: ;" onclick="top.location.href=\'' + GameString.Page.PageBase + 'Account?u=' + sd["Id"] + '\'">' + sd["UserName"] + '</a><br />'
                                    ) +
                                    (sd["FirstName"] ?
                                    '<span>' + sd["FirstName"] + ' ' + sd["LastName"] + '</span>'
                                    :
                                    '<span>' + sd["Name"] + '<br />' + sd["Address"] + '</span>') +
                                '</li>' +
                                '<li class="friendActions">' +
                                    (this.mode == 'FRIEND_RESPONSE' ?
                                    '<button id="' + this.id + 'bFriendAccept' + sd["Id"] + '">Follow Gamer</button>'
                                    :
                                    ''
                                    ) +
                                    (this.mode == 'FRIEND_REQUEST' ?
                                        (sd["RequestStatus"] == 1 ?
                                        '<span class="pending">Request Pending</span>'
                                        :   // 0 = you are already friends
                                        (sd["RequestStatus"] == 0 ?
                                        'You are already friends'
                                        :
                                        '<a href="javascript: ;" id="' + this.id + 'bFriendRequest' + sd["Id"] + '">Send Friend Request</a>'
                                        ))
                                    :
                                    (this.isOwner ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bDelStream' + sd["Id"] + '">Delete</button>' // Delete "remove friend"
                                    :
                                    '')
                                    ) +
                                    (this.mode == 'MEMBER_ADMIN' ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bAdminMember' + sd["Id"] + '">MakeAdmin</button>'
                                    :
                                    '') +
                                    (this.mode == 'MEMBER_ADMIN' || this.mode == 'MEMBERADMIN_ADMIN' ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bDelStream' + sd["Id"] + '">Remove</button>'
                                    :
                                    ''
                                    ) +
                                    (this.mode == 'GROUP_INVITE' ?
                                        (sd["RequestStatus"] == 0 ?
                                        'Already a Member'
                                        :
                                        '<button style="margin-left: 10px;" id="' + this.id + 'bInviteMember' + sd["Id"] + '">Invite</button>')
                                    :
                                    '') +
                                    (this.mode == 'GROUP_JOIN' ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bJoin' + sd["Id"] + '">Join</button><button style="margin-left: 10px;" id="' + this.id + 'bDelStream' + sd["Id"] + '">Remove</button>'
                                    :
                                    '') +
                                '</li>' +
                            '</ul>' +
                        '</div>' +
                        '</li>';
        if (prepend) {
            this.list.prepend(html);
            $('#' + this.id + 'atiStreamItem' + sd["Id"]).hide();
            $('#' + this.id + 'atiStreamItem' + sd["Id"]).show("slow");
        } else {
            this.list.append(html);
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////
        // EVENTS Now attach the events to needed elements.
        /////////////////////////////////////////////////////////////////////////////////////////////////////////            
        var cid = this.id;  // (this.id) has new context iside the closures so save it under a new name
        var that = this;
        if (this.mode == "FRIEND_REQUEST") {
            $('#' + this.id + 'bFriendRequest' + sd["Id"]).button({ icons: { primary: "ui-icon-plus"} }).click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                if (that.sendFriendRequest != null) {
                    that.sendFriendRequest(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0');
                    $('#' + cid + 'bFriendRequest' + sd["Id"]).html('<img src="' + that.checkImgSrc + '" />');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(3500);
                } else {
                    alert('No function defined for: sendFriendRequest');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'bFriendRequest' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
            });
        } else if (this.mode == "FRIEND_RESPONSE" && this.isOwner) {
            $('#' + this.id + 'bFriendAccept' + sd["Id"]).button({ icons: { primary: "ui-icon-check"} }).click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                // TODO: add a spinner graphic by the txt or something.                    
                if (that.acceptFriendAction != null) {
                    that.acceptFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.checkImgSrc + '" />');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(3500);
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
                return false;
            });
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                event.stopPropagation();
                if (confirm("Are you sure you want to reject this friend request?")) {
                    if (that.denyFriendAction != null) {
                        that.denyFriendAction(sd["Id"]);
                        $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                        //    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.checkImgSrc + '" />');
                        $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(1500);
                    } else {
                        alert('No function defined for: denyFriendAction');
                        $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'cc9999');
                        $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                    }
                }
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        } else if (this.mode == 'FOLLOWING_LIST' && this.isOwner) {
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                alert('delete click');
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        } else if (this.mode == 'MEMBER_ADMIN' || this.mode == 'MEMBERADMIN_ADMIN') {
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                if (that.onRemoveMember != null) {
                    that.onRemoveMember(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(1500);
                } else {
                    alert('No function defined for: onRemoveMember');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'cc9999');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
            $('#' + cid + 'bAdminMember' + sd["Id"]).button().click(function (event) {
                if (that.onMakeMemberAdmin != null) {
                    that.onMakeMemberAdmin(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(1500);
                } else {
                    alert('No function defined for: onMakeMemberAdmin');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'cc9999');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
                event.stopPropagation();
                return false;
            })
        } else if (this.isOwner) {
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                alert('TODO:');
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        } else if (this.mode == 'GROUP_INVITE') {
            $('#' + this.id + 'bInviteMember' + sd["Id"]).button().click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                if (that.acceptFriendAction != null) {
                    that.acceptFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0').fadeOut(3500);
                    $(this).html('<img src="' + that.checkImgSrc + '" />');
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $(this).html('<img src="' + that.errImgSrc + '" />');
                }
                return false;
            });

        } else if (this.mode == 'GROUP_JOIN') {
            $('#' + this.id + 'bJoin' + sd["Id"]).button().click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                if (that.acceptFriendAction != null) {
                    that.acceptFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0').fadeOut(3500);
                    $(this).html('<img src="' + that.checkImgSrc + '" />');
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $(this).html('<img src="' + that.errImgSrc + '" />');
                }
                return false;
            });
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                if (that.denyFriendAction != null) {
                    that.denyFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0').fadeOut(3500);
                    $(this).html('<img src="' + that.checkImgSrc + '" />');
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $(this).html('<img src="' + that.errImgSrc + '" />');
                }
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////
    },
    setTopPager: function (pager) {
        this.topPager = pager;
        this.topPager.hide();
        var that = this;
        this.topPager.onPageBack = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        this.topPager.onPageForward = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        if (this.pinfo) {
            this.topPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.topPager.show();
            }
        }
    },
    setBottomPager: function (pager) {
        this.bottomPager = pager;
        this.bottomPager.hide();
        var that = this;
        this.bottomPager.onPageBack = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        this.bottomPager.onPageForward = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        if (this.pinfo) {
            this.bottomPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.bottomPager.show();
            }
        }
    },
    generateStreamDom: function (results) {      
        var res = results;
        if (typeof (results) == "string") {
            res = eval("(" + results + ")");
        }
        this.pinfo = res.PagerInfo;
        if (this.topPager != null) {
            this.topPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.topPager.show();
            }
        } if (this.bottomPager != null) {
            this.bottomPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.bottomPager.show();
            }
        }
        this.json = res.Data;
        $(this.controlId).children().remove();
        if (this.mode == "FRIEND_REQUEST") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                            '<div><button id="bSendFriendRequest">Send Friend Request</button>' +
                                            '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' found</span>' +
                                            '</div>' +
                                            '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                        '</div>' +
                                        '<ul class="atiUserList" id="' + this.id + 'atiStreamList" style="margin: 0px; padding: 0px;"></ul>');
        } else if (this.mode == "FRIEND_LIST") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                                '<div style="min-height: 20px;">' +
                                                (this.isOwner ?
                                                '<button id="bDefriend">Defriend</button>'
                                                : '') +
                                                '<span>' + this.pinfo.Length + ' friends</span>' +
                                                '</div>' +
                                                '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList" style="margin: 0px; padding: 0px;"></ul>');
        } else if (this.mode == "GROUP_INVITE") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
            //  '<div><button id="bSendFriendRequest">Send Group Invite</button>' +
                                            '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' found</span>' +
                                            '</div>' +
                                            '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                        '</div>' +
                                        '<ul class="atiUserList" id="' + this.id + 'atiStreamList" style="margin: 0px; padding: 0px;"></ul>');
        } else if (this.mode == "GROUP_LIST" || this.mode == "MEMBER_ADMIN" || this.mode == "MEMBERADMIN_ADMIN" || this.mode == "GROUP_JOIN") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                                '<div style="min-height: 20px;">' +
                                                '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' found</span>' +
                                                '</div>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList" style="margin: 0px; padding: 0px;"></ul>');
        } else if (this.mode == "FRIEND_RESPONSE") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE"><h2>New Followers</h2>' +
                                                '<div><button id="bAccept">Follow</button><button id="bReject">Ignore</button>' +
                                                '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' requests</span>' +
                                                '</div>' +
                                                '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList" style="margin: 0px; padding: 0px;"></ul>');
        } else if (this.mode == "FOLLOWING_LIST") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                                '<div style="padding: 6px;">&nbsp;' +
                                                '<span class="title">' + this.title + '</span><span>Following: ' + this.pinfo.Length + '</span>' +
                                                '</div>' +
                                                '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList" style="margin: 0px; padding: 0px;"></ul>');
        }
        this.list = $('#' + this.id + 'atiStreamList');
        if (this.json.length <= 0) {
            $('#' + this.id + 'atiStreamList').append('<li><div class="noResults">No results were found.</div></li>');
        }
        for (var i = 0; i < this.json.length; i++) {
            this.generateStreamItem(this.json[i], false);
        }
        $('#bAccept, #bReject').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        $('#bGrouLeave').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        $('#bDefriend').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        $('#bSendFriendRequest').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        var cid = this.id;
        $('#' + this.id + 'selectAll').click(function () {
            $('#' + cid + 'atiStreamList input:checkbox').attr("checked", true);
        });
        $('#' + this.id + 'selectNone').click(function () {
            $('#' + cid + 'atiStreamList input:checkbox').attr("checked", false);
        });

    }
};
/////////////////////////////////////////////////////
//          END TimeSpan Script
/////////////////////////////////////////////////////




/////////////////////////////////////////////////////
//          *** Stream Script
/////////////////////////////////////////////////////


GameString.Page.Controls.GS_GameFeed = function (id, control, mode, skip, take, isSearch, editUrl, showTopPager, showBottomPager, showStreamSelect, atiStateSkipId, atiLoadingId) {
    this.id = id;
    this.controlId = '#' + control;
    this.json = null;
    this.list = null;
    this.start = parseInt(skip);
    this.take = take;
    this.mode = mode;
    this.isSearchMode = isSearch;
    this.editUrl = editUrl;
    this.MenuOptions = [];
    this.streamDeleteCallback = null;
    this.showTopPager = showTopPager;
    this.showBottomPager = showBottomPager;
    this.showStreamSelect = showStreamSelect;
    this.$atiStateSkip = $('#' + atiStateSkipId);
    this.$atiLoading = $('#' + atiLoadingId);
    this.onDeleteComment = null;
    this.onNeedData = null;
    this.noDataHtml = '<h2>No Data</h2>';
};

GameString.Page.Controls.GS_GameFeed.prototype = {
    commentSaveSuccess: function (comm) {
        var comment = eval("(" + comm + ")");
        if (comment["UserStreamKey"] > 0) {
            var $comList = $('#atiCommentAdd' + comment["UserStreamKey"]);
            $comList.before('<li id="atiComment' + comment["Id"] + '">' +
                                            '<div class="commentBoxLeft"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + comment["UserSettingkey"] + '" /></div>' +
                                            '<div class="commentBoxRight">' +
                                                '<a class="username" href="' + GameString.Page.PageBase + "Account?u="+comment["UserName"] + '">' + comment["UserName"] + '</a>' +
                                                '<span>&nbsp;-&nbsp;' + comment["Text"] + '<br /></span>' +
                                                '<ol><li><a href="javascript: ;" class="time">' + GameString.Utils.toTimeAgoString(new Date(comment["DateTicks"])) + '</a></li></ol>' +
                                            '</div>' +
                                        '</li>');
            $("#atiComment" + comment["Id"]).hide().slideDown("slow");
            $('#commentTxt' + sd["Id"]).val('');
        } else {
            this.commentSaveFail(comm);
        }
    },
    commentSaveFail: function (comm) {
        // TODO: failed to save comment
        alert('fail');
        var comment = eval("(" + comm + ")");
        if (comment["StreamKey"] > 0) {
            var bComm = GameString.$("atiButtonAddComm" + comment["StreamKey"]);
            bComm.enabled = true;
            var txt = GameString.$("commentTxt" + sid);
            txt.enabled = true;
        }
    },
    clear: function () {
        $(this.controlId).children().remove();
    },
    deleteStreamFail: function (error) {
        var stackTrace = error.get_stackTrace();
        var message = error.get_message();
        var statusCode = error.get_statusCode();
        var exceptionType = error.get_exceptionType();
        var timedout = error.get_timedOut();
        var txtMessage = "{" +
            "Stack Trace: " + stackTrace + "; " +
            "Service Error: " + message + "; " +
            "Status Code: " + statusCode + "; " +
            "Exception Type: " + exceptionType + "; " +
            "Timedout: " + timedout + "}";
        alert(txtMessage);
    },
    prependJson: function (json) {
        json = eval('(' + json + ')');
        this.generateStreamItem(json, true);
    },
    generateStreamItem: function (sd, prepend) {
        var numRecipe = 0;
        var followers = 0;
        var following = 0;
        /*
        for (var i = 0; i < sd["Metrics"].length; i++) {
        if (sd["Metrics"][i]["MetricType"] == GameString.Metric.NUM_RECIPES) {
        numRecipe = sd["Metrics"][i]["MetricValue"];
        } else if (sd["Metrics"][i]["MetricType"] == GameString.Metric.NUM_FOLLOWERS) {
        followers = sd["Metrics"][i]["MetricValue"];
        } else if (sd["Metrics"][i]["MetricType"] == GameString.Metric.NUM_YOU_FOLLOW) {
        following = sd["Metrics"][i]["MetricValue"];
        }
        }
        */
        var linkTitle = sd["Title"].replace(/ /g, '_');
        var shareTitle = sd["Title"];
        linkTitle = linkTitle.replace(/\+/g, '');
        linkTitle = escape(linkTitle);
        var shareUrl = GameString.Page.PageBase + 'Player?g=' + sd["GameSessionKey"];
        var statsLink = GameString.Page.PageBase + 'Player?g=' + sd["GameSessionKey"];
        var gameLink = statsLink;
        if (sd["StreamType"] == GameString.Stream.NOTIFICATION) {
            statsLink = GameString.Page.PageBase + 'requests?n=' + sd["Id"];
            gameLink = GameString.Page.PageBase + 'requests?n=' + sd["Id"];
        }
        var html = '<li id="atiStreamItem' + sd["Id"] + '" class="atiStreamItem" style="border-top: 1px solid #EEE;">' +
                        '<div class="atiStreamItemLeft">' +
                            ((sd["StreamType"] == GameString.Stream.NOTIFICATION) ?
                            '<a class="title" href="' + recipeUrl + '"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/notificationType' + sd["NotificationType"] + '.png" class="dropShadow" /></a>'
                            :
                            '<a href="' + GameString.Page.PageBase + 'account?us=' + sd["Id"] + '"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + sd["UserSettingkey"] + '" class="dropShadow" /></a>'
                            ) +
                        '</div>' +
                        '<div class="atiStreamItemRight">' +
                            ((sd["StreamType"] == GameString.Stream.NOTIFICATION) ?
                            '<img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/src0.png" />'
                            :
                            (sd["ToUserSettingKey"] > 0 ?
                            '<a class="username" href="' + GameString.Page.PageBase + 'account?us=' + sd["UserSettingkey"] + '">' + sd["UserName"] + '</a><em>&gt;</em> <a class="username" href="' + GameString.Page.PageBase + sd["ToUserName"] + '">' + sd["ToUserName"] + '</a>'
                            :
                            '<a class="username" href="' + GameString.Page.PageBase + 'account?us=' + sd["UserSettingkey"] + '">' + sd["UserName"] + '</a><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/src0.png" />')
                            ) +
                            (sd["StreamType"] == GameString.Stream.GAMEFEED ?
                            '<a href="' + gameLink + '"><div class="_gamePreview" style="position: absolute; right: 0px; top: 0px;"><img class="_animImage" src="' + GameString.Page.PageBase + 'Portals/0/adrenalinsnapshots/' + sd["UserSettingkey"] + '/' + sd["GameSessionKey"] + '/_thumb.jpg" /></div></a>'
                            :
                            ''
                            ) +
                             ((GameString.Page.UserId == sd["UserKey"]) ? // if this is the owner
                                '<a class="deleteStream" id="aDelStream' + sd["Id"] + '" style="display:none; cursor: pointer;" title=\"delete\">[X]</a>'
                                :
                                '') +
                            '<a href="' + gameLink + '" class="title">' + sd["Title"] + '</a>' +
                            '<p>' + ((sd["Description"] != null ? sd["Description"] : '')) + '&nbsp;</p>' +
                            '<div id="attachments_' + this.id + '_' + sd["Id"] + '" style="position: relative; margin-top: 10px;"></div>' +
                            '<ul class="hlist streamTools">' +

                                '<li class="shareStream">' +
                                    '<a href="javascript: ;" class="time" title="' + GameString.Utils.toLocalTime(sd["DateTicks"]).toString() + '">' + GameString.Utils.toTimeAgoString(sd["DateTicks"]) + '</a>' +
                                    '<span class="toolDiv">|</span>' +
                                    ((sd["StreamType"] == GameString.Stream.NOTIFICATION) ?
                                    (sd["WODKey"] > 0 ?
                                    '<button id="bWODInfo' + sd["Id"] + '">View Workout Info</button>'
                                    :
                                    (sd["MessageKey"] > 0) ?
                                    '<button id="bMessageInfo' + sd["Id"] + '">View Message</button>'
                                    :
                                    '') +
                                    '<button id="bRemNotification' + sd["Id"] + '">Remove Notification</button>'
                                    :
                                    '<img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/iPermission' + sd["Permission"] + '.png" title="' + (sd["Permission"] == 0 ? 'Public' : (sd["Permission"] == 1 ? 'Private' : 'Protected')) + '" />&nbsp;&nbsp;' +
                                    '<span class="toolDiv">|</span>' +
                                    '<a target=\"_blank\" href=\"http://twitter.com/share?url=' + shareUrl + '&related=flexfwd&text=' + shareTitle + '\" alt="Share on Twitter" title="Share on Twitter"><img src=\"' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/iTwitter.png\" /></a>' +
                                    '<span class="toolDiv">|</span>' +
                                    ((sd["StreamType"] != GameString.Stream.NOTIFICATION && sd["StreamType"] != GameString.Stream.RECIPE && GameString.Page.UserSettingsId > 0)
                                    ?
                                    '<a href="javascript: ;" id="atiLinkAddComment' + sd["Id"] + '"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/iComment.png" align="absmiddle" />&nbsp;comment</a>'
                                    :
                                    '<span style="padding-right: 9px; padding-left: 9px;">' + sd["Comments"].length + ' comments</span>'
                                    )) +
                                '</li>' +
                            '</ul>' +
                            '<ul class="atiCommentBox" id="atiCommentList' + this.id + '_' + sd["Id"] + '">' +
                            '</ul>' +
                            '<br style="clear: both;">' +
                        '</div></li>';
        var that = this;
        if (prepend) {
            this.list.prepend(html);
            $("#atiStreamItem" + sd["Id"]).hide();
            $("#atiStreamItem" + sd["Id"]).show("slow");
        } else {
            this.list.append(html);
        }
        /*
        if (sd["Attachments"].length > 0) {
        var $attachDiv = $('#attachments_' + this.id + '_' + sd["Id"]);
        for (var a = 0; a < sd["Attachments"].length; a++) {
        var attachment = sd["Attachments"][a];
        // should check the type here..
        if (attachment.Type == 1) { // photo
        $attachDiv.append('<a href="javascript: ;" onclick="GameString.Windows.PhotoWin.open(' + attachment.Id + ',\'' + sd["UserName"] + '\');"><img src="' + attachment.ThumbUrl + '" /></a>');
        } else if (attachment.Type == 2) { // link
        $attachDiv.append('<a href="' + attachment.LinkUrl + '"><div id="imgSelector" style="width: 80px; height: 60px; background-size: 100%; background-repeat:no-repeat; background-image:url(' + attachment.ThumbUrl + ');"></div></a>' +
        '<ul style="position: absolute; top: 0px;left: 100px; width: 300px; overflow:hidden;">' +
        '<li><a class="username" href="' + attachment.LinkUrl + '">' + attachment.LinkUrl + '</a></li>' +
        '<li>' + attachment.Title + '</li>' +
        '<li>' + attachment.Description + '</li>' +
        '</ul>');
        }
        }
        }
        */
        if (sd["Comments"] && (sd["StreamType"] != GameString.Stream.RECIPE)) {                   // append all comments to the list
            var $commentList = $('#atiCommentList' + that.id + '_' + sd["Id"]);
            for (var j = 0; j < sd["Comments"].length; j++) {
                (function () {  // create a closure 
                    var comment = sd["Comments"][j];
                    $commentList.append('<li id="atiComment' + comment["Id"] + '">' +
                                            '<div class="commentBoxLeft"><a href="' + GameString.Page.PageBase + 'account?us=' + comment["UserSettingkey"] + '"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + comment["UserSettingkey"] + '" /></a></div>' +
                                            '<div class="commentBoxRight">' +
                                                '<a class="username" href="' + GameString.Page.PageBase + 'account?us=' + comment["UserSettingkey"] + '">' + comment["UserName"] + '</a>' +
                                                '<span style="padding-right: 16px;">&nbsp;-&nbsp;' + comment["Text"] + '<br /></span>' +
                                                '<ul>' +
                                                    '<li><a href="javascript: ;" class="time" title="' + GameString.Utils.toLocalTime(comment["DateTicks"]).toString() + '">' + GameString.Utils.toTimeAgoString(comment["DateTicks"]) + '</a></li>' +
                                                    ((GameString.Page.UserId == comment["UserKey"]) ? // if this is the owner 
                                                    '<li class="deleteComment"><a href="javascript: ;" id="bDelComment' + comment["Id"] + '" class="hidden">[X]</a></li>'
                                                    :
                                                    '') +
                                                    '<li>' +
                                                '</ul>' +
                                            '</div>' +
                                        '</li>');
                    $('#atiComment' + comment["Id"]).hover(function () {
                        $('#bDelComment' + comment["Id"]).removeClass('hidden');
                    }, function () {
                        $('#bDelComment' + comment["Id"]).addClass('hidden');
                    });
                    $('#bDelComment' + comment["Id"]).click(function (event) {
                        if (confirm("Are you sure you want to delete?")) {
                            if (that.onDeleteComment) {
                                $("#atiComment" + comment["Id"]).hide("slow");
                                that.onDeleteComment(comment["Id"]);
                                //AfterCAD.WebService.StreamService.deleteComment(GameString.Page.UserId, GameString.Page.PortalId, GameString.Page.ProfileId, comment["Id"], function (json) { that.deleteCommentSuccess(json); }, function (json) { that.deleteStreamFail(json); });
                            }
                        }
                        event.stopPropagation();
                        return false;
                    });
                })();   // end closure ... and call it.
            }
            $commentList.append('<li id="atiCommentAdd' + sd["Id"] + '" style="display:none;">' +
                                    '<div class="commentBoxLeft">' +
                                        '<img src="' + GameString.Page.PageBase + "DesktopModules/GS_Base/services/images/profile.aspx?us=" + GameString.Page.UserSettingsId + '" />' +
                                    '</div>' +
                                    '<div class="commentBoxRight">' +
                                        '<img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/resources/images/speak.png" class="speak" />' +
                                        '<textarea id="commentTxt' + sd["Id"] + '" />' +
                                        '<button id="atiButtonAddComm' + sd["Id"] + '" type="button">done</button> <span style="font-size: 8px;">max (1024 characters)</span>' +
                                    '</div>' +
                                    '</li>');
            $('#commentTxt' + sd["Id"]).focus(function (event) {
                $(this).addClass('txtCommentFocus');
                event.stopPropagation();
                return false;
            });
            $('#atiButtonAddComm' + sd["Id"]).button().click(function () {
                var $txt = $('#commentTxt' + sd["Id"]);
                if ($txt.val() != "") {
                    $('#atiLinkAddComment' + sd["Id"]).trigger('click');
                    AfterCAD.WebService.StreamService.addComment(GameString.Page.UserSettingsId, GameString.Page.ProfileUserSettingsId, sd["Id"], $txt.val(), function (json) { that.commentSaveSuccess(json); }, function (json) { that.commentSaveFail(json); });
                } else {
                    $('#atiLinkAddComment' + sd["Id"]).trigger('click');
                }
            });
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////
        // EVENTS Now attach the events to needed elements.
        /////////////////////////////////////////////////////////////////////////////////////////////////////////
        //$('#atiLinkAddComment' + sd["Id"]).button({ icons: { primary: 'ui-icon-comment'} })
        $('#atiLinkAddComment' + sd["Id"]).click(function (event) {
            var $txt = $('#atiLinkAddComment' + sd["Id"]);
            var $comment = $("#atiCommentAdd" + sd["Id"]);
            if (!$comment.is(':visible')) {
                $comment.fadeIn("slow");
            } else {
                $comment.fadeOut("slow");
            }
            event.stopPropagation();
            return false;
        });
        if (sd["WODKey"] > 0) {
            $('#bWODInfo' + sd["Id"]).button().click(function (event) {
                top.location.href = GameString.Page.PageBase + 'workout/' + sd["WODKey"] + "?rn=" + sd["Id"];
                event.stopPropagation();
                return false;
            });
        }
        /*
        $('#aEditStream' + sd["Id"]).click(function (event) {
        self.location.href= that.editUrl + '?s='+sd["Id"];
        event.stopPropagation();
        return false;
        });
        */
        $('#bMessageInfo' + sd["Id"]).button().click(function (event) {
            top.location.href = GameString.Page.PageBase + "Profile/Inbox?m=" + sd["MessageKey"] + "&rn=" + sd["Id"];
            event.stopPropagation();
            return false;
        });
        $('#bRemNotification' + sd["Id"]).button();
        $('#aDelStream' + sd["Id"] + ', #bRemNotification' + sd["Id"]).click(function (event) {
            if (confirm("Are you sure you want to delete?")) {
                if (that.streamDeleteCallback) {
                    that.streamDeleteCallback(sd["Id"]);
                    $('#atiStreamItem' + sd["Id"]).hide("slow");
                    $('#atiStreamItem' + sd["Id"]).children().remove();
                } else {
                    alert("no streamDeleteCallback has been set");
                }
            }
            event.stopPropagation();
            return false;
        });

        $('#atiStreamItem' + sd["Id"]).hover(function () {
            $('#aDelStream' + sd["Id"]).show();
        }, function () {
            $('#aDelStream' + sd["Id"]).hide();
        });

        /////////////////////////////////////////////////////////////////////////////////////////////////////////
    },
    clearAndShowLoad: function () {
        this.clear();
        this.$atiLoading.show();
    },
    generateStreamDom: function (json) {
        $('#bStreamNext, #bStreamNext2').button('enable');
        if (this.start < 0) {
            this.start = 0;
        }
        this.json = eval("(" + json + ")");
        var that = this;
        var atEnd = false;
        if (this.json.length < this.take) {
            atEnd = true;
        }
        $(this.controlId).css('width', '100%');
        if (this.json.length == 0 && this.start == 0) {
            $(this.controlId).append('<div style="text-align: center;padding-top: 30px; padding-bottom: 30px;">' + this.noDataHtml + '<ul class="atiStreamList" id="atiStreamList' + this.id + '"></ul></div>');
            this.list = $('#atiStreamList' + this.id);
            this.$atiLoading.hide();
        } else {
            if (this.$atiLoading.is(':visible')) {    // this is a hack.. (we use this to tell if this is the first time rendered or not) 
                $(this.controlId).append((this.showTopPager ?
                                            '<div class="messageListHead">' +
                                               '<div><div style="float: right;"><button id="bStreamBack">Newer</button> ' + this.start + ' to ' + (this.start + this.json.length) + ' <button id="bStreamNext">Older</button></div></div>' +
                                            '</div>' :
                                            '') +
                                            (this.showStreamSelect ?
                                            '<div id="atiStreamSelect"><input type="radio" id="ssFriends" name="radio" ' + (this.mode == 0 ? ' checked="checked"' : '') + '/><label for="ssFriends">' + GameString.Page.ProfileUserName + '&nbsp;+&nbsp;Friends</label><input type="radio" id="ssMe" name="radio"' + (this.mode == 3 ? ' checked="checked"' : '') + '/><label for="ssMe">Just ' + GameString.Page.ProfileUserName + '</label></div>'
                                            :
                                            ''
                                            ) +
                                            '<ul class="atiStreamList" id="atiStreamList' + this.id + '"></ul>' +
                                            (this.showBottomPager ?
                                            '<div class="messageListHead">' +
                                                '<div><div style="float: right;"><button id="bBackToFullStream" style="display: none;">Back to full stream</button><button id="bStreamNext2">More ..</button></div></div>' +
                                            '</div>' :
                                            '')
                                            );
                this.list = $('#atiStreamList' + this.id);
                this.$atiLoading.hide();
                if (this.showStreamSelect) {
                    $("#atiStreamSelect").buttonset();
                    $('#ssMe').click(function (event) {
                        that.clear();
                        that.$atiLoading.show();
                        that.getStreamData(3, '');
                        // return false;
                    });
                    $('#ssFriends').click(function (event) {
                        that.clear();
                        that.$atiLoading.show();
                        that.getStreamData(0, '');
                        // return false;
                    });
                }
                $('#bStreamBack, #bStreamBack2').button({
                    icons: {
                        primary: 'ui-icon-seek-prev'
                    }
                }).click(function (event) {
                    that.start = that.start - that.take;
                    that.$atiStateSkip.val(that.start);
                    that.getStreamData(that.mode, that.query);
                    event.stopPropagation();
                    return false;
                });
                $('#bStreamNext, #bStreamNext2').button({
                    icons: {
                        primary: 'ui-icon-seek-next'
                    }
                }).click(function (event) {
                    $('#bStreamNext, #bStreamNext2').button('disable');
                    that.start = that.start + that.take;
                    that.$atiStateSkip.val(that.start);
                    that.getStreamData(that.mode, that.query);
                    event.stopPropagation();
                    return false;
                });

            }
            for (var i = 0; i < this.json.length; i++) {
                this.generateStreamItem(this.json[i], false);
            }

            if (this.start <= 0) {
                $('#bStreamBack, #bStreamBack2').button('disable');
            }
            if (atEnd) {
                $('#bStreamNext, #bStreamNext2').button('disable');
            }
        }
    },
    getStreamItem: function (id, mode, query) {
        var that = this;
        AfterCAD.WebService.StreamService.getStreamItem(id, function (json) {
            that.generateStreamDom(json);
            $('#bBackToFullStream').button().show().click(function (event) {
                $(this).hide();
                that.clearAndShowLoad();
                that.getStreamData(mode, query);
                event.stopPropagation();
                return false;
            });
        });
    },
    getStreamData: function (mode, query) {
        //this.clear();
        this.mode = mode;
        var that = this;
        this.query = query;
        if (this.onNeedData) {
            this.onNeedData(this.start, this.take);
        } else {
            AfterCAD.WebService.StreamService.getStreamData(GameString.Page.GroupSettingsId, GameString.Page.UserSettingsId, GameString.Page.ProfileUserSettingsId, GameString.Page.Permission, this.mode, this.start, this.take,
                function (json) { that.generateStreamDom(json); },
            //   WebServiceFailedCallback
                function () { }
            );

        }
    }

};

var interval = 0;

$(function () {
    interval = setInterval(function () {
        $('img._animImage').each(function (ind) {
            var src = $(this).attr('src');
            var d = new Date();
            src = src.split('?')[0];
            src += "?t=" + d.getTime();
            $(this).attr('src', src);
            clearInterval(interval);
        });
    }, 9000);  // refresh 1 time after 9 sec...
}); 


/////////////////////////////////////////////////////
//          END Stream Script
/////////////////////////////////////////////////////


/////////////////////////////////////////////////////
//          START FriendList Script
/////////////////////////////////////////////////////


GameString.Page.Controls.atiFriendList = function (id, control, mode, isOwner, loadImgSrc, checkImgSrc, errImgSrc, title) { // New object constructor
    this.id = id;
    this.controlId = '#' + control;
    this.mode = mode;
    this.acceptFriendAction = null;
    this.denyFriendAction = null;
    this.sendFriendRequest = null;
    this.isOwner = isOwner;
    this.loadingImgSrc = loadImgSrc;
    this.errImgSrc = errImgSrc;
    this.checkImgSrc = checkImgSrc;
    this.json = null;
    this.list = null;
    this.title = title;
    this.bottomPager = null;
    this.topPager = null;
    this.pinfo = null;
    this.onDataNeeded = null;
    this.onRemoveMember = null;
};


GameString.Page.Controls.atiFriendList.prototype = {
    generateStreamItem: function (sd, prepend) {
        var html = '<li id="' + this.id + 'atiStreamItem' + sd["Id"] + '">' +
                        '<div class="friendWrapper' + (sd["RequestStatus"] == 1 ? ' unread' : '') + '">' +
                            '<ul class="hList friendAvatar">' +
                                '<li class="checkboxCell" style="margin-left: 16px;">' +
                                '<input type="checkbox" id="' + this.id + 'atiMessageCheck' + sd["Id"] + '" />' +
                                '</li>' +
                                '<li>' +
                                    (this.mode == "GROUP_LIST" ?
                                    '<a href="' + GameString.Page.PageBase + 'Account?us=' + sd["Id"] + '"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + sd["Id"] + '" /></a>'
                                    :
                                    '<a href="javascript: ;" onclick="top.location.href=\'' + GameString.Page.PageBase + 'Account?us=' + sd["Id"] + '\'"><img src="' + GameString.Page.PageBase + 'DesktopModules/GS_Base/services/images/profile.aspx?us=' + sd["Id"] + '" /></a>'
                                    ) +
                                '</li>' +
                            '</ul>' +
                            '<ul class="hList friendInfo">' +
                                '<li>' +
                                    (this.mode == "GROUP_LIST" ?
                                    '<a class="username" href="' + GameString.Page.PageBase + 'Account?us=' + sd["Id"] + '">' + sd["UserName"] + '</a><br />'
                                    :
                                    '<a class="username" href="javascript: ;" onclick="top.location.href=\'' + GameString.Page.PageBase + 'Account?us=' + sd["Id"] + '\'">' + sd["UserName"] + '</a><br />'
                                    ) +
                                    (sd["FirstName"] ?
                                    '<span>' + sd["FirstName"] + ' ' + sd["LastName"] + '</span>'
                                    :
                                    '<span>' + sd["Name"] + '<br />' + sd["Address"] + '</span>') +
                                '</li>' +
                                '<li class="friendActions">' +
                                    (this.mode == 'FRIEND_RESPONSE' ?
                                    '<button id="' + this.id + 'bFriendAccept' + sd["Id"] + '">Accept Request</button>'
                                    :
                                    ''
                                    ) +
                                    (this.mode == 'FRIEND_REQUEST' ?
                                        (sd["RequestStatus"] == 1 ?
                                        '<span class="pending">Request Pending</span>'
                                        :   // 0 = you are already friends
                                        (sd["RequestStatus"] == 0 ?
                                        'You are already friends'
                                        :
                                        '<a href="javascript: ;" id="' + this.id + 'bFriendRequest' + sd["Id"] + '">Send Friend Request</a>'
                                        ))
                                    :
                                    (this.isOwner ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bDelStream' + sd["Id"] + '">Delete</button>' // Delete "remove friend"
                                    :
                                    '')
                                    ) +
                                    (this.mode == 'MEMBER_ADMIN' ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bAdminMember' + sd["Id"] + '">MakeAdmin</button>'
                                    :
                                    '') +
                                    (this.mode == 'MEMBER_ADMIN' || this.mode == 'MEMBERADMIN_ADMIN' ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bDelStream' + sd["Id"] + '">Remove</button>'
                                    :
                                    ''
                                    ) +
                                    (this.mode == 'GROUP_INVITE' ?
                                        (sd["RequestStatus"] == 0 ?
                                        'Already a Member'
                                        :
                                        '<button style="margin-left: 10px;" id="' + this.id + 'bInviteMember' + sd["Id"] + '">Invite</button>')
                                    :
                                    '') +
                                    (this.mode == 'GROUP_JOIN' ?
                                    '<button style="margin-left: 10px;" id="' + this.id + 'bJoin' + sd["Id"] + '">Join</button><button style="margin-left: 10px;" id="' + this.id + 'bDelStream' + sd["Id"] + '">Remove</button>'
                                    :
                                    '') +
                                '</li>' +
                            '</ul>' +
                        '</div>' +
                        '</li>';
        if (prepend) {
            this.list.prepend(html);
            $('#' + this.id + 'atiStreamItem' + sd["Id"]).hide();
            $('#' + this.id + 'atiStreamItem' + sd["Id"]).show("slow");
        } else {
            this.list.append(html);
        }
        /////////////////////////////////////////////////////////////////////////////////////////////////////////
        // EVENTS Now attach the events to needed elements.
        /////////////////////////////////////////////////////////////////////////////////////////////////////////            
        var cid = this.id;  // (this.id) has new context iside the closures so save it under a new name
        var that = this;
        if (this.mode == "FRIEND_REQUEST") {
            $('#' + this.id + 'bFriendRequest' + sd["Id"]).button({ icons: { primary: "ui-icon-plus"} }).click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                if (that.sendFriendRequest != null) {
                    that.sendFriendRequest(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0');
                    $('#' + cid + 'bFriendRequest' + sd["Id"]).html('<img src="' + that.checkImgSrc + '" />');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(3500);
                } else {
                    alert('No function defined for: sendFriendRequest');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'bFriendRequest' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
            });
        } else if (this.mode == "FRIEND_RESPONSE" && this.isOwner) {
            $('#' + this.id + 'bFriendAccept' + sd["Id"]).button({ icons: { primary: "ui-icon-check"} }).click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                // TODO: add a spinner graphic by the txt or something.                    
                if (that.acceptFriendAction != null) {
                    that.acceptFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.checkImgSrc + '" />');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(3500);
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
                return false;
            });
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                event.stopPropagation();
                if (confirm("Are you sure you want to reject this friend request?")) {
                    if (that.denyFriendAction != null) {
                        that.denyFriendAction(sd["Id"]);
                        $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                        //    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.checkImgSrc + '" />');
                        $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(1500);
                    } else {
                        alert('No function defined for: denyFriendAction');
                        $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'cc9999');
                        $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                    }
                }
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        } else if (this.mode == 'FOLLOWING_LIST' && this.isOwner) {
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                alert('delete click');
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        } else if (this.mode == 'MEMBER_ADMIN' || this.mode == 'MEMBERADMIN_ADMIN') {
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                if (that.onRemoveMember != null) {
                    that.onRemoveMember(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(1500);
                } else {
                    alert('No function defined for: onRemoveMember');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'cc9999');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
            $('#' + cid + 'bAdminMember' + sd["Id"]).button().click(function (event) {
                if (that.onMakeMemberAdmin != null) {
                    that.onMakeMemberAdmin(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $('#' + cid + 'atiStreamItem' + sd["Id"]).fadeOut(1500);
                } else {
                    alert('No function defined for: onMakeMemberAdmin');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'cc9999');
                    $('#' + cid + 'bFriendAccept' + sd["Id"]).html('<img src="' + that.errImgSrc + '" />');
                }
                event.stopPropagation();
                return false;
            })
        } else if (this.isOwner) {
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                alert('TODO:');
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        } else if (this.mode == 'GROUP_INVITE') {
            $('#' + this.id + 'bInviteMember' + sd["Id"]).button().click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                if (that.acceptFriendAction != null) {
                    that.acceptFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0').fadeOut(3500);
                    $(this).html('<img src="' + that.checkImgSrc + '" />');
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $(this).html('<img src="' + that.errImgSrc + '" />');
                }
                return false;
            });

        } else if (this.mode == 'GROUP_JOIN') {
            $('#' + this.id + 'bJoin' + sd["Id"]).button().click(function (event) {
                event.stopPropagation();
                $(this).html('sending ... <img src="' + this.loadingImgSrc + '" />');
                $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'EFEFEF');
                if (that.acceptFriendAction != null) {
                    that.acceptFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0').fadeOut(3500);
                    $(this).html('<img src="' + that.checkImgSrc + '" />');
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $(this).html('<img src="' + that.errImgSrc + '" />');
                }
                return false;
            });
            $('#' + cid + 'bDelStream' + sd["Id"]).click(function (event) {
                if (that.denyFriendAction != null) {
                    that.denyFriendAction(sd["Id"]);
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'f1f6f0').fadeOut(3500);
                    $(this).html('<img src="' + that.checkImgSrc + '" />');
                } else {
                    alert('No function defined for: acceptFriendAction');
                    $('#' + cid + 'atiStreamItem' + sd["Id"] + ' .friendWrapper').css('background-color', 'ffebe8');
                    $(this).html('<img src="' + that.errImgSrc + '" />');
                }
                event.stopPropagation();
                return false;
            }).button({
                icons: {
                    primary: 'ui-icon-closethick'
                },
                text: false
            });
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////////
    },
    setTopPager: function (pager) {
        this.topPager = pager;
        this.topPager.hide();
        var that = this;
        this.topPager.onPageBack = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        this.topPager.onPageForward = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        if (this.pinfo) {
            this.topPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.topPager.show();
            }
        }
    },
    setBottomPager: function (pager) {
        this.bottomPager = pager;
        this.bottomPager.hide();
        var that = this;
        this.bottomPager.onPageBack = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        this.bottomPager.onPageForward = function (skip, take, len) {
            if (that.onDataNeeded) {
                that.onDataNeeded(skip, take);
            }
        }
        if (this.pinfo) {
            this.bottomPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.bottomPager.show();
            }
        }
    },
    generateStreamDom: function (results) {
        var res = results;
        if (typeof (results) == "string") {
            res = eval("(" + results + ")");
        }
        this.pinfo = res.PagerInfo;
        if (this.topPager != null) {
            this.topPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.topPager.show();
            }
        } if (this.bottomPager != null) {
            this.bottomPager.setPagerInfo(this.pinfo);
            if (this.pinfo.Length > this.pinfo.Take) {
                this.bottomPager.show();
            }
        }
        this.json = res.Data;
        $(this.controlId).children().remove();
        if (this.mode == "FRIEND_REQUEST") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                            '<div><button id="bSendFriendRequest">Send Friend Request</button>' +
                                            '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' found</span>' +
                                            '</div>' +
                                            '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                        '</div>' +
                                        '<ul class="atiUserList" id="' + this.id + 'atiStreamList"></ul>');
        } else if (this.mode == "FRIEND_LIST") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                                '<div style="min-height: 20px;">' +
                                                (this.isOwner ?
                                                '<button id="bDefriend">Defriend</button>'
                                                : '') +
                                                '<span>' + this.pinfo.Length + ' friends</span>' +
                                                '</div>' +
                                                '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList"></ul>');
        } else if (this.mode == "GROUP_INVITE") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
            //  '<div><button id="bSendFriendRequest">Send Group Invite</button>' +
                                            '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' found</span>' +
                                            '</div>' +
                                            '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                        '</div>' +
                                        '<ul class="atiUserList" id="' + this.id + 'atiStreamList"></ul>');
        } else if (this.mode == "GROUP_LIST" || this.mode == "MEMBER_ADMIN" || this.mode == "MEMBERADMIN_ADMIN" || this.mode == "GROUP_JOIN") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                                '<div style="min-height: 20px;">' +
                                                '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' found</span>' +
                                                '</div>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList"></ul>');
        } else if (this.mode == "FRIEND_RESPONSE") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE"><h2>Friend Requests</h2>' +
                                                '<div><button id="bAccept">Accept</button><button id="bReject">Reject</button>' +
                                                '<span class="title">' + this.title + '</span><span>' + this.pinfo.Length + ' requests</span>' +
                                                '</div>' +
                                                '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList"></ul>');
        } else if (this.mode == "FOLLOWING_LIST") {
            $(this.controlId).append('<div class="friendListHead grad-FFF-EEE">' +
                                                '<div style="padding: 6px;">&nbsp;' +
                                                '<span class="title">' + this.title + '</span><span>Following: ' + this.pinfo.Length + '</span>' +
                                                '</div>' +
                                                '<span>Select: <a href="javascript: ;" id="' + this.id + 'selectAll">All</a>, <a href="javascript: ;" id="' + this.id + 'selectNone">None</a>' +
                                            '</div>' +
                                            '<ul class="atiUserList" id="' + this.id + 'atiStreamList"></ul>');
        }
        this.list = $('#' + this.id + 'atiStreamList');
        if (this.json.length <= 0) {
            $('#' + this.id + 'atiStreamList').append('<li><div class="noResults">No results were found.</div></li>');
        }
        for (var i = 0; i < this.json.length; i++) {
            this.generateStreamItem(this.json[i], false);
        }
        $('#bAccept, #bReject').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        $('#bGrouLeave').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        $('#bDefriend').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        $('#bSendFriendRequest').button().click(function (event) {
            alert('TODO:');
            event.stopPropagation();
            return false;
        });
        var cid = this.id;
        $('#' + this.id + 'selectAll').click(function () {
            $('#' + cid + 'atiStreamList input:checkbox').attr("checked", true);
        });
        $('#' + this.id + 'selectNone').click(function () {
            $('#' + cid + 'atiStreamList input:checkbox').attr("checked", false);
        });

    }
};
/////////////////////////////////////////////////////
//          END TimeSpan Script
/////////////////////////////////////////////////////






/////////////////////////////////////////////////////
//         atiDataPager
/////////////////////////////////////////////////////
GameString.Page.Controls.gsPagerInfo = function () {
    this.Skip = 0;
    this.Take = 0;
    this.Length = 0;
};

GameString.Page.Controls.gsDataPager = function (id, control, bPev, bNext) {
    this.id = id;
    this.$pControl = $('#' + control);
    this.info = new GameString.Page.Controls.gsPagerInfo();
    this.onPageBack = null;
    this.onPageForward = null;
    var that = this;
    this.$bPev = $('#' + bPev).button({ disabled: true, icons: { primary: 'ui-icon-seek-prev'} }).click(function (event) {
        if (that.onPageBack) {
            var skip = that.info.Skip - that.info.Take;
            if (skip < 0) {
                skip = 0;
            }
            that.onPageBack(skip, that.info.Take, that.info.Length);
        }
        event.stopPropagation();
        return false;
    });
    this.$bNext = $('#' + bNext).button({ disabled: true, icons: { primary: 'ui-icon-seek-next'} }).click(function (event) {
        if (that.onPageForward) {
            var skip = that.info.Skip + that.info.Take;
            that.onPageForward(skip, that.info.Take, that.info.Length);
        }
        event.stopPropagation();
        return false;
    });
};

GameString.Page.Controls.gsDataPager.prototype = {
    removePagerControl: function () {
        this.$pControl.empty();
        return this.$pControl;
    },
    hide: function () {
        this.$pControl.hide();
    },
    show: function () {
        this.$pControl.show();
    },
    setPagerInfo: function (pinfo) {
        this.info = pinfo;
        var skip = this.info.Skip;
        var take = skip + this.info.Take;

        this.$pControl.find('span.pageStart').html(skip);
        this.$pControl.find('span.pageEnd').html(this.info.Length < take ? this.info.Length : take);
        if (this.info.Length > take) {
            this.$bNext.button("option", "disabled", false);
        } else {
            this.$bNext.button("option", "disabled", true);
        }
        if (skip > 0) {
            this.$bPev.button("option", "disabled", false);
        } else {
            this.$bPev.button("option", "disabled", true);
        }
        this.$pControl.find('span.totalLen').html(this.info.Length);
    }
};
/////////////////////////////////////////////////////
//         END Data Pager
/////////////////////////////////////////////////////






