/**
 * @author Tyler Gaw <tylerg@arc90.com>
 *
 * Javascript document for the Registration portion of GradeGuru.
 *
 */


$(document).ready(function()
{
	PrepareFormSwitches();
	PrepareFormChoiceToggles();
	PrepareFormSubmissions();
	
	/**
	 * Initialize header FB connect link
	 */
	$('#nav-facebook a').click(function(){
		FB.Connect.requireSession(FBOnloginHandler); 
		return false;
	});
	
	/**
	 * Temporary form status errors
	 */
	$('#form-status.error, .feedback').hide();
	
	/**
	 * Anything that needs to happen after the form content has loaded throw in here
	 *
	 */
	$().bind('cbox_complete', function() {
		PrepareFormSwitches();
		PrepareFormChoiceToggles();
		PrepareExternalLinks();
		PrepareFormSubmissions();
		
		$('a.tooltip[title]').hovertip();
		
		/**
		 * Temporary form status errors
		 */
		$('#form-status.error, .feedback').hide();
	});
	
	/**
	 * Prepare the signup modal link
	 */
	var opts = getCreateModalOpts();
	$('#nav-signup a, #callout-message a').colorbox(opts, RegisterModalCallback);

	
	/**
	 * Prepare the login modal link
	 */
	var opts = getLoginModalOpts();
	$('#nav-login a').colorbox(opts, RegisterModalCallback);
});


/**
 *
 */
var DisplayFormErrors = function()
{
	$('#form-status, .feedback').show();
	$.fn.colorbox.position(580, 620, 100);
	$('#cboxLoadedContent').css('height', 585);
};


/**
 * The forms have a couple options that can be toggled on/off, etc.
 * Set those links up
 */
var PrepareFormChoiceToggles = function()
{
	/**
	 * KLUDGE
	 */
	$('#login-manual').hide();
	$('#login-manual-trigger').click(function()
	{

		if($(this).hasClass('active'))
		{
			$(this).removeClass('active');
		}
		else
		{
			$(this).addClass('active');
		}
		
		$('#login-manual').toggle();
		
		return false;
	});
	
	
	/**
	 * University/Personal email address switch
	 */
	var emailChoices = ['create-email-parent', 'create-uni-email-parent'];
	$('#' + emailChoices[0]).hide();
	
	$('.email-type-switch').click(
		function()
		{
			jQuery.each(emailChoices, 
				function(i)
				{
					$('#' + this).toggle();
				}
			);
			return false;
		}
	);
};


/**
 * Each for has a link to the other. Prepare those links to open the correct form
 */
var PrepareFormSwitches = function()
{
	var switchId = $('.form-footer-switch a').attr('id');
	var opts = {};

	/**
	 * Determime which window opts we need
	 */
	switch(switchId)
	{
		case 'switch-create':
			opts = getCreateModalOpts();
			break;
		case 'switch-login':
			opts = getLoginModalOpts();
			
	}
	
	$('.form-footer-switch a').colorbox(opts, RegisterModalCallback);
	
	/**
	 * Forgot/Remembered password switches
	 */
	var forgotOpts = getForgotPassModalOpts();
	$('#link-forgot-password').colorbox(forgotOpts, RegisterModalCallback);
	
	var rememberOpts = getLoginModalOpts();
	$('#link-remember-password').colorbox(rememberOpts, RegisterModalCallback);
};


/**
 * Prepare form submissions when colorbox is complete
 */
var PrepareFormSubmissions = function()
{
	/**
	 * This is placeholder, it's no good
	 */
	$('#form-create-account').submit(
		function()
		{
			DisplayFormErrors();
			return false;
		}
	);
	 
	 
	 /**
	  * Handle login modal form submit
	  * 	By Marshall
	  */
	 $(function(){
			var options = {
				url: '/secured/ggModalLogin.do?action=modalLogin',
				async: false,
				type: 'POST',
				dataType: 'json',
				error: function(xhrData){
					alert('There was an error submitting the form.');
				},
				success: function(data, textStatus){
					
					if(data.ajaxResponseStatus == 'errors'){ //errors were returned
						//TODO display errors related to form validation
						//$('#loginFormErrorMessageDiv').html(data.Errors[0]);
						alert('login errors ' + data.Errors[0]);
					} else { //success
						alert('login success');
						//TODO handle in process login if it was specified
						window.location='/home.do'; //default forward
					}
				}
			};
			$('#form-login').ajaxForm(options);
		});
	 
	 /**
	  * Handle registration modal form submit
	  * 	By Marshall
	  */
	 $(function(){
			var options = {
				url: '/secured/ggRegistrationModalAction.do?action=modalRegistration',
				async: false,
				type: 'POST',
				dataType: 'json',
				error: function(xhrData){
					alert('There was an error processing your regisration.');
				},
				success: function(data, textStatus){
					alert('callback registration modal ' + data.ajaxResponseStatus);
					if(data.ajaxResponseStatus == 'errors'){ //errors were returned
						//TODO handle validation errors
						//$('#registrationModalMessageDiv').html(data.Errors[0]);
						alert('Errors ' + data.Errors[0]);
					} else { //success
						//TODO handle in process login if it was specified
						window.location='/viewRegistrationThanksPage.do'; //default forward
					}
				}
			};
			$('#form-create-account').ajaxForm(options);
	});
	 
	 /**
	  * Handle registration integration form submit
	  * 	By Marshall
	  */
	 $(function(){
		var options = {
			url: '/secured/registrationIntegration.do?action=integrationRegistration',
			async: false,
			type: 'POST',
			dataType: 'json',
			error: function(xhrData){
				alert('There was an error processing your regisration.');
			},
			success: function(data, textStatus){
				//alert('callback registration modal ' + data.ajaxResponseStatus);
				if(data.ajaxResponseStatus == 'errors'){ //errors were returned
					//TODO handle validation errors
					//$('#registrationModalMessageDiv').html(data.Errors[0]);
					alert('Errors ' + data.Errors[0]);
				} else { //success
					//TODO handle in process login if it was specified
					window.location='/viewRegistrationThanksPage.do'; //default forward
				}
			}
		};
		$('#form-registration-integration').ajaxForm(options);
	});
};


