/************************************************
RA Javascript Library
	See http://wiki.ops.hearstdigital.com/wiki/RA_Javascript_Library
*************************************************/
var RA = {};
/** RA.vars - Holds various site variables we get during RA.init and used later on **/
RA.vars = {
	siteName: null, //site name.. might not need this
	facebookAppID: null, //fb app id.. need this to init FB API
	twitterAPI: null, //twitter API URL.. Site's cached twitter feed
	articleID: null, //article id.. might not need this
	adRefreshInterval: null, //ad refresh interval.. how many pageviews does it take to refresh the ads
	flipbookAdPosition: null, //ad position for the flipbook.. will be something like "ams_gh_flipbook"
	flipbookAdInterval: null, //flipbook ad interval.. how many slides before you see an ad
	pageAdsParams: null, //pageAdsParams.. global js variable declared in page-ads.js.. has ad targeting info for when we need to get new ads
	loadStart: new Date(), //time when library was loaded
	loadComplete: null, //time of library completion (reg init)
	domReady: null //time of domReady
};

/*****************************
*	RA.utils
*	- RA.utils is a namespace for utility methods
*	
******************************/
RA.utils = {
	key: {
		BACKSPACE: 8, TAB: 9, ENTER: 13, SHIFT: 16, CTRL: 17, ALT: 18, ESCAPE: 27, SPACE: 32, PAGEUP: 33, 
		PAGEDOWN: 34, END: 35, HOME: 36, LEFT: 37, UP: 38, RIGHT: 39, DOWN: 40, INS: 45, DEL: 46
	},
	setCookie: function(name,value,expires){
		var	domain = '.realage.com',
				path = '/',
				expDate = (expires == 0) ? new Date(0) : new Date(),
				cookieValue;
		expDate.setTime(expDate.getTime()+(expires*24*60*60*1000));
		cookieValue = value + ((expires == null) ? '' : ';expires=' + expDate.toUTCString()) + ((domain == null) ? '' : ';domain=' + domain) + ((path == null) ? '' : ';path=' + path);
		document.cookie = name + '=' + cookieValue;
	},
	getCookie: function(name){
		var nameEQ = name + "=",
			ca = document.cookie.split(';');	
		for(var i = 0; i < ca.length; i++) {
			var c = ca[i];
			while (c.charAt(0) === ' ') {c = c.substring(1,c.length);}
			if (c.indexOf(nameEQ) === 0) {
				var result = c.substring(nameEQ.length,c.length);
				return result;
			}
		}
		return null;
	},
	eraseCookie: function(name){
		if ( RA.utils.getCookie(name) ){
			RA.utils.setCookie(name,null,0);
		}
	},
	getCookieDump: function(){
		var cookies = document.cookie.split(';'), cookieDump = {};
		for (var i = 0; i < cookies.length; i++){
			var thisCookie = cookies[i].split('=');
			cookieDump[thisCookie[0]] = thisCookie[1];
		}
		return cookieDump;
	},
	buildScriptTag: function(src,callback){
		var script = document.createElement('script'), $head = $('head');
		$head.find('script').filter(function(i){
			return $(this).attr('src') && $(this).attr('src').split('?')[0] == src.split('?')[0];
		}).remove();
		script.src = src;
		script.onload = function(){
			try{
				callback();
			} catch(e){}
		};
		script.onreadystatechange = function(){
			if (script.readyState === 'loaded' || script.readyState === 'complete'){
				try{
					callback();
				} catch(e){}
			}
		};
		$head.get(0).appendChild(script);
	},
	cacheBust: function(){
		return Math.floor(1 + Math.random() * 100000);
	},
	getParameter: function(key){
		var params = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
		for (var i = 0, len = params.length; i < len; i++){
			var param = params[i].split('=');
			if (param[0] === key){
				return param[1];
			}
		}
		return false;
	},
	setBreadcrumb: function(){
		if (Modernizr.localstorage){
			localStorage.nextURL = window.location.href;
		} else {
			RA.utils.setCookie('nextURL',window.location.href);
		}
		return true;
	},
	getBreadcrumb: function(preserve){
		var nextURL = '';
		if (Modernizr.localstorage && !!localStorage.nextURL){
			nextURL = localStorage.nextURL;
			if (!preserve){ delete localStorage.nextURL; }
		} else {
			nextURL = RA.utils.getCookie('nextURL') || '/';
		}
		return nextURL;
	},
	storeData: function(key,data){
		if (Modernizr.localstorage){
			localStorage[key] = (typeof data === 'object') ? JSON.stringify(data) : data;
		} else {
			RA.utils.setCookie(key,encodeURIComponent(data));
		}
	},
	getData: function(key){
		if (Modernizr.localstorage){
			return localStorage[key];
		} else {
			return RA.utils.getCookie(key);
		}
	},
	eraseData: function(key){
		if (Modernizr.localstorage){
			localStorage.removeItem(key);
		} else {
			RA.utils.eraseCookie(key);
		}
	}
};

