var Twitter = function (options) {
    this.options = {api: 'http://search.twitter.com/search.json'};

    if (!('url' in options) || !('selector' in options)) {
        throw "Both 'url' and 'selector' should be passed - they are not optional";
    }

    for (var k in options) {
        this.options[k] = options[k];
    }

    this.element = $(this.options.selector);
}

Twitter.prototype = {
    queryString: function() {
        return '?' + $.param({q: this.options.url});
    },

    get: {
        user: function(item) {
            return '<a href="http://twitter.com/{user}">@{user}</a>'.format(
                {user: item.from_user});
        },
        time: function(item) {
            return '<a href="http://twitter.com/{from_user}/status/{id_str}">' +
                '{created_at}</a>'.format(item);
        }
    },

    render: function(tweets) {
        this.element.children().remove();
        if (!tweets.length)
            return;

        this.element.html('<h2>Mentions in Twitter</h2>');

        this.renderComments(tweets);
    },

    makeRequest: function() {
        var self = this;
        $.getJSON(this.options.api + this.queryString() + '&callback=?',
                  function(data) {
                      self.render(data.results);
                  });
    },

    renderComments: function(comments) {
        var self = this;
        if (!comments)
            return;

        var list = $('<ul>');
        $.each(comments, function(i, item) {
            var li = '<li><p>{text} &mdash; {user} at {time}</p></li>'.format(
                {text: item.text,
                 user: self.get.user(item),
                 time: self.get.time(item)});
            list.append(li);
        });
        this.element.append(list);
    }
}

String.prototype.format = function (data) {
    var s = this;
    for (var k in data) {
        s = s.replace(new RegExp('{' + k + '}', 'g'), data[k]);
    }
    return s;
}

if (!('toISOString' in Date.prototype)) {
    Date.prototype.toISOString = function () {
        function pad(n, hundred) {
            n = n < 10 ? '0' + n : n;
            return hundred && n < 100 ? n + '0' : n;
        };
        return '{y}-{m}-{d}T{h}:{M}:{s}Z'.format({
            y: this.getUTCFullYear(),
            m: pad(this.getUTCMonth() + 1),
            d: pad(this.getUTCDate()),
            h: pad(this.getUTCHours()),
            M: pad(this.getUTCMinutes()),
            s: pad(this.getUTCSeconds(), true)
        });
    };
}

