/*globals window,document, navigator, UNT */
if (!window.UNT) {window.UNT = {};}

/*
* @param config object containing three properties:
* *mobile_prefix : prefix appended to the hostname.
* *mobile_url : mobile url to use for the redirection.
* *mobile_scheme : url scheme (http/https).
* *cookie_hours : number of hours the cookie needs to exist after redirection.
* *redirection_paramName : parameter to pass in the querystring of the URL to avoid the redirection (the value must be equal to "false").
*/
UNT.redirection_mobile = function(config) {

	// Helper function for adding time to the current date
	var addTimeToDate = function(msec) {

		// Get the current date
		var exdate = new Date();

		// Add time to the date
		exdate.setTime(exdate.getTime() + msec);

		//Return the new Date
		return exdate;

	};

	// Helper function for getting a value from a parameter in the querystring
	var getQueryValue = function(param) {

		if (!param) {
			return;
		}

		var querystring = document.location.search,
			queryStringArray = querystring && querystring.substring(1).split("&"),
			i = 0,
			length = queryStringArray.length;

		for (; i < length; i++) {
			var token = queryStringArray[i],
				firstPart = token && token.substring(0, token.indexOf("="));
			if (firstPart === param ) {
				return token.substring(token.indexOf("=") + 1, token.length);
			}
		}

	};
				
	// Retrieve the User Agent of the browser
	var agent = navigator.userAgent.toLowerCase(),
	
		// Constants
		FALSE = "false",

		// configuration object
		config = config || {};
	
		// parameter to pass in the URL to avoid the redirection
		redirection_param = config.redirection_paramName || "mobile_redirect",
		
		// prefix appended to the hostname
		mobile_prefix = config.mobile_prefix || "m",
		
		// new url for the mobile site domain 
		mobile_url = config.mobile_url,
		
		// protocol for the mobile site domain 
		mobile_protocol = config.mobile_scheme ?
							config.mobile_scheme + ":" :
								document.location.protocol,
		
		// URL host of incoming request
		host = document.location.host,

		// value to avoid the redirection
		queryValue = getQueryValue(redirection_param),

		// Compose the mobile hostname (mobile_url) or (mobile_prefix)
		mobile_host = mobile_url ||
						(mobile_prefix + "." + 
							(!!host.match(/^www\./i) ?
								host.substring(4) : 
									host)),

		// Expire cookie
		cookie_hours = config.cookie_hours || 1,

		// Check if the UA is a mobile one.
		isUAMobile =!!(agent.match(/(android|avantgo|blackberry|blazer|elaine|hiptop|iPod|iPhone|iPod|iPad|kindle|midp|mmp|mobile|o2|opera mini|palm|palm os|pda|plucker|pocket|psp|smartphone|symbian|treo|vodafone|wap)/i));

	// Check for a mobile page.
	// querystring there is a parameter to avoid the redirection
	// Set a variable in the sessionStorage or in the cookie)
	if (document.referrer.indexOf(mobile_host) >= 0 || queryValue === FALSE ) {

		if (window.sessionStorage) {
			window.sessionStorage.setItem(redirection_param, FALSE);
		} else {
			document.cookie = redirection_param + "=" + FALSE + ";expires="+
								addTimeToDate(3600*1000*cookie_hours).toUTCString();
		}
	}

	// Check if the sessionStorage contain the parameter
	var isSessionStorage = (window.sessionStorage) ? 
							(window.sessionStorage.getItem(redirection_param) === FALSE) :
								false,
		
		// Check if the Cookie has been set up
		isCookieSet = document.cookie ? 
						(document.cookie.indexOf(redirection_param) >= 0) :
							false;

	// Check that User Agent is mobile, cookie is not set or value in the sessionStorage not present
	if (isUAMobile && !(isCookieSet || isSessionStorage)) {
		document.location.href = mobile_protocol + "//" + mobile_host;
	} 
};	
