﻿// ---------------------------------------------------------------------------
// (c) 2009 2XL Games
// Author: Ryan Christensen
// ryan@drawlabs.com
// ---------------------------------------------------------------------------

var xlwebapi;

var DEFAULT_TITLE = "2XL Games Live";

var XLLIVE_COOKIE_GAMER = "xllive-gamer";
var XLLIVE_COOKIE_GAME = "xllive-game";
var XLLIVE_COOKIE_VIEW = "xllive-view";

var XLLIVE_COOKIE_USER = "xllive-user";
var XLLIVE_COOKIE_USER_STATE = "xllive-user-state";
var XLLIVE_COOKIE_USER_NAME = "xllive-user-name";

var XLLIVE_COOKIE_ADMIN_USER = "xllive-admin-user";
var XLLIVE_COOKIE_ADMIN_USER_STATE = "xllive-admin-user-state";
var XLLIVE_COOKIE_ADMIN_USER_NAME = "xllive-admin-user-name";

var xlreturn_obj = null;
var xlreturn_url_obj = null;
var xlreturn_user_obj = null;
var xlreturn_adminuser_obj = null;
var xlreturn_api_obj = null;
var xlreturn_global_obj = null;

var xlreturn_collection_obj = null;
var xlreturn_user_achievement_obj = null;
var xlreturn_user_statistic_obj = null;
var xlreturn_achievement_obj = null;
var xlreturn_statistic_obj = null;
var xlreturn_leaderboard_obj = null;
var xlreturn_displaytable_obj = null;
var xlreturn_livefeed_obj = null;

var xlreturn_syndication_obj = null;

var DEFAULT_TIME_VALUE = "00:00:00.000";

var NUM_KEYS = 8;

var selected_class = "current-home";
var classitem = 'row-alt';

var options = { path: '/', expires: 10 };
var keys = new Array();
// ---------------------------------------------------------------------------
// setup the namespace objects to be good javascript form

if (!window.xlweb)
    window.xlweb = {};

if (!window.xlweb.api)
    window.xlweb.api = {};

if (!window.xlweb.global)
    window.xlweb.global = {};
    
if (!window.xlweb.liveadminuser)
    window.xlweb.liveadminuser = {};

if (!window.xlweb.liveadminprofiles)
    window.xlweb.liveadminprofiles = {};    

if (!window.xlweb.liveuser)
    window.xlweb.liveuser = {};

if (!window.xlweb.liveachievement)
    window.xlweb.liveachievement = {};

if (!window.xlweb.livestatistic)
    window.xlweb.livestatistic = {};

if (!window.xlweb.liveleaderboard)
    window.xlweb.liveleaderboard = {};

if (!window.xlweb.livefeed)
    window.xlweb.livefeed = {};

if (!window.xlweb.liveprofile)
    window.xlweb.liveprofile = {};

if (!window.xlweb.livehistory)
    window.xlweb.livehistory = {};

if (!window.xlweb.livecollection)
    window.xlweb.livecollection = {};

if (!window.xlweb.livedisplaytable)
    window.xlweb.livedisplaytable = {};
    
if (!window.xlweb.livesyndication)
    window.xlweb.livesyndication = {};

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.global = function() {

    this.url = document.location;

    // endpoints
    this.service_base = '/content/service/xlliveservice.ashx';
    this.content_service = this.service_base + '/content/';
    this.asset_service = this.service_base + '/asset/';
    this.user_service = this.service_base + '/user/';
    this.profile_service = this.service_base + '/profile/';
    this.profile_update_service = this.service_base + '/set-profile/';
    this.user_check_service = this.service_base + '/check-user/';
    this.admin_user_check_service = this.service_base + '/check-admin-user/';
    this.admin_profiles_service = this.service_base + '/admin-profiles/';
    this.admin_profile_service = this.service_base + '/admin-profile/';
    this.user_achievement_service = this.service_base + '/user-achievement/';
    this.user_statistic_service = this.service_base + '/user-statistic/';
    this.user_statistics_service = this.service_base + '/user-statistics/';
    this.leaderboard_service = this.service_base + '/leaderboard/';
    this.achievement_service = this.service_base + '/achievement/';
    this.statistic_service = this.service_base + '/statistic/';
    this.collection_service = this.service_base + '/collection/';
    this.collections_service = this.service_base + '/collections/';
    this.displaytables_service = this.service_base + '/display-tables/';
    this.displaytable_service = this.service_base + '/display-table/';
    this.live_service = this.service_base + '/live/';
    this.syndication_twitter_service = this.service_base + '/get-twitter/';

    this.api_key = '2XL-DEBUG-007';
    this.service_type = 'json';
    this.session_id = 'SESSION1';

    // When we add facebook/opensocial
    //this.sn_api_key = '5bc68eb87c5efce7c3146860e6e3c0a0';
    //this.sn_secret = 'f6476345b377588e8dd5662da0b03867';
    //this.sn_network = 'facebook';

    // game api info
    //this.game_id = '00000000-0000-0000-0000-92000000000';
    //this.game_code = '2xl-atv-offroad';
}

xlweb_global = new xlweb.global();

// ---------------------------------------------------------------------------

xlweb.livesyndication = function() {
    this.fn_callback;
    xlreturn_syndication_obj = this;
}

xlweb.livesyndication.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_twitter: function(fn) {
        this.fn_callback = fn;
        var service_url = xlweb_global.syndication_twitter_service;

        _log("serviceurl::", service_url);

        $.get(service_url,
            null
	        , fn
	        , "json");
    },
    //-------------------------------------------------
    get_twitter_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);

        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_admin_profile_callback", true);
        }
        else {
            _log("SUCCESS::get_admin_profile_callback", false);

            xlreturn_syndication_obj.draw_twitter_table(data.data);
        }
    },
    //-------------------------------------------------
    get_twitter_event: function(event) {
        xlreturn_syndication_obj.get_twitter(
            xlreturn_syndication_obj.get_twitter_callback);
    },
    //-------------------------------------------------
    draw_twitter_table: function(data) {
        // Admin
        var size = data[0].items.length;
        
        shtml = "<div id='twitter' style='padding:20px;' >";
        for (var i = 0; i < size; i++) {

            if (i % 2 == 0) {
                shtml += "<div style='text-align:left;padding:10px;' class='row-alt'>";
            } else {
                shtml += "<div style='text-align:left;padding:10px;' >";
            }
            shtml += data[0].items[i].text.replace(/(http:\/\/\S+)/g, "<a href='$1'>$1</a>");;
            shtml += "</div>";

        }
        shtml += "<\div>";
        $("#twitter-data").replaceWith(shtml);
    }
}

// ---------------------------------------------------------------------------

var times = new Array();
times.push("Today");
times.push("1 day ago");
times.push("2 days ago");
times.push("3 days ago");
times.push("4 days ago");
times.push("5 days ago");
times.push("6 days ago");
times.push("1 week ago");
times.push("2 weeks ago");
times.push("3 weeks ago");
times.push("1 month ago");
times.push("2 months ago");
times.push("3 months ago");
times.push("4 months ago");
times.push("5 months ago");
times.push("6 months ago");
times.push("7 months ago");
times.push("8 months ago");
times.push("9 months ago");
times.push("10 months ago");
times.push("11 months ago");
times.push("1 year ago");

xlweb.liveadminprofiles = function() {
    this.fn_callback;
    this.fn_callbacks;
    xlreturn_admin_profiles_obj = this;
    xlreturn_admin_profile_obj = this;
}

