var socket,
    tlPaper,
    twCx = {
        followLast : true,
        position : "0",
        date_levels : [
            3600 * 1000,
            15 * 60 * 1000,
            5 * 60 * 1000,
            60 * 1000
        ],
        timeLevel : 1,
        deltaX : 40,
        tlWidth : 150,
        tlHeight : 480,
        globalWords : {},
        refMouse : { x : 0, y : 0},
        refPosTl : { x : 0, y : 0},
        tlMouseMoved : false,
        tlMouseClicked : false,
        filtre : null
        },
    tlBuffer = '',
    relHover = [],
    wheelDelta = 0,
    scrollEnabled = false,
    scrollExtent = 8000 - 480,
    lastScrollPos = 0,
    rx_url = /https?:\/\/[0-9a-zA-Z\.%\/-_]+/g,
    rx_word = /[^ \.&;,'"!\?\d\(\)\+\[\]\\\…\-«»:\/]{3,}/g,
    stop_list = [ 'and', 'avec', 'aux', 'car', 'comme', 'dans', 'donc', 'des', 'elle', 'est', 'être', 'eux', 'ils', 'les', 'leur', 'leurs', 'mes', 'mon', 'tes', 'ton', 'notre', 'nos', 'nous', 'ont', 'pas', 'que', 'qui', 'sont', 'the', 'une', 'votre', 'vos', 'vous' ],
    l10n = { "rechercher" : "Rechercher" };

function getColor(annotation, lum) {
    return Raphael.hsl2rgb(annotations[annotation].colors.h, annotations[annotation].colors.s, lum);
}

function tweetPopup(url) {
    var popW = 550,
        popH = 350,
        scrW = screen.width,
        scrH = screen.height,
        posX = Math.round((scrW/2)-(popW/2)),
        posY = (scrH > popH ? Math.round((scrH/2)-(popH/2)) : 0);
    window.open(url,
        '',
        'left=' + posX + ',top=' + posY + ',width=' + popW + ',height=' + popH + ',personalbar=0,toolbar=0,scrollbars=1,resizable=1');
}

function arc(source, target) {
    var x3 = .3 * target.y - .3 * source.y + .8 * source.x + .2 * target.x;
    var y3 = .8 * source.y + .2 * target.y - .3 * target.x + .3 * source.x;
    var x4 = .3 * target.y - .3 * source.y + .2 * source.x + .8 * target.x;
    var y4 = .2 * source.y + .8 * target.y - .3 * target.x + .3 * source.x;
    return "M" + source.x + " " + source.y + "C" + [x3, y3, x4, y4, target.x, target.y].join(" ");
}

function addTweet(tweet) {
    function backRef(source_id, target_id, type) {
        var target = tweetById(target_id);
        if (target) {
            var brobj = {
                "referenced_by_id" : source_id,
                "type" : type
            }
            if (target.backRefs) {
                target.backRefs.push(brobj);
            } else {
                target.backRefs = [ brobj ]
            }
        }
    }
    
    if (twCx.idIndex.indexOf(tweet.id) != -1) {
        return;
    }
    
    var txt_date = tweet.created_at;
    if (navigator.userAgent.search(/MSIE/) != -1) {
        txt_date = txt_date.replace(/( \+)/, ' UTC$1');
    }
    tweet.date_value = Date.parse(txt_date);
    
    var tab = tweet.text.match(/\&\#[0-9]+\;/g);
    for (var i in tab) {
        var n = parseInt(tab[i].substr(2));
        if (n != NaN) {
            tweet.text = tweet.text.replace(tab[i], String.fromCharCode(n));
        }
    }
    
    var ann = [];
    for (var j in annotations) {
        if (j != "default") {
            for (var k in annotations[j].keywords) {
                if (tweet.text.search(annotations[j].keywords[k]) != -1) {
                    ann.push(j);
                    break;
                }
            }
        }
    }
    tweet.annotations = ann;

    if (tweet.in_reply_to_status_id) {
        backRef( tweet.id, tweet.in_reply_to_status_id, "reply" );
    }
    if (tweet.retweeted_status) {
        backRef( tweet.id,  tweet.retweeted_status.id, "retweet" );
    }
    
    var localWords = []
    
    var tab = tweet.text.replace(rx_url,'').match(rx_word);
    for (var i in tab) {
        var word = tab[i].toLowerCase();
        if (stop_list.indexOf(word) == -1 && tracking_keywords.indexOf(word) == -1) {
            if (twCx.globalWords[word]) {
                twCx.globalWords[word]++;
            } else {
                twCx.globalWords[word] = 1;
            }
            localWords.push(word);
        }
    }
    
    tweet.words = localWords;
    
    var p = twCx.idIndex.length;
    while (p && tweet.id < twCx.idIndex[p-1]) {
        p--;
    }
    twCx.tweets.splice(p, 0, tweet);
    twCx.idIndex.splice(p, 0, tweet.id);
    
    if (!twCx.timeline.length) {
        twCx.timeline = [ populateDateStruct(0, twCx.date_levels[0] * parseInt(tweet.date_value / twCx.date_levels[0])) ]
    }
    while (tweet.date_value > twCx.timeline[twCx.timeline.length - 1].end) {
        twCx.timeline.push( populateDateStruct(0, twCx.timeline[twCx.timeline.length - 1].end) );
    }
    
    insertIntoDateStruct(twCx.timeline, tweet);
}

function getSliceContent(slice) {
    if (slice.slices) {
        var result = [];
        for (var i in slice.slices) {
            result = result.concat(getSliceContent(slice.slices[i]));
        }
    } else {
        var result = slice.tweets;
    }
    return result;
}

function flattenDateStruct(slices, target_level) {
    var current_level = slices[0].level,
        result = [];
    if (current_level < target_level) {
        if (slices[0].slices) {
            for (var i in slices) {
                result = result.concat(flattenDateStruct(slices[i].slices, target_level));
            }
        }
    }
    else {
        for (var i in slices) {
            result.push({
                "start" : slices[i].start,
                "end" : slices[i].end,
                "tweets" : getSliceContent(slices[i])
            });
        }
    }
    return result;
}

function trimFDS() {
    var slices = flattenDateStruct(twCx.timeline, twCx.timeLevel);
    while (slices[0].tweets.length == 0) {
        slices.splice(0,1);
    }
    while (slices[slices.length - 1].tweets.length == 0) {
        slices.pop();
    }    
    var centralTweet = ( twCx.centralTweet ? twCx.centralTweet : twCx.tweets[twCx.tweets.length - 1] ),
        delta = 30 * twCx.date_levels[twCx.timeLevel],
        centre = Math.min(slices[slices.length - 1].end - delta , Math.max(slices[0].start + delta, centralTweet.date_value)),
        min = centre - delta,
        max = centre + delta;
    while (slices[0].start < min) {
        slices.splice(0,1);
    }
    while (slices[slices.length - 1].end > max) {
        slices.pop();
    }
    return slices;
}

function populateDateStruct(level, start) {
    var end = start + twCx.date_levels[level],
        struct = {
            "level" : level,
            "start" : start,
            "end" : end
        };
    if (level < twCx.date_levels.length - 1) {
        struct.slices = [];
        var newstart = start;
        while (newstart < end) {
            struct.slices.push(populateDateStruct(level + 1, newstart));
            newstart += twCx.date_levels[level + 1];
        }
    } else {
        struct.tweets = [];
    }
    return struct;
}

function insertIntoDateStruct(slices, tweet) {
    var creadate = tweet.date_value;
    for (var i in slices) {
        if (creadate < slices[i].end) {
            if (slices[i].slices) {
                insertIntoDateStruct(slices[i].slices, tweet);
            } else {
                slices[i].tweets.push(tweet.id);
            }
            break;
        }
    }
}

function placeHolder(className) {
    return '<li class="placeholder ' + className + '"></li>';
}

function tweetById(tweetid) {
    var pos = twCx.idIndex.indexOf(tweetid);
    return (pos == -1) ? false : twCx.tweets[pos];
}

function selectTweet(tweetid) {
    twCx.position = tweetid;
    twCx.followLast = (twCx.position == twCx.idIndex[twCx.tweets.length - 1]);
    updateDisplay();
}

function goToPos(nPos) {
    twCx.position = twCx.currentIdIndex[Math.min( twCx.currentIdIndex.length - 1, Math.max(0, nPos ) )];
    twCx.followLast = (!twCx.filtre && nPos == twCx.tweets.length - 1);
    updateDisplay();
}

function movePos(delta) {
    goToPos( delta + twCx.currentIdIndex.indexOf(twCx.position) );
}

function ktxHighlightTweet(tweet) {
    var _gF = $("#graphFrame");
    if ( _gF.is(":visible") && _gF.attr("src").indexOf("labs.knowtex.com") != -1 ) {
        _gF.attr("src",'http://labs.knowtex.com/enmi2011/#carto::user=' + tweet.user.screen_name + '&time=' + ~~(tweet.date_value/1000));
    }
}

function tweetToHtml(tweet, className, elName) {
    
    function highlight(texte) {
        return ( twCx.filtre ? texte.replace(twCx.filtre, '<span class="highlight">$1</span>' ) : texte );
    }
    
    if (!tweet) {
        return placeHolder(className);
    }
    var el = (elName ? elName : 'li');
    var html = '<' + el + ' class="tweet ' + className + '" id="tweet_' + tweet.id + '"';
    if (className != 'full') {
        html += ' onclick="selectTweet(\'' + tweet.id + '\'); return false;"';
    }
    html += ' onmouseover="rolloverTweet(\'' + tweet.id + "', " + ( className == 'icons' ) + ');"';
    if (twCx.followLast && className == 'full' && el == 'li') {
        html += ' style="display: none"';
    }
    html += '>';
    if (tweet.annotations.length) {
        html += '<div class="annotations">';
        for (var i in tweet.annotations) {
            html += '<div class="annotation" style="width:' + (100/tweet.annotations.length) + '%; background:' + getColor(tweet.annotations[i], (className == 'icons' ? .4 : .85)).hex + '"></div>';
        }
        html += '</div>';
    }
    html += '<div class="twmain">';
    var a_user = '<a href="http://twitter.com/' + tweet.user.screen_name + '"  onclick="filtrerTexte(\'@' + tweet.user.screen_name + '\'); return false;" target="_blank">';
    html += '<div class="around_img">' + a_user + '<img class="profile_image" src="' + tweet.user.profile_image_url + '" /></a>';
    if (className == 'full') {
        html += '<p class="created_at">' + new Date(tweet.date_value).toTimeString().substr(0,8) + '</a></p>';
    }
    html += '</div>';
    if (className != 'icons') {
        lastend = 0;
        var txt = '',
            entities = [];
        for (var i in tweet.entities.hashtags) {
            entities.push({
                "start" : tweet.entities.hashtags[i].indices[0],
                "end" : tweet.entities.hashtags[i].indices[1],
                "link" : '<a href="http://twitter.com/search?q=%23' + tweet.entities.hashtags[i].text + '" onclick="filtrerTexte(\'#' + tweet.entities.hashtags[i].text + '\'); return false;" target="_blank">',
                "text" : '#' + tweet.entities.hashtags[i].text
            });
        }
        for (var i in tweet.entities.urls) {
            var linkurl = ( tweet.entities.urls[i].expanded_url ? tweet.entities.urls[i].expanded_url : tweet.entities.urls[i].url ),
                dispurl = linkurl.replace(/https?:\/\//,'');
            if (linkurl.search(/https?:\/\//) == -1) {
                linkurl = 'http://' + linkurl;
            }
            entities.push({
                "start" : tweet.entities.urls[i].indices[0],
                "end" : tweet.entities.urls[i].indices[1],
                "link" : '<a href="' + linkurl  + '" target="_blank">',
                "text" : dispurl
            });
        }
        for (var i in tweet.entities.user_mentions) {
            entities.push({
                "start" : tweet.entities.user_mentions[i].indices[0],
                "end" : tweet.entities.user_mentions[i].indices[1],
                "link" : '<a href="http://twitter.com/' + tweet.entities.user_mentions[i].screen_name + '" onclick="filtrerTexte(\'@' + tweet.entities.user_mentions[i].screen_name + '\'); return false;" target="_blank">',
                "text" : '@' + tweet.entities.user_mentions[i].screen_name
            });
        }
        entities.sort(function(a, b) { return a.start - b.start });
        for (var i in entities) {
            txt += highlight( tweet.text.substring(lastend, entities[i].start) ) + entities[i].link + highlight( entities[i].text ) + '</a>';
            lastend = entities[i].end;
        }
        txt += highlight( tweet.text.substring(lastend) );
        html += '<p class="tweet_text"><b>' + a_user + highlight('@' + tweet.user.screen_name) + '</a>' + ( className == 'full' ? ' (' + tweet.user.name + ')</b><br />' : '</b> : ') + txt + '</p>';
        if (className == 'full' && el == 'li') {
            html += '<div class="tweet_actions"><a href="http://twitter.com/' + tweet.user.screen_name + '/status/' + tweet.id + '" onclick="tweetPopup(this.href); return false;" target="_blank">afficher tweet</a> - ';
            html += '<a href="http://twitter.com/intent/tweet?in_reply_to=' + tweet.id + '" onclick="tweetPopup(this.href); return false;" target="_blank">répondre</a> · ';
            html += '<a href="http://twitter.com/intent/retweet?tweet_id=' + tweet.id + '" onclick="tweetPopup(this.href); return false;" target="_blank">retweeter</a> · ';
            html += '<a href="http://twitter.com/intent/favorite?tweet_id=' + tweet.id + '" onclick="tweetPopup(this.href); return false;" target="_blank">favori</a></div>';
        }
    }
    html += '</div></' + el + '>';
    return html;
}

function tlIdFromPos(x, y, outside) {
    if (!twCx.tlOnDisplay) {
        return;
    }
    var ligne = Math.min( twCx.tlOnDisplay.length - 1, Math.max( 0, Math.floor(( twCx.tlHeight - y ) / twCx.scaleY) ) ),
        colonne = Math.floor(( x - twCx.deltaX ) / twCx.scaleX ),
        l = 0;
    if (colonne >= twCx.tlOnDisplay[ligne].totalTweets || colonne < 0 ) {
        if (outside) {
            colonne = Math.min( twCx.tlOnDisplay[ligne].totalTweets - 1, Math.max( 0, colonne ));
        } else {
            return null;
        }
    }
    for (var i in twCx.tlOnDisplay[ligne].displayData) {
        var nl = l + twCx.tlOnDisplay[ligne].displayData[i].length;
        if (colonne < nl) {
            return {
                "id" : twCx.tlOnDisplay[ligne].displayData[i][colonne - l],
                "annotation" : i
            }
        }
        l = nl;
    }
}

function tlPosTweet(tweet, annotation) {
    if (!twCx.tweets) {
        return;
    }
    var x,
        y,
        dt = tweet.date_value,
        ann = ( annotation ? annotation : ( tweet.annotations.length ? tweet.annotations[0] : 'default' ) );
    for (var i = 0; i < twCx.tlOnDisplay.length; i++) {
        if (twCx.tlOnDisplay[i].end > dt) {
            y = twCx.tlHeight - (i + .5) * twCx.scaleY;
            var l = 0;
            for (var j in twCx.tlOnDisplay[i].displayData) {
                if (j == ann) {
                    var p = twCx.tlOnDisplay[i].displayData[j].indexOf(tweet.id);
                    if (p != -1) {
                        x = twCx.deltaX + twCx.scaleX * ( p + l + .5 );
                    }
                    break;
                }
                l += twCx.tlOnDisplay[i].displayData[j].length;
            }
            break;
        }
    }
    return ( x && y ? { "x" : x, "y" : y } : null);
}

function rolloverTweet(tweetid, showPopup, annotation) {
    var t = tweetById(tweetid);
    if (!t) {
        return;
    }
    ktxHighlightTweet(t);
    var p = tlPosTweet(t, annotation);
    if (!p) {
        return;
    }
    var ptl = $("#timeline").offset();
    if (showPopup) {
        $("#hovercontent").html(tweetToHtml(t, 'full', 'div'));
        $("#hovertweet").css({
            "left" : parseInt(ptl.left + p.x) + "px",
            "top" : parseInt(ptl.top + p.y),
            "display" : "block"});
    } else {
        $("#hovertweet").hide();
    }
    for (var i in relHover) {
        relHover[i].remove();
    }
    relHover = drawTweetArcs(t, p, '#303030');
    relHover.push(drawTweetPos(p, '#ffffff'));
}

function drawTweetPos(pos, color) {
    var rel = tlPaper.rect(pos.x - .5 * twCx.scaleX, pos.y - .5 * twCx.scaleY, twCx.scaleX, twCx.scaleY);
    rel.attr({ "stroke" : color, "fill" : color, "fill-opacity" : .25 });
    return rel;
}

function drawTweetArcs(tweet, pos, color) {
    
    var res = [];

    function tweetAndArc(a, b, aorb) {
        if (a && b) {
            res.push(drawTweetPos(aorb ? a : b, color));
            var aa = tlPaper.path(arc(a,b))
                .attr({ "stroke" : color, "stroke-width" : 1.5, "stroke-opacity" : .8 });
            res.push(aa);
        }
    }
    
    if (tweet.retweeted_status) {
        var t = tweetById(tweet.retweeted_status.id);
        if (t) {
            tweetAndArc(pos, tlPosTweet(t));
        }
    }
    
    if (tweet.in_reply_to_status_id) {
        var t = tweetById(tweet.in_reply_to_status_id);
        if (t) {
            tweetAndArc(pos, tlPosTweet(t));
        }
    }
    
    if (tweet.backRefs) {
        for (var i in tweet.backRefs) {
            var t = tweetById(tweet.backRefs[i].referenced_by_id);
            if (t) {
            tweetAndArc(tlPosTweet(t), pos, true);
            }
        }
    }
    
    return res;
}

function mouseoverkw() {
    var _jel = $(this),
        _off = _jel.offset();
    _jel.css({
        color: "#0099ff"
    });
    $("#hoverkw")
        .css({
            "left" : _off.left + "px",
            "top" : ( parseInt(_off.top) + ~~ (_jel.height() / 2) )  + "px",
            "display" : "block"
        })
        .attr("kw", _jel.text());
}

function mouseoutkw() {
    $("#hoverkw").hide();
    $(this).css({
        color: "#000000"
    });
}

function makeTagCloud(tab, div) {
    var minfreq = _(tab).min( function(a) { return a.freq} ).freq,
        maxfreq = Math.max(minfreq + .1, _(tab).max( function(a) { return a.freq} ).freq),
        echfreq = 8 / Math.sqrt( maxfreq - minfreq ),
        html = '';
    _(tab).each(function(_j) {
        var maxann = 0,
            ann = "default";
        for (var k in _j.annotations) {
            if (_j.annotations[k] == maxann) {
                ann = "default";
            }
            if (_j.annotations[k] > maxann) {
                ann = k;
                maxann = _j.annotations[k];
            }
        }
        if (ann == "default") {
            var coul = '';
        } else {
            var c = getColor(ann, .6),
                coul = "background: rgba(" + [ Math.floor(c.r), Math.floor(c.g), Math.floor(c.b), ( _j.annotations[ann] / _j.freq )].join(',') + ")";
        }
        var fontsize = Math.floor( ( 12 + Math.sqrt( _j.freq - minfreq ) * echfreq ) );
        html += '<span style="line-height: ' + (8 + fontsize) + 'px; font-size: ' + fontsize + 'px;' + coul + '">' + _j.word + '</span> ';
    });
    $(div).html(html);
    $(div + " span")
        .mouseover(mouseoverkw)
        .mouseout(mouseoutkw)
        .click(function() {
            $("#hoverkw").toggle();
        });
}

function updateDisplay() {
    if (!twCx.tweets) {
        return;
    }
    if (twCx.filtre) {
        var tweets = twCx.tweets.filter(function(tweet) {
            var mention = '@' + tweet.user.screen_name;
            return ( tweet.text.search(twCx.filtre) != -1 ) || ( mention.search(twCx.filtre) != -1 );
        });
        $("#inp_q").val(twCx.filtreTexte + ' (' + tweets.length + ' tweets)');
        if (tweets.length) {
            var idIndex = tweets.map(function(tweet) {
                return tweet.id;
            });
            var p = idIndex.indexOf(twCx.position);
            if (p == -1) {
                for (p = idIndex.length - 1; p > 0 && idIndex[p] > twCx.position; p--) {
                }
            }
            twCx.position = idIndex[p];
            twCx.currentIdIndex = idIndex;
        }
        
    } else {
        twCx.currentIdIndex = twCx.idIndex;
        var tweets = twCx.tweets;
        var p = twCx.idIndex.indexOf(twCx.position);
        if (p == -1) {
            p = (twCx.followLast ? twCx.idIndex.length - 1 : 0);
        }
    }
    
    
    if (suggested_keywords && suggested_keywords.length) {
        var _skw = suggested_keywords.map(function(_e) {
            return {
                "word" : _e,
                "rgxp" : new RegExp(_e, "im"),
                "freq" : 0,
                "annotations" : {}
            }
        })
    }
    
    var l = tweets.length,
        lines = 0,
        ppy = 0,
        html = '',
        tweetsOnDisplay = [],
        localWords = {};
    
    function pushTweet(tp, className) {
        
        if (tp < l && tp >= 0) {
            
            if (_skw) {
                _(_skw).each(function(_k) {
                    if (tweets[tp].text.search(_k.rgxp) != -1) {
                        _k.freq++;
                        _(tweets[tp].annotations).each(function(_a) {
                            _k.annotations[_a] = 1 + ( _k.annotations[_a] || 0 )
                        })
                    }
                });
            }
            
            html += tweetToHtml(tweets[tp], className);
            
            tweetsOnDisplay.push(tp);
            
            for (var i in tweets[tp].words) {
                var w = tweets[tp].words[i];
                if (localWords[w]) {
                    localWords[w].freq++
                } else {
                    localWords[w] = {
                        "freq" : 1,
                        "annotations" : {}
                    }
                    for (var j in annotations) {
                        if (j != 'default') {
                            localWords[w].annotations[j] = 0;
                        }
                    }
                }
                for (var j in tweets[tp].annotations) {
                    localWords[w].annotations[tweets[tp].annotations[j]]++;
                }
            }
        } else {
            html += placeHolder(className);
        }
    }
    
    if (l) {
    
        lastScrollPos = Math.floor( scrollExtent * ( 1 - ( p / l ) ) );
        $("#scrollcont").scrollTop(lastScrollPos);
        
        if (l > p + 18) {
            lines++;
            ppy += 20;
            for (var i = p + 31; i >= p + 18; i--) {
                pushTweet(i, 'icons');
            }
        }
        if (l > p + 4) {
            lines++;
            ppy += 20;
            for (var i = p + 17; i >= p + 4; i--) {
                pushTweet(i, 'icons');
            }
        }
        for (var k = 3; k >= 1; k--) {
            if (l > p + k) {
                ppy += 47;
                lines++;
                pushTweet(p + k, 'half');
            }
        }
        pushTweet(p, 'full');
        var n = p - 1;
        for (var i = 0; i < Math.min(6, Math.max(3, 6 - lines)); i++) {
            if (n < 0) {
                break;
            }
            pushTweet(n, 'half');
            n--;
        }
        for (var i = 0; i < 14 * Math.min(4, Math.max(2, 7 - lines)); i++) {
            if (n < 0) {
                break;
            }
            pushTweet(n, 'icons');
            n--;
        }
        if (html != tlBuffer) {
            $("#tweetlist").html(html);
            $(".tweet.full").fadeIn();
            tlBuffer = html;
        }
        
        if (_skw) {
            makeTagCloud(_skw, "#suggkw");
        }
        /* Recherche des mots pertinents correspondant à la sélection */
        
        var tab = _(localWords).map(function(v, k) {
            return {
                "word": k,
                "freq" : v.freq,
                "annotations" : v.annotations,
                "score" : v.freq / Math.log( 2 + twCx.globalWords[j] )
            };
        }).filter(function(v) {
            return v.freq > 1;
        });
        
        if (tab.length) {
            
            tab = _(tab).sortBy( function(a) { return ( - a.score ) }).slice(0,20);
            makeTagCloud(tab,"#motscles");
        } else {
            $("#motscles").html('');
        }
        twCx.centralTweet = tweets[p];
    } else {
        $("#tweetlist").html('');
        tlBuffer = '';
        $("#motscles").html('');
    }
    
    twCx.tlOnDisplay = trimFDS();
    twCx.scaleY = twCx.tlHeight / twCx.tlOnDisplay.length;
    var maxTweets = 0,
        startTl = 0,
        endTl = twCx.tlOnDisplay.length - 1;
    if (l) {
        var startTw = tweets[tweetsOnDisplay[tweetsOnDisplay.length - 1]].date_value,
            endTw = tweets[tweetsOnDisplay[0]].date_value;
    }
    for (var i = 0; i < twCx.tlOnDisplay.length; i++) {
        if (l) {
            if (startTw >= twCx.tlOnDisplay[i].start && startTw < twCx.tlOnDisplay[i].end) {
                startTl = i;
            }
            if (endTw >= twCx.tlOnDisplay[i].start && endTw < twCx.tlOnDisplay[i].end) {
                endTl = i;
            }
        }
        var displayData = {};
        for (var j in annotations) {
            displayData[j] = [];
        }
        for (var j in twCx.tlOnDisplay[i].tweets) {
            var tweetid = twCx.tlOnDisplay[i].tweets[j],
                tweet = tweetById(tweetid);
            if (tweet) {
                if (tweet.annotations.length) {
                    for (var k in tweet.annotations) {
                        displayData[tweet.annotations[k]].push(tweetid);
                    }
                } else {
                    displayData['default'].push(tweetid);
                }
            }
        }
        var nbT = 0;
        for (var j in displayData) {
            nbT += displayData[j].length;
        }
        maxTweets = Math.max(maxTweets, nbT);
        twCx.tlOnDisplay[i].displayData = displayData;
        twCx.tlOnDisplay[i].totalTweets = nbT;
    }
    twCx.scaleX = ( twCx.tlWidth - twCx.deltaX ) / maxTweets;
    tlPaper.clear();
    relHover = null;
    
    // Dessin de la correspondance liste-timeline
    if (l) {
        var startY = twCx.tlHeight - startTl * twCx.scaleY,
            endY = twCx.tlHeight - ( endTl + 1 ) * twCx.scaleY,
            path = "M0 " + twCx.tlHeight + "C" + .7*twCx.deltaX + " " + twCx.tlHeight + " " + .3*twCx.deltaX + " " + startY + " " + twCx.deltaX + " " + startY + "L" + twCx.tlWidth + " " + startY + "L" + twCx.tlWidth + " " + endY + "L" + twCx.deltaX + " " + endY + "C" + .3*twCx.deltaX + " " + endY + " " + .7*twCx.deltaX + " 0 0 0";
        tlPaper.path( path ).attr({ "stroke" : "none", "fill" : "#000080", "opacity" : .2 });
    }   
    // dessin de la date de début
    
    tlPaper.text(twCx.deltaX / 2, twCx.tlHeight - 7, new Date(twCx.tlOnDisplay[0].start).toTimeString().substr(0,5))
        .attr({ "text-anchor" : "middle", "font-size": "9px" });
    
    // dessin de la date de fin
    
    tlPaper.text(twCx.deltaX / 2, 7, new Date(twCx.tlOnDisplay[twCx.tlOnDisplay.length - 1].end).toTimeString().substr(0,5))
        .attr({ "text-anchor" : "middle", "font-size": "9px" });
    
    for (var i = 0; i < twCx.tlOnDisplay.length; i++) {
        var n = 0,
            posY = twCx.tlHeight - ( i + 1 ) * twCx.scaleY;
        for (var j in twCx.tlOnDisplay[i].displayData) {
            var ll = twCx.tlOnDisplay[i].displayData[j].length;
            if (ll > 0) {
                tlPaper.rect( twCx.deltaX + n * twCx.scaleX, posY, ll * twCx.scaleX, twCx.scaleY )
                    .attr({"stroke" : "none", "fill" : getColor(j, .4).hex });
                n += ll;
            }
        }
        
        // Si on est à une demi-heure, on trace un axe secondaire + heure
        
        if (i < twCx.tlOnDisplay.length - 1 && !(twCx.tlOnDisplay[i].end % 1800000)) {
            tlPaper.path("M0 "+posY+"L" + twCx.tlWidth +" "+posY).attr({"stroke":"#ccc"});
            tlPaper.text(twCx.deltaX / 2, posY, new Date(twCx.tlOnDisplay[i].end).toTimeString().substr(0,5)).attr({ "text-anchor" : "middle", "font-size": "9px" });
        }
    }
    
    // dessin du tweet courant
    
    if (l) {
        
        if (twCx.filtre) {
            for (var i = 0; i < tweets.length; i++) {
                if (i != p) {
                    var pos = tlPosTweet(tweets[i]);
                    if (pos) {
                        drawTweetPos(pos, "#ffccff");
                    }
                }
            }
            
        }
        
        var posp = tlPosTweet(tweets[p]);
        if (posp) {
            
            drawTweetPos(posp, "#ffff00");
            var yy = posp.y - .5 * twCx.scaleY,
                path = "M0 " + ppy + "C" + ( .7 * twCx.deltaX ) + " " + ppy + " " + ( .2 * twCx.deltaX ) + " " + yy + " " + ( twCx.deltaX ) + " " + yy + "L" + ( posp.x - .5 * twCx.scaleX ) + " " + yy;
            yy = posp.y + .5 * twCx.scaleY;
            ppy += 117;
            path += "L" + ( posp.x - .5 * twCx.scaleX ) + " " + yy + "L" + twCx.deltaX + " " + yy + "C"  + ( .2 * twCx.deltaX ) + " " + yy + " " + ( .7 * twCx.deltaX ) + " " + ppy + " 0 " + ppy;
            tlPaper.path( path ).attr({"stroke":"#ffff00", "fill" : "#ffff00", "fill-opacity" : .15});
            
            drawTweetArcs(tweets[p], posp, '#800080');
        }
    }
}

function filtrerAnnotation(annotation) {
    if (annotations[annotation]) {
        effectuerFiltrage(annotations[annotation].display_name,
            new RegExp( "(" + annotations[annotation].keywords.map(function(a) { return a.source }).join("|") + ")", "gim" ) );
    } else {
        effectuerFiltrage('', null)
    }
}

function filtrerTexte(valeur) {
    effectuerFiltrage( valeur, valeur ? new RegExp("(" + valeur.replace(/(\W)/g, '\\$1') + ")" ,'gim') : null );
}

function effectuerFiltrage(filtreTexte, tabRegexp) {
    $("#recherche_annot").slideUp();
    $("#inp_q").val(filtreTexte).attr("class","rechercheCourante");
    twCx.filtreTexte = filtreTexte;
    twCx.filtre = tabRegexp;
    twCx.followLast = !tabRegexp && (twCx.position == twCx.idIndex[twCx.idIndex.length - 1]);
    updateDisplay();
}

function clicTl(evt) {
    var o = $("#timeline").offset();
    if (twCx.tlMouseClicked && twCx.tlMouseMoved) {
        var twid = tlIdFromPos(evt.pageX - o.left + twCx.refPosTl.x - twCx.refMouse.x, evt.pageY - o.top + twCx.refPosTl.y - twCx.refMouse.y, true);
        if (twid) {
            selectTweet(twid.id);
        }
    } else {
        var twid = tlIdFromPos(evt.pageX - o.left, evt.pageY - o.top, twCx.tlMouseClicked);
        if (twCx.tlMouseMoved && !twCx.tlMouseClicked) { 
            if (twid) {
                rolloverTweet(twid.id, true, twid.annotation);
            } else {
                $("#hovertweet").hide();
            }
        }
        if (twCx.tlMouseClicked && !twCx.tlMouseMoved) {
            if (twid) {
                selectTweet(twid.id);
            }
        }
    }
}

function loadTweets(tweets, append) {
    if (!append) {
        twCx.timeline = [];
        twCx.idIndex = [];
        twCx.tweets = [];
    }
    for (var i in tweets) {
        addTweet(tweets[i]);
    }
    if (twCx.followLast) {
        twCx.position = twCx.idIndex[twCx.tweets.length - 1];
    }
    updateDisplay();
}

function focusOutRecherche() {
    $("#recherche_annot").slideUp();
    var inpq = $("#inp_q"),
        val = inpq.val();
    if (val == '' || val == twCx.filtreTexte) {
        if (twCx.filtre) {
            inpq.attr("class", "rechercheCourante").val(twCx.filtreTexte);
        } else {
            inpq.attr("class", "greyed").val(l10n.rechercher);
        }
    }
}

function chaineTimeZoom() {
    var chaine = "",
        t = twCx.date_levels[twCx.timeLevel],
        h = 3600*1000,
        m = 60*1000,
        s = 1000,
        heures = Math.floor(t/h);
    if (heures) { chaine += heures + ' h. ' };
    t -= (heures * h);
    var minutes = Math.floor(t/m);
    if (minutes) { chaine += minutes + ' min. ' };
    t -= (minutes * m);
    if (t) { chaine += Math.floor(t/s) + ' sec.' }
    $("#time_scale").html(chaine);
    $("#time_zoomout").attr("class",(twCx.timeLevel == 0 ? "inactive" : ""));
    $("#time_zoomin").attr("class",(twCx.timeLevel == twCx.date_levels.length - 1 ? "inactive" : ""));
}

$(document).ready(function() {
    tlPaper = Raphael("timeline", twCx.tlWidth, twCx.tlHeight);
    
    connectTweets();
    
    var html = '';
    for (var j in annotations) {
        if (j != "default") {
            html += '<a href="#" style="background: ' + getColor(j, .7).hex + ';" onclick=filtrerAnnotation(\'' + j + '\'); return false;">' + annotations[j].display_name + '</a> '
        }
    }
    $("#rech_list_annot").html(html);
    
    chaineTimeZoom();
    
    $("#tweetlist").mousewheel(function(e, d) {
        wheelDelta += d;
        if (Math.abs(wheelDelta) >= 1) {
            movePos( parseInt(wheelDelta) );
            wheelDelta = 0;
        }
        return false;
    });
    $("#timeline").mousewheel(function(e, d) {
        wheelDelta += d;
        if (Math.abs(wheelDelta) >= 1) {
            if (wheelDelta > 0) {
                tl = Math.min(twCx.date_levels.length - 1, twCx.timeLevel + 1);
            } else {
                tl = Math.max(0, twCx.timeLevel - 1);
            }
            if (tl != twCx.timeLevel) {
                twCx.timeLevel = tl;
                chaineTimeZoom();
                updateDisplay();
            }
            wheelDelta = 0;
        }
        return false;
    });
    $("#time_zoomin").click(function() {
        if (twCx.timeLevel < twCx.date_levels.length - 1) {
            twCx.timeLevel++;
            chaineTimeZoom();
            updateDisplay();
        }
    });
    $("#time_zoomout").click(function() {
        if (twCx.timeLevel > 0) {
            twCx.timeLevel--;
            chaineTimeZoom();
            updateDisplay();
        }
    });
    $("#timeline, #tweetlist").mouseout(function() {
        twCx.tlMouseClicked = false;
        twCx.tlMouseMoved = false;
        $("#hovertweet").hide();
    });
    $("#timeline").mousemove(function(evt) {
        twCx.tlMouseMoved = true;
        clicTl(evt);
    }).mousedown(function(evt) {
        twCx.tlMouseClicked = true;
        twCx.tlMouseMoved = false;
        var o = $(this).offset();
        twCx.refMouse = { x : evt.pageX - o.left, y : evt.pageY - o.top };
        twCx.refPosTl = tlPosTweet(tweetById(twCx.position)) || twCx.refMouse;
    }).mouseup(function(evt) {
        clicTl(evt);
        twCx.tlMouseClicked = false;
        twCx.tlMouseMoved = false;
    });
    $("#inp_q").focus(function() {
        $("#recherche_annot").slideDown();
        $(this).val($(this).val().replace(/ \(.+\)$/, ''))
        if ($(this).hasClass("greyed")) {
            $(this).val("");
        }
        $(this).attr("class","");
    }).focusout(function() {
        focusOutRecherche();
    });
    $("#inp_reset").click(function() {
        $("#inp_q").val('');
        if (twCx.filtre) {
            twCx.filtre = null;
            updateDisplay();
        }
        twCx.filtreTexte = '';
        focusOutRecherche();
        return false;
    })
    $("#recherche").submit(function(evt) {
        evt.preventDefault();
        if (!$("#inp_q").hasClass("greyed")) {
            var valeur = $("#inp_q").val();
            filtrerTexte(valeur);
        }
        return false;
    });
    $("#hoverkw").mouseover(function() {
        $(this).dequeue().show();
    }).mouseout(function() {
        $(this).hide();
    });
    
    $("#hkwsearch").click(function() {
        var _hkw = $("#hoverkw");
        filtrerTexte(_hkw.attr("kw"));
        _hkw.hide();
        return false;
    });
    $("#hkwtweet").click(function() {
        var _hkw = $("#hoverkw");
        add_grammar(_hkw.attr("kw"));
        _hkw.hide();
        return false;
    });
    
    setInterval(function() {
        var sc = $("#scrollcont");
        if (sc.scrollTop() != lastScrollPos && twCx.tweets) {
            var p = Math.floor( twCx.currentIdIndex.length * ( 1 - sc.scrollTop() / scrollExtent ) );
            goToPos(p);
        }
        
    }, 100)
});

if (connect_type == "socketio") {
    document.write('<script type="text/javascript" src="' + source_address + '/socket.io/socket.io.js"><' + '/script>');
}

function connectTweets() {
    switch (connect_type) {
        case "socketio" :
            socket = io.connect( source_address );
            socket.on("initial_data", function(data) {
                loadTweets(data.tweets)
            });
            socket.on("update", function(data) {
                if (!twCx.tweets) {
                    return;
                }
                loadTweets(data.new_tweets, true);
            });
            break;
            
        case "gevent" :
            $.getJSON( source_address + '?callback=?', function(data) {
                loadTweets(data.tweets)
            } );
            
            setInterval(function() {
                if (!twCx.tweets) {
                    return;
                }
                $.getJSON( source_address + '/?after_id=' + twCx.tweets[twCx.tweets.length - 1].id + '&callback=?', function(data) {
                    loadTweets(data.tweets, true);
                });
            }, 1000);
            break;
        
        case "standalone" :
            $.getScript( source_address );
    }
}


