/**
* Twitter status and search grabber
*
* @version	1.0
* @author	Jasal Vadgama - Live Nation UK
* @require	jquery
* @license	GPL v3
**/

(function($) {
    $.fn.twitterfeed = function(settings) {
        var config = {
            user: "",
            feedId: "latestTweet",
            userLimit: 1,
            searchLimit: 5,
            hashtag: "",
            searchId: "searchTags"
        };

        if (settings) $.extend(config, settings);

        $.extend(this, {
            tidyPost: function(text) {
                // finds all @'s, hastags and links and converts to markup
                tweet = text.replace(/http:\/\/\S+/g, '<a href="$&" target="_blank">$&</a>')
					.replace(/(@)(\w+)/g, ' <a href="http://twitter.com/$2" target="_blank">@$2</a>')
					.replace(/(#)(\w+)/g, ' <a href="http://search.twitter.com/search?q=%23$2" target="_blank" class="by">#$2</a>');
                return tweet;
            },
            getRelTime: function(time_value) {
                // sets relative time from tweet post
                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';
                }
            },
            addSearch: function(hashtag, searchId) {
                var feed = this;
                var searchJSON = "http://search.twitter.com/search.json?callback=?&q=%23" + hashtag + "&rpp=" + config.searchLimit;

                $.getJSON(searchJSON, function(data) {
                    $("#" + searchId).html("");

                    if (data.results.length > 0) {
                        $.each(data.results, function(i, item) {
                            tweet = feed.tidyPost(item.text);
                            var values = item.created_at.split(" ");
                            time_value = values[2] + " " + values[1] + ", " + values[3] + " " + values[4];
                            tweetDate = feed.getRelTime(time_value);
                            tweetMethod = item.source.replace(/(&quot;)/g, "\"").replace(/(&lt;)/g, "<").replace(/(&gt;)/g, ">");
                            $("#" + searchId).append("<li><a href='http://www.twitter.com/" + item.from_user + "' title=''>" + item.from_user + ":</a> " + tweet + " <span class='tweetDetails'>" + tweetDate + " from " + tweetMethod + "</span></li>");
                        });
                    } else
                        $("#" + searchId).append("<li>no tweets to show...</li>");
                });
            },
            addLatest: function(user, feedId) {
                var feed = this;
                var timelineJSON = "http://twitter.com/statuses/user_timeline/" + user + ".json?callback=?&count=" + config.userLimit;

                $.getJSON(timelineJSON, function(data) {
                    $("#" + feedId).html("");
                    if (data.length > 0) {
                        $.each(data, function(i, item) {
                            tweet = feed.tidyPost(item.text);
                            var values = item.created_at.split(" ");
                            time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3];
                            tweetDate = feed.getRelTime(time_value);
                            $("#" + feedId).append("<li>" + tweet + " <span class='tweetDetails'>" + tweetDate + " from " + data[0].source + "</span></li>");

                            // added for download
                            $("#" + feedId).append("<li class=\"tweetActions\"><a href=\"http://twitter.com/home?status=RT @" + user + " " + item.text + "\" title=\"\" class=\"retweetLink\"><span>Retweet this</span></a> <a href=\"http://twitter.com/" + user + "\" title=\"\" class=\"followLink\"><span>Follow us</span></a><br clear='all' /></li>");
                        });
                    } else
                        $("#" + feedId).append("<li>no tweets to show...</li>");
                });
            }
        });

        // add search to page
        if (config.hashtag && config.searchId) this.addSearch(config.hashtag, config.searchId);

        // add user timeline to page
        if (config.user && config.feedId) this.addLatest(config.user, config.feedId);

        return this;
    };
})(jQuery);