/**
 *  Js Page      : ajax.js
 *  Author(s)    : Nikhil Sinha
 *  Creation Date: Feb 20, 2008
 *  Functionality: Provide helper functions for AJAX.
 *  Dependencies : N/A
 *  Copyright    : P&G
 *  Modifications: <Author> 	<Date> 			<Description of Modification>
 */


/**
 * This is the core function which updates an element with the values(html code) returned from the url.
 */
  var SimpleRequest = function(targetElementId, url, method, parameters) {  
	var targetElement = $(targetElementId);  
	if (targetElement == null) {  
		throw 'Target element is null!';
	}  
	if (url == null) {  
		throw 'URL has to be provided';
	}  
	if (method == null) {  
		method = 'get';  
	} else if (method != 'get' && method != 'post') {  
		throw 'Method should be get or post';   
	}  
	var myAjax = new Ajax.Updater(  
		{ success: targetElement },   
		url,   
		{   
			method: method,  
			parameters: parameters,   
			onFailure: function(request) {  
				new HandleFailure(targetElementId);
			},
			onLoading: function(request) {  
				new HandleLoading(targetElementId);
			},
			onComplete: function(request) {  
				new HandleComplete(targetElementId);
			},
			evalScripts: true  
		}
	);  
};  

/**
 * This function should be called on the bottom of the page specifing the formElementId.
 * This will submit the form using Ajax and replace the form with the server response.
 */
function formRequest(formElementId) {  
	Event.observe(formElementId, 'submit', handleSubmitEvent, true);  
}  

/**
 * This is a handler used by the formRequest method.
 */
function handleSubmitEvent(event) {  
	var formElement = Event.element(event); 
	Form.serializeElements( formElement.getInputs('text') ) 
	if (formElement.tagName.toLowerCase() != 'form') {  
		throw 'Element ' + formElement + ' is not a FORM element!';  
	}  
	var method = formElement.method;  
	if (method == null) {  
		method = 'get';  
	}  
	var url = formElement.action;  
	if (url == null) {  
		throw 'No action defined on ' + formElement;  
	}  
	try {  
		Event.stop(event);  
		new SimpleRequest(formElement.parentNode.id, url, method, Form.serialize(formElement));
	} finally {  
		return false;  
	}  
}

/**
 * This can be used to provide the page specific functionalities for the loading feature.
 */
var HandleLoading = function(id){
	try{
		eval('L_'+id+'()');
	} catch(e){}
};

/**
 * This can be used to provide the page specific functionalities to notify the ajax response completion.
 */
var HandleComplete = function(id){
	try{
		eval('C_'+id+'()');
	}catch(e){}
};

/**
 * This can be used to provide the page specific functionalities to notify the failure/ server error.
 */
var HandleFailure = function(id){
	try{
		eval('F_'+id+'()');
	}catch(e){}
};


