initial import from onelab svn codebase
[plewww.git] / misc / upload.js
1 // $Id: upload.js 144 2007-03-28 07:52:20Z thierry $
2
3 // Global killswitch
4 if (isJsEnabled()) {
5   addLoadEvent(uploadAutoAttach);
6 }
7
8 /**
9  * Attaches the upload behaviour to the upload form.
10  */
11 function uploadAutoAttach() {
12   var inputs = document.getElementsByTagName('input');
13   for (i = 0; input = inputs[i]; i++) {
14     if (input && hasClass(input, 'upload')) {
15       var uri = input.value;
16       // Extract the button ID based on a substring of the input name: edit[foo][bar] -> foo-bar
17       var button = input.name.substr(5, input.name.length - 6).replace('][', '-');
18       var wrapper = button + '-wrapper';
19       var hide = button + '-hide';
20       var upload = new jsUpload(uri, button, wrapper, hide);
21     }
22   }
23 }
24
25 /**
26  * JS upload object.
27  */
28 function jsUpload(uri, button, wrapper, hide) {
29   this.button = button;
30   this.wrapper = wrapper;
31   this.hide = hide;
32   redirectFormButton(uri, $(button), this);
33 }
34
35 /**
36  * Handler for the form redirection submission.
37  */
38 jsUpload.prototype.onsubmit = function () {
39   var hide = $(this.hide);
40   // Insert progressbar and stretch to take the same space.
41   this.progress = new progressBar('uploadprogress');
42   this.progress.setProgress(-1, 'Uploading file');
43   this.progress.element.style.width = '28em';
44   this.progress.element.style.height = hide.offsetHeight +'px';
45   hide.parentNode.insertBefore(this.progress.element, hide);
46   // Hide file form (cannot use display: none, this mysteriously aborts form
47   // submission in Konqueror)
48   hide.style.position = 'absolute';
49   hide.style.left = '-2000px';
50 }
51
52 /**
53  * Handler for the form redirection completion.
54  */
55 jsUpload.prototype.oncomplete = function (data) {
56   // Remove progressbar
57   removeNode(this.progress.element);
58   this.progress = null;
59   // Replace form and re-attach behaviour
60   $(this.wrapper).innerHTML = data;
61   uploadAutoAttach();
62 }
63
64 /**
65  * Handler for the form redirection error.
66  */
67 jsUpload.prototype.onerror = function (error) {
68   alert('An error occurred:\n\n'+ error);
69   // Remove progressbar
70   removeNode(this.progress.element);
71   this.progress = null;
72   // Undo hide
73   $(this.hide).style.position = 'static';
74   $(this.hide).style.left = '0px';
75 }