
function TwitterBox() {
    // parameters
    this.newTweetsPeriod = 30 * 60 * 1000;
    this.slideAnimationSpeed = 400;
    this.checkTweetsEveryMs = 60000;
    this.updateDatesEveryMs = 10000;
    // variables
    this.lastTweet = 0;
    this.firstDisplayedTweet = 0;
    this.lastDisplayedTweet = 0; // not same as lastTweet!
    this.page = 1;
    this.allTweets = null;
    this.newTweets = null;
    this.newTweetsPage = 1;
    this.newTweetsData = new Array();
    this.newTweetsTmp = new Array();
    this.twitterName = 'RIVtweet';
}

TwitterBox.prototype.getHistoryUrl = function(max_id) {
    return "http://twitter.com/statuses/user_timeline.json?screen_name=" + this.twitterName + "&max_id=" + max_id + "&callback=?";
//    return "http://twitter.vtk.vda-team.com/twitterTestFeed.php?max_id=" + max_id + "&callback=?";
}

TwitterBox.prototype.getUpdateUrl = function(page) {
    return "http://twitter.com/statuses/user_timeline.json?screen_name=" + this.twitterName + "&page=" + page + "&callback=?";
//    return "http://twitter.vtk.vda-team.com/twitterTestFeed.php?page=" + page + "&callback=?";
}

TwitterBox.prototype.callback = function(method) {
    var context = this;
    if (typeof(method) == 'string') method = context[method];
    return function() {
        method.apply(context, arguments);
    }
}

TwitterBox.prototype.setLastTweet = function(lastTweet) {
    this.lastTweet = lastTweet;
    cookies.saveCookie('lastTweet', lastTweet);
}

TwitterBox.prototype.loadTweets = function()
{
    var url;
    if (this.firstDisplayedTweet) {
        url = this.getHistoryUrl(this.firstDisplayedTweet - 1);
    } else {
        url = this.getUpdateUrl(1);
    }
    $('.more button').hide();
    $('.more .loader2').show();
    $.ajax({
        url: url,
        dataType: 'jsonp',
        success: this.callback(this.insertTweets)
    });
}

TwitterBox.prototype.insertTweets = function(data)
{
    for (var i in data) {
        this.displayTweetOnAllTweets(data[i]);
    }
    $('.more .loader2').hide();
    $('.more button').show();
}

/**
 * Insert tweet into twitterBox.allTweets.
 * Can't insert tweets beetween twitterBox.firstDisplayedTweet and
 * twitterBox.lastDisplayedTweet.
 *
 */
TwitterBox.prototype.displayTweetOnAllTweets = function(item)
{
    var append = true;
    if (this.firstDisplayedTweet == 0) {
        this.firstDisplayedTweet = this.lastDisplayedTweet = item.id;
    } else {
        if ((item.id >= this.firstDisplayedTweet) && (item.id <= this.lastDisplayedTweet)) {
            return;
        }
        if (item.id < this.firstDisplayedTweet) {
            this.firstDisplayedTweet = item.id;
        }
        if (item.id > this.lastDisplayedTweet) {
            this.lastDisplayedTweet = item.id;
            append = false;
        }
    }
    var li = $('<li/>');
    var tweetDate = this.parseTwitterDate(item.created_at);
    li.append($('<span class="msg"/>').html(this.replaceURLWithHTMLLinks(item.text)));
    if (isNaN(tweetDate)) alert(item.created_at);
    li.append($('<span class="dd"/>').text(dateDistance(new Date().getTime(), tweetDate)).attr('dt', tweetDate));
    if (append) {
        this.allTweets.append(li);
    } else {
        this.allTweets.prepend(li);
    }
    if (item.id > this.lastTweet) {
        this.setLastTweet(item.id);
    }
}

TwitterBox.prototype.parseTwitterDate = function(date) {
    if ($.browser.msie==true){
        date = date.replace(/^\w+\s(.*)\s(\d+)$/, '$2 $1');
    }
    return Date.parse(date);
}

TwitterBox.prototype.replaceURLWithHTMLLinks = function(text) {
    var exp = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/i;
    return text.replace(exp,'<a href="$1" target="_blank">$1</a>'); 
}

TwitterBox.prototype.showNewTweetsAlert = function()
{
    if (this.newTweetsData.length > 0) {
        $('.newTweetsCount').text(this.newTweetsData.length).show();
    }
}

TwitterBox.prototype.showNewTweets = function(needShowTwitterBox)
{
    if (needShowTwitterBox) {
        this.beforeAnimate = this.showNewTweets;
        this.show();
    } else {
        this.beforeAnimate = null;
        var nav = $("#twitterBox .content .nav");
        if (nav.css('display')=='none') {
            nav.show();
            $(window).resize();
        }
        $("#twitterBox .content").tabs('select', 1);
        this.insertNewTweets();
        $('.newTweetsCount').hide();
    }
}

TwitterBox.prototype.insertNewTweets = function()
{
    var date = new Date();
    this.newTweets.empty();
    var item;
    while (item = this.newTweetsData.shift()) {
        var li = $('<li/>');
        var tweetDate = this.parseTwitterDate(item.created_at);
        li.append($('<span class="msg"/>').html(this.replaceURLWithHTMLLinks(item.text)));
        li.append($('<span class="dd"/>').text(dateDistance(date, tweetDate)).attr('dt', tweetDate));
        this.newTweets.prepend(li);
        this.displayTweetOnAllTweets(item);
        if (item.id > this.lastTweet) {
            this.setLastTweet(item.id);
        }
    }
}

