/*
 * Redirect manager api
 */

// (hide everything except the things we make public explicitly)

//-- public constants --
// symbolic names of cms pages


(function() {
var embRedirectManager = new EmbRedirectManager();

// redirect manager is a singleton
window.embGetRedirectManager = function () {
	return embRedirectManager;
};

})();

function EmbRedirectManager() {
	
	var LOGIN = 0; // this is private and no valid symbolic link

	// -- private constansts --
	var SELECTOR_REDIRECT = "redirect";
	var SELECTOR_SETCOOKIES = "setcookies";
	var SELECTOR_LOGIN = "login";
	var SELECTOR_UPDATEPROFILEREF = "updateprofileref";
	
	var PARAMETER_BMCODE = "bmcode";
	var PARAMETER_TARGETURL = "targeturl";
	var PARAMETER_SYMBOLIC_NAME = "symbolictarget";
	var PARAMETER_TOKEN1 = "token1";
	var PARAMETER_CURRENTURL = "currenturl";
	var PARAMETER_STATE = "state";
	var PARAMETER_FROMSECUREPAGE = "fromsecurepage";
	var PARAMETER_LAYER_NAME = "layername";
	var PARAMETER_ADD_PARAMS = "addparams";
	
	var COOKIE_PROFILEREF = "profile_ref"

	this.CONSTANTA = "huhu"; 
	
	var signonHandle;
	var currentHandle;
	var secureHost;
	var isCurrentUrlSecure;
	
	var getCmsRedirectPageUrl = function(symbolicName, params, isFromSecurePage, bmCode, layerName, targetUrl, state) {
		var url = currentHandle + "." + SELECTOR_REDIRECT + ".html?";
		url += PARAMETER_SYMBOLIC_NAME + "=" + symbolicName;
		url += "&" + PARAMETER_FROMSECUREPAGE + "=" + isFromSecurePage;
		
		if (bmCode) {
			url += "&" + PARAMETER_BMCODE + "=" + bmCode;
		} else if (symbolicName == EmbRedirectManager.CONFIGURATOR 
				||symbolicName == EmbRedirectManager.PRODUCT_ENTRY) {
			if (window.console && window.console.log) {
				window.console.log("*** missing bmCode in redirect ***");
			}
		}
		if (layerName) {
			url += "&" + PARAMETER_LAYER_NAME + "=" + layerName;
		}
		// onyl relevant for login
		if (targetUrl) {
			url += "&" + PARAMETER_TARGETURL + "=" + targetUrl;
		}
		// only relevant for login
		if (state) {
			url += "&" + PARAMETER_STATE + "=" + state;
		}
		// these are parameters which are given to the redirect target
		if (params || symbolicName == EmbRedirectManager.CURRENT) {
			var addParams = "";
			if (params) {
				for (var param in params) {
				  addParams += param+"="+encodeURIComponent(params[param]) + "&";
				}
			}
			if (symbolicName == EmbRedirectManager.CURRENT) {
				var query = window.location.search;
				if (query.length > 1) {
					query = query.substring(1);
					addParams += query;
				}
			}
			url += "&" + PARAMETER_ADD_PARAMS + "=" + encodeURIComponent(addParams);
		}

		return url;
	};
	
	/**
	 * the page which is requested here must return a 302 with header location
	 * set
	 */
	var redirectToCmsPage = function(symbolicName, params, bmCode, layerName, targetUrl, state) {
		location.href = getCmsRedirectPageUrl(symbolicName, params, isCurrentUrlSecure, bmCode, layerName, targetUrl, state);
	};
	
	
	var redirectToSignon = function(selector, params) {
		var url = secureHost + signonHandle + "." + selector + ".html?"
		for (var param in params) {
			url += param + "=" + encodeURIComponent(params[param]) + "&";
		}
		location.href = url;
	};
	
	// -- public methods --
	
	/**
	 * Redirects to the standard login page.
	 * 
	 * @param targetUrl
	 *            specifies the targetUrl to which the user is redirected after
	 *            an successfull login
	 * @param state
	 *            one of the predefined states: STATE_NORMAL, STATE_TIMEOUT or
	 *            STATE_NO_TOKEN
	 */
	this.redirectToLogin = function (targetUrl, state, layerName) {
		redirectToCmsPage(LOGIN, null, null, layerName, targetUrl, state);
	};
	
	/**
	 * Redirects to a standard cms page, which is specified by the symbolic name.
	 * 
	 * @param symbolicName
	 *            one of the predefined names: INFO_AND_OVERVIEW, the info and
	 *            overview page (bmCode is not evaluated); CONFIGURATOR, the
	 *            carconfigurator page for the given bmCode; PRODUCT_ENTRY the
	 *            productentry page for the given bmCode.
	 */
	this.redirectToCMSPage = function (symbolicName, bmCode, layerName, params, targetPath) {
		redirectToCmsPage(symbolicName, params, bmCode, layerName, targetPath);
	};
	
	/**
	 * Persists the profileRef in cookies for HTTP and HTTPs, afterwards redirect to the
	 * page specified by symbolicName.
	 * This method should only be called in HTTPs
	 */
	this.updateProfileRef = function (profileRef, symbolicName, bmCode, layerName, params) {
		if (!isCurrentUrlSecure) {
			alert("this method is only allowed in https pages!");
			return;
		}
		
		// set profileref cookie
		set_cookie(COOKIE_PROFILEREF, profileRef, undefined, "/", undefined, true);
		
		var updateProfileRefParams = new Object();
		updateProfileRefParams[PARAMETER_TARGETURL] = getCmsRedirectPageUrl(symbolicName, params, false, bmCode, layerName);
		updateProfileRefParams[PARAMETER_CURRENTURL] = currentHandle;
		redirectToSignon(SELECTOR_UPDATEPROFILEREF, updateProfileRefParams);		
	};	
	
	/**
	 * Performs login (correctly sets the tokens), afterwards redirect to the
	 * page specified by symbolicName.
	 * This method should only be called in HTTPs
	 */
	this.login = function (token1, symbolicName, bmCode, layerName, params) {
		var loginParams = new Object();
		loginParams[PARAMETER_TOKEN1] = token1;
		loginParams[PARAMETER_CURRENTURL] = currentHandle + ".html";
		loginParams[PARAMETER_TARGETURL] = getCmsRedirectPageUrl(symbolicName, params, false, bmCode, layerName);
		redirectToSignon(SELECTOR_LOGIN, loginParams);
	};
	
	this.init = function(_secureHost, _signonHandle, _currentHandle) {
		secureHost = _secureHost;
		signonHandle = _signonHandle;
		currentHandle = _currentHandle;
		
		if (location.protocol == "https:") {
			isCurrentUrlSecure = true;
		} else {
			isCurrentUrlSecure = false;
		}
	};
}



