/**
 * 
 * jQuery plugin
 * 
 * 
 * Usage:
 * Should be attached to any forms on the page and handle form interactivity
 * and ajax submission of data to db.
 * 
 * Options:
 * {Object} mainDelegate
 * reference to main ewOscarChallenge object
 * 
 * 
 */

(function($) {
		
	    
	    $.fn.oc_forms = function(options){
		var that = $(this);

		var settings = {
			mainDelegate: null
    	};
		
		$(this).find('input[type=submit]').click(function(e){ if (!$(this).hasClass("searchButton")) submitClick(e, $(this)); });
		
		$("form").submit(function(e) {			
			if($(this).find(".submit").length > 0 ) {
				$(this).find("input[type=submit]").click();				
				return false;
			}
		});
		
		// extend settings if options are specified	
    	if(options){
			$.extend(settings, options);
		} 

		////////////////////////////////////////////////////////////////////////////
		// METHODS
		////////////////////////////////////////////////////////////////////////////
		
		/**
		 * Delegate method for when user clicks on a submit btn
		 * Can perform different actions based on class name of anchor
		 *
		 * NOTE: ALL SUBMIT EVENTS NEED TO BE ENCLOSED IN THE FORM TAG
		 *
		 * @param {Object} e - mouse event
		 * @param {Object} obj - item clicked on
		 */
		function submitClick(e, obj){
			e.preventDefault();
			var service = $("input#service_action").val();
			var currentForm =obj.parents(".service_form");
			var data =  currentForm.serialize();

			// Can perform different actions based on assigned class name 
			// to initial submit input field
			if ($(obj).hasClass('oc-login')) {				
				DataRetriever.FetchData(service + '?' + data, null, 
							'json', new GenericResponseFilter(), loginComplete, handleError,currentForm);
							
				return false;
			
			}
			else if ($(obj).hasClass('oc-email')) {	
				DataRetriever.FetchData(service + '?' + data, null, 
							'json', new GenericResponseFilter(), emailComplete, handleError, currentForm);
							
			}
			else if ($(obj).hasClass('logout')) {				
				return false;
			}
			
			
		
		// handle clicks on newly formed submit anchors	
		return $(this);
  };
};
/* SETTINGS FORM SLIDE */

$.fn.clearInputs = function() {
	$(this).find(":text, textarea").val("");
};


function logoutComplete(e, href) {
	//tbd
}	

function loginComplete(obj)
{
	//tbd
}

function emailComplete(obj)
{
	
	$(".popup").fadeOut();
	$("#newsletter").clearInputs();
}

function handleError(e, form)
{
	$(form).find(".errors").remove();
	var errors = $('<div class="errors"><!--empty--></div>');
	errors.html(e.message);
	$(form).prepend(errors);
	//alert("ERROR: " + e.message);
}


function indicateRequestActivity()
{
	alert("...RETREIVING DATA...");
}

})(jQuery);