/**
 * Retrieve the options for login colorbox
 *
 * @param height - [optional] height that will be used for the initial and final height
 * @return opts  - options object to be used the modal box
 */
var getLoginModalOpts = function(height)
{
	var loginWidth = 580;
	var loginHeight = (height != null) ? height : 315;
	
	return opts = {
		initialWidth: loginWidth, initialHeight: loginHeight, width: loginWidth, height: loginHeight 
	};
};


/**
 * Retrieve the options for create colorbox
 *
 * @param height - [optional] height that will be used for the initial and final height
 * @return opts  - options object to be used the modal box
 */
var getCreateModalOpts = function(height)
{
	var signUpWidth = 580;
	var signUpHeight = (height != null) ? height : 570;
	
	return opts = {
		initialWidth: signUpWidth, initialHeight: signUpHeight, width: signUpWidth, height: signUpHeight 
	};
};


/**
 * Retrieve the options for forgot pass colorbox
 *
 * @param height - [optional] height that will be used for the initial and final height
 * @return opts  - options object to be used the modal box
 */
var getForgotPassModalOpts = function(height)
{
	var signUpWidth = 580;
	var signUpHeight = (height != null) ? height : 315;
	
	return opts = {
		initialWidth: signUpWidth, initialHeight: signUpHeight, width: signUpWidth, height: signUpHeight 
	};
};


/**
 * Method to be called after each registration modal has been created
 */
var RegisterModalCallback = function()
{
	/**
	 * Be sure that FB is initialized
	 */
	FB.init($FBKey, $FBXD);
	
	/**
	 * FB connect button for all modals
	 */
	$('#fb-option a').click(function(){
		FB.Connect.requireSession(FBOnloginHandler); 
		return false;
	});
	
	/**
	 * Retrieve and hide the elem associated with the current box
	 */
	var elem = $.fn.colorbox.element();
	$(elem).animate({ opacity:0.4 });
	
	
	/**
	 * Show the element after the box has closed
	 */
	$().bind('cbox_closed', function() {
		$(elem).animate({ opacity:1 });
	});
};


/**
 * Make an ajax request to the server with FB id
 * 
 */
var FBConnectedHandler = function()
{	
	var options = {
			url: '/secured/facebookLogin.do?action=facebookLogin',
			async: false,
			type: 'GET',
			dataType: 'json',
			error: function(xhrData) 
			{
				alert('There was an error connecting to Facebook.');
			},
			success: function(data, textStatus) 
			{
				if(data.ajaxResponseStatus == 'errors')
				{
					alert('Facebook Error ' + data.Errors[0]);
				} 
				else 
				{
					//TODO handle in process login if it was specified
					if(data.pageForward == 'integrate')
					{
						window.location='/viewIntegrationPage.do';
					} 
					else 
					{
						window.location='/home.do';
					}
				}
			}
		};
		
	$.ajax(options);
};


/**
 * Called when FB.requireSession is called
 * @see http://wiki.developers.facebook.com/index.php/JS_API_M_FB.Connect.RequireSession
 * @see http://wiki.developers.facebook.com/index.php/JS_API_M_FB.Connect.IfUserConnected
 *
 */
var FBOnloginHandler = function()
{
	FB.Connect.ifUserConnected(FBConnectedHandler, FBNotConnectedHandler);
};


/**
 * If an error occurs connecting to FB (not likely to happen)
 *
 */
var FBNotConnectedHandler = function()
{
	alert('FB not connected.');
	$('#loginModalMessageDiv').html('There was an error connecting to Facebook.');
};