var AjaxArgs = Class.create();
AjaxArgs.prototype = {
	url: '',
	options: {},
	commandName: '',
	commandArg: '',
	postValues: '',
	IncludeViewState: false,
	serializedForm: '',
	onValidationFailure: null,
	initialize: function(url, options) {
		this.url = url;
		this.options = options;
		this.commandName = null;
		this.commandArg = null;
		this.postValues = null;
	},
	AddPostValue: function(name, value) {
		var val = "";
		if (this.postValues != '') {
			val = "&";
		}
		val += name + "=" + value;
		this.postValues += val;
	},
	SerializeForm: function(frm) {
		this.serializedForm = Form.serialize(frm);
	}
};

var _loading = "loading";
GlobalAjaxHandlers = {
	onCreate: function() {
		if ($(_loading)) {
			Element.show(_loading);
		}
	},
	onComplete: function() {
		if ($(_loading)) {
			if (Ajax.activeRequestCount == 0) {
				Element.hide(_loading);
			}
		}
	}
};

Ajax.Responders.register(GlobalAjaxHandlers);

FTAjax = {
    ExecuteAction: function(action, args, el) {
        var form = $('aspnetForm');
        alert('FTa');
        if (args.parameters) {
            args.parameters.XHR_ACTION = action;
            if (args.parameters.Controller) {
                args.parameters.XHR_CONTROLLER = args.parameters.Controller;
            }
        }
        else {    
		    Object.extend(args, {'parameters': {'XHR_ACTION': action}});
		}
		
		if (el) {
			var elem = $(el);
			if (elem) {
				_loading = "loading_" + elem.id;
				var loading_img = "<img id='" + _loading + "' src='/public/images/loading.gif' alt='loading...' class='loading-image' style='display:none' />";
				new Insertion.After(elem, loading_img);
		        Object.extend(args, {onComplete: function(){$(_loading).remove();}});
		    }
		}		
		
        return form.request(args);
    },
	ExecuteAjaxRequest:function(ajaxArgs, el) {
		this.loading(ajaxArgs, el);
		return this.AjaxRequest(ajaxArgs);
	},
	AjaxRequest:function(ajaxArgs) {
		this.SetArgs(ajaxArgs);
		return new Ajax.Request(ajaxArgs.url, ajaxArgs.options);
	},
	ExecuteAjaxUpdater:function(container, ajaxArgs, el) {
		this.loading(ajaxArgs, el);
		this.SetArgs(ajaxArgs);
		return new Ajax.Updater(container, ajaxArgs.url, ajaxArgs.options);
	},
	ExecuteAjaxPoll:function(ajaxArgs) {
		return new Ajax.Poll(ajaxArgs);
	},
	SetArgs:function(ajaxArgs) {
		if (ajaxArgs.options.method == "post") {
			var args = "__EVENTTARGET=AjaxCommand&";
			args += "__EVENTARGUMENT=" + ajaxArgs.commandName;
			args += "&COMMAND_NAME=" + ajaxArgs.commandName;
			if (ajaxArgs.commandArg != null) {
				args +=	"&__AJAXARGUMENT=" + ajaxArgs.commandArg;
				args += "&COMMAND_ARG=" + ajaxArgs.commandArg;
			}
			if (ajaxArgs.postValues) {
				//attach to the args being sent back in the post
				args += "&" + ajaxArgs.postValues;
			}
			if (ajaxArgs.serializedForm == '') {
				//we only want to include __VIEWSTATE if the form has not been serialized
				//else, we would have two __VIEWSTATE items
				if (ajaxArgs.IncludeViewState) {
					var viewstate = document.getElementsByName('__VIEWSTATE');
					if (viewstate.length > 0) {
						args += "&__VIEWSTATE=" + $F(viewstate[0]);
					}
				}
			}
			else {
				//attached the serialized form
				args += "&" + ajaxArgs.serializedForm;
			}
			var hff = document.getElementsByName('hff');
			if (hff.length > 0) {
				args += "&hff=" + $F(hff[0]);
			}
			//Add form elements to the body because we are posting back to ourselves
			Object.extend(ajaxArgs.options, {postBody: args});
		}
		
		if ( ajaxArgs.onValidationFailure && ajaxArgs.options.onSuccess){
			// sub our internal onSuccess handler so we can check for the onValidationFailure event
			this.onSuccessCallBack = ajaxArgs.options.onSuccess;
			this.onValidationFailure = ajaxArgs.onValidationFailure;
			ajaxArgs.options.onSuccess = this.FTAjax_onSuccess.bind(this);
		}		
	},
	
	onSuccessCallBack:null,
	onValidationFailure:null,
	
	FTAjax_onSuccess: function(response, json){
		if (this.onSuccessCallBack){
			var msg = response.getResponseHeader("X-ValidationFailure");
			if (msg != null && msg.length > 0){
				this.onValidationFailure(response, json);
			}
			else{
				this.onSuccessCallBack(response, json);
			}
			
		}
	},
	
	loading: function(ajaxArgs, el) {
		if (el) {
			var elem = $(el);
			if (elem) {
				_loading = "loading_" + elem.id;
				var img = "<img id='" + _loading + "' src='/public/images/loading.gif' alt='loading...' class='loading-image' style='display:none' />";
				new Insertion.After(elem, img);

				Object.extend(ajaxArgs.options, {onComplete: function(){Element.remove(_loading);}});
			}
		}
	},
	evalResponse: function(resp) {
		return eval("(" + resp.responseText + ")");
	}
}

Ajax.Poll = Class.create();
Ajax.Poll.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(ajaxArgs) {
	this.ajaxArgs = ajaxArgs;
	this.ajaxArgs.showProcessingImage = false;
    this.setOptions(this.ajaxArgs.options);
    this.onComplete = this.ajaxArgs.options.onComplete;

    this.frequency = (this.ajaxArgs.options.frequency || 2);
    this.decay = (this.ajaxArgs.options.decay || 1);

    this.ajaxTransport = {};

    this.start();
  },

  start: function() {
	this.cancel = false;
    this.ajaxArgs.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
	this.cancel = true;
    this.ajaxArgs.options.onComplete = undefined;
    this.ajaxTransport.onComplete = undefined;
    if (this.timer) {
		clearTimeout(this.timer);
    }
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.ajaxArgs.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.ajaxArgs.options.decay : 1);

      this.lastText = request.responseText;
    }
    if (! this.cancel) {
		this.timer = setTimeout(this.onTimerEvent.bind(this),
		this.decay * this.frequency * 1000);
    }
  },

  onTimerEvent: function() {
	this.ajaxTransport = FTAjax.AjaxRequest(this.ajaxArgs);
  }
});
