/*
 * Session-reentry methods,
 * needs cookiehandling.js
 */


function EmbSessionReentry() {
	var SESSION_REENTRY_PREFIX = "sr_";
	var SESSION_REENTRY_MODEL_SUFFIX = "_model";
	var PCN_TARGET_PATH_PREFIX = "pcntp_";
	var IS_FLIPFOCUS_PARAMETER = "isflipfocus";
	
	/**
	 * returns the appid extracted from a session-reentry-model cookie. Returns null if cookie with the given name
	 * is not referring to the given bmCode.
	 */
	var getAppId = function(cookieName, bmCode) {
		// check for correct session_reentry prefix and ends with session_reentry model suffix
		if ((cookieName.indexOf(SESSION_REENTRY_PREFIX) == 0) && 
			(cookieName.lastIndexOf(SESSION_REENTRY_MODEL_SUFFIX) == cookieName.length - SESSION_REENTRY_MODEL_SUFFIX.length)) {
				
			// check for cookie value (bmcode)
			if (bmCode == get_cookie(cookieName)) {
				// extract the middle part of the name (app id)
				return cookieName.substring(SESSION_REENTRY_PREFIX.length, cookieName.length - SESSION_REENTRY_MODEL_SUFFIX.length);
			}	
		}
		return null;
	};
	
	var getFlipfocusPath = function() {
		var newpath = location.pathname;
		// new extension
		newpath = newpath.replace(/\.html/, ".shtml");
		newpath += "?" + IS_FLIPFOCUS_PARAMETER + "=1";
		return newpath;
	};
	
	this.getUrl = function(appId) {
		// find the appropriate session reentry cookie
		return get_cookie(SESSION_REENTRY_PREFIX + appId);
	};
	
	this.redirectToFlipfocus = function(bmCode) {
		// only check if pcntargetpath is not contained in query
		if (location.search.indexOf(PCN_TARGET_PATH_PREFIX) != -1 || location.search.indexOf(IS_FLIPFOCUS_PARAMETER) != -1) {
			return;
		}
		
		// go through all cookies
		var cookies = get_cookie_list();
		for (var i in cookies) {
			var name = cookies[i];
			// find app id 
			var appId = getAppId(cookies[i], bmCode);
			if (appId) {
				// find the appropriate session reentry cookie
				var url = this.getUrl(appId);
				if (url) {
					// redirect to flipfocus (same page with different extension and additional parameter to disable caching)
					location.href = getFlipfocusPath();
				}
			}	 
		}
	};
	
}

