var SaveForm = new Class({
	initialize: function(item) {
		var obj = this;
		this.form = item;
		this.result = true
		this.action = this.form.get('action');
		// Upload frame
		if ($chk(obj.form.getElement('input[type=file]')) && !$chk($('UploadFrame')))
			new IFrame({'id': 'UploadFrame', 'name': 'UploadFrame', 'styles': {'display': 'none'}}).inject($(document.body).getElement('div.container'));
		
		this.form.addEvent('submit', function(e){
			// Upload
			if ($chk(obj.form.getElement('input[type=file]')) && obj.form.getElement('input[type=file]').get('value')!="" && obj.result) {
				obj.upload();
			// Regular sending
			} else {
				e.stop();
				if ($chk(obj.form.getElement('input[type=file]'))) {
					new Request({url: obj.form.get('action'), method: 'post', onComplete: function(responseText) { obj.parse(responseText); }}).send(obj.form.toQueryString()+'&file='+obj.form.getElement('input[type=file]').get('value'));
				} else 
				obj.form.set('send', {onSuccess: function(response) { obj.parse(response); }}).send();
			}
		});
	},
	parse: function(response) {
		//alert(response);
		var responseJSON = JSON.decode(response);
		// Message
		if ($chk(responseJSON.msg)) {
			window.location = window.location.href.split('?')[0].split('#')[0];
		// Change url
		} else if ($chk(responseJSON.url)) {
			if ($chk($(document.body).getElement('div[class*=lightbox]'))) lightbox.get(responseJSON.url, 'lightbox2');
			else window.location = responseJSON.url;
		// Errors
		} else {
			var error = "";
			$each(responseJSON.results, function(item) { if (item!=0&&error=="") { error = item; } });
			if (!$chk($(document.body).getElement('span.error'))) {
					new Element('span', {'class': 'error', 'html': error}).inject(this.form, 'top');
			} else {
				$(document.body).getElement('span.error').set('html', error);
				new Fx.Tween($(document.body).getElement('span.error')).start('opacity', 0 , 1);
			}
			// Scroll to see errors
			if (window.getScroll().y>$(document.body).getElement('span.error').getPosition().y-24)
				new Fx.Scroll(window).start(0, $(document.body).getElement('span.error').getPosition().y-24);
		}
	},
	upload: function() {
		var obj = this;
		this.progress = 0;
		this.id = $('APC_UPLOAD_PROGRESS').get('value');
		var name = encodeURI($('name').get('value'));
		
		// Get display elements to show upload progress
		new Request({url: this.action+'?progress=true&file='+name, onSuccess: function (responseText) {
			if ($chk(lightbox.shadow)) lightbox.shadow.destroy();
			if ($chk(lightbox.box)) lightbox.box.destroy();
			lightbox.show(responseText, obj.action+'?progress=true', 'lightbox2');
			obj.getStatus();
		}}).send();
	},
	getStatus: function () {
		var obj = this;
		// If upload is not finished, get statud (under 100)
		if (obj.progress < 100 && this.getIframeData()=="") {
			// Your file should respond with the var progress when progress_key is given
			new Request.JSON({url: this.action+'?progress_key='+this.id, onSuccess: function (response) {
				obj.progress = (response.progress>0 ? response.progress : 1);
				obj.time = response.time;
			}}).send();
			// You get the status each 2.5 secones (maybe change it to a lower value, you impatient foul)
			this.getStatus.delay(2500, obj);
		} else {
			// New method
			this.parse(this.getIframeData());
		}
		// Get the with of the progress bar (Important to give the "progress" id to your div)
		// Also, your progress bar needs a div inside that represents the progress
		if ($chk($('progress')) && $defined(this.time)) {
			var width = $('progress').getSize().x.toInt();
			// Show the progress
			$(document.body).getElements('span.progress')[1].set('html', obj.progress+'%');
			$('progress').getElement('div').setStyle('width', (width/100*obj.progress).limit(5, width));
			var time = $(document.body).getElements('span.progress')[0];
			time.set('html', time.get('html').split(':')[0]+': '+this.time);
		}
	},
	getIframeData: function() {
		// IE8+
		if (Browser.Engine.trident)
			return $('UploadFrame').contentWindow.document.body.innerHTML;
		// Other browsers
		else if ($('UploadFrame').contentDocument)
			return $('UploadFrame').contentDocument.defaultView.document.body.innerHTML;
		// Some old browser I guess
		else return $('UploadFrame').document.body.innerHTML;
	}
});

var saveform = new Array();
window.addEvent('domready', function() {
	$each($(document.body).getElements('form[action*=/sync]'), function(item) {
		saveform[item.get('name').toString()] = new SaveForm(item);
	});
});
