/* Required by a script in templates; Remove this after community launch */
var rs_memb = '';
var rs_beta = '';

/* jQuery noConflict code used with Prototype */ 
var $j = jQuery;

/* IE6 background image caching */	
try { document.execCommand ('BackgroundImageCache', false, true); } catch (e) {}

/* Set the base domain */
(function ()
{
	try
	{
		var domainSplit = document.domain.split ('.');
		document.domain = domainSplit.splice (domainSplit.length - 2, 2).join ('.');
		document.cookie = 'domain=' + document.domain;
	}
	catch (error) {}
}) ();

/* Firebug console wrapper for error-free debugging - But don't leave any $console/console calls in the code! */
var $console = {};
$console.exists = typeof console == 'object';
$console.log = function (arg0)
{
	if (this.exists)
	{
		if (typeof arguments [1] != 'undefined') { console.log (arg0, arguments [1]); }
		else { console.log (arg0); }
	}
}

/* $trc is the Real Simple namespace for global constants and static functions, which will be transferred to $RS in the future */
var $trc = 
{
	POLL_TIMEOUT : 10000,
	POLL_INTERVAL : 500,
	IS_OPERA : typeof window.opera != 'undefined',
	IS_IE : typeof document.all != 'undefined' && !this.IS_OPERA && navigator.vendor != 'KDE',
	IS_TV : new RegExp ('/television/', 'i').test (location.pathname),
	domHook: null,
	setDomHook : function () { var domHook = $ ('<div id="domHook"></div>'); domHook.appendTo ('body'); this.domHook = domHook [0]; },
	IS_RS_HOST : /realsimple\.com/i.test (location.href),
	getUrlParameter : function (key, alternateQueryString, noHash, delimiter)
	{
		delimiter = typeof delimiter == 'string' && delimiter != '' ? delimiter : '&';
		key = key.replace (/[\[]/, '\\\[').replace (/[\]]/, '\\\]');
		var regex = new RegExp ('[\\?' + delimiter + ']' + key + '=([^' + delimiter + (typeof noHash == 'boolean' && noHash ? '' : '#') + ']*)');
		var result = regex.exec (typeof alternateQueryString == 'string' && alternateQueryString.length > 0 ? '?' + alternateQueryString : location.href);
		return result == null ? '' : result [1];
	}
}
$trc.setDomHook ();
$trc.HOST_PREFIX = $trc.IS_RS_HOST ? ((/^http:\/\/dev\./i.test (location.href) || /^http:\/\/dev-/i.test (location.href)) ? 'dev-' : ((/^http:\/\/qa\./i.test (location.href) || /^http:\/\/qa-/i.test (location.href)) ? 'qa-' : '')) : '';
$trc.HOST_DOT_PREFIX = $trc.HOST_PREFIX == '' ? '' : $trc.HOST_PREFIX.replace ('-', '.');
$trc.IMG_PREFIX = $trc.IS_TV ? 'tv/' : '';
$trc.NON_PREVIEW_LOCATION = location.href.replace (new RegExp ('^http://' + $trc.HOST_PREFIX + 'preview.realsimple.com'), 'http://' + $trc.HOST_DOT_PREFIX + 'realsimple.com');

/* Sets the root folder paths for static files */
	var RELATIVE_URL = '../..';
	var rsSTIRoot = RELATIVE_URL;
	var rsStaticRoot = RELATIVE_URL;
	if (/realsimple\.com/i.test (location.href))
	{
		rsSTIRoot = rsStaticRoot = 'http://' + $trc.HOST_PREFIX + 'img4.realsimple.com/static';
	}
	if (typeof rsAssignedRoot != 'undefined' && rsAssignedRoot && rsAssignedRoot != '') { rsSTIRoot = rsAssignedRoot; }
	if (typeof rsAssignedStaticRoot != 'undefined' && rsAssignedStaticRoot && rsAssignedStaticRoot != '') { rsStaticRoot = rsAssignedStaticRoot; }

/* Dynamic Script Attachment */
function rsAddScript (src) {
    var scriptToAdd = document.createElement ('script');
    scriptToAdd.type = 'text/javascript';
    scriptToAdd.src = rsSTIRoot + src;
	if (typeof $trc.head != 'object' || !$trc.head)
	{
		/* Don't use $j ('head') for the line below because the current line performs more efficiently */
		$trc.head = document.getElementsByTagName ('head').item (0);
	}
    $trc.head.appendChild (scriptToAdd);
}

/* $RS is the Real Simple namespace for global constants and static functions */ 
var $RS =
{
	getParam : function (key, queryString, delimiter) { return $trc.getUrlParameter (key, queryString, true, delimiter	); }
};
$RS.getCookie = function (key) { return this.getParam (key, document.cookie, '; ') };

