/*
Script: Swiff.Uploader.js
	Contains <Swiff.Uploader>

Author:
	Valerio Proietti, <http://mad4milk.net>,
	Harald Kirschner, <http://digitarald.de>

License:
	MIT-style license.
*/

/*
Class: Swiff.Uploader
	creates an uploader instance. Requires an existing Swiff.Uploader.swf instance.

Arguments:
	object - the flash object to atatch the uploader instance to.
	callBacks - an object, containing key/value pairs, representing the possible callbacks. See below.

callBacks:
	onOpen - a function to fire when the user opens a file.
	onProgress - a function to fire when the file is uploading. passes the name, the current uploaded size and the full size.
	onSelect - a function to fire when the user selects a file.
	onComplete - a function to fire when the file finishes uploading
	onError - a function to fire when there is an error.
	onCancel - a function to fire when the user cancels the file uploading.
*/

Swiff.Uploader = new Class({

	setOptions: function(options){
		this.options = {
			types: false,
			multiple: true,
			queued: true,
			url: null
		};
		Object.extend(this.options, options || {});
	},

	setCallBacks: function(callBacks){
		this.callBacks = Object.extend({
			onOpen: Class.empty,
			onProgress: Class.empty,
			onSelect: Class.empty,
			onComplete: Class.empty,
			onError: Class.empty,
			onCancel: Class.empty
		}, callBacks || {});
		for (p in this.callBacks) this.callBacks[p] = this.callBacks[p].bind(this);
	},

	initialize: function(callBacks, onLoaded, options){
		if (Swiff.getVersion() < 8) return false;
		this.setCallBacks(callBacks);
		this.onLoaded = onLoaded;
		this.setOptions(options);
		this.object = Swiff.Uploader.register(this.loaded.bind(this), this.options.url);
		this.instance = Swiff.nextInstance();
		Swiff.callBacks[this.instance] = this.callBacks;
		return this;
	},

	loaded: function(){
		Swiff.remote(this.object, 'create', this.instance, this.options.types, this.options.multiple, this.options.queued);
		this.onLoaded();
	},

	browse: function(){
		Swiff.remote(this.object, 'browse', this.instance);
	},

	send: function(url){
		Swiff.remote(this.object, 'upload', this.instance, url);
	},

	remove: function(name, size){
		Swiff.remote(this.object, 'remove', this.instance, name, size);
	},

	fileIndex: function(name, size){
		return Swiff.remote(this.object, 'fileIndex', this.instance, name, size);
	},

	fileList: function(){
		return Swiff.remote(this.object, 'filelist', this.instance);
	}

});

Swiff.Uploader.extend = Object.extend;

Swiff.Uploader.extend({

	swfUrl: 'Swiff.Uploader.swf',

	callBacks: [],

	register: function(callBack, url){
		Swiff.Uploader.callBacks.push(callBack);
		if (!Swiff.Uploader.object) {
			Swiff.Uploader.object = new Swiff(url || Swiff.Uploader.swfUrl, {vars: {'onLoad': Swiff.Uploader.loaded}});
			document.body.appendChild(Swiff.Uploader.object);
		}
		return Swiff.Uploader.object;
	},

	loaded: function(){
		Swiff.Uploader.callBacks.each(function(fn){fn();});
	}

});
