/* == Refer a Friend Form Javascript == */
/**
 * A ShareFriend object
 *
 * @param string saveCallbackFunction	a callback function (or function name) to utilise when saving the share friend data
 * @param string closeCallbackFunction	a callback function (or function name) to utilise when closing the share friend hover
 */
var ShareFriend = function( saveCallbackFunction, closeCallbackFunction )
{
	var _saveCallbackFunction;
	var _closeCallbackFunction;

	/**
	 * @param integer _referralFields the number of referral fields on the form
	 */
	var _referralFields = 4;


	/**
	 * Initialisation
	 *
	 * @param string saveCallbackFunction	a callback function (or function name) to utilise when saving the share friend data
	 * @param string closeCallbackFunction	a callback function (or function name) to utilise when closing the share friend hover
	 */
	this.init = function( saveCallbackFunction, closeCallbackFunction )
	{
		_saveCallbackFunction = saveCallbackFunction;
		_closeCallbackFunction = closeCallbackFunction;
	}

	/**
	 * Displays the hover for the refer friends form
	 */
	this.show = function()
	{
		var self = this;

		$('#hoverContainer').load('/share/friends/hover/', function()
		{
			// Center the container using the jquery.center plugin
			// http://andreaslagerkvist.com/jquery/center/
			//$("#hoverContainer").center();
			centerPanel($("#hoverContainer"));

			// Fade in the container for the form
			$('#hoverContainer').fadeIn(1200);

			// On submit, save the data via an ajax submission if the form is valid.
			// Then use javascript to send the response to flash.
			$('#shareFriend').submit(function()
			{
				try
				{
					if( self.validate() == false )
					{
						return false;
					}
				}
				catch(e)
				{
					return true;
				}

				// Save the friends
				self.save();

				// Return false so the form won't be posted
				return false;
			});

			// Ensure the back button closes the hover
			$("input[name=btnBack], #btnClose").click( function()
			{
				self.close();
			});

			// Oninute tracking
			omnitureTracking.shareFriends();
		});
	}


	/**
	 * Closes the hover of the refer friends form
	 */
	this.close = function()
	{
		$('#hoverContainer').fadeOut(800, function()
		{
			$('#hoverContainer').empty();

			// Issue the callback function if exists
			if( typeof _closeCallbackFunction == 'function' )
			{
				_closeCallbackFunction();
			}
		});
	}


	/**
	 * Validates the share friends form
	 */
	this.validate = function()
	{
		var fieldErrors = new Array();
		var errorExists = false;
		var regexEmail = /^((\"[^\"\f\n\r\t\v\b]+\")|([\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/;

		for( var fieldNum = 1; fieldNum <= _referralFields; fieldNum++ )
		{
			var errorItem = null;

			fieldErrors['friend' + fieldNum + 'Name'] = false;
			fieldErrors['friend' + fieldNum + 'Email'] = false;

			// Validate the 'Name' field
			if( ($('#friend' + fieldNum + 'Email').val().length > 0) && ($('#friend' + fieldNum + 'Name').val().length == 0) )
			{
				fieldErrors['friend' + fieldNum + 'Name'] = 'Please enter a name';
				errorExists = true;
			}

			// Validate the 'Email' field
			if( ($('#friend' + fieldNum + 'Name').val().length > 0) && ($('#friend' + fieldNum + 'Email').val().length == 0) )
			{
				fieldErrors['friend' + fieldNum + 'Email'] = 'Please enter an email address';
				errorExists = true;
			}
			else if( ($('#friend' + fieldNum + 'Email').val().length > 0) && (regexEmail.test($('#friend' + fieldNum + 'Email').val()) == false) )
			{
				fieldErrors['friend' + fieldNum + 'Email'] = 'Please enter a valid email address';
				errorExists = true;
			}
		}

		if( errorExists == true )
		{
			// Update the error display and return failure.
			_updateErrorDisplay(fieldErrors);

			return false;
		}

		// No errors
		return true;
	}


	/**
	 * Save the referrals and then informs the flash that the action is completed.
	 */
	this.save = function()
	{
		$('#hoverContainer').fadeOut(800, function()
		{
			// Save the data using ajax
			var requestData = $('#shareFriend').serialize();

			$.post('/share/friend/ajax/', requestData, function(responseData)
			{
				if( typeof _saveCallbackFunction == 'function' )
				{
					_saveCallbackFunction(responseData);
				}

				// Omniture tracking
				omnitureTracking.shareFriendsSubmit();

			}, 'json');
		});
	}


	/**
	 * Updates the display of error messages in the form
	 *
	 * @param object fieldErrors	e.g. fieldErrors{ 'friend1Name' : false, 'friend1Email' : 'Please enter a valid email address' ... }
	 */
	function _updateErrorDisplay( fieldErrors )
	{
		for( var fieldId in fieldErrors )
		{
			error = fieldErrors[fieldId];

			if( error != false )
			{
				var htmlErrorDiv = '<div id="' + fieldId + '_errorDiv">'
				+ '<span class="error">' + error + '</span>'
				+ '<br/>'
				+ '</div>';

				if( $("#" + fieldId).parent().hasClass('errorCustom') == false )
				{
					$("#" + fieldId).parent().addClass('errorCustom');
					$("#" + fieldId).parent().addClass('error');
					$("#" + fieldId).after(htmlErrorDiv);
				}
				else
				{
					$("#" + fieldId + '_errorDiv').replaceWith(htmlErrorDiv);
				}
			}
			else
			{
				if( $("#" + fieldId).parent().hasClass('errorCustom') )
				{
					$('#' + fieldId + '_errorDiv').remove();
					$('#' + fieldId).parent().removeClass('error');
					$('#' + fieldId).parent().removeClass('errorCustom');
				}
			}
		}
	}

	// Initialise
	this.init(saveCallbackFunction, closeCallbackFunction);
}
