/**
 * Ajax Library
**/
var AjaxLoader = {
	attach: function (id, event , action){
		e = $(id);
		if (e) eval("e."+event+" = function(){"+action+"};");					
	},
	formSubmit: function (formElement, options){
		var formElement = $(formElement);
		encodedForm = FormTools.encode(formElement.id);
		//Set options
		options.requestVars = encodedForm;
		options.url = formElement.action;
		
		//Check if there are extra parameters to add into the requestVariable
		if (options.parameters){
			var parameters = new Array();
			for(param in options.parameters){
				paramVal = options.parameters[param];
				parameters.push(param+'='+encodeURIComponent(paramVal));
			}
			parameters = parameters.join('&');
			options.requestVars += '&'+parameters;
		}
		//Run our ajax
		new Ajax(options);
	}, 
	feedbackAnimation: function (element,state){
		var e = $(element);
		var className = 'feedBack';
		
		//For the log process wait
		if (element == 'contentWrapper'){
		 	className = 'feedBackLogProcess';
		}
		
		if (state == 'processing'){
			e.className = className;
			if (element != 'contentWrapper'){
				e.style.filter = 'alpha(opacity=50)';
				e.style.opacity = '0.8';	
			}
		} else if (state == 'ready'){
			if (e){
				e.className = '';
				e.style.filter = '';
				e.style.opacity = '1';
			}
		}
	}
}

var AjaxRunner = {
	getFunc : function(AjaxObj){
		return(function(){AjaxObj.send();});
	}
}

/**
 * The Ajax Object
 * @param obj myParameters 
 */
var Ajax = function(myParameters){
	this.completedReadyState = false;
	this.request = null;
	this.requestVars = null;
	this.intervalId = null;
	this.busy = false;
	
	this.options = {
		url: null,
		method: 'post',
		requestVars: null,
		async: true,
		period: false,
		feedbackFunction: null,
		feedbackElement: null,
		updateElement: null,
		onReadyState: 'onReadyState'
	};
	this.init();
	this.loadParameters(myParameters);	
	if (this.options.period == false){
		this.send();
	} else {
		this.send();
		var myFunc  = AjaxRunner.getFunc(this);
		this.intervalId = setInterval(myFunc, this.options.period);
	}
	
	return false;
};

Ajax.prototype = {
	init: function (){
	    try { this.request = new ActiveXObject("Msxml2.XMLHTTP");  return 1; } catch (e) {}
	    try { this.request = new ActiveXObject("Microsoft.XMLHTTP"); return 1; } catch (e) {}
	    try { this.request = new XMLHttpRequest( ); return 1; } catch(e) {}	
	    alert("XMLHttpRequest not supported");
	},
	loadParameters: function (myParameters){ //Initialises the options from creation
		for (var property in myParameters){
			prop = this.options[property] = myParameters[property] || this.options[property];
		};
	},
	send : function (){
		
		if (this.busy) return false;
		
		if (this.options.method == 'post'){			
			this.request.open('POST', this.options.url, this.options.async);
			this.request.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');			
		} else {
			randomInt = parseInt(Math.random()*999999);
			// add random number to URL to avoid cache problems
			var intervalId = this.intervalId != null ? '&jsIntervalId='+this.intervalId : '';
			var url  = this.options.url+"&rand="+randomInt+intervalId;
			this.request.open('GET', url, this.options.async);
		}
		
		var self = this;	
		
		this.request.onreadystatechange = function(){
			self.onReadyState.call(self);
		}
		
		//Send request 
		if (this.options.method == 'get'){
			this.request.send(null);
		} else {
			this.request.send(this.options.requestVars);
		}
		this.busy = true;
		//Check if theres a feedback function and a feedback element
		if(this.options.feedbackElement != null && this.completedReadyState == false){	
			eval(this.options.feedbackFunction+'(\''+this.options.feedbackElement+'\',\'processing\');');			
			this.completedReadyState = true;
		}
	},
	onReadyState: function (){
		var readyState = this.request.readyState;
		if (readyState == 4){
			//Check if theres a feedback function and a feedback element
			if(this.options.feedbackElement != null){
				eval(this.options.feedbackFunction+'(\''+this.options.feedbackElement+'\',\'ready\');');
			}
			if(this.request.status == 200 || this.request.status == 0) {				
				
				if (this.options.updateElement != null){
					 mye = $(this.options.updateElement);
					 if (mye){
					 	mye.innerHTML = this.request.responseText;
					 	this.evaluateJs();
					 }
				}
				this.busy = false;
	        } else {
	            alert("Error: " + this.request.statusText);
	        }
	        this.cleanUp();
		} 
	},
	evaluateJs: function(){
		if(scripts = this.request.responseText.match(/<script[^>]*?>[\S\s]*?<\/script>/g)){
			for (i =0; i < scripts.length; i++){
				script = scripts[i];
				eval(script.replace(/^<script[^>]*?>/, '').replace(/<\/script>$/, ''));
			}
		}
	},
	cleanUp: function(){
		if (this.period == false){
			this.request = null;	
		}
	}
}



/**
 * Generic form tools. Mainly used to encode the form so it can be submitted via ajax
 */
var FormTools = {
	/**
	 * Encodes the form
	 */		
	encode: function (form){
		var encodedElements = new Array();
		form = $(form);
		if (!form) return '';
		//Iterate through the form elements
		for (var i = 0; i < form.elements.length; i++){			
			enc = FormTools.encodeElement(form.elements[i]);
			if (typeof enc == 'string'){
				encodedElements.push(enc);
			}
		}
		
		encodedString = encodedElements.join('&');
		return(encodedString);
		
	},
	/**
	 * Encodes the element
	 */
	encodeElement: function(element){
		//check the type
		var ret = false;
		eType = element.type;
		
		if (eType == 'checkbox'){
			ret = FormTools.encodeCheckboxRadio(element);				
		} else if (eType == 'select-multiple'){
			
		} else {
			ret = FormTools.encodeSimple(element);
		}
		return ret;	
	},
	
	/**
	 * Encode simple fields such as text, textarea, hidden, 
	 */
	encodeSimple: function (element){
		ret = false;
		if (element.name){
			ret = element.name + '=' + encodeURIComponent(element.value);
		}
		return ret;
	},
	encodeCheckboxRadio: function (element){
		ret = false;
		if (element.checked){
			ret = element.name + '=' + encodeURIComponent(element.value);
		}
		return ret;
	}
}

/**
 * $(e) - get document element by id.
 * @param string - the name of the id
 * @return element
 */
$ = function (e){
	var ret  = false;
	
	if (typeof e == 'string'){
		ret = document.getElementById(e) || false;
	} else if (typeof e == 'object'){
		ret = e;
	}
	return ret;
}