(function (a) {
    if (!a.fn.reverse) {
        a.fn.reverse = function () {
            return this.pushStack(this.get().reverse(), arguments)
        }
    }
    a.fn.liveTwitter = function (d, b, e) {
        var c = this;
        a(this).each(function () {
            var f = {};
            if (this.twitter) {
                f = jQuery.extend(this.twitter.settings, b);
                this.twitter.settings = f;
                if (d) {
                    this.twitter.query = d
                }
                this.twitter.limit = f.limit;
                this.twitter.mode = f.mode;
                if (this.twitter.interval) {
                    this.twitter.refresh()
                }
                if (e) {
                    this.twitter.callback = e
                }
            } else {
                f = jQuery.extend({
                    mode: "search",
                    rate: 15000,
                    limit: 10,
                    refresh: true
                }, b);
                if (typeof f.showAuthor == "undefined") {
                    f.showAuthor = (f.mode == "user_timeline") ? false : true
                }
                if (!window.twitter_callback) {
                    window.twitter_callback = function () {
                        return true
                    }
                }
                this.twitter = {
                    settings: f,
                    query: d,
                    limit: f.limit,
                    mode: f.mode,
                    interval: false,
                    container: this,
                    lastTimeStamp: 0,
                    callback: e,
                    relativeTime: function (i) {
                        var h = Date.parse(i);
                        var k = (Date.parse(Date()) - h) / 1000;
                        var j = "";
                        if (k < 60) {
                            j = k + " seconds ago"
                        } else {
                            if (k < 120) {
                                j = "a minute ago"
                            } else {
                                if (k < (45 * 60)) {
                                    j = (parseInt(k / 60, 10)).toString() + " minutes ago"
                                } else {
                                    if (k < (90 * 60)) {
                                        j = "an hour ago"
                                    } else {
                                        if (k < (24 * 60 * 60)) {
                                            j = "" + (parseInt(k / 3600, 10)).toString() + " hours ago"
                                        } else {
                                            if (k < (48 * 60 * 60)) {
                                                j = "a day ago"
                                            } else {
                                                j = (parseInt(k / 86400, 10)).toString() + " days ago"
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        return j
                    },
                    refreshTime: function () {
                        var h = this;
                        a(h.container).find("span.time").each(function () {
                            a(this).find("a").html(h.relativeTime(this.timeStamp))
                        })
                    },
                    refresh: function (h) {
                        var k = this;
                        if (this.settings.refresh || h) {
                            var i = "";
                            var n = {};
                            if (k.mode == "search") {
                                if (this.query && this.query !== "") {
                                    n.q = this.query
                                }
                                if (this.settings.geocode) {
                                    n.geocode = this.settings.geocode
                                }
                                if (this.settings.lang) {
                                    n.lang = this.settings.lang
                                }
                                if (this.settings.rpp) {
                                    n.rpp = this.settings.rpp
                                } else {
                                    n.rpp = this.settings.limit
                                }
                                var l = [];
                                for (var m in n) {
                                    if (n.hasOwnProperty(m)) {
                                        l[l.length] = m + "=" + encodeURIComponent(n[m])
                                    }
                                }
                                l = l.join("&");
                                i = "http://search.twitter.com/search.json?" + l + "&callback=?"
                            } else {
                                if (k.mode == "user_timeline") {								
                                    i = "http://api.twitter.com/1/statuses/user_timeline/" + encodeURIComponent(this.query) + ".json?count=" + k.limit + "&callback=?"
                                } else {
                                    if (k.mode == "list") {
                                        var o = encodeURIComponent(this.query.user);
                                        var j = encodeURIComponent(this.query.list);
                                        i = "http://api.twitter.com/1/" + o + "/lists/" + j + "/statuses.json?per_page=" + k.limit + "&callback=?"
                                    }
                                }
                            }
                            a.getJSON(i, function (q) {
                                var p = null;
                                if (k.mode == "search") {
                                    p = q.results
                                } else {
                                    p = q
                                }
                                var r = 0;
                                a(p).reverse().each(function () {
                                    var x = "";
                                    var v = "";
                                    if (k.mode == "search") {
                                        x = this.from_user;
                                        v = this.profile_image_url;
                                        created_at_date = this.created_at
                                    } else {
                                        x = this.user.screen_name;
                                        v = this.user.profile_image_url;
                                        created_at_date = this.created_at.replace(/^(\w+)\s(\w+)\s(\d+)(.*)(\s\d+)$/, "$1, $3 $2$5$4")
                                    }
                                    var u = "http://twitter.com/" + x + "/statuses/" + this.id;
                                    var s = this.user;
                                    var w = this.text.replace(/[A-Za-z]+:\/\/[A-Za-z0-9-_]+\.[A-Za-z0-9-_:%&\?\/.=]+/, function (z) {
                                        return z.link(z)
                                    });
                                    w = w.replace(/@[A-Za-z0-9_]+/g, function (z) {
                                        return z.link("http://twitter.com/" + z.replace(/^@/, ""))
                                    });
                                    w = w.replace(/#[A-Za-z0-9_\-]+/g, function (z) {
                                        return z.link("http://search.twitter.com/search?q=" + z.replace(/^#/, "%23"))
                                    });
                                    if (!k.settings.filter || k.settings.filter(this)) {
                                        if (Date.parse(created_at_date) > k.lastTimeStamp) {
                                            r += 1;
                                            var y = '<div class="tweet tweet-' + this.id + '">';
                                            if (k.settings.showAuthor) {
                                                y += '<img width="24" height="24" src="' + v + '" /><p class="text"><span class="username"><a href="http://twitter.com/' + x + '">' + x + "</a>:</span> "
                                            } else {
                                                y += '<p class="text"> '
                                            }
                                            y += w + ' <span class="time"><a href="' + u + '">' + k.relativeTime(created_at_date) + "</a></span></p></div>";
                                            a(k.container).prepend(y);
                                            var t = created_at_date;
                                            a(k.container).find("span.time:first").each(function () {
                                                this.timeStamp = t
                                            });
                                            if (!h) {
                                                a(k.container).find(".tweet-" + this.id).hide().fadeIn()
                                            }
                                            k.lastTimeStamp = Date.parse(created_at_date)
                                        }
                                    }
                                });
                                if (r > 0) {
                                    a(k.container).find("div.tweet:gt(" + (k.limit - 1) + ")").remove();
                                    if (k.callback) {
                                        k.callback(c, r)
                                    }
                                    a(c).trigger("tweets")
                                }
                            })
                        }
                    },
                    start: function () {
                        var h = this;
                        if (!this.interval) {
                            this.interval = setInterval(function () {
                                h.refresh()
                            }, h.settings.rate);
                            this.refresh(true)
                        }
                    },
                    stop: function () {
                        if (this.interval) {
                            clearInterval(this.interval);
                            this.interval = false
                        }
                    },
                    clear: function () {
                        a(this.container).find("div.tweet").remove();
                        this.lastTimeStamp = null
                    }
                };
                var g = this.twitter;
                this.timeInterval = setInterval(function () {
                    g.refreshTime()
                }, 5000);
                this.twitter.start()
            }
        });
        return this
    }
})(jQuery);
