// jQuery plugin - Simple RSS Aggregator
(function($){
    $.fn.aRSSFeed = function() {
        return this.each( function(){
            var $Cont = $(this);
            var iMaxNum = parseInt($Cont.attr( 'rssnum' ) || 0);
            var sFeedURL = $Cont.attr('rss_url');
            var type = $Cont.attr('type');
            if (sFeedURL == undefined)
                return false;
            $.getFeed ({
                url: 'wp-content/themes/ogilvy_blog_2009/get_rss_feed.php?url=' + escape(sFeedURL),
                success: function(feed) {
                    if (feed != undefined && feed.items) {
                        var sCode =
                            '<ul class="list">';
                        var iCount = 0;
                        for (var iItemId = 0; iItemId < feed.items.length; iItemId ++) {
                            var item = feed.items[iItemId];
                            var sDate;
                            var a;
                            var oDate

                            if (null != (a = item.updated.match(/(\d+)-(\d+)-(\d+)T(\d+):(\d+):(\d+)Z/)))
                                oDate = new Date(a[1], a[2], a[3], a[4], a[5], a[6], 0);
                            else
                                oDate = new Date(item.updated);
                            sDate = oDate.toLocaleString();
                            if (type == 'twitter') {
                                var description = item.description.split(': ');
                                description[1] = description[1].replace(/(http:\/\/\S+)/g, "<a target='_blank' href='$1'>$1</a>");
                                description[1] = description[1].replace(/@(\w+)/g, "<a href=\"http://www.twitter.com/$1\" target=\"_blank\">@$1</a>");
                                description[1] = description[1].replace(/#(\w+)/g, "<a href=\"http://search.twitter.com/search?q=$1\" target=\"_blank\">#$1</a>");
                                
                                sCode += '<li>' + description[1] + '<br/>' + sDate + '<br />from <a href="' + item.link + '" title="' + item.title + '">' + description[0] +'</a></li>';
                            }
                            else if (type == 'foursquare'){
                                sCode += '<li><a href="' + item.link + '" title="' + item.title + '">' + item.description + '"</a><br />' + sDate + '</li>';
                            }
                            iCount ++;
                            if (iCount == iMaxNum) break;
                        }

                        sCode +=
                            '</ul>';
                        
                        $Cont.html(sCode);
                    }
                },
                error: function(xhr, ajaxOptions, thrownError) {
                    $Cont.html('');
                }
            } );
        } );
    };
})(jQuery);

