// 03/09/2011 - function moved up to pass JSHint review

function updateLeaderboard(filename) {

    // This function will take a JSON file name and load it. Clean code, etc.
    //
    // TODO: toss an if here? (i.e. if the leaderboard has data, slide / blank / slide?)
    //
    // Though, currently, nuking the HTML and repopulating looks fine with no animation..
    //
    // Or do we put a loading modal in front, maybe?

    //$("#leaderboard").slideUp("fast").html("&nbsp;").slideDown("fast");
    $("#leaderboard").html("&nbsp;");
    //$("#leaderboard").slideDown("fast");

    $.getJSON(filename, function (data) {
        $.each(data, function (i, user) {

            // 04/02/2010 - cleaned up to match lbtest.html
            // 08/14/2010 - cleaned up to match changed JSON values
            // 10/21/2010 - new user_imgs directory
            //var str = "<h3 class='lhead'><a><div id='lbimagesml'><img src='" + user.img_url + "' alt='" + user.username + "' height='24' width='24'/></div><div id='tuname' class='lg'>@" + user.username + "</div> <div id='pts' class='lg'>" + user.total_pts + " points</div></a></h3> <p class='lfoot' style='display:block;'><span id='lbimagelg'><img src='" + user.img_url + "' alt='" + user.username + "' height='108' width='108'/></span><span id='perinfo' class='white'><span id='rname' class='lg'>" + user.name + "</span><span class='flink big'><a href='http://twitwitgames.com/twitpardy/user/" + user.username + "'>View User</a></span><span id='loc' class='center big'>" + user.location + "</span></span> <span id='leadivbottom' class='center white'><span id='corpert' class='center'>% correct<br/><span class='lg'>" + user.correct_pct + "%</span></span><span id='cortemp' class='center'>correct/attempted<br/><span class='lg'>" + user.correct_ans + "/" + user.total_ans + "</span></span><span id='cater' class='center'>Best Category<br/><span class='lg'>" + user.best_cat + "</span></span></span></p>";
            var str = "<h3 class='lhead'><a><div id='lbimagesml'><img src='user_imgs/" + user.uid + "_t.png' alt='" + user.username + "' height='24' width='24'/></div><div id='tuname' class='lg'>@" + user.username + "</div> <div id='pts' class='lg'>" + user.total_pts + " points</div></a></h3> <p class='lfoot' style='display:block;'><span id='lbimagelg'><img src='user_imgs/" + user.uid + "_s.png' alt='" + user.username + "' height='108' width='108'/></span><span id='perinfo' class='white'><span id='rname' class='lg'>" + user.name + "</span><span class='flink big'><a href='http://twitwitgames.com/twitpardy/user/" + user.username + "'>View User</a></span><span id='loc' class='center big'>" + user.location + "</span></span> <span id='leadivbottom' class='center white'><span id='corpert' class='center'>% correct<br/><span class='lg'>" + user.correct_pct + "%</span></span><span id='cortemp' class='center'>correct/attempted<br/><span class='lg'>" + user.correct_ans + "/" + user.total_ans + "</span></span><span id='cater' class='center'>Best Category<br/><span class='lg'>" + user.best_cat + "</span></span></span></p>";

            $("#leaderboard").append(str);
        });

        //leaderboard slider

        // Because the leaderboard div isn't getting populated until page load,
        // nothing really exists in the leaderboard when the page is ready. So,
        // this stuff all has to come into the getJSON() call.

        //$("#leaderboard p:not(:first)").hide();
        $("#leaderboard p").hide();

        $("#leaderboard h3").click(function () {
            $(this).next("p").slideToggle("fast")
            .siblings("p:visible").slideUp("fast");

        });

        // slideToggle is causing the first item in the div to slide up, I
        // think. Let's slide it down instead. (Or, we could do nothing and
        // it would still show).
        //$("#leaderboard p:first").slideToggle("fast");
        $("#leaderboard p:first").slideDown("fast");
    });
}

/* *********************************************************************** */

/* 09/01/2011 - issues with current Twitpardy tweet pull. Adding below code.
 *
 * Thanks to Twitter for their code that I'm blatantly borrowing:
 *
 * https://twitter.com/javascripts/blogger.js
 */

function updateTweetBox(filename) {

    // On success, update the tweet box.
    var jqxhr = $.getJSON(filename, function (tweet) {

        var username = tweet.screen_name;

        var status = tweet.status.text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\<\>]*[^.,;'">\:\s\<\>\)\]\!])/g, function(url) {
            return '<a href="'+url+'">'+url+'</a>';
        }).replace(/\B@([_a-z0-9]+)/ig, function(reply) {
            return  reply.charAt(0)+'<a href="http://twitter.com/'+reply.substring(1)+'">'+reply.substring(1)+'</a>';
        });

        $("#twitter_update_list").html('<li><span>'+status+'</span> <a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+tweet.status.id_str+'">'+relative_time(tweet.status.created_at)+'</a></li>');
    })
    
    // On error, stick an error msg in the tweet box.
    .error(function() {
        $("#twitter_update_list").html('<span class="error_twit">It looks like Twitter is down at the moment. But that usually doesn\'t last long. Check back in a few.</span>');
    });
}

function relative_time(time_value) {
    var values = time_value.split(" ");
    time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var delta = parseInt((relative_to.getTime() - parsed_date) / 1000);
    delta = delta + (relative_to.getTimezoneOffset() * 60);

    if (delta < 60) {
        return 'less than a minute ago';
    } else if(delta < 120) {
        return 'about a minute ago';
    } else if(delta < (60*60)) {
        return (parseInt(delta / 60)).toString() + ' minutes ago';
    } else if(delta < (120*60)) {
        return 'about an hour ago';
    } else if(delta < (24*60*60)) {
        return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago';
    } else if(delta < (48*60*60)) {
        return '1 day ago';
    } else {
        return (parseInt(delta / 86400)).toString() + ' days ago';
    }
}

/* *********************************************************************** */

$(document).ready(function () {

    // Click handlers for Top X.
    //
    // TODO: add checks to see if JSON is loaded already?
    //
    // That means, if Top 20 is displayed, can we stop a reload of Top 20?
    $("#top20").click(function () {
        updateLeaderboard("data/top20_weekly.json");
    });

    $("#top50").click(function () {
        updateLeaderboard("data/top50_weekly.json");
    });

    $("#top100").click(function () {
        updateLeaderboard("data/top100_weekly.json");
    });

    $("#week").click(function () {
        updateLeaderboard("data/top20_weekly.json");
    });

    $("#30day").click(function () {
        updateLeaderboard("data/top50_thirty.json");
    });

    $("#alltime").click(function () {
        updateLeaderboard("data/top100.json");
    });

    // Load Top 20 on page ready.
    //
    // TODO: nevermind! Added in index.html (no need for document.ready!).
    //updateLeaderboard("data/top20_weekly.json");
});

