/**
 * @name         Genome Credits Toolbar controller
 * 
 * @uses        GenomeCredits
 * @Package      
 * @subpackage  
 * @author 		Jon Beebe
 * @category    interface
 * @access      Vortal Group Programming Team 
 * @version     1.0 
 * @since       30 April, 2010
 * @copyright   Vortal Group, 2010
 * 
 * Empowers the Credit toolbar
 * 
 * Responsible for handing the email form and all gui feedback
 */




// Our main toolbar object
var creditToolbarObjects = {};

// Objects responsible for defining behavior
creditToolbarObjects.button;
creditToolbarObjects.dropDown;

// Instances of our objects
creditToolbarObjects.$GoButton;
creditToolbarObjects.$MessageContainer;




// Initialize all objects
creditToolbarObjects.init = function(options) {
	
	// Create the Go button for the invite header
	creditToolbarObjects.$GoButton = creditToolbarObjects.button.CreateGoButton(
		'#go',
		{
			url:options.goButtonUrl,
			extraParams:'inviteAjax=true',
			onBeforeSend: function(action, XMLHttpRequest) {
				
				// Before we send this form let's be sure we are not asking for
				// the user's first and last name. If we are then do not send
				// the form until they have properly filled out both fields.
			
				var lastNameField = $('input[name=senderLastName]');
				
				// console.log(lastNameField);
				
				// If there is no last name field, or if exists and IS NOT
				// an empty string, then submit the form
				if( lastNameField.length == 0 || lastNameField.val() != '' ) {
					return true;
				}
				// Otherwise, expose the first/last name inputs to user
				else {
					creditToolbarObjects.$MessageContainer.slideDown(false);
					return false;
				}
				
			},
			onSuccess: function(action, data) {
			
				if(data.success) {
					//console.log('success');
					
					var successMessage = "You&rsquo;ve successfully invited " + data.emailAddresses.length + " friends";
					creditToolbarObjects.$MessageContainer.SetStateSuccess(successMessage);
					creditToolbarObjects.$MessageContainer.slideDown();
					
				}
				else {
					if(data.error != '') {
						//console.log("error: " + data.error);
					}
					creditToolbarObjects.$MessageContainer.SetStateError(data.error);
				}
				
				creditToolbarObjects.$MessageContainer.slideDown();
				
				// Clear the email input on success
				var parentForm = $(action.selector).closest('form');
				$('input[name=friends]', parentForm).val('');
				
			},
			onError: function(XMLHttpRequest, textStatus, errorThrown) {
			
				creditToolbarObjects.$MessageContainer.SetStateError(errorThrown);
				creditToolbarObjects.$MessageContainer.slideDown();
				
			}
		}
	);
	
	if(creditToolbarObjects.$GoButton) {
		creditToolbarObjects.$GoButton.init();
	}
	
	// Create the message dropdown that gives the user feedback
	creditToolbarObjects.$MessageContainer = creditToolbarObjects.dropDown.CreateMessageContainer(
		'#singe_friend_invite_response'
	);
	
	if(creditToolbarObjects.$MessageContainer) {
		creditToolbarObjects.$MessageContainer.init();
	}

}




// Our dropdown container
creditToolbarObjects.dropDown = {};

