tweetcast/nodejs-bis/client/js/script.js
author Raphael Velt <raph.velt@gmail.com>
Tue, 22 Nov 2011 18:33:51 +0100
changeset 390 239f91ac1f31
parent 385 886bfa7441d0
child 391 698e4280d270
permissions -rw-r--r--
Ajout de la recherche dans page live

/**
 * @author raph
 */

var socket,
    tlPaper,
    twCx = {
        zoomLevel : 1,
        followLast : true,
        position : "0",
        date_levels : [
            15 * 60 * 1000,
            5 * 60 * 1000,
            60 * 1000,
            15 * 1000
        ],
        timeLevel : 0,
        deltaX : 40,
        tlWidth : 150,
        tlHeight : 450,
        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 - 452,
    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' ];

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

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 centralTweet = ( twCx.centralTweet ? twCx.centralTweet : twCx.tweets[twCx.tweets.length - 1] )
        slices = flattenDateStruct(twCx.timeline, twCx.timeLevel),
        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.idIndex[Math.min( twCx.tweets.length - 1, Math.max(0, nPos ) )];
    twCx.followLast = (nPos == twCx.tweets.length - 1);
    updateDisplay();
}

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

function tweetToHtml(tweet, className, elName) {
    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 : .8)).hex + '"></div>';
        }
        html += '</div>';
    }
    html += '<div class="twmain">';
    a_user = '<a href="http://twitter.com/' + tweet.user.screen_name + '" var target="_blank" title="' + tweet.user.name + '">';
    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) + '</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],
                "html" : '<a href="http://twitter.com/search?q=%23' + tweet.entities.hashtags[i].text + '" target="_blank">#' + tweet.entities.hashtags[i].text + '</a>'
            });
        }
        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],
                "html" : '<a href="' + linkurl  + '" target="_blank">' + dispurl + '</a>'
            });
        }
        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],
                "html" : '<a href="http://twitter.com/' + tweet.entities.user_mentions[i].screen_name + '" target="_blank" title="' + tweet.entities.user_mentions[i].name + '">@' + tweet.entities.user_mentions[i].screen_name + '</a>'
            });
        }
        entities.sort(function(a, b) { return a.start - b.start });
        for (var i in entities) {
            txt += tweet.text.substring(lastend, entities[i].start) + entities[i].html;
            lastend = entities[i].end;
        }
        txt += tweet.text.substring(lastend);
        html += '<p class="tweet_text"><b>' + a_user + '@' + tweet.user.screen_name + '</b></a>: ' + txt + '</p>';
    }
    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) {
    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;
    }
    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 updateDisplay() {
    
    if (twCx.filtre) {
        var tweets = twCx.tweets.filter(function(tweet) {
            return ( tweet.text.search(twCx.filtre) != -1 ) || ( tweet.user.screen_name.search(twCx.filtre) != -1 )
        });
        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--) {
                }
            }
            console.log(p);
        }
        
    } else {
        var tweets = twCx.tweets;
        var p = twCx.idIndex.indexOf(twCx.position);
        if (p == -1) {
            p = (twCx.followLast ? twCx.idIndex.length - 1 : 0);
        }
    }

    var l = tweets.length,
        lines = 0,
        ppy = 0,
        html = '',
        tweetsOnDisplay = [],
        localWords = {};
    
    function pushTweet(tp, className) {
        if (tp < l && tp >= 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;
        }
        
        /* Recherche des mots pertinents correspondant à la sélection */
        
        for (var j in localWords) {
            if (localWords[j].freq < 2) delete localWords[j];
        }
        var tab = [];
        for (var j in localWords) {
            tab.push({
                "word": j,
                "freq" : localWords[j].freq,
                "annotations" : localWords[j].annotations,
                "score" : localWords[j].freq / Math.log(1+twCx.globalWords[j])
            });
        }
        tab.sort( function(a,b){ return ( b.score - a.score ) }).splice(20);
        var minfreq = tab[tab.length - 1].score,
            maxfreq = Math.max(minfreq + .1, tab[0].score),
            echfreq = 8 / Math.sqrt( maxfreq - minfreq ),
            html = '';
        for (var j in tab) {
            var maxann = 0,
                ann = "default";
            for (var k in tab[j].annotations) {
                if (tab[j].annotations[k] == maxann) {
                    ann = "default";
                }
                if (tab[j].annotations[k] > maxann) {
                    ann = k;
                    maxann = tab[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), ( tab[j].annotations[ann] / tab[j].freq )].join(',') + ")";
            }
            var fontsize = Math.floor( ( 12 + Math.sqrt( tab[j].score - minfreq ) * echfreq ) );
            html += '<span style="line-height: ' + (8 + fontsize) + 'px; font-size: ' + fontsize + 'px;' + coul + '" onclick="filtrer(\'' + tab[j].word.replace(/('|")/g, '\\$1') + '\')">' + tab[j].word + '</span> ';
        }
        $("#motscles").html(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 += 84;
            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 filtrer(valeur) {
    twCx.filtreTexte = valeur;
    $("#inp_q").val(valeur).attr("class","rechercheCourante");
    twCx.filtre = ( valeur ? new RegExp(valeur.replace(/(\W)/g, '\\$1'),'ig') : null );
    twCx.followLast = !valeur && (twCx.position == twCx.idIndex[twCx.tweets.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) {
    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() {
    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("Rechercher dans les tweets");
        }
    }
}

$(document).ready(function() {
    tlPaper = Raphael("timeline", twCx.tlWidth, twCx.tlHeight);
    
    if (typeof STANDALONE_APP == "undefined" || !STANDALONE_APP) {
        console.log("Loading from socket.io");
        socket = io.connect('http://' + document.location.hostname );
        socket.on("initial_data", function(data) {
            loadTweets(data.tweets)
        });
        socket.on("update", function(data) {
            if (!twCx.tweets) {
                return;
            }
            for (var i in data.new_tweets) {
                addTweet(data.new_tweets[i]);
            }
            if (twCx.followLast) {
                twCx.position = twCx.idIndex[twCx.tweets.length - 1];
            }
            updateDisplay();
        });
    } else {
        $.getScript("tweetdata.js");
    }
    
    
    $("#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;
                updateDisplay();
            }
            wheelDelta = 0;
        }
        return false;
    });
    $("#timeline, #tweetlist").mouseout(function() {
        twCx.tlMouseClicked = false;
        twCx.tlMouseMoved = false;
        $("#hovertweet").hide();
    });
    $("#timeline").mousemove(function(evt) {
        twCx.tlMouseMoved = true;
        clicTl(evt);
    });
    $("#timeline").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;
    });
    $("#timeline").mouseup(function(evt) {
        clicTl(evt);
        twCx.tlMouseClicked = false;
        twCx.tlMouseMoved = false;
    });
    $("#inp_q").focus(function() {
        if ($(this).hasClass("greyed")) {
            $(this).val("");
        }
        $(this).attr("class","");
    });
    $("#inp_q").focusout(function() {
        focusOutRecherche();
    });
    $("#inp_reset").click(function() {
        if (twCx.filtre) {
            twCx.filtre = null;
            updateDisplay();
        }
        focusOutRecherche();
        return false;
    })
    $("#recherche").submit(function() {
        if (!$("#inp_q").hasClass("greyed")) {
            var valeur = $("#inp_q").val();
            filtrer(valeur);
        }
        return false;
    });
    
    setInterval(function() {
        var sc = $("#scrollcont");
        if (sc.scrollTop() != lastScrollPos) {
            var p = Math.floor( twCx.tweets.length * ( 1 - sc.scrollTop() / scrollExtent ) );
            goToPos(p);
        }
        
    }, 100)
});