(function($){
	if (undefined == $) return console.error('reditor must be loaded after jQuery');
	
	// SO wrapper
	var redSo = {
		
		// Default Settings
		settings : {lang:'en', afterLoginUrl:'/', afterLogoutUrl:'/'},
		
		/**
		 * Customer logged in mode
		 */	
		loggedin	: function(customer)
		{
			// customer info
			var fn 			= customer.FirstName;
			var ln 			= customer.LastName;
			var currency 	= customer.currency;
			
			// Show the logged in elements, remove the rest
			$('[red-so-loggedout],[red-slo]').remove();
			$('[red-so-loggedin],[red-sli]').removeClass('hidden');

			// Populate DOM elements
			$('[red-so-cname]').text(fn + ' ' + ln);
			$('[red-so-fname]').text(fn);
			$('[red-so-lname]').text(ln);
			$('[red-so-cid]').text(customer.id);
			
			// Logout button event
			$('[red-so-logout]').click(function(e)
			{
				SO.model.Customer.logout({
					onSuccess : function()
					{
						location.href = redSo.settings.afterLogoutUrl;
					}
				});
			});
			
			// Balance listener
			$(document).bind('customerBalance.update', function (options, balance) {
				$('[red-so-cbalance]').text(AppData.currencySigns[currency]+balance);
			});
			
			// Session expired listener
			$(document).bind('spotoptionSession.expired', function () {
				location.href = redSo.settings.afterLogoutUrl;
			});
		},
		
		/**
		 * Customer logged in mode
		 */	
		loggedout	: function()
		{
			// Show the logged out elements, remove the rest
			$('[red-so-loggedin],[red-sli]').remove();
			$('[red-so-loggedout],[red-slo]').removeClass('hidden');
				
			// Login form
			$('[red-so-login]').submit(function(e)
			{
				e.preventDefault();
				SO.model.Customer.login({
					email	: $('[red-so-email]').val(),
					password: $('[red-so-pass]').val(),
					onSuccess : function()
					{
						location.href = redSo.settings.afterLoginUrl;
					},
					onFail : function(msg)
					{
						$('[red-so-loginerr]').text(msg).removeClass('hidden');
					}
				});
			});

			
			// Registration form
			$('[red-so-reg]').submit(function(e)
			{
				// Currently registration is via SO plugin, not needed yet.
				e.preventDefault();
			});
		},
		
		loaded	: function()
		{
			// Check for SpotOption global plugin, if it does not exist, nothing to do.
			if (undefined == SO) return;
			(SO.model.Customer.isLoggedIn())
				? redSo.loggedin(SO.model.Customer.currentCustomer)
				: redSo.loggedout();
		},
		
		init: function(settings)
		{
			redSo.settings = settings;
		}
	};
	
	
	
	// binds
	$(document).bind('spotoptionPlugin.ready', redSo.loaded);
	
	// globalize
	window.Reditor = redSo;
})(jQuery);