TwitterBox.prototype.collectNewTweets = function(data)
{
    var firstTweetDate = new Date().getTime() - this.newTweetsPeriod;
    var lastCheckedTweet = 0;
    if (this.newTweetsData.length) {
        lastCheckedTweet = this.newTweetsData[this.newTweetsData.length - 1].id;
    }
    for (var i in data) {
        var item = data[i];
        if ((item.id > this.lastTweet) && (item.id > lastCheckedTweet) &&
                (this.parseTwitterDate(item.created_at) > firstTweetDate)) {
            this.newTweetsTmp.unshift(item);
        } else {
            this.newTweetsData = this.newTweetsData.concat(this.newTweetsTmp);
            this.newTweetsTmp = new Array();
            this.showNewTweetsAlert();
            return;
        }
    }
    this.getNextPageOfNewTweets();
}

TwitterBox.prototype.getNextPageOfNewTweets = function()
{
    $.getJSON(this.getUpdateUrl(this.newTweetsPage++), {}, this.callback(this.collectNewTweets));
}

TwitterBox.prototype.checkForNewTweets = function()
{
    this.newTweetsPage = 1;
    this.getNextPageOfNewTweets();
}

TwitterBox.prototype.showTwitterButton = function()
{
    $("#twitterBoxShow").show();
}

TwitterBox.prototype.hide = function()
{
    var box = $("#twitterBox");
    var animateOptions = {
        direction: "left",
        distance: box.width() - 30
    };
    box.hide("slide", animateOptions, this.slideAnimationSpeed, this.callback(this.showTwitterButton));
}

TwitterBox.prototype.appendTwitterBox = function(data)
{
    $('body').append(data);
    $(window).resize(twitterBox.callback('ajustHeight')).resize();
    $("#twitterBox .content").tabs();
    // to don't toogle twitter box by clicking on "new tweets" red circle
    $('.newTweetsCount').click(function(e){
        e.stopPropagation();
    });
    this.allTweets = $('#allTweetsTab ul.tweets');
    this.newTweets = $('#newTweetsTab ul.tweets');
    this.loaded = true;
    $('#twitterBoxShow img.loader').remove();
    this._show();
    this.loadTweets();
}

TwitterBox.prototype.show = function()
{
    if (!this.loaded) {
        $('#twitterBoxShow .loader').show();
        $.ajax({
            url: '/ajax/informers/tweetboxContent.php',
            success: this.callback(this.appendTwitterBox)
        });
    } else {
        this._show();
    }
}
TwitterBox.prototype._show = function()
{
    if (typeof(this.beforeAnimate) == 'function') {
        this.beforeAnimate();
    }
    $("#twitterBoxShow").hide();
    $("#twitterBox").show("slide", {direction: "left"}, this.slideAnimationSpeed);
}

TwitterBox.prototype.ajustHeight = function()
{
    var content = $('#twitterBox');
    var height = document.documentElement.clientHeight;
    height -= 1+6; // .wrap padding
    $('.wrap', content).height(height);
    height -= 32+2*5; // .content margin/padding
    $('.content', content).height(height);
    if ($('.nav', content).css('display')=='block') {
        height -= 40; // .nav height
    }
    $('#allTweetsTab').add('#newTweetsTab').height(height);
}

TwitterBox.prototype.updateDates = function()
{
    $('.dd[dt]').each(function(){
        $(this).text(dateDistance(new Date().getTime(), $(this).attr('dt')));
    });
}
TwitterBox.prototype.initialize = function()
{
    twitterBox.lastTweet = parseInt(cookies.readCookie('lastTweet'));
    if (isNaN(twitterBox.lastTweet)) twitterBox.lastTweet = 0;
    $('.newTweetsCount').click(function(e){
        e.stopPropagation();
    });
    setInterval(twitterBox.callback('checkForNewTweets'), twitterBox.checkTweetsEveryMs);
    setInterval(twitterBox.callback('updateDates'), twitterBox.updateDatesEveryMs);
    twitterBox.checkForNewTweets();
}

function dateDistance(to, from)
{
    var distance_in_seconds = ((to - from) / 1000);
    var distance_in_minutes = Math.floor(distance_in_seconds / 60);

    if (distance_in_minutes <= 0) { return 'less than a minute ago'; }
    if (distance_in_minutes == 1) { return 'a minute ago'; }
    if (distance_in_minutes < 45) { return distance_in_minutes + ' minutes ago'; }
    if (distance_in_minutes < 90) { return 'about 1 hour ago'; }
    if (distance_in_minutes < 1440) { return 'about ' + Math.floor(distance_in_minutes / 60) + ' hours ago'; }
    if (distance_in_minutes < 2880) { return '1 day ago'; }
    if (distance_in_minutes < 43200) { return Math.floor(distance_in_minutes / 1440) + ' days ago'; }
    if (distance_in_minutes < 86400) { return 'about 1 month ago'; }
    if (distance_in_minutes < 525960) { return Math.floor(distance_in_minutes / 43200) + ' months ago'; }
    if (distance_in_minutes < 1051199) { return 'about 1 year ago'; }

    return 'more than ' + Math.floor(distance_in_minutes / 525960) + ' years ago';
}

twitterBox = new TwitterBox();
