var mywedding = window.mywedding || {}
/*
 * Convenience methods for simple ajax requests.
 */
mywedding.ajax = {
	"timeout": 30000,
	
	/*
	 * Sends an ajax get request and automatically loads the response into the given element.
	 */
	"getIntoElement": function(url, params, element, callback) {
		this.contentRequest('GET', url + "?" + params, "", element, callback);
	},
	/*
	 * Sends an ajax post request and automatically loads the response into the given element.
	 */
	"postIntoElement": function(url, params, element, callback) {
		this.contentRequest('POST', url, params, element, callback);
	},
	/*
	 * Sends an ajax request using a form and automatically loads the response into the given element.
	 * The form's action and request method will be used in addition to its variables.
	 */
	"submitIntoElement": function(form, element, callback) {
		YAHOO.util.Connect.setForm(form);
		this.contentRequest(form.method, form.action, "", element, callback);
	},
	
	/**
	 * Initializes an ajax request using the given informtion.
	 */
	"contentRequest": function(method, url, params, element, callback) {
		var callback = {
			success: this.loadResponse,
			failure: this.handleFailure,
			scope: this,
			argument: [ element, callback ],
			timeout: this.timeout
		}
		YAHOO.util.Connect.asyncRequest(method, url, callback, params);
	},
	
	"loadResponse": function(o) {
		var resume = this.doCallback(o.argument[1], "beforeLoad");
		/*
		 * If the result of doCallback(o.argument[1], "beforeLoad"); is defined as false, do not insert loaded content into specified element
		 */ 
		if ("undefined" == typeof resume || resume) {
			var element = o.argument[0];
			if (typeof element == "string") {
				element = document.getElementById(element);
			}
			element.innerHTML = o.responseText;
		}
		this.doCallback(o.argument[1], "afterLoad");
	},
	"handleFailure": function(o) {
		var resume = this.doCallback(o.argument[1], "failure");
		// If the result of doCallback(o.argument[1], "failure") is defined as false, skip the default error alert
		if ("undefined" == typeof resume || resume) {
			alert("Unable to process request: " + o.statusText + " (" + o.status + ")");
		}
	},
	/**
	 * callback may be a function, or an object with the following methods optionally defined, "failure", "beoreLoad", "afterLoad"
	 * if callback.beforeLoad returns false - content will not be loaded into the specified element
	 * if callback.failure returns false, the default error status will not display
	 * callback.afterLoad does not effect standard behavior
	 */
	"doCallback": function(callback, event) {
		if ("undefined" == typeof callback) {
			return true;
		}
		if (typeof callback[event] == "function") {
			return callback[event]();
		}
		else if (typeof callback == "function") {
			return callback(event);
		}
	}
}