/**
 * AxHandler.js
 * 
 * @version 0.0.3 
 * @date 2008-01-21 18:01:56
 * @author Maiko Tepe <maiko.tepe@yoc.de>
 * @package system
 * @subpackage javascript
 *
 * Updates:
 * 2008-02-11 10:48:19 - neuer task src
 * 
 */
 
 var AxHandler = Class.create({
 	url		   : null,
 	
 	initialize : function(url){
		if (url == undefined) 
			this.url = document.URL;
		else
			this.url = url;
 	},
	
	processAjax : function(params, callback, onLoading, onComplete){
		if (params != undefined) params = Object.toJSON(params); else params = '{}';
		
		var a = new Ajax.Request(this.url,{
			method		: 'post',
			parameters 	: 'AX_HANDLER=TRUE&AX_PARAMS='+params,
			onLoading	: onLoading,
			onComplete  : onComplete,
			onSuccess	: function(result){
			
				var r = result.responseText.evalJSON();
				if (r.AX_TASKS) {
					var a = $A(r.AX_TASKS);
					a.each(function(e){
						if (e[0] == 'innerHTML'){
							
							if ( $(e[1].id) == null ) alert("error, unknown element '"+e[1].id+"'"); 
							$(e[1].id).innerHTML = e[1].value;
							
						}else if (e[0] == 'value'){
							if ( $(e[1].id) == null ) alert("error, unknown element '"+e[1].id+"'");
							
							if (Object.isArray( e[1].value )) {
								
								for (i=0; i < $(e[1].id).options.length;i++){
									var oo = $(e[1].id).options[i];
									oo.selected = false;
									
									for(j=0; j < e[1].value.length; j++){
										if ( oo.value == e[1].value[j] ) oo.selected = true;
										continue;
									}
								}  
								
							}else{
								$(e[1].id).value = e[1].value;
							}
						
						}else if (e[0] == 'options') {
						
							if ( $(e[1].id) == null ) alert("error, unknown element '"+e[1].id+"'");
							var field = $(e[1].id);
							field.options.length = 0;
							var opts = e[1].options;
							if(Object.isArray(opts)){
								for(i=0;i<opts.length;i++){
									field.options[field.options.length] = new Option(opts[i],i);
								} 
							}else{ // HASH
								$H(opts).each(function(elm){
									field.options[field.options.length] = new Option(elm.value,elm.key);
								});
							}
						}else if (e[0] == 'script') {
							eval(e[1]);
						}else if (e[0] == 'source') {
							$(e[1].id).src = e[1].source;
						}
					}); // each
				} // if r.AX_TASKS
				
				
				if (callback != undefined) callback(r.AX_RESULT);			
			
			} // onSuccess
		});  // AjaxRequesst + Callback
		
	} // processAjax
});