xlweb.liveadminprofiles.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_admin_profile: function(todate, fn) {
        this.fn_callback = fn;
        var service_url = xlweb_global.admin_profile_service
                + "/end-date/" + todate;

        _log("serviceurl::", service_url);

        $.get(service_url,
        null
	    , fn
	    , "json");
    },
    //-------------------------------------------------
    get_admin_profile_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);

        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_admin_profile_callback", true);
        }
        else {
            _log("SUCCESS::get_admin_profile_callback", false);

            xlreturn_admin_profile_obj.draw_inner_admin_profile_table(data.data);

            toggle_admin_data_by_user_state();
        }
    },
    //-------------------------------------------------
    get_admin_profile_event: function(event) {
        xlreturn_admin_profile_obj.get_admin_profile(
            xlreturn_admin_profile_obj.get_admin_profile_callback);
    },
    //-------------------------------------------------
    get_admin_profiles: function(todates, col, fn) {

        this.fn_callbacks = fn;

        if (xlwebapi.gamer != "" && xlwebapi.gamer != null) {
            var service_url = xlweb_global.admin_profiles_service
                + "/end-dates/" + todates;

            _log("serviceurl:get_admin_profiles:", service_url);

            $.get(service_url,
        null
	    , fn
	    , "json");
        }
    },
    //-------------------------------------------------
    get_admin_profiles_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);


        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_admin_profiles_callback", true);
        }
        else {
            _log("SUCCESS::get_admin_profiles_callback", false);

            xlreturn_admin_profiles_obj.draw_inner_stats_tables(data.data);

            toggle_admin_data_by_user_state();

        }

    },
    //-------------------------------------------------
    get_admin_profiles_event: function(event) {
        xlreturn_admin_profiles_obj.get_admin_profiles(
            xlreturn_admin_profiles_obj.get_admin_profiles_callback);
    },
    //-------------------------------------------------
    draw_inner_admin_profile_table: function(data) {
        // Admin
        var size = data.items.length;
        shtml = "<table width=\"100%\">";

        shtml += "<tr>";
        shtml += "<th>";
        shtml += "";
        shtml += "</th>";
        shtml += "<th colspan='5' nowrap align='left'>";
        shtml += "Profiles";
        shtml += "</th>";
        shtml += "<th colspan='4' nowrap align='left'>";
        shtml += "PPM - Profiles Per Minute";
        shtml += "</th>";
        shtml += "<th colspan='4' nowrap align='left'>";
        shtml += "PPH - Profiles Per Hour";
        shtml += "</th>";
        shtml += "</tr>";



        shtml += "<tr>";
        shtml += "<th>";
        shtml += "Date";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "All";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "ATV";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "SX";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "Snocross";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "FD";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "24hrs.";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "Week";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "Month";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "All-Time";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "24hrs.";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "Week";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "Month";
        shtml += "</th>";
        shtml += "<th>";
        shtml += "All-Time";
        shtml += "</th>";
        shtml += "</tr>";
        for (var i = 0; i < size; i++) {

            if (i % 2 == 0) {
                shtml += "<tr class='row-alt'>";
            } else {
                shtml += "<tr>";
            }
            shtml += "<td nowrap align='left'>";
            shtml += times[i];
            shtml += "</td>";
            shtml += "<td>";
            shtml += addCommas(data.items[i].totalProfiles);
            shtml += "</td>";
            shtml += "<td>";
            shtml += addCommas(data.items[i].totalProfilesATV);
            shtml += "</td>";
            shtml += "<td>";
            shtml += addCommas(data.items[i].totalProfilesSupercross);
            shtml += "</td>";
            shtml += "<td>";
            shtml += addCommas(data.items[i].totalProfilesSnocross);
            shtml += "</td>";
            shtml += "<td>";
            shtml += addCommas(data.items[i].totalProfilesFleetDefense);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerMinuteLast24Hours.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerMinuteLast7Days.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerMinuteLast31Days.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerMinuteAlltime.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerHourLast24Hours.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerHourLast7Days.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerHourLast31Days.toFixed(3);
            shtml += "</td>";
            shtml += "<td>";
            shtml += data.items[i].totalProfilesPerHourAlltime.toFixed(3);
            shtml += "</td>";
            shtml += "</tr>";

        }
        shtml += "</table>";
        $("#admin-data").replaceWith(shtml);
    }
    ,
    //-------------------------------------------------
    draw_inner_admin_profiles_table: function(data) {

    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.liveadminuser = function() {
    this.liveadminusername = "";
    this.liveadminhash = "";
    this.adminloggedin = false;
    this.fn_callback;
    xlreturn_admin_user_obj = this;
}

xlweb.liveadminuser.prototype = {
    //-------------------------------------------------
    set_admin_user_state: function(user, hash, loggedin) {
        this.liveadminusername = user;
        this.liveadminhash = hash;
        this.adminloggedin = loggedin;
    },
    //-------------------------------------------------
    login: function(username, password, fn) {

        showLoading();

        this.fn_callback = fn;

        $.post(xlweb_global.admin_user_check_service,
        {
            username: $("#username").val()
		    , password: $("#password").val()
        }
	    , fn
	    , "json");
    },
    //-------------------------------------------------
    logout: function() {
        //$.cookie(XLLIVE_COOKIE_ADMIN_USER, "");
        //$.cookie(XLLIVE_COOKIE_ADMIN_USER_STATE, "");
        //$.cookie(XLLIVE_COOKIE_ADMIN_USER_NAME, "");
    },
    //-------------------------------------------------
    logout_event: function(event) {
        xlreturn_admin_user_obj.logout();
    },
    //-------------------------------------------------
    login_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);

        if (data.error > 0 || data.error.length > 1) {

            _log("errors", true);

            show_message("#msg", data.message);
            //$.cookie(XLLIVE_COOKIE_ADMIN_USER_STATE, 0);
        }
        else {
            _log("errors", false);
            _log(XLLIVE_COOKIE_ADMIN_USER_STATE, $.cookie(XLLIVE_COOKIE_ADMIN_USER_STATE));
            _log("cookie user", $.cookie(XLLIVE_COOKIE_ADMIN_USER));

            xlreturn_admin_user_obj.set_admin_user_state($("#live-username").val(), "000000000000000000000000==", 1);

            toggle_admin_data_by_user_state();

            document.location = "#admin/profiles";
        }
    },
    //-------------------------------------------------
    login_event: function(event) {
        _log("event:",event);
        xlreturn_admin_user_obj.login(
            event.data.username,
            event.data.password,
            xlreturn_admin_user_obj.login_callback);
    },
    //-------------------------------------------------
    load: function() {
        if ($.cookie(XLLIVE_COOKIE_ADMIN_USER) != "" && $.cookie(XLLIVE_COOKIE_ADMIN_USER) != "") {
            var obj = $.cookie(XLLIVE_COOKIE_ADMIN_USER);
            this.set_admin_user_state(obj.username, obj.hash, obj.logged_in);
        }
    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.liveuser = function() {
    this.liveusername = "";
    this.livehash = "";
    this.loggedin = false;
    this.fn_callback;
    xlreturn_user_obj = this;
}

xlweb.liveuser.prototype = {
    //-------------------------------------------------
    set_user_state: function(user, hash, loggedin) {
        this.liveusername = user;
        this.hash = hash;
        this.loggedin = loggedin;
    },
    //-------------------------------------------------
    set_user: function(fn) {
        showLoading();

        this.fn_callback = fn;

        $.get(xlweb_global.profile_update_service,
            {
                username: $("#profile-username").html(),
                password: $("#profile-password").val(),
                password2: $("#profile-password2").val(),
                email: $("#profile-email").val(),
                dob: $("#profile-dob").val()
            }
	        , fn
	        , "json");

        _log("xlweb_global.profile_update_service::", xlweb_global.profile_update_service);
    },
    //-------------------------------------------------
    set_user_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);

        if (data.error > 0 || data.error.length > 1) {

            _log("errors", true);
            show_message("#msg", data.message);
        }
        else {
            _log("errors", false);

            //show_message("#msg", data.message);

            toggle_data_by_user_state();

            xlwebapi.xlliveuser.get_user($.cookie(XLLIVE_COOKIE_USER_NAME), "", xlwebapi.xlliveuser.get_user_callback);
        }

        hideLoading();
    },
    //-------------------------------------------------
    set_user_event: function(event) {
        xlreturn_user_obj.set_user(
            xlreturn_user_obj.set_user_callback);
    },
    //-------------------------------------------------
    get_user: function(user, pwd, fn) {
        showLoading();

        _log("calling get_user::", user);

        this.fn_callback = fn;

        $.get(xlweb_global.profile_service,
            {
                username: user,
                password: pwd
            }
	        , fn
	        , "json");

        _log("xlweb_global.profile_service::", xlweb_global.profile_service);
    },
    //-------------------------------------------------
    get_user_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);

        if (data.error > 0 || data.error.length > 1) {

            _log("errors", true);
            //show_message("#msg", data.message);
        }
        else {
            _log("errors", false);
            //show_message("#msg", data.message);

            toggle_data_by_user_state();
            xlreturn_user_obj.draw_profile(data.data);
        }

        hideLoading();
    },
    //-------------------------------------------------
    get_user_event: function(event) {
        xlreturn_user_obj.get_user(
            event.data.username,
            xlreturn_user_obj.get_user_callback);
    },
    //-------------------------------------------------
    draw_profile: function(data) {

        $("#profile-email").val(data.email);
        $("#profile-username").html(data.username);
        $("#profile-password").val(data.password);
        $("#profile-password2").val(data.password);
        $("#profile-dob").val(data.dob);
        $("#profile-date-created").html(data.creationDate);
        $("#profile-date-last-created").html(data.lastConnectionDate);
        $("#profile-time-connected").html(data.timesConnected);
        $("#profile-id").val(data.profileIndex);

        $("#profile-form").show();
    }
    ,
    //-------------------------------------------------
    login: function(username, password, fn) {

        showLoading();

        this.fn_callback = fn;

        $.get(xlweb_global.user_check_service,
        {
            username: $("#username").val()
		    , password: $("#password").val()
        }
	    , fn
	    , "json");
    },
    //-------------------------------------------------
    logout: function() {
        //$.cookie(XLLIVE_COOKIE_USER, "");
        //$.cookie(XLLIVE_COOKIE_USER_STATE, "");
        //$.cookie(XLLIVE_COOKIE_USER_NAME, "");
        xlwebapi.gamer = '';
        $("#q").val(xlwebapi.gamer);
        document.location = '/logout';
        toggle_data_by_user_state();
        //changeState();
    },
    //-------------------------------------------------
    logout_event: function(event) {
        xlreturn_user_obj.logout();
    },
    //-------------------------------------------------
    login_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);

        if (data.error > 0 || data.error.length > 1) {

            _log("errors", true);

            show_message("#msg", data.message);
            //$.cookie(XLLIVE_COOKIE_USER_STATE, 0);
        }
        else {
            _log("errors", false);

            //show_message("#msg", data.message);
            // $.cookie(XLLIVE_COOKIE_USER_STATE, 1);
            // $.cookie(XLLIVE_COOKIE_USER, { logged_in: 1, username: $("#username").val() });

            _log(XLLIVE_COOKIE_USER_STATE, $.cookie(XLLIVE_COOKIE_USER_STATE));
            _log("cookie user", $.cookie(XLLIVE_COOKIE_USER));

            xlreturn_user_obj.set_user_state($("#live-username").val(), "", 1);

            toggle_data_by_user_state();

            var loggedin = $.cookie(XLLIVE_COOKIE_USER_STATE);
            if (loggedin == "1") {
                xlwebapi.xlliveuser.get_user($.cookie(XLLIVE_COOKIE_USER_NAME), "", xlwebapi.xlliveuser.get_user_callback);
            }

            document.location = "#profile";

            link_state_profile(".statistics a");
            link_state_profile(".achievements a");
        }

        hideLoading();
    },
    //-------------------------------------------------
    login_event: function(event) {
        xlreturn_user_obj.login(
            event.data.username,
            event.data.password,
            xlreturn_user_obj.login_callback);
    },
    //-------------------------------------------------
    load: function() {
        if ($.cookie(XLLIVE_COOKIE_USER) != "" && $.cookie(XLLIVE_COOKIE_USER) != "") {
            var obj = $.cookie(XLLIVE_COOKIE_USER);
            this.set_user_state(obj.username, obj.hash, obj.logged_in);
        }
    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.livefeed = function() {
    this.fn_callback;
    xlreturn_livefeed_obj = this;
}

xlweb.livefeed.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_livefeed: function(fn) {

        showLoading();

        this.fn_callback = fn;

        var service_url = xlweb_global.live_service
            + "game/" + getUrlParamValue('game')
            + "/gamer/" + getUrlParamValue('gamer');

        _log("serviceurl::", service_url);

        $.get(service_url,
        null
	    , fn
	    , "json");
    },
    //-------------------------------------------------
    get_livefeed_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);

        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_livefeed_callback", true);
        }
        else {
            _log("SUCCESS::get_livefeed_callback", false);

            //xlreturn_collection_obj.draw_select(data.data);
            //$("#collection-keys").html(shtml);

            xlreturn_livefeed_obj.draw_items(data.data);

            $("#data-results").slideDown("fast");

            toggle_data_by_user_state();
        }

        hideLoading();
    },
    //-------------------------------------------------
    get_livefeed_event: function(event) {
        xlreturn_livefeed_obj.get_livefeed(
            xlreturn_livefeed_obj.get_livefeed_callback);
    },
    //-------------------------------------------------
    draw_items: function(data) {
        var size = data.length;
        shtml = "";
        for (var i = 0; i < size; i++) {
            shtml += "<div class=\"live-item\">";

            shtml += "<div class=\"big\">";
            shtml += "<a  rel=\"history\" href=\"/statistics/gamer/" + escape(data[i].username) + "/game/2xl-atv-offroad\"> " + data[i].username + "</a> " + data[i].message + "</option>";
            shtml += "</div>";

            shtml += "<div>";
            shtml += data[i].dateCreated + " from " + data[i].gameName + " iPhone Version";
            shtml += "</div>";

            shtml += "</div>";
        }
        $("#live-results").html(shtml);
    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.liveleaderboard = function() {
    this.fn_callback;
    this.divtoload;
    this.range;
    xlreturn_leaderboard_obj = this;
}

xlweb.liveleaderboard.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_leaderboard: function(range, divtoload, key1, key2, key3, key4, key5, key6, key7, key8, fn) {

        showLoading();

        this.divtoload = divtoload;
        this.fn_callback = fn;
        this.range = range;

        var service_url = xlweb_global.leaderboard_service
            + "game/" + getUrlParamValue('game')
            + "/range/" + range
            + "/key1/" + key1
            + "/key2/" + key2
            + "/key3/" + key3
            + "/key4/" + key4
            + "/key5/" + key5
            + "/key6/" + key6
            + "/key7/" + key7
            + "/key8/" + key8;

        _log("serviceurl::", service_url);

        $.get(service_url,
            null
	        , fn
	        , "json");
    },
    //-------------------------------------------------
    get_leaderboard_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);


        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_leaderboard_callback", true);
        }
        else {
            _log("SUCCESS::get_leaderboard_callback", false);

            xlreturn_leaderboard_obj.draw_items(data.data);
        }

        hideLoading();
    },
    //-------------------------------------------------
    get_leaderboard_event: function(event) {
        xlreturn_leaderboard_obj.get_leaderboard(
            xlreturn_leaderboard_obj.get_leaderboard_callback);
    },
    //-------------------------------------------------
    draw_items: function(data) {
        href = xlweburl.get_href();
        var size = data.items.length;
        shtml = "<table class=\"sorted\" width=\"100%\">";
        shtml += "<tr>";


        shtml += "<th width='140px'>";
        shtml += "Rank"
        shtml += "</th>";

        shtml += "<th width='310px'>";
        shtml += "Gamer";
        shtml += "</th>";

        shtml += "<th width='200px'>";
        shtml += "Date/Time";
        shtml += "</th>";

        shtml += "<th width='200px'  align='right'>";
        shtml += "Stat Value";
        shtml += "</th>";

        shtml += "</tr>";

        var rank = 1;


        for (var i = 0; i < size; i++) {
            if (rank > 250)
                break;
            //shtml += "<tr>";
            if (i % 2 == 0) {
                shtml += "<tr class='row-alt'>";
            } else {
                shtml += "<tr>";
            }

            shtml += "<td width='140px'>";
            shtml += rank++;
            shtml += "</td>";

            shtml += "<td width='310px'>";
            shtml += "<a   rel=\"history\" href=\"/statistics/game/" + xlwebapi.game + "/gamer/" + escape(data.items[i].userName) + "\">" + data.items[i].userName + "</a>";
            shtml += "</td>";

            shtml += "<td width='200px'>";
            shtml += data.items[i].date;
            shtml += "</td>";

            shtml += "<td width='200px' align='right'>";
            var _value = data.items[i].value;
            var _rank = "";
            var _output = _value;
            var _output_pristine = _value;
            if (!isNaN(_value)) {
                _value = addCommas(_value);
            }
            try {
                _value += data.items[i].value.toFixed(2);
            }
            catch (e) {
            }

            // TODO: game specific
            if (is_game_fleetdefense() && xlweburl.get_url_param_value("key1") == "280") {
                _rank = convertFDCurrentRankToRank(_output_pristine);
                _output = _rank + " (" + _value + ")";
                shtml += _output;
            }
            else {
                shtml += _value;
            }
            shtml += "</td>";

            shtml += "</tr>";
        }
        shtml += "</table>";

        //shtml += "  <scr" + "ipt type=\"text/javascript\">";
        //shtml += "  $(document).ready(function(){";
        //shtml += "   $(\"table\").tablesorter();";
        //shtml += "  });";
        //shtml += "  </scr" + "ipt>";

        if (getUrlParamValue("tab") == data.viewType) {
            $("#leaderboard-" + data.viewType + "-content").html(shtml);
        }

        showLeaderboard();
    }
}