/* Set community ad parameters */
$RS.setCAdParams = function (adFactory)
{
	var community_ad_cookie = decodeURIComponent (this.getCookie ('ti_community_ad'));
	var adKeys = 'comm con comm1 comm2 comm3'.split (' ');
	for (var i = 0, l = adKeys.length; i < l; i++)
	{
		var key = adKeys [i];
		adFactory.setParam (key, this.getParam (key, community_ad_cookie));
	}
};

/* These variables should normally be in global.js (which is near the end of the page), but they need to be in the <head> section early on. That's' why they're here */

/* TV flat pages flag */
var tv_hide_css = document.getElementById ('tv_hide_css');

/* Utilities proper */
function tii_dom_removeWhitespaceTextNodes(node) {
	for (var x = 0; x < node.childNodes.length; x++) {
		var child = node.childNodes [x];
		if (child.nodeType == 3 && !/\S/.test(child.nodeValue)) {
			node.removeChild(node.childNodes[x]);
			x--;
		}
		if (child.nodeType == 1) {
			tii_dom_removeWhitespaceTextNodes(child);
		}
	}
}

function tii_callFunctionOnElementLoad(targetId, functionToCall) {
	var myArguments = arguments;
	$j (document).ready (function () {
		window.loaded = true;
	});
	var targetElement = document.getElementById (targetId);
	if (targetElement == null && !window.loaded) {
		var pollingInterval = setInterval (function () {
			if (window.loaded) {
				clearInterval (pollingInterval);
			}
			targetElement = document.getElementById (targetId);
			if (targetElement != null) {
				clearInterval(pollingInterval);
				var argumentsTemp = new Array();
				var argumentsTempLength = myArguments.length - 2;
				for (var i = 0; i < argumentsTempLength; i++) {
					argumentsTemp[i] = myArguments[i + 2];
				}		
				functionToCall.apply(this, argumentsTemp);
			}
		}, 250); /* Used to be 10 milliseconds */
	}
}

function tii_addEventHandler(targetElement, eventType, functionToCall, bubbleEventUpDOMTree) {
	if (!targetElement) {
		window.status = 'Warning: Tried to attach event to null object';
		return false;
	}
	if (typeof targetElement.addEventListener != 'undefined') {
		targetElement.addEventListener (eventType, functionToCall, bubbleEventUpDOMTree);
	}
	else if (typeof targetElement.attachEvent != 'undefined') {
		targetElement.attachEvent ('on' + eventType, functionToCall);
	}
	else {
		eventType = 'on' + eventType;
		if (typeof targetElement [eventType] == 'function') {
			var oldListener = targetElement [eventType];
			targetElement [eventType] = function () {
				oldListener ();
				return functionToCall ();


			}
		}
		else {
			targetElement [eventType] = functionToCall;
		}
	}
	return true;
}

function tii_stopDefaultAction (event) {
	event.returnValue = false;
	if (typeof event.preventDefault != 'undefined') {
		event.preventDefault ();
	}
}

function tii_getParameter (searchName, searchString)
{
	var pairs = searchString.split (';');
	for (var i = 0; i < pairs.length; i++)
	{
		var pairCrumbs = pairs [i].split ('=');
		var pairName = pairCrumbs [0];
		pairName = pairName.replace (' ', '');
		var pairValue = pairCrumbs [1];
		if (pairName == searchName) { return pairValue; }
	}
	return false;
}

/*Sniffing*/
var ua = navigator.userAgent;
var isMac = ua.indexOf('Mac OS X') == -1 ? false : true;
var isFirefox = ua.indexOf('Firefox') == -1 ? false : true;
var isSafari = ua.indexOf('Safari') == -1 ? false : true;
if(isMac && isFirefox) {
	head = document.getElementsByTagName('head')[0];
	newStyle = document.createElement('style');
	newStyle.setAttribute('type','text/css');
	newStyle.innerHTML='.bc{background-position:right center;}';
	head.appendChild(newStyle);
}

/*Background Fader*/
function toHex(x) {
	hex = [];
	for(i=0;i<10;i++){hex[i]=i;}
	hex[10] = "a";
	hex[11] = "b";
	hex[12] = "c";
	hex[13] = "d";
	hex[14] = "e";
	hex[15] = "f";
	return ("" + hex[Math.floor(x/16)] + hex[x%16]);
}