creditToolbarObjects.dropDown.CreateMessageContainer = function(selector, options){
	
	// If an item exists within the dom then proceed
	if($(selector).length > 0) {
		//console.log('CreateMessageContainer: "' + selector + '"');
	}
	else {
		return null;
	}
	
	var action = {};
	action.self = this;
	action.selector = selector;
	action.interval = null;     // the interval controlling the auto-hide
	
	action.defaults = {
		speed:500,             /* The speed of the up/down animation */
		autoHideDelay:5000
	};
	
	action.opts = $.extend(action.defaults, options);
	
	/**
	 * Slide the container down. By default this will auto-hide itself
	 * after a brief delay. Passing in false it will disable auto-hide
	 * 
	 * @param bool autoHide If false autoHide is disabled, True otherwise.
	 */
	action.slideDown = function(autoHide) {
		
		clearInterval(action.interval);
		
		slideDownResponse = function() {};
		if(autoHide !== false) {
			slideDownResponse = function() {
				
				action.interval = window.setInterval(function(action) {
					
					clearInterval(action.interval);
					action.slideUp();
					
				}, action.opts.autoHideDelay, action);
				
			};
		}
		
		$(action.selector).slideDown(action.opts.speed, slideDownResponse);
		
	}
	
	/**
	 * Slide the container up
	 * 
	 * @param object event An event object. Optional.
	 */
	action.slideUp = function(event) {
		
		clearInterval(action.interval);
		$(action.selector).slideUp(action.opts.speed);
		
		if(event) {
			event.stopPropagation();
			return false;
		}
		
	}
	
	/**
	 * Put the container in a successful state
	 */
	action.SetStateSuccess = function(message) {
		
		$('.inner_container', action.selector).
			removeClass('error').
			children('.error_message').css('display', 'none').end().
			children('.success_message').css('display', 'block').html(message);
		
	}
	
	/**
	 * Put the container in an error state
	 */
	action.SetStateError = function(message) {
		
		$('.inner_container', action.selector).
			addClass('error').
			children('.success_message').css('display', 'none').end().
			children('.error_message').css('display', 'block').html(message);
		
	}
	
	action.init = function() {
		
		$('button.dismiss', action.selector).click( action.slideUp );

	}

	return action;
	
}




// Our form submit button
creditToolbarObjects.button = {};

creditToolbarObjects.button.CreateGoButton = function(selector, options){
	
	// If an item exists within the dom then proceed
	if($(selector).length > 0) {
		//console.log('CreateGoButton: "' + selector + '"');
	}
	else {
		return null;
	}
	
	var action = {};
	action.self = this;
	action.selector = selector;
	
	action.defaults = {
		url:'',                      /* the url that this submits to */
		onSuccess:function() {},     /* success callback */
		onBeforeSend:function() {    /* before sending callback */
			return true; 
		},  
		onError:function() {}        /* error callback */
	};
	
	action.opts = $.extend(action.defaults, options);

	action.BeforeSend = function(XMLHttpRequest) {
		
		result = action.opts.onBeforeSend(action, XMLHttpRequest);
		
		// If the result was false then we are not ready to send the  form
		// so reset the button to its default state
		if(!result) {
			action.SetStateSuccess();
		}
		
		return result;
		
	};

	action.Error = function(XMLHttpRequest, textStatus, errorThrown) {
	
		action.SetStateError();
		
		action.opts.onError(XMLHttpRequest, textStatus, errorThrown);
		
	};

	action.Success = function(data, textStatus, XMLHttpRequest) {
		
		action.SetStateSuccess();
		
		if(data.success) {
			
			// do success code
        	
		}
		else {
		
			// do error code
			
		}
			
		// Call our success callback
		action.opts.onSuccess(action, data);
		
	};
	
	/**
	 * Put the container in a successful state
	 */
	action.SetStateSuccess = function() {
		
		$(action.selector).removeClass("progress");
		
	};
	
	/**
	 * Put the container in an error state
	 */
	action.SetStateError = function() {
		
		$(action.selector).removeClass("progress");
		
	};
	
	/**
	 * Put the container in a successful state
	 */
	action.SetStateProgress = function() {
		
		$(action.selector).addClass("progress");
		
	};
	
	/**
	 * Collect all input items from the button's parent form
	 * 
	 * @return string The url string to submit
	 */
	action.GatherData = function() {
		
		var form = $(action.selector).closest('form');
		var data = '';
		
		if(form.length > 0) {
			data = form.serialize();
		}
		
		if(action.opts.extraParams != '' && action.opts.extraParams != undefined) {
			data += '&' + action.opts.extraParams;
		}
		
		return data;
		
	};

	action.SelectorClick = function(event) {
		
		action.SetStateProgress();
		
		$.ajax({
			url        : action.opts.url, 
			dataType   : 'json',
			data       : action.GatherData(),
			beforeSend : action.BeforeSend,
			error      : action.Error,
			success    : action.Success
		});
			
		event.stopPropagation();
		return false;
		
	};

	action.init = function() {
		
		$(action.selector).closest('form').submit(action.SelectorClick);

	}

	return action;
	
};