// ---------------------------------------------------------------------------

function showLeaderboardByType(viewType) {
    
    if (is_section_leaderboard()) {
        $("#leaderboard-alltime-content").hide();
        $("#leaderboard-daily-content").hide();
        $("#leaderboard-weekly-content").hide();
        $("#leaderboard-monthly-content").hide();

        $("#leaderboard-tab-alltime").removeClass("leaderboard-tab-selected");
        $("#leaderboard-tab-daily").removeClass("leaderboard-tab-selected");
        $("#leaderboard-tab-monthly").removeClass("leaderboard-tab-selected");
        $("#leaderboard-tab-weekly").removeClass("leaderboard-tab-selected");

        $("#leaderboard-" + viewType + "-content").show();
        $("#leaderboard-tab-" + viewType).addClass("leaderboard-tab-selected");
    }
}

// ---------------------------------------------------------------------------

function showLeaderboard() {
    href = xlweburl.get_href();
    if (is_section_leaderboard()) {
        if (href.indexOf("tab/weekly") > -1) {
            showLeaderboardByType("weekly");
        }
        else if (href.indexOf("tab/daily") > -1) {
            showLeaderboardByType("daily");
        }
        else if (href.indexOf("tab/monthly") > -1) {
            showLeaderboardByType("monthly");
        }
        else {
            showLeaderboardByType("alltime");
        }
    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.livestatistic = function() {
    this.fn_callback;
    this.fn_callbacks;
    xlreturn_user_statistic_obj = this;
    xlreturn_user_statistics_obj = this;
}

xlweb.livestatistic.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_user_statistic: function(key1, col, fn) {

        this.fn_callback = fn;

        if (xlwebapi.gamer != "" && xlwebapi.gamer != null) {
            var service_url = xlweb_global.user_statistic_service
            + "game/" + xlwebapi.game
            + "/gamer/" + xlwebapi.gamer
            + "/key1/" + key1
            + "/col/" + col;

            _log("serviceurl::", service_url);

            $.get(service_url,
        null
	    , fn
	    , "json");
        }
    },
    //-------------------------------------------------
    get_user_statistic_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);


        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_user_statistic_callback", true);
        }
        else {
            _log("SUCCESS::get_user_statistic_callback", false);

            xlreturn_user_statistic_obj.draw_inner_stat_table(data.data);

            toggle_data_by_user_state();
        }
    },
    //-------------------------------------------------
    get_user_statistic_event: function(event) {
        xlreturn_user_statistic_obj.get_user_statistic(
            xlreturn_user_statistic_obj.get_user_statistic_callback);
    },
    //-------------------------------------------------
    get_user_statistics: function(keysparam, col, fn) {

        this.fn_callbacks = fn;
        _log("!!keys!! - I want my two dollars!:", keys);

        if (xlwebapi.gamer != "" && xlwebapi.gamer != null) {
            var service_url = xlweb_global.user_statistics_service
            + "game/" + xlwebapi.game
            + "/gamer/" + xlwebapi.gamer
            + "/key1/" + keysparam
            + "/col/" + col;

            _log("serviceurl:get_user_statistics:", service_url);

            $.get(service_url,
        null
	    , fn
	    , "json");
        }
    },
    //-------------------------------------------------
    get_user_statistics_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);


        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_user_statistics_callback", true);
        }
        else {
            _log("SUCCESS::get_user_statistics_callback", false);

            xlreturn_user_statistics_obj.draw_inner_stats_tables(data.data);

            toggle_data_by_user_state();

        }

    },
    //-------------------------------------------------
    get_user_statistics_event: function(event) {
        xlreturn_user_statistics_obj.get_user_statistics(
            xlreturn_user_statistics_obj.get_user_statistics_callback);
    },
    //-------------------------------------------------
    draw_inner_stat_table: function(data) {
        if (is_game_fleetdefense()) {
            drawSingleStatTableIndividualFD(data);
        }
        else {
            drawSingleStatTableIndividual(data);
        }
    }
    ,
    //-------------------------------------------------
    draw_inner_stats_tables: function(data) {
        var size = 0; //data.items.length;

        shtml = "";
        var key = "";
        for (var i = 0; i < data.length; i++) {
            if (i > 0) {
                key += "-";
            }
            key += data[i].data[0].uniqueId;
        }

        doDrawTables(key, data);
    }
}


// ---------------------------------------------------------------------------

function drawSingleStatTableIndividual(data) {
    var size = data.items.length;
    shtml = "<table width=\"100%\">";
    for (var i = 0; i < size; i++) {

        var col = 2;
        //if (data[i].key3 != "0")
        //    col = 3;

        if (i % 2 == 0) {
            shtml += "<tr class='row-alt'>";
        } else {
            shtml += "<tr>";
        }
        shtml += "<td>";
        shtml += data.items[i].id;
        shtml += "</td>";
        shtml += "<td>";
        shtml += data.items[i].keyname;
        shtml += "</td>";
        shtml += "<td align='right'>";
        var _value = data.items[i].value1;
        if (!isNaN(_value)) {
            _value = addCommas(_value);
        }
        shtml += _value;
        shtml += "</td>";
        // TODO work in count == 5 when data corrected            
        shtml += "</tr>";

    }
    shtml += "</table>";
    $("#" + data.statID).replaceWith(shtml);
}

// ---------------------------------------------------------------------------

function drawSingleStatTable(key, data) {

    for (var i = 0; i < data.length; i++) {
        shtml += "<div style='float:left;'><table width=\"100%\">";
        for (var j = 0; j < data[i].data[0].items.length; j++) {

            shtml += "<tr>";

            if (i == 0) {

                // shtml += "<td>";
                // shtml += data[i].data[0].items[j].id;
                // shtml += "</td>";
                shtml += "<td>";
                shtml += data[i].data[0].items[j].keyname;
                shtml += "</td>";
            }
            shtml += "<td  align='right'>";
            var _value = data[i].data[0].items[j].value1;
            if (!isNaN(_value)) {
                _value = addCommas(_value);
            }
            shtml += _value;
            shtml += "</td>";
            shtml += "</tr>";

        }
        shtml += "</table></div>";
    }
    $("#" + key).replaceWith(shtml);
}

// ---------------------------------------------------------------------------

function drawDefaultStatTable(key, data) {

    for (var i = 0; i < data.length; i++) {
        shtml += "<div style='float:left;'><table width=\"100%\">";
        for (var j = 0; j < data[i].data[0].items.length; j++) {

            shtml += "<tr>";

            if (i == 0) {

                // shtml += "<td>";
                // shtml += data[i].data[0].items[j].id;
                // shtml += "</td>";
                shtml += "<td>";
                shtml += data[i].data[0].items[j].keyname;
                shtml += "</td>";
            }
            shtml += "<td  align='right'>";
            var _value = data[i].data[0].items[j].value1;
            if (!isNaN(_value)) {
                _value = addCommas(_value);
            }
            shtml += _value;
            shtml += "</td>";
            shtml += "</tr>";

        }
        shtml += "</table></div>";
    }
    $("#" + key).replaceWith(shtml);
}

// ---------------------------------------------------------------------------

