var timeplot;

function onLoad() {
    switchChart(6);
}

var resizeTimerID = null;
function onResize() {
    if (resizeTimerID == null) {
        resizeTimerID = window.setTimeout(function() {
            resizeTimerID = null;
            timeplot.repaint();
        }, 100);
    }
}

window.onload = onLoad;
window.onresize = onResize;
var checkedboxes = [4, 14];
var victim = 2;

function colorFromNumber(i) {
    switch (i) {
    case 0:
	return '#800000';
	break;
    case 1:
	return '#000080';
	break;
    case 2:
	return '#008000';
	break;
    case 3:
	return '#ff8000';
	break;
    }
}

function switchChart(column) {
    checkedid = 'check' + column;

    thisbox = document.getElementById(checkedid);

    if (thisbox.checked == true) {
	checkedboxes[victim] = column;
	victim ++;
    } else {
	ncb = [];
	for (i = 0; i < checkedboxes.length; i ++) {
	    cb = checkedboxes[i];
	    if (cb != column) {
		ncb.push(cb);
	    }
	}
	checkedboxes = ncb;
    }

    /* Rotate the element slated for replacement. */
    if (victim > 3) {
	victim = 0;
    }

    $('input.switchers').each(function() {
	this.checked = false;
    });

    $('span.labels').each(function() {
	this.style.color = 'black';
	this.style.fontWeight = 'normal';
    });

    for (i = 0; i < checkedboxes.length; i++) {
	col = checkedboxes[i];
	$('#check' + col).each(function() {
	    this.checked = true;
	    el = document.getElementById('lbl' + col);
	    el.style.fontWeight = 'bold';
	    el.style.color = colorFromNumber(i);
	});
    }
    makeChart(checkedboxes);
}

function makeChart(checkedboxes) {
    var eventSource = new Timeplot.DefaultEventSource();

    plotInfo = [];
    for (i = 0; i < checkedboxes.length; i ++) {
	color = colorFromNumber(i);
	col = checkedboxes[i];
	plotInfo.push(
	    Timeplot.createPlotInfo({
		id: "plot" + col,
		dataSource: new Timeplot.ColumnSource(eventSource, col),
		valueGeometry: new Timeplot.DefaultValueGeometry({
		    gridColor: "#000000",
		    axisLabelsPlacement: "left",
		    min: 0,
		    max: 100
		}),
		lineColor: color,
		timeGeometry: new Timeplot.DefaultTimeGeometry({
		    gridColor: "#000000",
		    axisLabelsPlacement: "top"
		})
	    }));
    }

    timeplot = Timeplot.create(document.getElementById("languagetimeline"),
			       plotInfo);
    timeplot.loadText("/data.txt", ",", eventSource);
}