/**
 * iframeFileUplod for mailformplus
 */
var iframeFileUpload = new Class({

	options: {
	},

	initialize: function(options){
		this.setOptions(options);
		this.addEvents();
	},

	addEvents: function(){
		
		$$('form').each(function(pform){
			pform.getElements('input[type=file]').each(function(element){
				element.addEvent(
					'change',
					function(){
						this.uploadFile(element,pform);
					}.bind(this)
				);
			}.bind(this))
		}.bind(this))		
	},

	uploadFile: function(element,pform){

		var n = 'f' + Math.floor(Math.random() * 99999);
		var iframe = new Element('iframe', {
	    	'styles': {
		        'display': 'none'
		    },
		    'src': 'about:blank',
		    'id': n,
		    'name': n
		});

		var box = new Element('div', {
	    	'styles': {
		        'display': 'none'
		    },
		    'id': 'box-'+n
		});
		var result = new Element('div', {
	    	'styles': {
		        'display': 'none'
		    }
		});
		

		box.adopt(iframe);
		box.adopt(result);
		$$('body').adopt(box);

		var oldTarget = pform.getProperty('target');
		var oldAction = pform.getProperty('action');

		pform.setProperty('target',n);
		pform.setProperty('action','de/fileupload/');
		
		clickMan.waitCursor(true);
		iframe.addEvent(
			'load',
			function(){

		        if (iframe.contentDocument) {
		            var d = iframe.contentDocument;
		        } else if (iframe.contentWindow) {
		            var d = iframe.contentWindow.document;
		        } else {
		            var d = window.frames[id].document;
		        }
				result.setHTML(d.body.innerHTML);
				var errors = result.getElements('#error');
				$$('#error').each(function(element){
					element.remove();
				});
				$('displayError').adopt(errors);
				clickMan.waitCursor(false);

				result.remove();

				pform.setProperty('target',oldTarget);
				pform.setProperty('action',oldAction);
				// box.remove();
			}.bind(this)
		);

		pform.submit();
		
	}

});

iframeFileUpload.implement(new Events);
iframeFileUpload.implement(new Options);
iframeFileUpload.implement(new Chain);
