Element.extend({
	toObject:function(){
		var object = {};
		this.getFormElements().each(function(el){
			var name = $(el).name;
			var value = el.getValue();
			if (!el.disabled && value !== false)
				object[name] = value;
		});
		return object;
	}
});

var AjaxCommand = new Class({
	initialize : function(component) {
		this.component = component;
	},
	
	run : function(command, querydata) {
		busy.start();
		
		var queryobj = {option : this.component, task : 'ajax_task', func : command, data : Json.toString(querydata)};
		
		new Ajax(ajax_live_site, {
			method: 'post',
			data: queryobj,
			onComplete: this.commandComplete,
			onFailure: this.ajaxFailure
		}).request();
	},
	
	
	commandComplete : function(response) {
		busy.end();
		
		var obj = Json.evaluate(response);

		if (obj.error != 0) {
			alert(obj.errorMsg);
			return;
		}
		
		new BatchRunner().runBatch(obj.data);
	},
	
	ajaxFailure : function() {
		busy.end();
		
		alert('AJAX Error!');
	}
});

var AjaxBusy = new Class({
	initialize : function() {
		this.busyid	= 'ajax_busy_image';
		this.elemid = '';
	},
	
	attach : function(elemid) {
		this.elemid = elemid;
	},
	
	start : function() {
		if (!$(this.elemid)) {
			return;
		}
		
		$(this.busyid).injectAfter(this.elemid);
		
		$(this.busyid).setStyles({
			'opacity' : 0,
			'visibility' : 'visible',
			'display' : 'inline'
		});
		
		
		$(this.busyid).effects({
			duration: 1000,
			transition: Fx.Transitions.quadOut
		}).start({
			'opacity':[0,1]
		});
	},
	
	end : function() {
		$(this.busyid).effects({
			duration: 1000,
			transition: Fx.Transitions.quadOut
		}).start({
			'opacity':[1,0]
		});
		$(this.busyid).setStyles({
			'opacity' : 0,
			'visibility' : 'hidden',
			'display' : 'none'
		});
	}
});

var busy = new AjaxBusy();

var BatchRunner = new Class({

	initialize : function() {
	},
	
	runBatch : function(batchobj) {
		batchobj.each(function(cmdobj,index) {
			var cmd 		= cmdobj[0];
			var id			= cmdobj[1];
			var property 	= cmdobj[2];
			var data 		= cmdobj[3];

			switch(cmd){
				case 'as': 	// assign or clear
					if ($(id)) {
						$(id).setProperty(property, data);
					}
					break;
					
				case 'al':	// alert
					if(data){
						alert(data);}
					break;
				
				case 'ce':
					var elem = new Element(property);
					elem.setProperty('id', data);
//					alert(elem.id);
					if ($(id)) {
						$(id).adopt(elem);
					}
					break;
					
				case 'rm':
					if ($(id)) {
						$(id).remove();
					}
					break;
					
				case 'cs':	// call script
					var scr = id + '(';
					if($type(data) == 'array'){
						scr += 'data[0]';
						for (var l=1; l<data.length; l++) {
							scr += ',data['+l+']';
						}
					} else {
						scr += 'data';
					}
					scr += ');';
					eval(scr);
					break;
				case 'ev':
//					alert(data);
//					console.log(data);					
					eval(data);
					break;
				default:
					alert("Unknow command: " + cmd);
			}
		});
	}
});