﻿function loadTwitter() {
    //$.getJSON('http://twitter.com/statuses/user_timeline/ChadEmm.json?count=5&callback=?', {}, loadTwitter_Complete);
    $.getJSON('database.php?type=feed', {}, loadFeed_Complete);
}

var feedResult;

function loadFeed_Complete(result){
    feedResult = result;
    //insert twitter items
    try
    {
        $.getJSON('http://twitter.com/statuses/user_timeline/ChadEmm.json?count=5&callback=?', {}, loadTwitter_Complete);
    }
    catch(ex)
    {
        //display feed anyways, just without twitter items
        displayFeed();
    }        
}

function loadTwitter_Complete(result){
    //insert twitter items
    $.each(result, function(i, tweet) {
        feedResult.data.push(eval("({ 'Link':'', 'Title':'" + tweet.text + "', 'Source':'twitter', 'Date':'" + format_date(new Date(tweet.created_at)) + "' })"));
    });
    
    //sort by date
    feedResult.data.sort(function(a, b) { return a.Date < b.Date });
    displayFeed();
}

function displayFeed() {
    var output = $('#feedItem').parseTemplate(feedResult);
    $('#feedcontent').html(output);
    while($('#feedcontent').height() > 405)
    {
        //remove last element
        $('#feedcontent > .feedItem:last').remove();
    }
}

function format_date(date){
    //returns YYYY-MM-DD hh:mm:ss
    return date.getFullYear() + "-" + addZero(date.getMonth() + 1) + "-" + addZero(date.getDate()) + " " + 
        addZero(date.getHours()) + ":" + addZero(date.getMinutes()) + ":" + addZero(date.getSeconds());
}

function addZero(value){
    if(value < 10) return "0" + value;
    else return value;
}

$(document).ready(function() {
    loadTwitter();
    loadBlog();
});

$.fn.parseTemplate = function(data)
{
    var str = (this).html();
    var _tmplCache = {}
    var err = "";
    try
    {
        var func = _tmplCache[str];
        if (!func)
        {
            var strFunc =
            "var p=[],print=function(){p.push.apply(p,arguments);};" +
                        "with(obj){p.push('" +
            str.replace(/[\r\t\n]/g, " ")
               .replace(/'(?=[^#]*#>)/g, "\t")
               .split("'").join("\\'")
               .split("\t").join("'")
               .replace(/<#=(.+?)#>/g, "',$1,'")
               .split("<#").join("');")
               .split("#>").join("p.push('")
               + "');}return p.join('');";

            //alert(strFunc);
            func = new Function("obj", strFunc);
            _tmplCache[str] = func;
        }
        return func(data);
    } catch (e) { err = e.message; }
    return "< # ERROR: " + err.toString() + " # >";
}
