// Copyright (c) 2008 Don Schonknecht (http://undesigned.org.za/)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
// For more information visit http://undesigned.org.za/

var UploadProgress = {
	// Request URI (this bit needs work and might break with multiple progress meters if the request URIs are different)
	uri: null,

	// Request frequency
	frequency: 1000,

	// To track null failures
	nullFails: 0,

	// Bar styling: http://www.barenakedapp.com/the-design/displaying-percentages
	bar: {
		image: 'images/percentImage.png',
		background: 'images/percentImage_back.png',
		style: ''
	},

	// Default callback - used to preload images
	onLoad: function() {
		var images = [ new Image(), new Image() ];
		images[0].src = UploadProgress.bar.image;
		images[1].src = UploadProgress.bar.background;
		UploadProgress.bar.style = 'padding: 0; background-position: -121px 0; '+
		'background: #eef6f6 url("'+UploadProgress.bar.background+'") top left no-repeat;';
	},

	// Default callback - creates a progress bar
	onCreate: function(identifier, form) {
		if (!$('upload_' + identifier)) {
			var img = document.createElement('img');
			img.setAttribute('id', 'upload_' + identifier);
			img.setAttribute('style', UploadProgress.bar.style);
			img.setAttribute('src', UploadProgress.bar.image);
			img.setAttribute('alt', '0%');
			img.setAttribute('title', '0%');
			/** var img = Builder.node('img', {
				id: 'upload_' + identifier, style: UploadProgress.bar.style, alt: '0%',
				src: UploadProgress.bar.image
			}); */
			form.appendChild(img);
		}
		$('upload_' + identifier).style.backgroundPosition = '-121px';
	},

	// Default callback - updates a progress bar
	onUpdate: function(identifier, data) {
		var percent = Math.floor(data['bytes_uploaded'] * 100 / data['bytes_total']);
		$('upload_' + identifier).style.backgroundPosition = (percent - 110) + 'px 0';
		$('upload_' + identifier).alt = percent + '%';
		$('upload_' + identifier).title = percent + '%';

		if ($('uploadSpeed'))
			$('uploadSpeed').innerHTML = Math.floor(data['speed_average'] / 1024)+'KB/s';
		$('Percent').innerHTML = percent + '%';
	},

	// Default callback
	onComplete: function(identifier, data) {
		$('upload_' + identifier).style.backgroundPosition = '1px';
		$('upload_' + identifier).alt = '100%';
		$('upload_' + identifier).title = '100%';
		//$('upload_' + identifier).remove();
	},

	// Enables the progress meter on a form
	__enable: function(form) {
		if (form.select('input[name="UPLOAD_IDENTIFIER"]')[0]) {
			var identifier = form.select('input[name="UPLOAD_IDENTIFIER"]')[0].value;
			if (UploadProgress.uri == null) UploadProgress.uri = form.getAttribute('action');
			UploadProgress.onCreate(identifier, form);
			setTimeout('UploadProgress.__tick("'+identifier+'")', UploadProgress.frequency);
		}
	},

	// Timer function
	__tick: function(identifier) {
		var uri = UploadProgress.uri;
		if ($('uploadForm_' + identifier)) uri = $('uploadForm_' + identifier).getAttribute('action');
		new Ajax.Request(UploadProgress.uri, { method: 'get', parameters: { UPLOAD_IDENTIFIER: identifier } });
	},

	// Called by the server
	__update: function(identifier, data) {
		if (data == null || data['bytes_uploaded'] == data['bytes_total']) {
			if (data == null) {
				UploadProgress.nullFails = UploadProgress.nullFails + 1;
				if (UploadProgress.nullFails < 3)
					setTimeout('UploadProgress.__tick("'+identifier+'");', UploadProgress.frequency);
				else {
					UploadProgress.onComplete(identifier, data);
					UploadProgress.nullFails = 0;
				}
			} else UploadProgress.onComplete(identifier, data);
		} else {
			setTimeout('UploadProgress.__tick("'+identifier+'");', UploadProgress.frequency);
			UploadProgress.onUpdate(identifier, data);
		}
	}
};

Event.observe(window, 'load', function() {
	$$('form').each(function(form) {
		Event.observe(form, 'submit', function() { UploadProgress.__enable(this); });
		UploadProgress.onLoad();
	});
});