function fader(element,f,t,time) {
	var fadeCount=1;
	var fadeInterval = setInterval(function(){
		if(fadeCount==30) {clearInterval(fadeInterval);}
		element.style.backgroundColor='#'+toHex(Math.ceil(f[0]+((t[0]-f[0])/30)*fadeCount))+toHex(Math.ceil(f[1]+((t[1]-f[1])/30)*fadeCount))+toHex(Math.ceil(f[2]+((t[2]-f[2])/30)*fadeCount));
		fadeCount++;
	},Math.floor(time/30));
}

/* Check ad popups */
TiiAdConfig.prototype.checkPopups = function () { if (!/realsimple\.com/.test (document.referrer)) { this.setPopups (false); } }

/* Temporary ad fix */
TiiAd.prototype.removePgUrl = false;

function TiiAd_getAdParams() {
	var adParams	= this._formatParams();
	var tileParam	= ";tile=" + this.tileNumber;

	var secureParam = "";
	if (TiiAd_isSecure()) {
		secureParam = ";sec=1";
	}

	var puParam = "";
	if (!this.config.popups) {
		puParam = ";pu=0";
	}

	var ordParam	= ";ord=" + this.randomNumber;
	var rhost	= document.referrer.split("/")[2];
	var rhostParam	= "";
	if (typeof(rhost) != "undefined") rhostParam	= ";rhost=" + rhost;
	var pageParam = '';
	if (!this.removePgUrl)
	{
		pageParam	= ";pgurl=" + escape(document.location);
	}
	
	return this.sitename + "/" + this.zone.toLowerCase() + adParams + pageParam + rhostParam + tileParam + puParam + secureParam + ordParam + "?";
}

/* Homepage Carousel */
var hpc = {
	flashHash : {},
	register : function (data)
	{
		this.flashHash [data.slideIndex] = data.videoIndex;
	}
};

/*** Navigation ***/
// available jQuery Plugin 1.0 - faster than domready
// By John Terenzio (http://terenz.io)
// http://plugins.jquery.com/project/available
(function($){
	$.fn.available = function(fn){
		if (!this.length && !$.isReady) {
			setTimeout(function(selector){
				return function(){
					$(selector).available(fn);
				};
			}($(this).selector),0);
			return;
		}
		return this.eq(0).each(fn);
	};
})(jQuery);

/* Highlight the current channel in the topnav */
function topnav_currentNavHighlight() {
	var highlightId;
	/* Array holding the channel IDs for determining the current channel */
	var topNavHash = new Array (['beauty-fashion', 'tn_beauty'], ['food-recipes', 'tn_recipes'], ['health', 'tn_health'], ['holidays-entertaining', 'tn_holidays'], ['home-organizing', 'tn_home'], ['work-life', 'tn_work'], ['magazine-more', 'tn_magazine']);
	
	var tnhLength = topNavHash.length;
	for (var i = 0; i < tnhLength; i++) {
		if (new RegExp ('/' + topNavHash [i] [0] + '/', 'i').test (location.href)) {
			highlightId = topNavHash [i] [1];
			break;
		}
	}	// End for loop
	
	if (highlightId) {
		var jQSelector = '#' + highlightId;
		$(jQSelector).addClass("current_page");
	}
}	// End function topnav_currentNavHighlight()
					
$('#topnav_loaded').available(function(){
	topnav_currentNavHighlight();
	
	/* Start DOM search at #menu element to reduce DOM traversing by jQuery */
	var menuRoot = $("#menu");
	var flyoutRoot = menuRoot.find("ul.tn_flyout");
	
		/* Remove vertical line image on last nav item */
	menuRoot.find(".tn_a_prime").filter(":last").css("background", "none");
	
	menuRoot.find("li.tn_flyout_li_browseall").each(function(i){
		$(this).prepend('<div class="flyout_hideborder"></div>')
	});
	
	menuRoot.find("li.tn_li_prime").not(":last").hover(
		function() {
			$(this).addClass("active");
			$("ul.tn_flyout", this).addClass("flyout_active");
		},
		function() {
			$(this).removeClass("active");
			$("ul.tn_flyout", this).removeClass("flyout_active");
		}
	);
	
	/* Magazine and More nav flyout opens up to the left, so it needs separate processing */
	menuRoot.find("li.tn_li_prime").filter(":last").hover(
		function() {
			$(this).addClass("active");
			$("ul.tn_flyout", this).addClass("flyout_last_active");
		},
		function() { 
			$(this).removeClass("active");
			$("ul.tn_flyout", this).removeClass("flyout_last_active");
		}
	);
	
	flyoutRoot.children("li").hover(
		function() {
			$(this).addClass("active_item"); 
		},
		function() { 
			$(this).removeClass("active_item"); 
		}
	);
});

