﻿/**
 * @fileOverview Redirection for mobile devices.
 * @author Wouter Bos
 * @since 1.0 - 2011-05-19
 * @version 1.1 - 2011-09-28
 */



/**
 * Redirects mobile devices once. After the first visit a cookie is set that
 * indicates that no more redirection should be done. The cookie is not deleted
 * after the end of the session.
 * 
 * @param {Number} screenWidth Screens with less pixels than the supplied value
 *    are considered mobile devices
 * @param {String} forwardUrl The URL all devices are redirected to
 * @author Wouter Bos
 * @example
 *   <script src="/Estate/Scripts/redirect.js" type="text/javascript"></script>
 *   <script type="text/javascript">
 *     mobileRedirect(960, 'http://MOBILE_URL');
 *   </script>
 */
function mobileRedirect(screenWidth, forwardUrl) {
	var redirectType = 'session'; // Possible values: 'cookie', 'session'
	var cookieName = 'mobileForwarded2';
	var cookieExpire = (1825*24*60*60*1000); // Expires after 5 years
	
	if (screen.width < screenWidth) {
		if (getCookieValue(cookieName) != '1') {
			var cookieString = cookieName + '=1' + createExpiresCookieString() + '; path=/';
			document.cookie = cookieString;
			document.location = forwardUrl;
		}
	};

	function getCookieValue(name) {
		var dc = document.cookie;
		var prefix = name + "=";
		var begin = dc.indexOf("; " + prefix);
		if (begin == -1) {
			begin = dc.indexOf(prefix);
			if (begin != 0) return null;
		} else {
			begin += 2;
		}
		var end = document.cookie.indexOf(";", begin);
		if (end == -1) {
			end = dc.length;
		}
		return decodeURIComponent(dc.substring(begin + prefix.length, end));
	}
	
	function createExpiresCookieString() {
		if (redirectType == 'cookie') {
			var date = new Date();
			date.setTime(date.getTime()+(cookieExpire));
			return '; expires=' + date.toGMTString();
		} else {
			return '';
		}
	}
}