EmbRedirectManager.INFO_AND_OVERVIEW = 1;
EmbRedirectManager.CONFIGURATOR = 2;
EmbRedirectManager.PRODUCT_ENTRY = 3;
EmbRedirectManager.CURRENT = 4;
EmbRedirectManager.SHOWROOM = 5;
EmbRedirectManager.MYFAVORITE = 6;
EmbRedirectManager.SHOWROOM_CC = 7;

// states of the login page (equal to the selectors of the landing page)
EmbRedirectManager.STATE_NORMAL = "";
EmbRedirectManager.STATE_TIMEOUT = "ll2";
EmbRedirectManager.STATE_NO_TOKEN = "ll1";

//layer applications (type of layer within service)
EmbRedirectManager.LAYER_MYPROFILE = "LayerMyProfile";
EmbRedirectManager.LAYER_REGISTRATION_ADDED_VALUE = "LayerRegistrationAddValue";
EmbRedirectManager.LAYER_REGISTRATION = "LayerRegistration";
EmbRedirectManager.LAYER_FORGOTTEN_PASSWORD = "LayerLostPassword";
EmbRedirectManager.LAYER_SAVEDVEHICLES = "LayerSavedVehicles";
EmbRedirectManager.LAYER_OPT_OUT = "LayerOptOut";