/** RA.registration **/
RA.registration = {
	loggedInQueue: [],
	loginLinks: null,
	host: 'https://login.realage.com',
	status: {
		raLoggedIn: null,
		hdmLoggedIn: null
	},
	setHost: function() {
		var self = this;
		if (window.location.href.match(/alphapreview/i)) {
			self.host = self.host.replace('https://','http://');
			self.host = self.host.replace('login.','alphapreview.');
			if (window.location.port) {
				self.host += ':'+window.location.port;
			}
		} else if (window.location.href.match(/betapreview/i)) {
			self.host = self.host.replace('login.','betapreview.login.');
		}
	},
	runLoggedInQueue: function() {
		var self = RA.registration;
		for (var i = 0; i < self.loggedInQueue.length; i++) {
			self.loggedInQueue[i]();
		}
	},
	loggedIn: function(passedFunction) {
		if (typeof(passedFunction) == 'function') {
			this.loggedInQueue.push(passedFunction);
			return true;
		} else {
			return false;
		}
	},	
	//logs the user out of RA
	logout: function(){
		var self = this,
			//get our current location, so we can redirect the user from logout
			nextURL = ( window.location.href.match('/registration/') ) ? '/' : window.location.href;
		RA.utils.eraseCookie('raap_member_id');
		RA.utils.eraseCookie('raap_child_id');
		RA.utils.eraseCookie('sessionLength');
		raTest.clearResumeLocation_StoredValues();
		raTest.clearMyRA_StoredValues();
		raTest.clearCompletionUX();
		//if this browser supports localStorage and we have a mag_user stored.
		window.location.href = '/registration/logout?next_url=' + nextURL;		
	},
	setExtendedSessionCookies: function(){
		var sessionLength = RA.utils.getCookie('sessionLength');
		if (sessionLength == 'extended') {
			var	self = this,
					expiry = 14,
					raap_member_id = RA.utils.getCookie('raap_member_id'),
					raap_child_id = RA.utils.getCookie('raap_child_id');
			
			// reset auth cookies with 2 week expiry
			if (sessionLength) RA.utils.setCookie('sessionLength','extended',expiry);
			if (raap_member_id) RA.utils.setCookie('raap_member_id',raap_member_id,expiry);
			if (raap_child_id) RA.utils.setCookie('raap_child_id',raap_child_id,expiry);
		}
	},
	init: function(settings){
		var self = this;
		settings = (typeof(settings) == 'undefined') ? {} : settings;
		self.loginLinks = $(settings.loginLinks);
		self.setHost();
		
		if (mag_user.logged_in && !RA.utils.getCookie('sessionLength')) {
			self.logout();
		} else if (mag_user.logged_in) {
			self.status.hdmLoggedIn = true;
			var username = mag_user.email;
			if (username.length > 25) {
				username = username.substring(0,25) + "...";
			}
			var $welcomeMessage = $('<li>Hello '+username+'</li>')
			var $myAccount = $('<li><a href="/registration/editProfile.html" class="button11">My Account</a></li>');
			var $signOut = $('<li><a href="#" class="button12">Sign Out</a></li>');
			
			self.loginLinks.append($welcomeMessage);
			self.loginLinks.append($myAccount);
			$signOut.click(function(){
				self.logout();
				return false;
			}).appendTo(self.loginLinks);
			
			this.runLoggedInQueue();
			
			self.setExtendedSessionCookies();
			
		} else {
			var $joinFree = $('<li><a href="https://login.realage.com/join/?Dest='+encodeURIComponent(window.location.href)+'" class="button11">Join Free</a></li>');
			var $signIn = $('<li><a href="https://login.realage.com/login/?Dest='+encodeURIComponent(window.location.href)+'" class="button12">Sign In</a></li>');
			self.loginLinks.append($joinFree);
			self.loginLinks.append($signIn);
		}
		
		//set all login links to use correct host
		if (window.location.href.match(/(alphapreview|betapreview)/i)) {
			$(document).ready(function(){
				$('a').each(function(){
					var href = $(this).attr('href');
					href = href.replace(/https:\/\/login.realage.com/gi,self.host);
					$(this).attr('href',href);
				});
			});
		}
		
		//set loadComplete and domReady vars for benchmark calculations
		RA.vars.loadComplete = new Date();
		$(document).ready(function(){
			RA.vars.domReady = new Date();
		});
		//show benchmarking results between loadComplete & domReady
		$(document).ready(function(){
			console.log("loadComplete: " + (RA.vars.loadComplete - RA.vars.loadStart) + "ms");
			console.log("domReady: " + (RA.vars.domReady - RA.vars.loadStart) + "ms");
		});
		
	}
};
