var AjaxWrapper = Class.create();
AjaxWrapper.prototype = {
	initialize: function(remoteURL,clazz,method,obj,options){
		this.remoteURL = remoteURL;
		this.obj = obj;
		this.clazz = clazz;
		this.method = method;
		this.request;

		if(options == null)
			options = new Array();
			
		this.options = options;
		this.ajaxRenderedIds = new Array();
		
		this.reRenderIds = options["reRenderIds"];
		this.callback = options["callback"];
		this.error = options["error"];
		this.ajaxRendered = (options["ajaxRendered"] != null?options["ajaxRendered"]:false);
		this.append = (options["append"] != null?options["append"]:false);
		this.prepend = (options["prepend"] != null?options["prepend"]:false);
		this.loader = (options["loader"] !=null?options["loader"]:false);
		
		if(this.reRenderIds != null && options["ajaxRendered"] == null)
			this.ajaxRendered = true;
		
		if(this.ajaxRendered)
		{
			if(this.reRenderIds != null)
			{
				//if its not an array
				if (this.reRenderIds.constructor.toString().indexOf("Array") == -1)
					this.ajaxRenderedIds[0] = this.reRenderIds;
				else
					this.ajaxRenderedIds = this.reRenderIds;
			}
			else
			{
				$$('.ajaxRendered').each(
				  function(elm)
				  {
					 this.ajaxRenderedIds[this.ajaxRenderedIds.length] = elm.id;
				  });
			}
		}
		
	},
	send: function()
	{
		if(this.loader != false)
		{
			var loaderImage = new Element('img', { 'class': 'loader', src: this.loader });
			for (var index = 0; index < this.ajaxRenderedIds.length; ++index)
			{
				if(!this.append && !this.prepend)
					$(this.ajaxRenderedIds[index]).update(loaderImage);
			}
		}
		
		var successFunction = this.onSuccess.bind(this);
		var failureFunction = this.onFailure.bind(this);
		
		this.request = new Ajax.Request(this.remoteURL, {
			parameters: 
			{
				funct:this.method, 
				data:JSON.stringify(this.obj), 
				clazz:this.clazz , 
				ajaxRendered:JSON.stringify(this.ajaxRendered), 
				reRenderIds:JSON.stringify(this.ajaxRenderedIds), 
				inputs:new Hash(Form.serializeElements($$('.ajax_input'),{getHash:true})).toJSON() 
			},
			onSuccess: successFunction,
			onFailure: failureFunction
		});
	},
	onSuccess: function(transport)
	{
		if(this.ajaxRendered == true) 
		{
			var response = JSON.parse(transport.responseText);
			var newHTML = response.renderedHTML;

			for (var index = 0, len = response.reRenderIds.length; index < len; ++index)
			{
				if(!this.append && !this.prepend)
					$(response.reRenderIds[index]).update(newHTML[index]);
				else if(this.append)
					$(response.reRenderIds[index]).insert(newHTML[index]);
				else if(this.prepend)
					$(response.reRenderIds[index]).insert({top:newHTML[index]});
			}
		}
		if(this.callback != null)
			this.callback(JSON.parse(transport.responseText).result);
	},
	onFailure: function()
	{
		if(this.error != null)
			this.error();
		else
			alert('Something went wrong...');
	}
};