function drawFastestLapsStatTable(key, data) {

    shtml = "";

    shtml += "<table width=\"100%\">";

    shtml += "<tr>";
    shtml += "<th>";
    shtml += "Track";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "1 lap";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "3 laps";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "5 laps";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "10 laps";
    shtml += "</th>";
    shtml += "</tr>";

    //if (envs.length == 0) {
    loadEnvs();
    //}
    
    for (var i = 1; i < envs.length; i++) {

        if (i % 2 == 0) {
            shtml += "<tr class='row-alt'>";
        } else {
            shtml += "<tr>";
        }
        shtml += "<td>";
        shtml += envs[i];
        shtml += "</td>";

        // TODO add in the columns


        for (var j = 0; j < data.length; j++) {
            shtml += "<td >";
            shtml += getValueFromDataMatching(envs[i], data[j], DEFAULT_TIME_VALUE);
            shtml += "</td>";
        }

        shtml += "</tr>";
    }
    shtml += "</table>";
    $("#" + key).replaceWith(shtml);
}

// ---------------------------------------------------------------------------

function getValueFromDataMatching(lookingfor, dataitem, defaulttext) {

    var value = defaulttext;
    for (var j = 0; j < dataitem.data[0].items.length; j++) {
        if (lookingfor == dataitem.data[0].items[j].keyname) {
            value = dataitem.data[0].items[j].value1;
            break;
        }
    }
    return value;
}

// ---------------------------------------------------------------------------

function drawTimesFinishedStatTable(key, data) {
    shtml = "";
    shtml += "<table width=\"100%\">";
    shtml += "<tr>";
    shtml += "<th>";
    shtml += "Track";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "1st";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "2nd";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "3rd";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "4th";
    shtml += "</th>";
    shtml += "<th>";
    shtml += "5th";
    shtml += "</th>";
    shtml += "</tr>";

   // if (envs.length == 0) {
    loadEnvs();
    //}

    for (var i = 0; i < envs.length; i++) {

        if (i % 2 == 0) {
            shtml += "<tr class='row-alt'>";
        } else {
            shtml += "<tr>";
        }
        shtml += "<td>";
        shtml += envs[i];
        shtml += "</td>";

        // TODO add in the columns

        for (var j = 0; j < data.length; j++) {
            shtml += "<td>";
            shtml += getValueFromDataMatching(envs[i], data[j], "0");
            shtml += "</td>";
        }

        shtml += "</tr>";
    }
    shtml += "</table>";
    $("#" + key).replaceWith(shtml);
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.livecollection = function() {
    this.fn_callback;
    xlreturn_collection_obj = this;
}

xlweb.livecollection.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_collections: function(fn) {

        showLoading();

        this.fn_callback = fn;

        var service_url = xlweb_global.collections_service
            + "game/" + xlwebapi.game;

        if (xlwebapi.gamer != null && xlwebapi.gamer != "") {
            service_url = service_url + "/gamer/" + xlwebapi.gamer;
        }

        _log("serviceurl::", service_url);

        $.get(service_url,
        null
	    , fn
	    , "json");
    },
    //-------------------------------------------------
    get_collection: function(key, fn) {

        showLoading();

        this.fn_callback = fn;

        var service_url = xlweb_global.collections_service
            + "game/" + xlwebapi.game
            + "/gamer/" + xlwebapi.gamer
            + "/col/" + key;

        _log("serviceurl::", service_url);

        $.get(service_url,
        null
	    , fn
	    , "json");
    },
    //-------------------------------------------------
    get_collections_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.collections", data.data.collections);


        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_collections_callback", true);
        }
        else {
            _log("SUCCESS::get_collections_callback", false);

            //xlreturn_collection_obj.draw_select(data.data);
            $("#collection-keys").html(shtml);

            toggle_data_by_user_state();
        }

        hideLoading();
    },
    //-------------------------------------------------
    get_collection_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.collections", data.data.collections);

        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_collection_callback", true);
        }
        else {
        
            _log("SUCCESS::get_collection_callback", false);

            xlreturn_collection_obj.draw_select(data.data);

            xlreturn_collection_obj.draw_grid(data.data);
            //$("#collection-keys").html(shtml);

            $("#data-results").slideDown("fast");
            $("#leaderboard-results").slideDown("fast");

            if (is_section_leaderboard()) {
                loadLeaderboardContent();
            }

            toggle_data_by_user_state();

            link_state_parent("#leaderboard-tab-alltime");
            link_state_parent("#leaderboard-tab-weekly");
            link_state_parent("#leaderboard-tab-daily");
            link_state_parent("#leaderboard-tab-monthly");
        }

        hideLoading();
    },
    //-------------------------------------------------
    get_collection_event: function(event) {
        xlreturn_collection_obj.get_collection(
            event.data.key,
            xlreturn_collection_obj.get_collection_callback);
    },
    //-------------------------------------------------
    get_collections_event: function(event) {
        xlreturn_collection_obj.get_collections(
            xlreturn_collection_obj.get_collection_callback);
    },
    //-------------------------------------------------
    draw_select: function(data) {

        var key1ColRace = new Array();
        var key1ColStunt = new Array();
        var key1ColRaceVal = new Array();
        var key1ColStuntVal = new Array();

        var key2Col = new Array();
        var key2ColSingle = new Array();
        var key3Col = new Array();

        var key1ColVal = new Array();
        var key2ColVal = new Array();
        var key2ColSingleVal = new Array();
        var key3ColVal = new Array();

        var nowStunt = false;

        var collection1_size = data.collection1.collections.length;
        var collection2_size = data.collection2.collections.length;
        var collection3_size = 0;

        try {
            collection3_size = data.collection3.collections.length;
        }
        catch (e) {
            _log("ERROR", e);
        }

        // draw key 1 select 
        shtml = "";
        shtml += "<select id=\"key1\" name=\"key1\">";
        shtml += "<option>Select Leaderboard</option>";

        for (var i = 0; i < collection1_size; i++) {

            var id = data.collection1.collections[i].id;
            var uniqueID = data.collection1.collections[i].uniqueID;
            var show = filterStatsFromDisplay(uniqueID);

            if (show) {

                shtml += "<option value=\"" + data.collection1.collections[i].uniqueID + "\">"
                        + data.collection1.collections[i].displayName + "</option>";

                // Checks for stunt stats to show different drop downs.
                if (checkForStuntStats(data.collection1.collections[i].uniqueID)) {
                    nowStunt = true;
                }

                if (!nowStunt) {
                    key1ColRace.push(data.collection1.collections[i].displayName);
                    key1ColRaceVal.push(data.collection1.collections[i].uniqueID);
                }
                else {
                    key1ColStunt.push(data.collection1.collections[i].displayName);
                    key1ColStuntVal.push(data.collection1.collections[i].uniqueID);
                }
            }
        }
        shtml += "</select>";

        // draw key 2 select

        shtml += "<select id=\"key2\" name=\"key2\">";
        if (!is_game_fleetdefense()) {
            shtml += "<option>Select Track</option>";
        }
        for (var i = 0; i < collection2_size; i++) {
            shtml += "<option value=\"" + data.collection2.collections[i].uniqueID + "\">"
                    + data.collection2.collections[i].displayName + "</option>";


            key2Col.push(data.collection2.collections[i].displayName);
            key2ColVal.push(data.collection2.collections[i].uniqueID);

            if (i > 0) {
                key2ColSingle.push(data.collection2.collections[i].displayName);
                key2ColSingleVal.push(data.collection2.collections[i].uniqueID);
            }
        }
        shtml += "</select>";

        try {

            // draw key 3 select

            shtml += "<select id=\"key3\" name=\"key3\">";
            if (!is_game_fleetdefense()) {
                shtml += "<option>Select Track</option>";
            }
            for (var i = 0; i < collection3_size; i++) {

                shtml += "<option value=\"" + data.collection3.collections[i].uniqueID + "\">"
                    + data.collection3.collections[i].displayName + "</option>";
                key3Col.push(data.collection3.collections[i].displayName);
                key3ColVal.push(data.collection3.collections[i].uniqueID);
            }
            shtml += "</select>";
        } catch (e) {
            _log("ERROR", e);
        }

        $("#collection-keys").html(shtml);

        // bind events after load

        $("#key1").bind("change", function(event) {
            $("#key2").hide();
            $("#key3").hide();

            var me = $(event.target);
            var meval = me.val();
            var metext = me.text();

            for (var i = 0; i < key1ColRaceVal.length; i++) {
                if (key1ColRaceVal[i] == meval) {
                    //if (document.location.href.indexOf("fleet-defense") == -1) {
                    $("#key2").show();
                    // }
                    break;
                }
            }

            for (var i = 0; i < key1ColStuntVal.length; i++) {
                if (key1ColStuntVal[i] == meval) {
                    if (!is_game_fleetdefense()) {
                        $("#key3").show();
                    }
                    break;
                }
            }

            if ($("#key1").text().indexOf("Fastest") > -1) {
                $("#key2 option[value='100']").remove();
            }

            if ($("#key2").val().indexOf("Select") == -1 && $("#key2").is(":visible")) {
                loadContentIntoPath($("#key1").val(), $("#key2").val(), 0, 0, 0, 0, 0, 0);
            }

            if (href.indexOf("fleet-defense") == -1) {
                if ($("#key3").val().indexOf("Select") == -1 && $("#key3").is(":visible")) {
                    loadContentIntoPath($("#key1").val(), 0, $("#key3").val(), 0, 0, 0, 0, 0);
                }
            }


        });

        $("#key2").bind("change", function(event) {
            var me = $(event.target);
            //alert(me.attr('id'));
            if ($("#key2").val().indexOf("Select") == -1 && $("#key2").is(":visible")) {
                loadContentIntoPath($("#key1").val(), $("#key2").val(), 0, 0, 0, 0, 0, 0);
            }

        });

        $("#key3").bind("change", function(event) {
            var me = $(event.target);
            //alert(me.attr('id'));
            if ($("#key3").val().indexOf("Select") == -1 && $("#key3").is(":visible")) {
                loadContentIntoPath($("#key1").val(), 0, $("#key3").val(), 0, 0, 0, 0, 0);
            }
        });
    },
    //-------------------------------------------------
    draw_grid: function(data) {

    }
}

// ---------------------------------------------------------------------------

function is_empty(value){
    var empty = true;
    if(value != null && value != "" && value != "0" && value != 0){
        empty = false;
    }
    return empty;
}

// ---------------------------------------------------------------------------

function loadContentIntoPath(key1, key2, key3, key4, key5, key6, key7, key8) {

    href = xlweburl.get_href();
    
    if (is_section_leaderboard()) {
    
        //hash = xlweburl.get_hash();
        _log("href:", href);

        var range = getUrlParamValue("tab");
        if (range == null || range == "" || range == undefined) {
            range = "alltime";
        }

        if (!is_empty(range))
            href = changeUrlToState(href, "tab", range);

        href = changeUrlToState(href, "key1", key1);
        href = changeUrlToState(href, "key2", key2);
        href = changeUrlToState(href, "key3", key3);

        if (!is_empty(key4))
            href = changeUrlToState(href, "key4", key4);

        if (!is_empty(key5))
            href = changeUrlToState(href, "key5", key5);

        if (!is_empty(key6))
            href = changeUrlToState(href, "key6", key6);

        if (!is_empty(key7))
            href = changeUrlToState(href, "key7", key7);

        if (!is_empty(key8))
            href = changeUrlToState(href, "key8", key8);

        _log("leaderboard href:", href);

        document.location = href.replace('#','');
    }
}

