var socket,
    tlPaper,
    twPaper,
    tweetData = {
        "tweetcount" : 0,
        "position" : 0,
        "followLast" : true,
        "zoomLevel" : 3,
        "timeLevel" : 2,
        "tweets" : [],
        "posIndex" : [],
        "tlChanged" : true
    },
    displaySplitting = [
        {
            positions : [ 10, 20, 22, 24, 25, 26, 27, 28, 29, 31, 33, 43, 53 ],
            classNames : [ 'icons fade', 'icons', 'quarter fade', 'quarter', 'half fade', 'half', 'full', 'half', 'half fade', 'quarter', 'quarter fade', 'icons', 'icons fade' ]
        },
        {
            positions : [ 1, 3, 5, 7, 13, 33, 53 ],
            classNames : [ 'full', 'half', 'half fade', 'quarter', 'quarter fade', 'icons', 'icons fade' ]
        }
    ],
    blockUpdate = false,
    waitUpdate = true,
    wheeldelta = 0;

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

function tweetToHtml(tweet, className) {
	html = '<li class="tweet ' + className + '" id="tweet_' + tweet.pos + '"';
	if (tweetData.followLast && tweet.pos == tweetData.position) {
	    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:' + annotations[tweet.annotations[i]].colors.tweet + '"></div>';
    	}
    	html += '</div>';
	}
	html += '<div class="twmain">';
	a_user = '<a href="http://twitter.com/' + tweet.user.screen_name + '" target="_blank" title="' + tweet.user.name + '">';
	if (tweet.user.profile_image_url) {
		html += a_user + '<img class="profile_image" src="' + tweet.user.profile_image_url + '" /></a>';
	}
	html += '<h4>' + a_user + '@' + tweet.user.screen_name + '</a></h4><p class="created_at">' + new Date(tweet.created_at).toLocaleTimeString() + '</p><p class="tweet_text">';
	lastend = 0;
	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) {
	    entities.push({
	        "start" : tweet.entities.urls[i].indices[0],
	        "end" : tweet.entities.urls[i].indices[1],
	        "html" : '<a href="' + tweet.entities.urls[i].expanded_url + '" target="_blank">' + tweet.entities.urls[i].display_url + '</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 += txt + '</p></li></div>';
	return html;
}


function getUpdate() {
    tweetData.posToDisplay = [];
    if (tweetData.followLast) {
        for (var i = tweetData.tweetcount; i >= tweetData.tweetcount - 52; i--) {
            tweetData.posToDisplay.push( i > 0 ? i : -1 );
        }
        tweetData.end = tweetData.tweetcount;
        tweetData.start = Math.max(1, tweetData.end - 52);
    } else {
        for (var i = tweetData.position + 26; i >= tweetData.position - 26; i--) {
            tweetData.posToDisplay.push( i > 0 && i <= tweetData.tweetcount ? i : -1 );
        }
        tweetData.end = Math.min(tweetData.tweetcount, tweetData.position + 26 );
        tweetData.start = Math.max(1, tweetData.position - 26);
    }
    var tweetsToGet = [];
    for (var i = tweetData.start; i <= tweetData.end; i++) {
        if (!tweetByPos(i)) {
            tweetsToGet.push(i);
        }
    }
    if (tweetsToGet.length) {
        socket.emit('updateTweets', {
            "tweets" : tweetsToGet
        });
    } else {
        drawTweetList();
        //drawDisplay();
    }
    if (tweetData.tlChanged) {
        socket.emit('updateTimeline', {
            "level" : tweetData.timeLevel
        });
    } else {
        drawTimeLine();
    }
}

function tweetByPos(pos) {
    var index = tweetData.posIndex.indexOf(pos);
    return (index == -1 ? false : tweetData.tweets[index]);
}

function delayedUpdate() {
    blockUpdate = false;
    if (waitUpdate) {
        updateDisplay();
    }
}

function updateDisplay() {
    if (blockUpdate) {
        waitUpdate = true;
    } else {
        waitUpdate = false;
        getUpdate();
        blockUpdate = true;
        setTimeout(delayedUpdate, 100);
    }
}

function setTimeZoom(level) {
    if (level >= 0 && level <= 4) {
        tweetData.timeLevel = level;
        tweetData.tlChanged = true;
        updateDisplay();
    }
}

function drawTweetList() {
    html = '';
    var i = 0;
    while (i < tweetData.posIndex.length) {
        if (tweetData.posToDisplay.indexOf(tweetData.posIndex[i]) == -1) {
            tweetData.posIndex.splice(i,1);
            tweetData.tweets.splice(i,1);
        } else {
            i++;
        }
    }
    for (var i in tweetData.posToDisplay) {
        var ds = displaySplitting[tweetData.followLast ? 1 : 0];
        for (var j in ds.positions) {
            if (ds.positions[j] > i) {
                var className = ds.classNames[j];
                break;
            }
        }
        html += ( tweetData.posToDisplay[i] != -1 ? tweetToHtml(tweetByPos(tweetData.posToDisplay[i]), className) : placeHolder(className) );
    }
    $("#tweetlist").html(html);
    if (tweetData.followLast) {
        $("#tweet_" + tweetData.position).fadeIn(500);
    }
    drawTimeWindow();
}

function drawTimeWindow() {
    twPaper.clear();
    if (!tweetData.timeline || !tweetData.timeline.length) return;
    
    var dtfintl = new Date ( tweetData.timeline[ tweetData.timeline.length - 1 ].end ),
        dtdebtl = new Date ( tweetData.timeline[0].start ),
        dtfintw = new Date( tweetByPos( tweetData.end ).created_at ),
        dtdebtw = new Date( tweetByPos( tweetData.start ).created_at ),
        scY = 600 / ( dtfintl - dtdebtl );
    twPaper.rect( 0, scY * ( dtfintl - dtfintw ), 300, scY * ( dtfintw - dtdebtw )).attr({"stroke":"none","fill":"#8080ff","fill-opacity":.2});
    var dtcour = new Date( tweetByPos( tweetData.position ).created_at ),
        posY = scY * ( dtfintl - dtcour ); 
    twPaper.path("M0 "+posY+"L300 "+posY).attr({"stroke":"#ff0"});
}

function drawTimeLine() {
    tlPaper.clear();
    if (!tweetData.timeline || !tweetData.timeline.length) return;
    tweetData.tlTweetRects = [];
    var scaleY = 600 / tweetData.timeline.length,
        max = 0;
    for (var i = 0; i < tweetData.timeline.length; i++) {
        max = Math.max(max, tweetData.timeline[i].tweets);
    }
    var scaleX = 160 / max;
    
    // dessin de l'axe vertical
    
    tlPaper.path("M160 0L160 600").attr({"stroke":"#ccc"});
    
    // dessin de la date de début
    
    tlPaper.text(165, 592, new Date(tweetData.timeline[0].start).toLocaleTimeString()).attr({ "text-anchor" : "start", "font-size": "12px" });
    
    // dessin de la date de fin
    
    tlPaper.text(165, 7, new Date(tweetData.timeline[tweetData.timeline.length - 1].end).toLocaleTimeString()).attr({ "text-anchor" : "start", "font-size": "12px" });
    for (var i = 0; i < tweetData.timeline.length; i++) {
        var posY = 600 - (i * scaleY);
        
        // Si on est à une demi-heure, on trace un axe secondaire + heure
        
        if (i && !(new Date(tweetData.timeline[i].start).valueOf() % 1800000)) {
            tlPaper.path("M0 "+posY+"L165 "+posY).attr({"stroke":"#ccc"});
            tlPaper.text(165, posY, new Date(tweetData.timeline[i].start).toLocaleTimeString()).attr({ "text-anchor" : "start", "font-size": "12px" });
        }
        var anz = {
            "default" :tweetData.timeline[i].tweets
        };
        for (var j in tweetData.timeline[i].annotations) {
            anz.default -= tweetData.timeline[i].annotations[j];
            anz[j] = tweetData.timeline[i].annotations[j];
        }
        var posX = 0;
        for (var j in anz) {
            var largX = scaleX * anz[j];
            tlPaper.rect(posX, 600 - scaleY * (i+1), largX, scaleY).attr({"stroke": "none", "fill": annotations[j].colors.timeline});
            posX += largX;
        }
    }
    
    drawTimeWindow();
/*    for (var i = 0; i < tweetData.arcs.length; i++) {
        var x1 = scaleX * (tmptw[tweetData.arcs[i].from].x + .5),
            x2 = scaleX * (tmptw[tweetData.arcs[i].to].x + .5),
            y1 = 600 - scaleY * (tmptw[tweetData.arcs[i].from].y + .5),
            y2 = 600 - scaleY * (tmptw[tweetData.arcs[i].to].y + .5),
            d = "M"+x1+" "+y1+"C";
        if (y1 == y2) {
            d += x1+" "+(y1 - 30)+" "+x2+" "+(y2 - 30);
        } else {
            d += (x1 + 60)+" "+y1+" "+(x2 + 60)+" "+y2;
        }
        paper.path(d+" "+x2+" "+y2);
    } */
}

$(document).ready(function() {
    tlPaper = Raphael("timeline", 220, 600);
    twPaper = Raphael("timewindow", 220, 600);
    socket = io.connect('http://' + document.location.hostname );
    socket.on('tweetSummary', function (data) {
        if (tweetData.tweetcount != data.tweetcount) {
            tweetData.tweetcount = data.tweetcount;
            tweetData.tlChanged = true;
            if (tweetData.followLast) {
                tweetData.position = data.tweetcount;
            }
            updateDisplay();
        }
    });
    socket.on('tweets', function (data) {
        for (var i in data) {
            if (tweetData.posIndex.indexOf(data[i].pos) == -1) {
                tweetData.tweets.push(data[i]);
                tweetData.posIndex.push(data[i].pos);
            }
        }
        drawTweetList();
    });
    socket.on('timeline', function (data) {
        tweetData.timeline = data;
        drawTimeLine();
    });
    socket.on('display', function (data) {
        tweetData.tlChanged = false;
        for (var i in data.tweets) {
            if (tweetData.posIndex.indexOf(data.tweets[i].pos) == -1) {
                tweetData.tweets.push(data.tweets[i]);
                tweetData.posIndex.push(data.tweets[i].pos);
            }
        }
        if (data.timeline) {
            tweetData.timeline = data.timeline
        }
        tweetData.arcs = data.arcs;
        drawDisplay();
    });
    $("#tweetlist").mousewheel(function(e, d) {
        wheeldelta += d;
        if (Math.abs(wheeldelta) >= 1) {
            tweetData.position = Math.min( tweetData.tweetcount, Math.max(1, parseInt(wheeldelta) + tweetData.position ) );
            tweetData.followLast = (tweetData.position == tweetData.tweetcount);
            updateDisplay();
            wheeldelta = 0;
        }
        return false;
    });
    $("#timewindow").mousewheel(function(e, d) {
        wheeldelta += d;
        if (Math.abs(wheeldelta) >= 1) {
            if (wheeldelta > 0) {
                setTimeZoom(tweetData.timeLevel + 1);
            } else {
                setTimeZoom(tweetData.timeLevel - 1);
            }
            wheeldelta = 0;
        }
        return false;
    });
});