/*
 * JS Redirection Mobile
 *
 * Developed by
 * Sebastiano Armeli-Battana (@sebarmeli) - http://sebarmeli.com
 * Release under the MIT licence
 * @version 0.7
 * 
 */
if(!window.SA){
	window.SA={};
}

SA.redirection_mobile=function(config){
	var addTimeToDate=function(msec){
		var exdate=new Date();
		exdate.setTime(exdate.getTime()+msec);
		return exdate;
	};
	
	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);
			}
		}
	};
	
	var agent=navigator.userAgent.toLowerCase(),
	FALSE="false",
	config=config||{};redirection_param=config.redirection_paramName||"mobile_redirect",
	mobile_prefix=config.mobile_prefix||"m",
	mobile_url=config.mobile_url,
	mobile_protocol=config.mobile_scheme?config.mobile_scheme+":":document.location.protocol,host=document.location.host,
	queryValue=getQueryValue(redirection_param),
	mobile_host=mobile_url||(mobile_prefix+"."+(!!host.match(/^www\./i)?host.substring(4):host)),cookie_hours=config.cookie_hours||1,isUAMobile=!!(agent.match(/(iPhone|iPod|iPad|blackberry|android|htc|kindle|lg|midp|mmp|mobile|nokia|opera mini|palm|pocket|psp|sgh|smartphone|symbian|treo mini|Playstation Portable|SonyEricsson|Samsung|MobileExplorer|PalmSource|Benq|Windows Phone|Windows Mobile|IEMobile|Windows CE|Nintendo Wii)/i));
	
	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();
		}
	}
	
	var isSessionStorage=(window.sessionStorage)?(window.sessionStorage.getItem(redirection_param)===FALSE):false,
	isCookieSet=document.cookie?(document.cookie.indexOf(redirection_param)>=0):false;
	
	if(isUAMobile&&!(isCookieSet||isSessionStorage)){
		document.location.href=mobile_protocol+"//"+mobile_host;
	}
};