// ---------------------------------------------------------------------------

function getUrlParamValue(key) {
    href = xlweburl.get_href();
    var value = "";
    if (href.indexOf(key + "/") > -1) {
        var params = href.split("/");
        for (var i = 0; i < params.length; i++) {
            if (params[i] == key) {
                if (params[i + 1] != null) {
                    value = params[i + 1];
                }
            }
        }
    }
    return value;
}

// ---------------------------------------------------------------------------

function getUrlParamLeaderboardValue(key) {
    var value = "";
    if (is_section_leaderboard()) {
        value = getUrlParamValue(key);
        //_log(key, value);
        if (value == "") {
            value = "0";
        } 
    }
    return value;
}

// ---------------------------------------------------------------------------
function setKeysValues() {
    keys = new Array();
    for (var i = 0; i < NUM_KEYS; i++) {
        var _val = getUrlParamLeaderboardValue("key" + (i + 1).toString());
        //_log("setkey", "key" + (i + 1).toString());
        //_log("setkeyval", _val);
        keys.push(_val);
    }

    _log("setkeyvalkeys[0]", keys[0]);
}

// ---------------------------------------------------------------------------

function loadLeaderboardContent() {
    if (is_section_leaderboard()) {
        setKeysValues();
        for (var i = 0; i < NUM_KEYS; i++) {
            if (i > 0) {
                $("#key" + (i + 1).toString()).hide();
            }
        }
        for (var i = 0; i < NUM_KEYS; i++) {
            if (i > 0 && keys[i] != "0" && keys[i] != 0) {
                for (var j = 0; j < NUM_KEYS; j++) {
                    if (j != i && i != 0) {
                        keys[j] = "0";
                        if (j > 0) {
                            $("#key" + (j + 1).toString()).hide();
                        }
                    }
                }
            }
        }
        loadContentIntoDiv(keys);
    }
}

// ---------------------------------------------------------------------------

