// constructor of leaderboard object
function Leaderboard(name, tmpl, baseUrl, options)
{
	this.name = name;
	this.tmpl = tmpl;
	this.panel = jQuery('#' + name);
	this.panel.leaderboard = this;

	this.PageMode = 'home'; // home, game

	var leaderboard = this;
	this.panel.addClass('listen_login');
	this.panel.bind('login', function() { leaderboard.update('login'); });
	//this.panel.addClass('listen_init');
	//this.panel.bind('init', function() { leaderboard.update('init'); });
	this.panel.addClass('listen_logout');
	this.panel.bind('logout', function() { leaderboard.update('logout'); });

	this.NTop = 100;

	this.Type = "treats";
	this.UserID = 0;
	this.GameID = 0;
	this.Group = "all";
	this.Period = "today";
	this.TournamentID = 0;

	this.Current = undefined; // special row; hash of elements of current user
	this.baseUrl = baseUrl;

	jQuery.extend(this, options);

	// game mode init.
	if ('game' == this.PageMode)
		this.Type = 'score';

	// restore from cookies
	this.Type = jQuery.cookie('lbType_' + this.PageMode) || this.Type;
	this.Group = jQuery.cookie('lbGroup') || this.Group;
	this.Period = jQuery.cookie('lbPeriod') || this.Period;

	return this;
}

Leaderboard.prototype._saveCookies = function() {
	jQuery.cookie('lbType_' + this.PageMode, this.Type, { expires: 300, path: "/" });
	jQuery.cookie('lbGroup', this.Group, { expires: 300, path: "/" });
	jQuery.cookie('lbPeriod', this.Period, { expires: 300, path: "/" });
}

Leaderboard.prototype._render = function() {
	this.panel.html(this.tmpl(this));
	var leaderboard = this;

	this._saveCookies();
	
	// leaderboard user avatar popup
	var cur = jQuery("#lb_current", this.panel);
	if (cur.length > 0) {
		cur.avatar_anchor({
			beforeShow: function(item) {
				var l_pos = cur.offset();
				item.options.x = l_pos.left - 200;
				item.options.data = leaderboard.Current;
			}
		});
	}
	jQuery(".lb_item", this.panel).each(function() {
		var $this = jQuery(this);
		$this.avatar_anchor({
			beforeShow: function(item) {
				var l_pos = $this.offset();
				item.options.x = l_pos.left - 200;
				item.options.data = leaderboard.Items[item.attr('id').substring(8)];
			}
		});
	});

};
Leaderboard.prototype._getData = function() {
    var leaderboard = this;

    jQuery.ark.ajaxJSON(
		leaderboard.baseUrl + '/ajaxServices/Leaderboard.svc/GetLeaderboard',
		'{"leaderboardRequest":{'
			+ '"Type":"' + leaderboard.Type + '"'
			+ ',"Period":"' + leaderboard.Period + '"'
			+ ',"Group":"' + leaderboard.Group + '"'
			+ ',"GameID":' + leaderboard.GameID
			+ ',"TournamentID":' + leaderboard.TournamentID
			+ ',"NTop":' + leaderboard.NTop
			+ '}}',
		function(data) {
		    var listResponse = data.d;
		    var getRecord = function(listRecord) {
		        return {
		            UserID: listRecord[0],
		            UserName: listRecord[1],
		            Value: listRecord[2],
		            Rank: listRecord[3],
		            AvatarID: listRecord[4],
		            IsOnline: listRecord[5],
		            RatingID: listRecord[6],
		            TagLine: listRecord[7],
		            GreatRating: listRecord[8],
		            Timestamp: listRecord[9]
		        };
		    };
		    var response = {
		        UserID: listResponse[0]
                , Current: (null == listResponse[1] ? null : getRecord(listResponse[1]))
                , Items: []
		    };
		    for (var i = 0; i < listResponse[2].length; ++i)
		        response.Items[response.Items.length] = getRecord(listResponse[2][i]);
		    leaderboard._getData_CallBack(response);
		},
		leaderboard.panel);
};
Leaderboard.prototype._getData_CallBack = function(response) {
    var updateUrls = function(record) {
        if (null == record)
            return;
        var avatarID = (null == record.AvatarID ? 0 : record.AvatarID);
        record.UrlAvatar = jQuery.ark.StaticBaseUrl + "users/avatars/" + avatarID + "_32x32.jpg" + (0 == avatarID ? "" : "?" + record.AvatarID + record.UserID + record.Timestamp);
        record.UrlLargeAvatar = jQuery.ark.StaticBaseUrl + "users/avatars/" + avatarID + "_189x189.jpg" + (0 == avatarID ? "" : "?" + record.AvatarID + record.UserID + record.Timestamp);
        record.UrlRating = jQuery.ark.StaticBaseUrl + "static/img/user raiting/" + record.RatingID + "_" + (record.IsOnline ? "online" : "offline") + ".gif";
        record.UrlProfile = jQuery.ark.SiteBaseUrl + "/PersonProfile.aspx?userID=" + record.UserID;
    };
    this.UserID = response.UserID;
    this.Current = response.Current;
    updateUrls(this.Current);
    this.Items = response.Items == null ? [] : response.Items;
    for (var i = 0; i < this.Items.length; i++)
        updateUrls(this.Items[i]);
    this._render();
};

Leaderboard.prototype.update = function () {
	this._getData();
};

Leaderboard.prototype.update = function(event) {
    if (event == 'login') {
        jQuery("#Group_friends").attr('disabled', '');
    }
    if (event == 'logout') {
        jQuery("#Group_friends").attr('disabled', 'disabled');

        this.Group = 'all';
        jQuery('input[type=radio][name=Group][value=' + this.Group + ']').attr('checked', 'checked');
    }
    this._getData();
};

Leaderboard.OnlineStatus = function(isOnline) {
	return isOnline ? "Online" : "Offline";
};

function PrepareLeaderboard(pageMode, gameID, tournamentID, baseUrl, initial_data)
{
    var options = { PageMode: pageMode, GameID: gameID, TournamentID: tournamentID };
	if (!IsLoggedIn())
	{
		jQuery('#Group_friends').attr('disabled', 'disabled');
		options.Group = 'all';
	}
	var leaderboard = new Leaderboard('Leaderboard', tmpl('tmplLeaderboard'), baseUrl, options);
	var update = function()
	{
		leaderboard.Type = jQuery('input[type=radio][name=Type]:checked').val();
		leaderboard.Period = jQuery('input[type=radio][name=Period]:checked').val();
		leaderboard.Group = jQuery('input[type=radio][name=Group]:checked').val();
		leaderboard.update();
	}

	jQuery('input[type=radio][name=Type][value=' + leaderboard.Type + ']').attr('checked', 'checked');
	jQuery('input[type=radio][name=Period][value=' + leaderboard.Period + ']').attr('checked', 'checked');
	jQuery('input[type=radio][name=Group][value=' + leaderboard.Group + ']').attr('checked', 'checked');
	jQuery('input[type=radio][name=Type]').click(update);
	jQuery('input[type=radio][name=Period]').click(update);
	jQuery('input[type=radio][name=Group]').click(update);

	jQuery('#Leaderboard').bind('treats', function() { leaderboard.update(); });

	if (typeof initial_data == 'undefined')
	    leaderboard.update();
	else
	    leaderboard._getData_CallBack(initial_data);
}
