﻿function twitterTicker() {

    $('#twitter_update_list').cycle({
        fx: 'fade',
        pause: 1,
        timeout: 7000,
        cssAfter: {
            display: 'none'
        },
        cssBefore: {
            display: 'block'
        }
    });

}


function PopulateTwitterFeed() {
    //$.getJSON("http://twitter.com/statuses/user_timeline/ideasopenminds.json?callback=twitterCallback2&count=5",
    $.getJSON("http://twitter.com/statuses/user_timeline.json?screen_name=ideasopenminds&count=5&callback=?",
             function(tweetdata) {

                 var index = 0;
                 var tweetlist = $("#twitter_update_list");
                 tweetlist.empty();
                 $.each(tweetdata,
                       function(i, tweet) {
                           var content = "";

                           if (index < 4) {
                               content = content + ('<li>');
                               content = content + ('<span>' + urlToLink(tweet.text) + '</span>');
                               content = content + (' (<a href="http://twitter.com/ideasopenminds/statuses/' + tweet.id_str + '">' + relTime(tweet.created_at) + '</a>)')
                               content = content + ('</li>');
                               tweetlist.append(content);
                           }

                           index++;
                       }
                         )

                 twitterTicker();

             }
            );
}

function relTime(time_value) {
    time_value = time_value.replace(/(\+[0-9]{4}\s)/ig, "");
    var parsed_date = Date.parse(time_value);
    var relative_to = (arguments.length > 1) ? arguments[1] : new Date();
    var timeago = parseInt((relative_to.getTime() - parsed_date) / 1000);
    if (timeago < 60) return 'less than a minute ago';
    else if (timeago < 120) return 'about a minute ago';
    else if (timeago < (45 * 60)) return (parseInt(timeago / 60)).toString() + ' minutes ago';
    else if (timeago < (90 * 60)) return 'about an hour ago';
    else if (timeago < (24 * 60 * 60)) {
        var hours = (parseInt(timeago / 3600));
        var plural = '';
        if (hours > 1) {
            plural = 's';
        }
        return 'about ' + hours.toString() + ' hour' + plural + ' ago';
    }
    else if (timeago < (48 * 60 * 60)) return '1 day ago';
    else return (parseInt(timeago / 86400)).toString() + ' days ago';
}

function urlToLink(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    return text.replace(exp, "<a href='$1'>$1</a>");
}

