/*********
* Javascript for file upload demo
* Copyright (C) Tomas Larsson 2006
* http://tomas.epineer.se/
*
* Added changes to upload.js for feature chnanges to original script
* Copyright (C) Jason Ward 2006
* http://www.cubedthree.com
* 1) Added percentage complete to progress bar
* 2) Automatically submits master form after file upload complete
* 3) Disables button on master form after clicking
* 4) Changes text on button to 'uploading...' after clicking

* Licence:
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.mozilla.org/MPL/
*
* Software distributed under this License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*/
var uploads_in_progress = 0;
var sids = {};

function beginUpload(ul,pf,sid,btn) {
        btn.value="Uploading...";
        btn.disabled=true;
	ul.submit();
	sids[ul.name] = sid;
	uploads_in_progress = uploads_in_progress + 1;

	var pm = $(ul.name + "_progressmaster");
	var pb = $(ul.name + "_progress");

	Element.show(pm);
	new Ajax.PeriodicalUpdater({},'fileprogress.php',{'decay': 2,'frequency' : 0.5,'method': 'post','parameters': 'sid=' + sid,'onSuccess' : function(request){updateProgress(ul,pf,request)},'onFailure':function(request){updateFailure(ul,request)}})
}

function updateProgress(ul,pf,req) {
	var percent = parseInt(req.responseText);
	if(!percent) percent = 0;

	var pm = $(ul.name + "_progressmaster");
	var pb = $(ul.name + "_progress");

	pb.style.width = percent + "%";
	document.getElementById('percentcomplete').innerHTML=percent.toString() + '%';
	if(percent >= 100) {
                var inp_id = ul.name;
		if(sids[inp_id]) {
			uploads_in_progress = uploads_in_progress - 1;
			var inp = $(inp_id);
			if(inp) {
				inp.value = sids[inp_id];
			}
		}
                Element.hide(pm);
		sids[inp_id] = false;
		pf.submit();
	}
}

function updateFailure(ul,req) {
	var mes = req.responseText;
	var pb = $(ul.name + "_progress");

	pb.style.width=0;
	alert(mes);
	uploads_in_progress = uploads_in_progress - 1;
}
