


/**
* Singleton class for Kick Apps Single Sign on (SSO) implementation
*/
var KickAppsManager = (function() {
	
	/**
	* Write debug statements to firebug console if it is open
	* @param {value} The value to write to the console
	*/
	var debug = function(value) {
		// MAKE SURE CONSOLE EXISTS AND WRITE VALUE
		window.console && console.log("[KickAppsManager] " + value);
	}
	
	/** All final constants used for Kick Apps Single Signon */
	KICKAPPS_CONSTANTS = (function() {
		var globals = {};
		
		/** The URL to the iFrame to use to invoke a single signon */
		globals.SINGLE_SIGNON_URL = "http://affiliate.kickapps.com/service/openCustomPage.kickAction";
		
		/** The query string parameter used to pass a Kick Apps Session Token */
		globals.PARAM_KICK_APPS_SESSION_TOKEN = "st";

		/** The query string parameter used to pass a Kick Apps Session Token */
		globals.PARAM_KICK_APPS_TRANSACTION_ID = "tid";
		
		/** The query string parameter used to pass a Kick Apps affiliate Site ID */
		globals.PARAM_KICK_APPS_AFFILIATE_SITE_ID = "asid";
		
		/** The jQuery DOM location where a login form submit button is expected */
		globals.DOM_LOGIN_SUBMIT_BUTTON = '#loginOffers input[name="login_submit"]';
		
		/** The jQuery DOM location where the iFrame to complete SSO should be appended */
		globals.DOM_IFRAME_APPEND_DESTINATION = "#footer";
		
		/** The URL for the rest call to start logging a user into KickApps */
		globals.KICK_APPS_USER_REST_URL = "/content/system/modules/com.dispatch.kickapps/rest/getKickappsUserTokens/index.jsp";
	
		/** The name of the cookie used to store information about the state of Single Sign On */
		globals.KICK_APPS_COOKIE_NAME = "KA_data";
		
		/** The value for the cookie when a Kick Apps Single Signon should be attempted */
		globals.COOKIE_STATE_LOGGING_IN = "logging-in"
		
		/** Accessor method for Kick Apps Constants 
		@param {valueName} The string name of a constant to return
		*/
		return { getValue : function(valueName) {
				debug("Attempting to read constant: " + valueName);
				debug("Value found: " + globals[valueName]);
				return globals[valueName];
			}
		}
	}());
	
	/** The affiliate Id */
	var affiliateId = "";
	
	/** The Kick Apps cookie for the current user */
	var kickAppsCookie = readCookie(KICKAPPS_CONSTANTS.getValue("KICK_APPS_COOKIE_NAME"));
	
	/**
	* Bind an event to the login form submit button which will write a cookie prior to the login attempt
	*/
	var startClickListener = function() {
	
		// LOG THE ATTEMPT TO SEARCH FIND 
		debug("Trying to setup a click event for login form submit button");
	
		// LOOK FOR A LOGIN FORM SUBMIT BUTTON AND BIND CODE ON CLICK
		jQuery(KICKAPPS_CONSTANTS.getValue("DOM_LOGIN_SUBMIT_BUTTON")).click(function() {

			// LOG THE CLICK OF THE SUBMIT BUTTON
			debug("Entering bind method for KickAppsManager on login form submit");
		
			// ERASE ANY PREVIOUS COOKIE RELATED TO THIS
			eraseCookie(KICKAPPS_CONSTANTS.getValue("KICK_APPS_COOKIE_NAME"));
			debug("Cookie Data Cleared");
			
			// SETUP A NEW COOKIE SAYING LISTENER WAS ENGAGED
			createCookie(KICKAPPS_CONSTANTS.getValue("KICK_APPS_COOKIE_NAME"), 
				KICKAPPS_CONSTANTS.getValue("COOKIE_STATE_LOGGING_IN"));
			debug("Updated Cookie Data: " + cookieData);
			
		});
		
		// LOG THE COMPLETION OF THE START CLICK LISTENER ROUTINE
		debug("Done configuring click event for login submit");
		
	}
	
	/**
	* Attempt a single signon to KickApps as the user recently went through a login process
	*/
	var attemptSingleSignon = function() {
	
		// LOG THE SINGLE SINGON ATTEMPT
		debug("Attempting to sign user in to KickApps");
		
		// MAKE AJAX CALL TO BEGIN KICK APPS SINGLE SIGNON
		jQuery.ajax({
			type: 'POST',
			url: KICKAPPS_CONSTANTS.getValue("KICK_APPS_USER_REST_URL"),
			data: 'data',
			dataType: 'JSON',
			jsonp: null,
            		jsonpCallback: null,
			success: function( payload ) {
			
				// LOG THE RESPONSE PAYLOAD
				debug("KickApps SingleSignOn Rest Call complete");
				debug(payload);
				
				// SEE IF A BAD PAYLOAD WAS RETURNED
				if ( payload == null ) {
				
					// LOG THE FAILED ATTEMPT TO LOGIN TO KICKAPPS
					debug("Attempt to login user to KickApps failed");

				} else {
				
					// LOG THE RETURNED SESSION TOKEN AND TRANSACTION ID
					debug("Kick Apps Session Token Returned: " + payload.sessionToken);
					debug("Kick Apps Transaction ID Returned: " + payload.transactionId);

					// CREATE AN IFRAME TO FINISH SSO WITH NEW CREDENTIALS
					var iframeUrl = KICKAPPS_CONSTANTS.getValue("SINGLE_SIGNON_URL") + "?" + 
						KICKAPPS_CONSTANTS.getValue("PARAM_KICK_APPS_AFFILIATE_SITE_ID") + "=" + affiliateId + "&" +
						KICKAPPS_CONSTANTS.getValue("PARAM_KICK_APPS_SESSION_TOKEN") + "=" + payload.sessionToken + "&" +
						KICKAPPS_CONSTANTS.getValue("PARAM_KICK_APPS_TRANSACTION_ID") + "=" + payload.transactionId;
				
					// CREATE SSO IFRAME TO FINISH LOGIN
					debug("KickApps SSO IFrame Source: " + iframeUrl);
					
					// ADD THE IFRAME TO THE FOOTER
					jQuery(KICKAPPS_CONSTANTS.getValue("DOM_IFRAME_APPEND_DESTINATION"))
						.append("<iframe src=\"" + iframeUrl + 
						"\" width=\"1\" height=\"1\" id=\"kickapps-sso\"></iframe>");

					// LOG THE COMPLETION OF THE SINGLE SIGNON PROCESS
					debug("Single signon completed");
					
					// IF ARRIVED FROM KICKAPPS, READ DESTINATION COOKIE
					var destination = readCookie("KA_SSO_Redirect");
						debug("Reading Redirect Cookie");
						debug("Redirect URL: " + destination);
					eraseCookie("KA_SSO_Redirect");
						debug("Redirect Cookie Deleted");
						
					// FUNCTION FOR REDIRECTING TO PREVIOUS KICKAPPS SITE	
					destinationGo = function() { window.location = destination; }
					
					// FUNCTION FOR INSERTING A FALLBACK LINK
					insertFallbackLink = function() {
						$('#message').append('<a href="'+destination+'">Click here for your destination</a>');
					}
					
					// IF THE KA_SSO_REDIRECT COOKIE EXISTS
					if ( ( destination != '' ) && ( destination != undefined ) ) {
						setTimeout('destinationGo()', 5500); 
						setTimeout('insertFallbackLink()', 5000); 
					}
				
				}
				
				// ERASE THE COOKIE AS EITHER LOGIN FAILED OR SSO COMPLETED
				eraseCookie(KICKAPPS_CONSTANTS.getValue("KICK_APPS_COOKIE_NAME"));
				
				// LOG THE DELETE OF THE KICK APPS COOKIE
				debug("KickApps cookie for SSO has been deleted");
				
			}
		});
	
	}
	
	/** All the public methods for this class attach here */
	var publicMethods = {};
	
	/**
	* Start the Kick Apps Manager for single Sign On
	* @param {asid} The Kick Apps affiliate ID to start the Kick Apps Manager for
	*/
	publicMethods.start = function(asid) {
	
		// LOG THE AFFILIATE SITE ID
		debug("Starting Kick Apps Manager with affiliate ID: " + asid);
	
		// STORE THE AFFILIATE SITE ID TO USE
		if(asid) {
			affiliateId = asid;
		}
		
		// START THE CLICK LISTENER FOR THE LOGIN PAGE
		startClickListener();
		
		// READ KICK APPS COOKIE
		debug("Current users Kick Apps cookie Data: " + kickAppsCookie);

		// CHECK TO SEE THAT A COOKIE IS DEFINED
		if (kickAppsCookie === undefined) {
		
			// LOG THE LACK OF A COOKIE;
			debug("No kick apps cookie currently exists for this user");
		
		} else {
		
			// A KICK APPS COOKIE EXISTS
			if(kickAppsCookie === KICKAPPS_CONSTANTS.getValue("COOKIE_STATE_LOGGING_IN") ) {
			
				attemptSingleSignon();
			
			}
		}	
	}

	/** Return the public methods */
	return publicMethods;

}());