function handleKeyDropDowns(key, keynum, value) {

    _log("handle" + key, keynum);
    _log("handle" + key, value);
    if (is_section_leaderboard()) {
        _log("handle" + key, keynum);
        _log("handle" + key, value);
        if (value != "0" && value != 0) {
            //key1 = "0";
            if (keynum < 2)
                key2 = "0";
            if (keynum < 2)
                key3 = "0";
            if (keynum < 2)
                key4 = "0";
            if (keynum < 2)
                key5 = "0";
            if (keynum < 2)
                key6 = "0";
            if (keynum < 2)
                key7 = "0";
            if (keynum < 2)
                key8 = "0";
            if (keynum < 2) {
                // $("#key1").hide();
                for (var i = 0; i < NUM_KEYS; i++) {
                    $("#key" + (i + 1).toString()).hide();
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------

function loadContentIntoDiv(keys) {

    if (is_section_leaderboard()) {
        
        var divtoload = "";
        var range = "";
        

        range = getUrlParamValue("tab");
        if (range == null || range == "" || range == undefined) {
            range = "alltime";
        }
        divtoload = "#leaderboard-" + range;

        var str = "";
        setKeysValues();

        keys[0] = getUrlParamValue("key1");
        
        for (var i = 0; i < NUM_KEYS; i++) {
            str = str + keys[i].toString() + ",";
            //_log("keys[i]", keys[i]);
        }
        //_log("keysstr", str);

        $(divtoload).html(
            "<script>xlwebapi.xlleaderboard.get_leaderboard(\"" + range + "\",'"
            + divtoload + "',"
            + str +" xlwebapi.xlleaderboard.get_leaderboard_callback);</script>");

        // set selections
        for (var i = 0; i < NUM_KEYS; i++) {
            //_log("handle" + i, keys[i]);
            //_log("handle" + i, "key" + (i + 1).toString());
            handleKeySelects("key" + (i + 1).toString(), keys[i]);
        }
    }
}

// ---------------------------------------------------------------------------

function handleKeySelects(key, value) {
    if (value != null && value != "" && value != "0" && value != 0) {
        $("#" + key).val(value).show();
    }
}

// ---------------------------------------------------------------------------

xlweb.livedisplaytable = function() {
    this.fn_callback;
    xlreturn_displaytable_obj = this;
}

xlweb.livedisplaytable.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_displaytables: function(fn) {
        this.fn_callback = fn;

        if (xlwebapi.gamer != "" && xlwebapi.gamer != null) {

            showLoading();

            var service_url = xlweb_global.displaytable_service
            + "game/" + xlwebapi.game
            + "/gamer/" + xlwebapi.gamer;

            _log("serviceurl::", service_url);

            $.get(service_url,
                null
	            , fn
	            , "json");
        }
    },
    //-------------------------------------------------
    get_displaytables_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);

        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_displaytables_callback", true);
        }
        else {
            _log("SUCCESS::get_displaytables_callback", false);

            xlreturn_displaytable_obj.draw_stat_cards(data.data);

            toggle_data_by_user_state();
        }

        $("#data-results").slideDown("fast");

        hideLoading();
    },
    //-------------------------------------------------
    get_displaytables_event: function(event) {
        xlreturn_displaytable_obj.get_displaytables(
            xlreturn_displaytable_obj.get_collection_callback);
    },
    //-------------------------------------------------
    draw_stat_cards: function(data) {

        var size = data.length;
        href = xlweburl.get_href();

        var col = 2;

        if (is_game_fleetdefense()) {
            $("#stat-cards").append("<div style=\"clear:both;\"></div><h1>Battle Stats</h1>");
        }
        else {
            $("#stat-cards").append("<div style=\"clear:both;\"></div><h1>Racing Stats</h1>");
        }

        var arrTables = new Array();
        var arrMultis = new Array();

        var arrTimesFinished = new Array();
        var arrTimesFinishedData = new Array();

        arrTimesFinished.push("Times Finished 1st");
        arrTimesFinished.push("Times Finished 2nd");
        arrTimesFinished.push("Times Finished 3rd");
        arrTimesFinished.push("Times Finished 4th");
        arrTimesFinished.push("Times Finished 5th");

        var arrFastestLaps = new Array();
        var arrFastestLapsData = new Array();

        arrFastestLaps.push("Fastest Single Lap");
        arrFastestLaps.push("Fastest 3 Laps");
        arrFastestLaps.push("Fastest 5 Laps");
        arrFastestLaps.push("Fastest 10 Laps");

        for (var i = 0; i < size; i++) {
            shtml = "";
            var dataitem = data[i];

            // TODO add this in however it is unique as it has no tracks     
            if (dataitem.tableTitleText != "Total Multiplayer Time Played") {

                if (dataitem.tableTitleText == "Points in a Single Jump") {
                    col = 3;
                }

                // If it is a single table draw it
                if (!IsInArray(dataitem.tableTitleText, arrFastestLaps)
                    && !IsInArray(dataitem.tableTitleText, arrTimesFinished)) {

                    if (is_game_fleetdefense()) {
                        createSingleTableRow(dataitem.tableTitleText, dataitem, col);
                    }
                    else {
                        createSingleTable(dataitem.tableTitleText, dataitem, col);
                    }
                }
                else {

                    // If it is a multiple table tally the data

                    if (IsInArray(dataitem.tableTitleText, arrTimesFinished)) {
                        arrTimesFinishedData.push(dataitem);
                    }

                    if (IsInArray(dataitem.tableTitleText, arrFastestLaps)) {
                        arrFastestLapsData.push(dataitem);
                    }

                    // If it is the last item of each array type, draw the larger table

                    if (dataitem.tableTitleText == arrFastestLaps[arrFastestLaps.length - 1]) {
                        createFastestLapsTable(data, "Fastest Laps", arrFastestLaps, arrFastestLapsData, col);
                    }

                    if (dataitem.tableTitleText == arrTimesFinished[arrTimesFinished.length - 1]) {
                        createTimesFinishedTable(data, "Times Finished", arrTimesFinished, arrTimesFinishedData, col);
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------

function IsInArray(name, arr) {
    var isInArray = false;
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] == name) {
            isInArray = true;
            break;
        }
    }
    return isInArray;
}

// ---------------------------------------------------------------------------
var classitemdisplay = " row-alt";
function createSingleTableRow(name, dataitem, col) {
    shtml = "";

    if (classitemdisplay == "") {
        classitemdisplay = " row-alt";
    }
    else {
        classitemdisplay = "";    
    }
    shtml += "<div class=\"statcard-full" + classitemdisplay + "\">";

    shtml += "<script>xlwebapi.xlstatistic.get_user_statistic(" + dataitem.uniqueID + ", " + col + ", xlwebapi.xlstatistic.get_user_statistic_callback);</script>";
    shtml += "<div id=\"" + dataitem.statCode + "\"><img src=\"/static/img/loader.gif\" border=\"0\" /></div>";
    shtml += "</div>";
    $("#stat-cards").append(shtml);
}

// ---------------------------------------------------------------------------

function createSingleTable(name, dataitem, col) {
    shtml = "";

    if (dataitem.tableTitleText == "Points in a Single Jump") {
        shtml += "<div style=\"clear:both;\"></div><h1>Stunt Stats</h1>";
    }

    if (col == 3)
        shtml += "<div class=\"statcard-small\">";
    else
        shtml += "<div class=\"statcard\">";
    shtml += "<script>xlwebapi.xlstatistic.get_user_statistic(" + dataitem.uniqueID + ", " + col + ", xlwebapi.xlstatistic.get_user_statistic_callback);</script>";
    shtml += "<h5>" + dataitem.tableTitleText + "</h5>";
    shtml += "<div id=\"" + dataitem.statCode + "\"><img src=\"/static/img/loader.gif\" border=\"0\" /></div>";
    shtml += "</div>";
    $("#stat-cards").append(shtml);
}

// ---------------------------------------------------------------------------

function createFastestLapsTable(data, maintitle, arrname, dataitems, col) {
    var _key = "";
    for (var i = 0; i < dataitems.length; i++) {
        if (i > 0)
            _key += "-";
        _key += dataitems[i].uniqueID;
    }

    _log("KeyFastestLap", _key);

    shtml = "";
    shtml += "<div style=\"clear:both;\"></div>";
    shtml += "<div class=\"statcard-wide\">";
    shtml += "<script>xlwebapi.xlstatistic.get_user_statistics('" + _key + "', " + col + ", xlwebapi.xlstatistic.get_user_statistics_callback);</script>";
    shtml += "<h5>Fastest Laps</h5>";
    shtml += "<div id=\"" + _key + "\"><img src=\"/static/img/loader.gif\" border=\"0\" /></div>";
    shtml += "</div>";
    $("#stat-cards").append(shtml);
}

// ---------------------------------------------------------------------------

function createTimesFinishedTable(data, maintitle, arrname, dataitems, col) {

    var _key = "";
    for (var i = 0; i < dataitems.length; i++) {
        if (i > 0)
            _key += "-";
        _key += dataitems[i].uniqueID;
    }

    _log("KeyTimesFinished", _key);

    shtml = "";
    shtml += "<div style=\"clear:both;\"></div>";
    shtml += "<div class=\"statcard-wide\">";
    shtml += "<script>xlwebapi.xlstatistic.get_user_statistics('" + _key + "', " + col + ", xlwebapi.xlstatistic.get_user_statistics_callback);</script>";
    shtml += "<h5>Times Finished</h5>";
    shtml += "<div id=\"" + _key + "\"><img src=\"/static/img/loader.gif\" border=\"0\" /></div>";
    shtml += "</div>";
    $("#stat-cards").append(shtml);
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.liveachievement = function() {
    this.fn_callback;
    this.total_achievement_points = 0;
    this.total_achievement_items = 0;
    xlreturn_user_achievement_obj = this;
}

xlweb.liveachievement.prototype = {
    //-------------------------------------------------
    init: function() {

    }
    ,
    //-------------------------------------------------
    get_user_achievements: function(username, fn) {

        this.fn_callback = fn;
        if (xlwebapi.gamer != "" && xlwebapi.gamer != null) {

            showLoading();
            
            var service_url = xlweb_global.user_achievement_service
            + "game/" + xlwebapi.game
            + "/gamer/" + xlwebapi.gamer;

            _log("serviceurl::", service_url);

            $.get(service_url,
        null
	    , fn
	    , "json");
        }
    },
    //-------------------------------------------------
    get_user_achievements_callback: function(data) {

        _log("data", data);
        _log("data.error", data.error);
        _log("data.info", data.info);
        _log("data.message", data.message);
        _log("data.data", data.data);
        _log("data.data.items", data.data.items);
        _log("data.data.totalAchievementPoints", data.data.totalAchievementPoints);
        _log("data.data.totalAchievementPointsCompleted", data.data.totalAchievementPointsCompleted);
        _log("data.data.totalAchievements", data.data.totalAchievements);
        _log("data.data.totalAchievementsCompleted", data.data.totalAchievementsCompleted);
        _log("data.data.achievementProgress", data.data.achievementProgress);
        _log("data.data.displayProgress", data.data.displayProgress);

        if (data.error > 0 || data.error.length > 1) {
            _log("errors::get_user_achievements_callback", true);
        }
        else {
            _log("SUCCESS::get_user_achievements_callback", false);

            // draw the table from the service response
            xlreturn_user_achievement_obj.draw_table(data.data);

            $("#user-achievement-points-total").html(data.data.totalAchievementPointsCompleted);
            // $("#achievement-points-total").html(data.data.totalAchievementPoints);
            $("#user-achievement-point-percentage").html(data.data.achievementProgress);

            $("#achievement-display").html(data.data.displayProgress);
            $("#achievement-total").html(data.data.totalAchievements);
            $("#achievement-completed").html(data.data.totalAchievementsCompleted);

            xlreturn_user_achievement_obj.total_achievement_points = (data.data.totalAchievementPointsCompleted / 10000) * 100;
            xlreturn_user_achievement_obj.total_achievement_items = (data.data.totalAchievementsCompleted / data.data.totalAchievements) * 100;

            $("#user-achievement-point-percentage").html(xlreturn_user_achievement_obj.total_achievement_points.toFixed(1) + "% Completed");
            $("#achievement-display").html(xlreturn_user_achievement_obj.total_achievement_items.toFixed(1) + "% Completed");

            toggle_data_by_user_state();
        }

        hideLoading();
    },
    //-------------------------------------------------
    get_user_achievements_event: function(event) {
        //xlreturn_user_achievement_obj.login(
        //    event.data.username,
        //    event.data.password,
        //    xlreturn_user_obj.login_callback);
    }
    ,
    //-------------------------------------------------
    draw_table: function(obj) {
        var i, imax, shtml;
        var json = obj;

        var irowmax = json.items.length;

        if (irowmax < 1) {
            //alert('No rows in table');
            return;
        }

        var cols = new Array();
        //get an array of column names
        for (var key in json.items[0]) {  //assumign all columns present in first record
            cols[cols.length] = key;
        }

        icolmax = cols.length;

        shtml = "<table border=\"0\" align=\"center\" class=\"achievement-table\" width=\"100%\"><tr class=\"achievement-tr\">";          //create header row - save html of table in shtml
        for (i = 0; i < icolmax; i++) {
            var columnName = cols[i];
            switch (columnName) {
                case "achievementName":
                    columnName = "Name";
                    break;
                case "achieved":
                    columnName = "Completed";
                    break;
                case "points":
                    columnName = "Points";
                    break;
                case "description":
                    columnName = "Description";
                    break;
            }
            shtml += "<th class=\"achievement-cols\">" + columnName + "</th>";
        }
        shtml += "</tr>";

        var irowmax = json.items.length;

        for (irow = 0; irow < irowmax; irow++) {  //add the rows
            //shtml += "<tr class=\"achievement-tr\">";
            if (irow % 2 == 0) {
                shtml += "<tr class=\"row-alt achievement-tr\">";
            } else {
                shtml += "<tr class=\"achievement-tr\">";
            }
            for (i = 0; i < icolmax; i++) {

                var value = json.items[irow][cols[i]];
                //if (value != "") {
                if (value == "true" || value == true)
                    value = "<img src=\"/static/img/2xl-go-24px.png\" valign=\"absmiddle\" />";
                if (value == "false" || value == false)
                    value = "";                

                if (i % 2 == 0)
                    shtml += "<td class=\"\">" + value + "</td>";
                else
                    shtml += "<td class=\"\">" + value + "</td>";
                //}
            }
            shtml += "</tr>";
        }
        shtml += "</table>";

        $("#achievements-table").html(shtml);   //write the table into div mydiv

        $(".achievement-table").slideDown("slow");

        // $("#data").slideDown("fast");
        $("#data-results").slideDown("fast");

        xlreturn_user_achievement_obj.update_progress_bar_points();
        xlreturn_user_achievement_obj.update_progress_bar_totals();
    },
    //-------------------------------------------------
    update_progress_bar_points: function() {
        $("#progressbar").progressbar({ value: 0 });
        setTimeout(xlreturn_user_achievement_obj.update_progress_bar_points_gui);
    },
    //-------------------------------------------------
    update_progress_bar_points_gui: function() {
        var progress;
        progress = $("#progressbar")
            .progressbar("option", "value");
        if (progress < xlreturn_user_achievement_obj.total_achievement_points) {
            $("#progressbar")
            .progressbar("option", "value", progress + 1);
            setTimeout(xlreturn_user_achievement_obj.update_progress_bar_points_gui, 5);
        }
    },
    //-------------------------------------------------
    update_progress_bar_totals: function() {
        $("#progressbar2").progressbar({ value: 0 });
        setTimeout(xlreturn_user_achievement_obj.update_progress_bar_totals_gui);
    },
    //-------------------------------------------------
    update_progress_bar_totals_gui: function() {
        var progress;
        progress = $("#progressbar2")
            .progressbar("option", "value");
        if (progress < xlreturn_user_achievement_obj.total_achievement_items) {
            $("#progressbar2")
            .progressbar("option", "value", progress + 1);
            setTimeout(xlreturn_user_achievement_obj.update_progress_bar_totals_gui, 5);
        }
    }
}

// ---------------------------------------------------------------------------
// ---------------------------------------------------------------------------

xlweb.api = function() {

    this.url = document.location;

    this.xlliveuser = new xlweb.liveuser();
    this.xlglobal = new xlweb.global();
    this.xlachievement = new xlweb.liveachievement();
    this.xlcollection = new xlweb.livecollection();
    this.xldisplaytable = new xlweb.livedisplaytable();
    this.xllivefeed = new xlweb.livefeed();
    this.xlstatistic = new xlweb.livestatistic();
    this.xlleaderboard = new xlweb.liveleaderboard();
    this.xlliveadminuser = new xlweb.liveadminuser();
    this.xlliveadminprofiles = new xlweb.liveadminprofiles();
    this.xllivesyndication = new xlweb.livesyndication();

    // endpoints 
    // TODO, change services to correct planned enpoints
    //this.content_service = xlweb_global.content_service;
    //this.asset_service = xlweb_global.asset_service;

    this.api_key = xlweb_global.api_key; // temp for now
    this.service_type = xlweb_global.service_type;
    this.session_id = xlweb_global.session_id; // temp for now

    this.game = getUrlParamValue("game");
    this.gamer = getUrlParamValue("gamer");
    this.view = "";

    this.cookiename = "xllivegame";

    // this.required_params = '?format=' + this.service_type + '&api_key=' + this.api_key + '&session_id=' + this.session_id;
    // this.callback_param = '&callback=';
    // this.fb_fields_info = 'uid,about_me,activities,affiliations,birthday,books,current_location,education_history,email_hashes,first_name,hometown_location,hs_info,interests,is_app_user,last_name,locale,meeting_for,meeting_sex,movies,music,name,notes_count,pic,pic_with_logo,pic_big,pic_big_with_logo,pic_small,pic_small_with_logo,pic_square,pic_square_with_logo,political,profile_update_time,profile_url,proxied_email,quotes,relationship_status,religion,sex,significant_other_id,status,timezone,tv,wall_count,work_history';
    // this.fb_fields_info = this.fb_fields_info + '';
}

xlweb.api.prototype = {
    //-------------------------------------------------
    init: function() {
        this.get_game();
        this.get_gamer();
        this.get_view();
        xlwebapi.game = getUrlParamValue("game"); ;
        xlwebapi.gamer = getUrlParamValue("gamer"); ;
              
    },
    //-------------------------------------------------
    get_game: function() {
        href = xlweburl.get_href();
        var game = getUrlParamValue("game");
        this.game = game;
        xlwebapi.game = game;
        //$.cookie(XLLIVE_COOKIE_GAME, this.game);
        //_log("this.game:", this.game);
    },
    //-------------------------------------------------
    get_gamer: function() {
        href = xlweburl.get_href();
        var gamer = getUrlParamValue("gamer");
        this.gamer = gamer;
        xlwebapi.gamer = gamer;
        //$.cookie(XLLIVE_COOKIE_GAMER, this.gamer);
        //_log("this.gamer:", this.gamer);
    },
    //-------------------------------------------------
    get_view: function() {
        if (is_section_leaderboard()) {
            this.view = "leaderboard";
        }
        else if (is_section_profile()) {
            this.view = "profile";
        }
        else if (is_section_login()) {
            this.view = "login";
        }
        else if (is_section_live()) {
            this.view = "live";
        }
        else if (is_section_statistics()) {
            this.view = "statistics";
        }
        else if (is_section_achievements()) {
            this.view = "achievements";
        }
        else if (is_section_admin()) {
            this.view = "admin";
        }
        else {
            this.view = "content";
        }
        $.cookie(XLLIVE_COOKIE_VIEW, this.view);
        //_log("this.view:", this.view);
    },
    //-------------------------------------------------
    hide_loading: function() {
        $("loading-data").hide("fast");
    },
    //-------------------------------------------------
    show_loading: function() {
        $("loading-data").show("fast");
    },
    //-------------------------------------------------
    distance_of_time_in_words: function(to, from) {
        var distance_in_seconds = ((to - from) / 1000);
        var distance_in_minutes = (distance_in_seconds / 60).floor();

        if (distance_in_minutes == 0) { return 'less than a minute ago'; }
        if (distance_in_minutes == 1) { return 'a minute ago'; }
        if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes ago'; }
        if (distance_in_minutes < 90) { return 'about 1 hour ago'; }
        if (distance_in_minutes < 1440) { return 'about ' + (distance_in_minutes / 60).floor() + ' hours ago'; }
        if (distance_in_minutes < 2880) { return '1 day ago'; }
        if (distance_in_minutes < 43200) { return (distance_in_minutes / 1440).floor() + ' days ago'; }
        if (distance_in_minutes < 86400) { return 'about 1 month ago'; }
        if (distance_in_minutes < 525960) { return (distance_in_minutes / 43200).floor() + ' months ago'; }
        if (distance_in_minutes < 1051199) { return 'about 1 year ago'; }

        return 'over ' + (distance_in_minutes / 525960).floor() + ' years ago';
    },
    //-------------------------------------------------
    get_function_name: function(fn) {
        var name = fn.toString();
        name = name.substr('function '.length);
        name = name.substr(0, name.indexOf('('));
        return name;
    },
    //-------------------------------------------------
    log_info: function(name, value) {
        // uses firebug
        if (window.console && window.console.info) {
            console.info(name);
            console.info(value);
        }
    },
    //-------------------------------------------------
    log_debug: function(name, value) {
        // uses firebug
        if (window.console && window.console.debug) {
            console.debug(name);
            console.debug(value);
        }
    },
    //-------------------------------------------------
    log_error: function(name, value) {
        // uses firebug
        if (window.console && window.console.error) {
            console.error(name);
            console.error(value);
        }
    }
}

// ---------------------------------------------------------------------------

function select_key1() {
    $("key2").hide();
    $("key3").hide();
}

// ---------------------------------------------------------------------------

function showGameSelect() {
    //$("#game-rollout").slideDown("slow");
    //$("#game-rollout").show("slow");
}

// ---------------------------------------------------------------------------

function hideGameSelect() {
    //delayedHideGameSelect();
}

// ---------------------------------------------------------------------------

function showLoading() {
    //$("#loading-data").slideDown("slow");
}

// ---------------------------------------------------------------------------

function hideLoading() {
   // $("#loading-data").slideUp("fast");
}

// ---------------------------------------------------------------------------

function delayedHideGameSelect() {
    //$("#game-rollout").slideUp("fast");
    //$("#game-rollout").hide("fast");
}

// ---------------------------------------------------------------------------

function show_message(id, msg) {
    $(id).html(msg);
    $(id).show();
    setTimeout(hide_message, 3000, id);
}

// ---------------------------------------------------------------------------

function hide_message(id) {
    $(id).hide();
}

function load_page(_hash)
{
    var basehash = {};

    href = xlweburl.get_href();
    //hash = xlweburl.get_hash(); 

    xlwebapi.init();
    
    var arrpaths = href.split('/');
    arrpaths.splice(0, 3);
    
    _hash = arrpaths.join("/"); 
    hash_code = _hash;
    hash_params = "";
    if (_hash.indexOf("?") > -1) {
        hash_code = _hash.split("?")[0];
        hash_params = _hash.split("?")[1];
    }

    // restore ajax loaded state
    if (hash_params != "")
        hash_params = "?" + hash_params;
        
    _log("hash_code::", hash_code);
    if(hash_code == '' || hash_code == 'undefined')
    {
        hash_code = 'home';
        _log("hash_code::", hash_code);
    }

    var hash_full_path_content = "/content/content.aspx?_p=" + hash_code + "" + hash_params + "";
    var hash_full_path_info = hash_code + ".aspx" + hash_params;
    var hash_full_path = "/content/" + hash_code + ".aspx?_p=" + hash_params;
    var hash_params = hash_params;

    basehash.hash_full_path_content = hash_full_path_content;
    basehash.hash_full_path_info = hash_full_path_info;
    basehash.hash_full_path = hash_full_path;
    basehash.hash_params = hash_params;
    basehash.hash_params = hash_params;

    _log("basehash::", basehash);
    _log("loading content::", hash_full_path_content);
    _log("xlwebapi.game::", xlwebapi.game);
    _log("xlwebapi.gamer::", xlwebapi.gamer);
    
    $("#load").load(hash_full_path_content);
}

// ---------------------------------------------------------------------------
// PageLoad function
// This function is called when:
// 1. after calling $.historyInit();
// 2. after calling $.historyLoad();
// 3. after pushing "Go Back" button of a browser

function pageload(_hash) {
    // hash doesn't contain the first # character.

    href = xlweburl.get_href();
    //hash = xlweburl.get_hash(); 

    xlwebapi.init();
    
    var arrpaths = href.split('/');
    arrpaths.splice(0, 3);
    
    _hash = arrpaths.join("/");  
 
     if (_hash) {

        if (_hash != "#") {
            load_page(_hash);
        }

    }
    else {
        // start page
        _log("loading default content::", "/content/content.aspx?_p=home");

        $("#load").load("/content/content.aspx?_p=home");
    }

    changeState();
}

// ---------------------------------------------------------------------------

function changeState() {

    href = xlweburl.get_href();
    //hash = xlweburl.get_hash(); 
    if (href.indexOf('#http://') > -1) {
        document.location.replace(href.split('#')[1]);
    }

    xlweburl.set_url_state();
    xlwebapi.init();

    href = xlweburl.get_href();

    if (href.indexOf('#http://') > -1) {
        document.location.replace(href.split('#')[1]);
    }

    if (href.indexOf("#statistics") > -1 || href.indexOf("#leaderboards") > -1) {
        loadEnvs();
    }

    // Make sure we have a hash path
    switch_to_dynamic();

    set_select();
    
    link_state_profile(".statistics a");
    link_state_profile(".achievements a");

    link_state(".leaderboards a");
    link_state(".achievements a");
    link_state(".statistics a");
    

    // UI MANGEMENT
    if (   xlwebapi.gamer != "" 
        && xlwebapi.gamer != null)
            $("#q").val(xlwebapi.gamer);

    toggle_data_by_user_url();

    toggle_data_by_user_state();

    if (href.indexOf("leaderboard") > -1) {
        link_state_parent("#leaderboard-tab-alltime");
        link_state_parent("#leaderboard-tab-weekly");
        link_state_parent("#leaderboard-tab-daily");
        link_state_parent("#leaderboard-tab-monthly");
        showLeaderboard();
        loadLeaderboardContent();
    }

    // set onlick event for buttons
    $("a[rel='history']").click(function() {
        //
        var _hash = this.href;

        _log("this.href", this.href);
        _hash = _hash.replace(/^.*#/, '');

        _log("this.href", this.href);

        _log("hash", _hash);

        // moves to a new page. 
        // pageload is called at once.
        $.historyLoad(_hash);

        return false;
    });
    
}

// ---------------------------------------------------------------------------

var currentNav = 1;

function toggle_data_by_user_state() {

    var loggedin = $.cookie(XLLIVE_COOKIE_USER_STATE);

    _log("loggedin:", loggedin);

    if (loggedin == "1") {
        // if there is a gamer
        $("#live-login-profile").show();
        $("#live-login-form").hide();
        $("#profile-form").show();

        _log("gamer logged in:", true);

        if (currentNav == 1) {
            changeNavSprite("nav2", "current2");
            currentNav = 2;
        }
    }
    else {
        $("#live-login-profile").hide();
        $("#live-login-form").show();
        $("#profile-form").hide();

        _log("gamer logged in:", false);

        if (currentNav != 1) {
            changeNavSprite("nav", "current");
            currentNav = 1;
        }
    }
}

// ---------------------------------------------------------------------------

function toggle_admin_data_by_user_state() {

    var loggedin = $.cookie(XLLIVE_COOKIE_ADMIN_USER_STATE);

    _log("loggedin:", loggedin);

    if (loggedin == "1") {
        $("#logged-in").show();
        $("#not-logged-in").hide();
        
        _log("loggedin:", true);
        //document.location = '/admin/profiles';
    }
    else {
        $("#logged-in").hide();
        $("#not-logged-in").show();
        _log("loggedin:", false);
        //document.location = '/admin';
    }
}

// ---------------------------------------------------------------------------

function loginlogoutlinkevent(event) {
    loginlogoutlink();
}

// ---------------------------------------------------------------------------

function loginlogoutlink() {
    var loggedin = $.cookie(XLLIVE_COOKIE_USER_STATE);

    _log("loggedin:", loggedin);

    if (loggedin == "1") {
        xlwebapi.xlliveuser.logout(xlwebapi.xlliveuser.logout_callback);
        document.location = "/logout";
    }
    else {
        document.location = "/profile";
    }

}

// ---------------------------------------------------------------------------

function toggle_data_by_user_url() {
    if (   xlwebapi.gamer != "" 
        && xlwebapi.gamer != null) {
        // if there is a gamer
        $("#no-user").hide();
        $("#no-data").hide();
        $("#data").show('slow');
    }
    else {
        $("#no-user").show('fast');
        $("#no-data").show('fast');
        $("#data").hide();
    }
}

// ---------------------------------------------------------------------------

function do_gamer_search() {

    if (   $("#q").val() != "Search for player..." 
        && $("#q").val() != "") {

        _log("searching for gamer:", $("#q").val());
        xlwebapi.gamer = $("#q").val();

        _log("xlwebapi.gamer", xlwebapi.gamer);

        // Default to latest game if no game passed...
        if (   xlwebapi.gamer != null 
            || xlwebapi.gamer != "") {

            href = xlweburl.get_href();
            _log("searching for gamer hrefhref:", href);

            if (href.indexOf("gamer/") == -1) {
                if (href.lastIndexOf("/") == href.length - 1)
                    href = hash.substr(0, href.length - 1);
                href += "/gamer/" + xlwebapi.gamer;
                _log("searching for gamer href1:", href.replace('#', ''));
                document.location = href;
            }
            else {
                var arr = href.split("/");
                for (i = 0; i < arr.length; i++) {
                    if (arr[i] == "gamer") {
                        arr[i + 1] = xlwebapi.gamer;
                        //changeState();
                        document.location = arr.join("/").replace('#','');
                        _log("searching for gamer2 href:", arr.join("/").replace('#',''));
                        break;
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------

function link_state_obj(obj) {

    var appendGameToUrl = "";
    var appendGamerToUrl = "";
    
    if (obj) {
        var hrefval = obj.attr("href");
                
        xlwebapi.init();

        if (xlwebapi.game != ""
            && xlwebapi.game != null) {
            appendGameToUrl += "/game/" + xlwebapi.game;
        }

        if (xlwebapi.gamer != ""
            && xlwebapi.gamer != null) {
            appendGamerToUrl += "/gamer/" + xlwebapi.gamer;
        }

        if (appendGameToUrl != ""
            && appendGameToUrl != null) {
            if (hrefval != null
                && hrefval != "undefined") {
                if (hrefval.indexOf("game/") == -1) {
                    if (hrefval.lastIndexOf("/") == hrefval.length - 1)
                        hrefval = hrefval.substr(0, hrefval.length - 1);
                    obj.attr("href", hrefval + appendGameToUrl);
                } else {
                    var arr = hrefval.split("/");
                    for (i = 0; i < arr.length; i++) {
                        if (arr[i] == "game") {
                            arr[i + 1] = xlwebapi.game;
                            break;
                        }
                    }
                    hrefval = arr.join("/");
                    obj.attr("href", hrefval);
                }
            }
        }

        if (appendGamerToUrl != ""
            && appendGamerToUrl != null) {
            if (hrefval != null
                && hrefval != "undefined") {
                if (hrefval.indexOf("gamer/") == -1) {
                    if (hrefval.lastIndexOf("/") == hrefval.length - 1)
                        hrefval = hrefval.substr(0, hrefval.length - 1);
                    obj.attr("href", hrefval + appendGamerToUrl);
                } else {
                    var arr = hrefval.split("/");
                    for (i = 0; i < arr.length; i++) {
                        if (arr[i] == "gamer") {
                            arr[i + 1] = xlwebapi.gamer;
                            break;
                        }
                    }
                    hrefval = arr.join("/");
                    obj.attr("href", hrefval);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------

function link_state_obj_keys(obj) {

    if (is_section_leaderboard()) {
        var appendKeyToUrl = "";

        if (obj) {
            var hrefval = obj.attr("href");


            for (var i = 1; i <= 8; i++) {
                if (getUrlParamLeaderboardValue("key" + i) != "0") {
                    appendKeyToUrl += "/key" + i + "/" + getUrlParamLeaderboardValue("key" + i);
                }

                if (appendKeyToUrl != ""
                    && appendKeyToUrl != null) {
                    if (hrefval != null
                        && hrefval != "undefined") {
                        if (hrefval.indexOf("key" + i + "/") == -1) {
                            if (hrefval.lastIndexOf("/") == hrefval.length - 1)
                                hrefval = hrefval.substr(0, hrefval.length - 1);
                            obj.attr("href", hrefval + appendKeyToUrl);
                        } else {
                            var arr = hrefval.split("/");
                            for (i = 0; i < arr.length; i++) {
                                if (arr[i] == "key" + i) {
                                    arr[i + 1] = getUrlParamLeaderboardValue("key" + i);
                                    break;
                                }
                            }
                            hrefval = arr.join("/");
                            obj.attr("href", hrefval);
                        }
                    }
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------

function link_state(objname) {
    var obj = $(objname);
    link_state_obj(obj);
    if (objname.indexOf("leaderboard") > -1) {
        link_state_obj_keys(obj);
    }
}

// ---------------------------------------------------------------------------

function link_state_parent(objname) {
    var obj = $(objname).parent();
    link_state_obj(obj);
    if (objname.indexOf("leaderboard") > -1) {
        link_state_obj_keys(obj);
    }
}

// ---------------------------------------------------------------------------

function link_state_profile(objname) {

    var appendGameToUrl = "";
    var appendGamerToUrl = "";
    if ($(objname)) {
        var hrefval = $(objname).attr("href");

        var gamercookie = $.cookie(XLLIVE_COOKIE_USER_NAME);
        xlwebapi.init();
        //if (gamercookie != null && gamercookie != "") {
        //    xlwebapi.gamer = gamercookie; 
        //}

        if (   xlwebapi.game != "" 
            && xlwebapi.game != null) {
            appendGameToUrl += "/game/" + xlwebapi.game;
        }

        if (   gamercookie != "" 
            && gamercookie != null) {
            appendGamerToUrl += "/gamer/" + gamercookie;
        }

        if (   appendGameToUrl != "" 
            && appendGameToUrl != null) {
            if (   hrefval != null 
                && hrefval != "undefined") {
                if (hrefval.indexOf("game/") == -1) {
                    if (hrefval.lastIndexOf("/") == hrefval.length - 1)
                        hrefval = hrefval.substr(0, hrefval.length - 1);
                    $(objname).attr("href", hrefval + appendGameToUrl);
                } else {
                    var arr = hrefval.split("/");
                    for (i = 0; i < arr.length; i++) {
                        if (arr[i] == "game") {
                            arr[i + 1] = xlwebapi.game;
                            break;
                        }
                    }
                    hrefval = arr.join("/");
                    $(objname).attr("href", hrefval);
                }
            }
        }

        if (   appendGamerToUrl != "" 
            && appendGamerToUrl != null) {
            if (   hrefval != null 
                && hrefval != "undefined") {
                if (hrefval.indexOf("gamer/") == -1) {
                    if (hrefval.lastIndexOf("/") == hrefval.length - 1)
                        hrefval = hrefval.substr(0, hrefval.length - 1);
                    $(objname).attr("href", hrefval + appendGamerToUrl);
                } else {
                    var arr = hrefval.split("/");
                    for (i = 0; i < arr.length; i++) {
                        if (arr[i] == "gamer") {
                            arr[i + 1] = gamercookie;
                            break;
                        }
                    }
                    hrefval = arr.join("/");
                    $(objname).attr("href", hrefval);
                }
            }
        }
    }
}

// ---------------------------------------------------------------------------

function do_gamer_login() {
    xlwebapi.xlliveuser.login($("#username").val(), $("#password").val(), xlwebapi.xlliveuser.login_event);
    return false;
}

// ---------------------------------------------------------------------------

function select_section(obj) {
   //set_nav_selection(obj);
   // _log("obj", obj);
   // _log("selected_class pre", selected_class);
   // $(".nav").removeClass(selected_class);
   // selected_class = ".current-" + obj;
   // _log("selected_class post", selected_class);
   // $(".nav").addClass(selected_class);
}

// ---------------------------------------------------------------------------

function set_select() {
    if (is_section_statistics()) {
        select_section('statistics');
    }
    else if (is_section_achievements()) {
        select_section('achievements');
    }
    else if (is_section_leaderboard()) {
        select_section('leaderboards');
    }
    else if (is_section_home()) {
        select_section('home');
    }
    else if (is_section_login()) {
        select_section('login');
    }
    else if (is_section_profile()) {
        select_section('profile');
    }
    else if (is_section_live()) {
        select_section('live');
    }
    else if (is_section_games()) {
        select_section('games');
    }
    else if (is_section_content()) {
        select_section('content');
    }
    else if (is_section_admin()) {
        select_section('admin');
    }
    else {
        select_section('home');
    }
}

// ---------------------------------------------------------------------------

var accordion = function(toggleEl, accEl) {
    toggleEl.click(function() {
        accEl.slideToggle(function() { });
        return false;
    });
}

// ---------------------------------------------------------------------------

function changeUrlToStateSingle(param, paramvalue) {

    var dl = xlweburl.get_dl();
    hash = xlweburl.get_hash();
    href = xlweburl.get_href();

    if (href.indexOf(param) > -1) {
        // hash contains param, just update

        var _params = href.split("/");
        for (var i = 0; i < _params.length; i++) {
            if (_params[i] == param) {
                _params[i + 1] = paramvalue;
            }
        }

        document.location.replace(_params.join("/"));
    }
    else {
        // has not present, append it
        if (href.indexOf(param + "/") == -1) {
            if (href.lastIndexOf("/") == href.length - 1)
                href = href.substr(0, href.length - 1);
            var _href = href += "/" + param + "/" + paramvalue + "/";
            document.location.replace(_href);
        }
    }
}

// ---------------------------------------------------------------------------

function changeUrlToState(href, param, paramvalue) {

    var _returnurl = "";

    if (href.indexOf(param) > -1) {
        // hash contains param, just update

        var _params = href.split("/");
        for (var i = 0; i < _params.length; i++) {
            if (_params[i] == param) {
                _params[i + 1] = paramvalue;
            }
        }

        _returnurl = _params.join("/");
    }
    else {
        // has not present, append it
        if (href.indexOf(param + "/") == -1) {
            if (href.lastIndexOf("/") == href.length - 1)
                href = href.substr(0, href.length - 1);
            _returnurl = href + "/" + param + "/" + paramvalue;
        }
    }
    return _returnurl;
}

// ---------------------------------------------------------------------------

function addButtonEvents() {

    // Form handling and events

    $("#q").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            do_gamer_search();
            return false;
        } else {
            return true;
        }
    });

    $("#password").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            do_gamer_login();
            return false;
        } else {
            return true;
        }
    });

    $("#username").keypress(function(e) {
        if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
            do_gamer_login();
            return false;
        } else {
            return true;
        }
    });

    $(".defaultText").focus(function() {
        if ($(this).val() == $(this)[0].title) {
            $(this).removeClass("defaultTextActive");
            $(this).val("");
        }
    });

    $(".defaultText").blur(function() {
        if ($(this).val() == "") {
            $(this).addClass("defaultTextActive");
            $(this).val($(this)[0].title);
        }
    });

    $(".defaultText").blur();

    $("#loginlogoutlink").bind("click"
		, null
		, loginlogoutlinkevent);
}


xlwebapi = new xlweb.api();

// ---------------------------------------------------------------------------

$(function() {

    xlweburl.set_url_state();

    // Load up the api that contains user, global and api functions
    xlwebapi.init();

    addButtonEvents();

    changeState();

    // default page...
    href = xlweburl.get_href();
        
    if(href.indexOf('.com/#') > -1){
        document.location = href.replace('#','');
    }

    if (xlwebapi.gamer != "")
        $("#q").val(xlwebapi.gamer);

    // -----------------------------------------------------------------
    // Initialize history plugin.
    // The callback is called at once by present location.hash. 
    //$.historyInit(pageload);
    
    load_page(href);

    // set onlick event for buttons
    $("a[rel='history']").click(function() {
        //
        var _hash = this.href;

        _log("this.href", this.href);
        _hash = _hash.replace(/^.*#/, '');

        _log("this.href", this.href);

        _log("hash", _hash);

        // moves to a new page. 
        // pageload is called at once.
        $.historyLoad(_hash);

        return false;
    });

});



