/*globals window,document, navigator, SA */
if (!window.CmpMobile) { window.CmpMobile = {}; }

/*
CmpMobile.Redirect ({
	cname : "Cookie name",
	mobile_url : "Mobile URL",
	cmin : "Cookie expiration in minutes"
});
*/
CmpMobile.Redirect = function(config) {

	// Helper function
	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;
	};

	// Retrieve the User Agent of the browser
	var agent = navigator.userAgent.toLowerCase();
	var param = config.cname || "CmpMobile";
	var mobile_url = config.mobile_url || '';
	var host = document.location.host;
	var cmin = config.cmin || 60;
	if (mobile_url == '')
		return;

	// Check if the UA is a mobile one (iphone, ipod, android, blackberry)
	var ismobile = !!(agent.match(/(iPhone|iPod|blackberry|android|htc|kindle|lg|midp|mmp|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone)/i));

	// Check if the referrer was a mobile page of the site
	// (in that case we need to set a variable in the sessionStorage or in the cookie)
	if (document.referrer.indexOf(mobile_url) >= 0) {
		document.cookie = param + "=true;expires=" + AddTimeToDate(60 * 1000 * cmin).toUTCString();
	}

	//var has_session = (window.sessionStorage) ? (window.sessionStorage.getItem(param) == 'true') : false;
	var has_cookie = document.cookie ? (document.cookie.indexOf(param) >= 0) : false;

	if (ismobile && !(has_cookie)) {
		document.location.href = mobile_url;
	}
};

