/**
 * @author hrw7
 */

ILR.namespace("Widget");

if( !ILR.Widget.Uploader ) {
	
	/**
	 * @namespace ILR.Widget
	 * @class Uploader
	 * @constructor
	 * @param {String} url The url of the upload handler.
	 * @param {String} query The query string
	 */
	ILR.Widget.Uploader = function(url, query) {
		this.init(url, query);
	};
	
	/**
	 * Ajax callback object for dealing with a completed upload request.
	 * @property ILR.Widget.Uploader._UploadCallback
	 * @type Object
	 * @private
	 */
	ILR.Widget.Uploader._UploadCallback = {
		/**
		 * Handles the upload case for the callback
		 * @property ILR.Widget.Uploader._UploadCallback.upload
		 * @type Function
		 * @private
		 */
		upload:function(o) {
			this.uploadEvent.fire(o);
		}
	}
	
	ILR.Widget.Uploader.prototype = {
		/**
		 * The constructor for the Uploader class
		 * @property constructor
		 * @type Function
		 */
		constructor: ILR.Widget.Uploader,
		
		/**
		 * The url of the upload handler.
		 * @property url
		 * @type String
		 */
		url: "",
		
		/**
		 * The query string
		 * @property query
		 * @type String
		 */
		query: "",
		
		/**
		 * Initializes the uploader.
		 * @method init
		 * @param {String} url The url of the upload handler.
	 	 * @param {String} query The query string
		 */
		init:function(url, query) {
			this.url = url;
			this.query = query;
			
			this.initEvents();
		},
		
		/**
		 * Initializes the custom events for the uploader.
		 * @method initEvents
		 */
		initEvents:function() {
			/**
			 * CustomEvent fired before uploading begins.
			 * @event beforeUploadEvent
			 */
			this.beforeUploadEvent = new YAHOO.util.CustomEvent("beforeUpload", this);
			
			/**
			 * CustomEvent fired after uploading has completed.
			 * @event beforeUploadEvent
			 */
			this.uploadEvent = new YAHOO.util.CustomEvent("upload", this);
		},
		
		/**
		 * Uploads a file using ajax.
		 * @method upload
		 * @param {String} el The element id of the input to upload OR
		 * @param {HTMLElement} el The element of the input to upload
		 */
		upload:function(el) {
			if( YAHOO.lang.isString(el) ) {
				el = document.getElementById(el);
			}
			
			this.beforeUploadEvent.fire(el);
			
			var callback = {
				upload: ILR.Widget.Uploader._UploadCallback.upload,
				scope: this,
				argument: {el: el}
			};
			
			var form = document.createElement("form");
			
			YAHOO.util.Dom.setStyle(el, "display", "none");
			
			form.appendChild(el);
			
			document.body.appendChild(form);
			
			YAHOO.util.Connect.setForm(form, true);
			YAHOO.util.Connect.asyncRequest("POST", this.url, callback, this.query);
		}
	};
}