
var totalWidth = 600;
var pct = 0.01;
var incr = 0.1;
var inProgress = false;
var received = false;
var visible = false;
var errorCt = 0;

function moveTo(v, id) {
    if (v <= pct) {
	return;
    }
    if (v > 100.0) {
	v = 100.0;
    }
    pct += incr;
    $(id).width = (pct / 100.0) * totalWidth ;
    setTimeout('moveTo(' + v + ',"' + id + '")', 10);
}

function doit(frm) {
    inProgress = true;
    var key = $('upload-key').value;
    setTimeout('go("' + key + '")', 5000);
    frm.submit();
    return false;
}

function go(key) {
    url = '/filedrop/progress/' + key;
    var rq = new Ajax.Request(
			      url,
			      {
				  method: 'get',
				  onComplete: doResponse,
				  onException: doError
			      }
			      );
}

function doResponse(req) {
    var key = $('upload-key').value;
    var values = req.responseText.split('/');
    if (values == null || values.length < 4) {
	if (inProgress) {
	    setTimeout('go("' + key + '")', 5000);
	}
	return;
    }
    if (values[0].match(/ERROR/)) {
	top.location = '/filedrop/error/' + key;
    }
    else if (values[0].match(/RECEIVED/)) {
	if (!received) {
	    $('msg').innerHTML = "Processing ...";
	    $('ul').width = totalWidth;
	    pct = 0.01;
	    received = true;
	}
	if (!visible) {
	    Effect.Appear('status');
	    visible = true;
	}
	var pctDisplay = values[3];
	if (pctDisplay > 100.0) {
	    pctDisplay = 100.0;
	}
	moveTo(pctDisplay, 'pl');
	$('size').innerHTML = values[1];
	$('rcvd').innerHTML = values[2];
	$('pct').innerHTML = pctDisplay + '%';
	$('time').innerHTML = values[4];
	if (inProgress) {
	    setTimeout('go("' + key + '")', 5000);
	}
    }
    else if (values[0].match(/COMPLETED/)) {
	$('pl').width = totalWidth;
	inProgress = false;
    }
    else {
	if (!inProgress) {
	    return;
	}
	if (!visible) {
	    Effect.Appear('status');
	    visible = true;
	}
	var pctDisplay = values[3];
	if (pctDisplay > 100.0) {
	    pctDisplay = 100.0;
	}
	moveTo(pctDisplay, 'ul');
	$('size').innerHTML = values[1];
	$('rcvd').innerHTML = values[2];
	$('pct').innerHTML = pctDisplay + '%';
	$('time').innerHTML = values[4];
	if (inProgress) {
	    setTimeout('go("' + key + '")', 5000);
	}
    }
}

function doError(req, ex) {
    /*    alert(ex); */
    if (errorCt > 5) {
	inProgress = false;
    }
    else {
	errorCt += 1;
	var key = $('upload-key').value;
        setTimeout('go("' + key + '")', 5000);
    }
}
