/*
 * Requires SVUI Object
 */
if (typeof(SVUI) == 'undefined') throw("SVUI.FileUpload requires svui.js");

/*
 * SVUI.FileUpload
 */

SVUI.AjaxForm = Class.create(SVUI.Base, {
	forms: new Array(),
	initialize: function(obj) {
		
	},
	
	Element: Class.create(SVUI.Element, {
		observers: null,
		iframes: null,
		fileUploadsComplete: false,
		initialize: function($super, element) {
			$super(element);
			
			this.observers = new Array();
			this.iframes = new Array();
			
			element.observeSubmit = this.observeSubmit.bind(this);
			element.observe('submit', this.onSubmit.bind(this));
			element.submitCheck = this.submitCheck.bind(this);
		},
		
		onSubmit: function(event) {
			
			Event.stop(event);
			/* Reset Form Elements */
			$('dbox_submit').disabled = true;
			this.iframes = this.element.getElementsBySelector('iframe.fileupload');
			this.iframes.each(function(iframe) {
				iframe.fileUploadComplete = false;
			});
			
			/* Check Form Elements */
			this.submitCheck();
		},
		
		submitCheck: function() {
			//Check for forms that have not been submitted
			this.fileUploadsComplete = true;
			if(!this.iframes.length == 0) this.iframes.each(function(iframe) {
				if(!this.submitIFrameFile(iframe)) {
					this.fileUploadsComplete = false;
					throw $break;
				}
			}.bind(this));
			if(!this.fileUploadsComplete) return;
			
			this.submitFormData();
		},
		
		submitIFrameFile: function(iframe) {
			if(!iframe.contentWindow.document.forms[0]) return true;
			form = iframe.contentWindow.document.forms[0];
			
			/* If the iframe doesn't have a file upload input or the file 
			 * input is empty, check it as complete. */
			if(!form['file'] || form['file'].value == '') {
				iframe.fileUploadComplete = true;
				return true;
			}
			
			/* If the iframe form hasn't been submitted yet, submit and 
			 * start polling */
			if(!iframe.fileUploadComplete && iframe.submitForm) {
				 iframe.submitForm();
				 return false;
			}
			
			return true;
		},
		
		submitFormData: function() {
			$('dbox_submit').disabled = true;
			var post_data = Form.serializeElements($$('#dbox form input, #dbox form select, #dbox form textarea'));
			var post_href = $('dbox_form').action+'/display:dbox';
			new Ajax.Updater($('dbox-content'), post_href, {
				evalScripts: true, 
				postBody: post_data,
				onComplete: this.onComplete.bind(this)
			});
		},
		
		observeSubmit: function(func) {
			this.observers.push(func);
		},
		
		onComplete: function() {
			$('dbox').show();
			SVUI.load('dbox');
			this.observers.each(function(f) {
				f();
			});
		}
	}),
	
	options: {
		autoLoad: true,
		classSelector: ['form.ajax_form']
	}
});

SVUI.AjaxForm_IFrameFileUpload = Class.create(SVUI.Base, {
	initialize: function(obj) {
		
	},
	
	Element: Class.create(SVUI.Element, {
		timer: null,
		form: null,
		src: null,
		status: null,
		initialize: function($super, element) {
			$super(element);
			element.submitForm = this.submit.bind(this);
			element.fileUploadComplete = false;
			this.src = element.src;
			
			this.element.ancestors().each(function(ele) { 
				if(ele.tagName == 'FORM')  {
					this.form = ele;
					throw $break;
				}
			}.bind(this));
		},
		
		poll: function() {
			new Ajax.Request(this.src+'/poll/display:fragment', {onComplete: this.pollResult.bind(this)});
		},
		
		pollResult: function(result) {
			this.status.innerHTML = '<h3>File Uploading</h3';
			var poller = $('file_poller');
			poller.innerHTML = result.responseText;
		},
		
		submit: function() {
			if(!this.element.contentWindow.document.forms[0]) return;
			form = this.element.contentWindow.document.forms[0];
			form.submit();
			new Effect.Fade(this.element, {from: 1, to: 0, duration: .2});
			this.status = new Element('div');
			this.status.innerHTML = '<h3>File Upload Initializing</h3';
			var anc = this.element.ancestors();
			
			anc[0].insert(this.status, {position: top});
			new Effect.Fade(this.status, {from: 0, to: 1, duration: .3});
			
			this.timer = new PeriodicalExecuter(function() {				
				if(this.element.contentWindow.document.body.innerHTML) {
					try {
						var response = json_parse(this.element.contentWindow.document.body.innerHTML);
					} catch (Exception) {
						var response = { result : 'uploading' };
					}
					
					//alert(this.element.contentWindow.document.body.innerHTML);
					
					switch(response.result) {
						case 'success':
							$('inp_'+this.element.identify()).value = response.key;
							this.element.fileUploadComplete = true;
							this.status.innerHTML = '<h3>File Upload Complete</h3';
							this.form.submitCheck();
							this.timer.stop();
							break;
						case 'error':
							this.timer.stop();
							break;
						case 'uploading':
							this.poll();
							break;
					}
				} else {
					
				}
			
			}.bind(this), 1.5);
		}
	}),
	
	options: {
		autoLoad: true,
		classSelector: ['iframe.fileupload']
	}
});