Function.prototype.bind = function() { var fn = this; var args = $.makeArray(arguments); var scope = args.shift(); return function() { return fn.apply(scope, arguments); }}

var Class = function(d) { var c = function() { this.initialize.apply(this, arguments) }; for(var i in d) c.prototype[i] = d[i]; return c };

function updateTwitter(updates, container) {

    jQuery.each(updates, function(i, item) {
        var created_at = Date.parse(item.created_at);
        item.text += ' <em>' + since(created_at) + '</em>';

        var dd = jQuery('<li><img><cite><a class="cite-updates2" target="_blank"></a></cite> <span>' + item.text + '</span></li>');
        
        dd.children('img').attr('src', item.profile_image_url).width(36).height(36);
        dd.find('cite > a').attr('href', 'http://twitter.com/' + item.from_user).text('@' + item.from_user);
        
        dd.hide();
        jQuery(container).prepend(dd);
        dd.fadeIn('slow');
        
    });
    
}

var stream = stream || {};

stream.Twitter = new Class({

    initialize: function(keywords, callback, container, options) {    
        this.options = jQuery.merge(this.options, options || {});
        this.params   = '?rpp='+ this.options.count +'&q=' + encodeURIComponent(keywords);
        this.callback = callback;
        this.container = container;
    },

    update: function() {

        if(this.options.clear) {
            jQuery(this.container).empty();
        }

        jQuery.ajax({
            'url': 'http://search.twitter.com/search.json' + this.params,
            'success': this.success.bind(this),
            'dataType': 'jsonp'
        });

    },

    success: function(response) {

        if(response['results']) {

            this.params = response.refresh_url;
            response.results.reverse();


            this.callback.apply(this.callback, [response.results, this.container]);

        }

      setTimeout(this.update.bind(this), this.options.interval * 1000);
    },

    options: {'count': 5, 'clear': false, 'interval': 20},
    params: null, 
    callback: null
});

function since(timestamp) {

    var now = new Date().getTime();
    var seconds = Math.round(now/1000 - timestamp/1000);

    if(seconds < 60)    return ' hace ' + seconds + ' segundos';
    if(seconds < 3600)  return ' hace ' + Math.round(seconds / 60) + ' minutos';
    if(seconds < 86400) return ' hace ' + Math.round(seconds / 3600) + ' horas';
    
    return '';
}
