/* Find the largest value in an array. */
function arraymax(arr) {
    var max = 0;
    for(var i = 0; i < arr.length; i++) {
	if (arr[i][1] > max) {
	    max = arr[i][1];
	}
    }
    return max;
}

/* Normalize an array in an array of arrays format used.  */

function normalize(aoa) {
    reslist = [];
    max = arraymax(aoa);
    for(var i = 0; i < aoa.length; i++) {
	reslist.push([aoa[i][0], aoa[i][1] / max]);
    }
    return reslist;
}

/* Redraw things on the screen, using the controls in controldiv, and
placing the results in resultdiv. */
function redraw(obj, controldiv, resultdiv) {
    var totalweight = 0;
    /* Get the total of all weights. */
    for (var i in obj) {
	totalweight += parseFloat($F($(i + "_weight")));
    }

    var data = null;
    var hash = new Hash();
    /* Calculate values and put them in the hash table - which is
    easier for lookups than the array of arrays.  */
    for (var i in obj) {
	data = obj[i];
	var weight = $F($(i + "_weight"));
	normalize(data).each(function(e) {
	    var label = e[0].replace(' ', '&nbsp;');
	    oldval = hash.get(label);
	    if (oldval == undefined) {
		oldval = 0;
	    }
	    hash.set(label, (e[1] * weight) + oldval);
	});
    }
    var results = [];
    hash.each(function(e) {
	results.push([e[0], e[1] / totalweight]);
    });

    data = [];
    var labels = [];
    var i = 1;

    results.sort(function(left, right) {
	a = left[1];
	b = right[1];
	return a < b ? -1 : a > b ? 1 : 0;
    }).each(function(r) {
	data.push([r[1], i]);
	labels.push([i + 0.4, r[0]]);
	i ++;
    });
    Flotr.draw(resultdiv, [data],
	       {yaxis: {ticks: labels},
		xaxis: {max: 1},
		bars: {barWidth: 0.8, show: true, horizontal: true}});
}

function normalize_and_display_data(obj, resultdivname, controldivname, namemap) {
    var controldiv = $(controldivname);
    var resultdiv = $(resultdivname);

    redrawclosure = function(el) {
	redraw(obj, controldiv, resultdiv);
    };
    for (var i in obj) {
	var data = obj[i];
	controldiv.insert(
	    new Element('label').insert("  " + namemap[i] + ": ")
	);
	var input = new Element('input', {id: i + '_weight', type: 'text',
	    size: 4, value: 1});
	controldiv.insert(input);
	new Form.Element.Observer(input.id, 0.2, redrawclosure);
    }
    redraw(obj, controldiv, resultdiv);
}