/* Request controller for login authentication and general constant source */
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 () { document.write ('<div id="domHook"></div>'); this.domHook = document.getElementById ('domHook'); }
};

$trc.setDomHook ();
$trc.IS_RS_HOST = /realsimple\.com/i.test (location.href)
$trc.HOST_PREFIX = $trc.IS_RS_HOST ? ((/dev\./i.test (location.href) || /dev-/i.test (location.href)) ? 'dev-' : 
	((/qa\./i.test (location.href) || /qa-/i.test (location.href)) ? 'qa-' : '')) : '';
$trc.HOST_DOT_PREFIX = $trc.HOST_PREFIX == '' ? (/sitepreview.realsimple.com/i.test (location.href) ? 'sitepreview.' : '') : $trc.HOST_PREFIX.replace ('-', '.');
$trc.IMG_PREFIX = $trc.IS_TV ? 'tv/' : '';

/* 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))
	{
		var HOST_PREFIX = $trc.HOST_PREFIX == '' ? 'www.' : $trc.HOST_PREFIX.replace ('-', '.');
		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; }

$j.fn.check = function(){
    return this.each(function(){
        this.checked = true;
    });
};

$j(function()
{
	rs_setFooterEmailBox ();
});



jQuery.cookie=function(name,value,options){
	if(typeof value!='undefined'){
		options=options||{};
		if(value===null){
			value='';
			options.expires=-1;
		}
		var expires='';
		if(options.expires&&(typeof options.expires=='number'||options.expires.toUTCString)){
			var date;
			if(typeof options.expires=='number'){
				date=new Date();
				date.setTime(date.getTime()+(options.expires*24*60*60*1000));
			}
			else{
				date=options.expires;
			}
			expires='; expires='+date.toUTCString();
		}
		var path=options.path?'; path='+(options.path):'';
		var domain=options.domain?'; domain='+(options.domain):'';
		var secure=options.secure?'; secure':'';
		document.cookie=[name,'=',encodeURIComponent(value),expires,path,domain,secure].join('');
		}
	else{
		var cookieValue=null;
		if(document.cookie&&document.cookie!=''){
			var cookies=document.cookie.split(';');
			for(var i=0;i<cookies.length;i++){
				var cookie=jQuery.trim(cookies[i]);
				if(cookie.substring(0,name.length+1)==(name+'=')){
					cookieValue=decodeURIComponent(cookie.substring(name.length+1));
					break;
				}
			}
		}
	return cookieValue;
	}
};

jQuery.extend({
    getURLParam: function(strParamName){
        var strReturn = "";
        var strHref = window.location.href;
        var cmpFound = false;
        
        var cmpstring = strParamName + "=";
        var cmplen = cmpstring.length;
        
        if (strHref.indexOf("?") > -1) {
            var strQueryString = strHref.substr(strHref.indexOf("?") + 1);
            var aQueryString = strQueryString.split("&");
            for (var iParam = 0; iParam < aQueryString.length; iParam++) {
                if (aQueryString[iParam].substr(0, cmplen) == cmpstring) {
                    var aParam = aQueryString[iParam].split("=");
                    strReturn = aParam[1];
                    cmpFound = true;
                    break;
                }
            }
        }
        if (cmpFound == false) 
            return null;
        return strReturn;
    }
});

/* set pageID globally */
var pageID = $j('div[class=pagewrap]').attr("id");

/* Transfers the top ad code from the bottom of the page to the top */
function rs_setAdTop ()
{
	var adtop = document.getElementById ('adtop');
	var adtoploader = document.getElementById ('adtoploader');
	if (adtop && adtoploader)
	{
		var pollTime = 0;
		var nonScriptElementFound = false;
		var child;
		var pollInterval = setInterval (function ()
		{
			if (pollTime > $trc.POLL_TIMEOUT) { clearInterval (pollInterval); return; }
			var children = adtoploader.getElementsByTagName ('*');
			var childrenLength = children.length;
			for (var i = 0; i < childrenLength; i++)
			{
				child = children [i];
				if (typeof child != 'undefined' && child && child.parentNode == adtoploader &&
					(child.nodeType == 3 || (child.nodeType == 1 && child.nodeName != 'SCRIPT')))
				{
					adtop.appendChild (child);
					clearInterval (pollInterval);
					nonScriptElementFound = true;
					break;
				}
			}
			if (nonScriptElementFound)
			{
				for (nextSibling = child; nextSibling != null; nextSibling = nextSibling.nextSibling)
				{
					if (nextSibling.nodeType == 3 || (nextSibling.nodeType == 1 && nextSibling.nodeName != 'SCRIPT'))
					{
						adtop.appendChild (nextSibling);
					}
				}
			}
		}, $trc.POLL_INTERVAL);
	}
}

/* Footer Newsletter Email Input */
function rs_setFooterEmailBox ()
{
	var emailBox = document.getElementById ('ftr_nl_email');
	if (emailBox)
	{
		tii_addEventHandler (emailBox, 'focus', function ()
		{
			if (emailBox.value = 'Enter Email Address')
			{
				emailBox.value = '';
			}
		}, false);
	}
}

/*li Navigation*/
function rs_setHighlightNav(li_id) {
	var li = $j("#"+li_id);
	li.className += (li.className == '' ? '' : ' ') + 'current_page';
}

/*Get # of Related Cokkies*/
function getNumCookies(prefix,maxNum) {
	var num=0;
	for(i=1;i<=maxNum;i++) {
		if($j.cookie(prefix+'_history'+i)) {
			num++;
		}
		else {
			return num;
		}
	}
	return maxNum;
}

/*Omniture Tracking for Content Toolbar */
function omniCTB(element) {
	if(element.childNodes[0]) {
		var s=s_gi(s_account);
		s_time.linkTrackVars = 'prop3'; 
		s_time.linkTrackEvents = 'none';
		s_time.prop3 = 'ContentToolbar:'+element.childNodes[0].nodeValue;  
		s_time.tl(this,'o','ContentToolbar:Action');
		s_time.linkTrackVars = 'None';  
	}
}
if(document.getElementById("cntTB") && document.getElementById("cntTB").getElementsByTagName("a")) {
	var ctbAs = document.getElementById("cntTB").getElementsByTagName("a");
	for(i=0;i<ctbAs.length;i++) {				
		tii_addEventHandler(ctbAs[i],'click',function(event){
		var target = typeof event.target != 'undefined'? event.target : event.srcElement;
		omniCTB(target);return true;		
		},false);
	}
}

/**
 * RS_COOKIE_CONFIG is used to ensure cookie consistency
 */
var RS_COOKIE_CONFIG = {
	path: '/',
	domain: '.realsimple.com'
};

/*Page History*/
function escapeArray(){
//escape print pages
if (document.getElementById('prnFooter')) {
		return;
	}
//escape specified content ID's
var escapePages = new Array ('homepage','channel','brwsPg','searchPg','searchPgNoRslt','myrealsimple','home');
	for (i=0;i<escapePages.length;i++) {
		if (pageID == escapePages[i]) {
			return;
		}	
	}
	append_page_view();
}
escapeArray();

function append_page_view() {	
		// Get document title & URL
		var title = document.title.replace(' - Real Simple', '');
		
		// Don't record 404s
		if (title.toLowerCase() == 'page not found') {
			return;
		}

		var url   = location.href;
				
		// Create history queue & add current page to queue
		var history = [{
			title: 	title,
			url: 	url
		}];
	
		var cookie_title_key = 'page_history';
		var cookie_url_key = 'page_history_url';
		var cookie_length = getNumCookies('page', 4);		
		var cookie_title, cookie_url;
		 
		// Read existing history from cookie into memory
		for (var i = 1; i <= cookie_length; ++i) {
			
			// Extract cookie URL from existing history
			cookie_url = $j.cookie(cookie_url_key + i);
			
			// If cookie page does not match current page, add to queue
			if (cookie_url !== url) {
				
				// Extract cookie title from existing history
				cookie_title = $j.cookie(cookie_title_key + i);
			
				// Add to queue
				history.push({
					title: 	cookie_title,
					url: 	cookie_url
				});
			}
		}
		
		// Update history cookies
		var cookie_index = 1;
		for (i = 0, len = history.length; i < len; ++i) {
			$j.cookie(cookie_title_key + cookie_index, history[i].title, RS_COOKIE_CONFIG);
			$j.cookie(cookie_url_key + cookie_index, history[i].url, RS_COOKIE_CONFIG);
			cookie_index++;
		}
		
		// Delete unused history cookies
		for (i = cookie_index; i <= cookie_length; ++i) {
			$j.cookie(cookie_title_key + i, null, RS_COOKIE_CONFIG);
			$j.cookie(cookie_url_key + i, null, RS_COOKIE_CONFIG);
		}
	}

/*Search History*/
function append_search(search_value) {

	var cookie_value_key = 'search_history';
	
	// Create history queue & add current search term to queue
	var history = [search_value];
	
	var cookie_length = getNumCookies('search', 5);	
	var cookie_value;
	
	// Read existing history from cookie into memory
	for (var i = 1; i <= cookie_length; ++i) {
				
		// Extract cookie value from existing history
		cookie_value = $j.cookie(cookie_value_key + i);

		// If cookie value does not match current search term, add to queue
		if (cookie_value !== search_value) {
			
			// Add to queue 
			history.push(cookie_value);
		}
	}

	// Update history cookies
	var cookie_index = 1;
	for (i = 0, len = history.length; i < len; ++i) {
		$j.cookie(cookie_value_key + cookie_index, history[i], RS_COOKIE_CONFIG);
		cookie_index++;
	}
	
	// Delete unused history cookies
	for (i = cookie_index; i <= cookie_length; ++i) {
		$j.cookie(cookie_value_key + i, null, RS_COOKIE_CONFIG);
	}
}



function displaySearchHistory () {	
	var div = document.getElementById('LnkLstUl');
	
	if (!div) {
		return;
	}

	var cookie_length = getNumCookies('search', 5);
		
	if (cookie_length == 0) {
		return;
	}

	var search_URL = '/results.html?Ntt=';
	var cookie_value_key = 'search_history';

	var h3 = document.createElement('h3');
	var h3_text = document.createTextNode('Your Most Recent Searches');
	h3.appendChild(h3_text); 
	
	// Create history container
	var ul = document.createElement('ul');
	ul.id = 'search_history_list';
	
	var cookie_value;
	var li, a, txt, a_text;
	
	// Read existing history from cookie into memory
	for (var i = 1; i <= cookie_length; ++i) {
				
		// Extract cookie value from existing history
		cookie_value = $j.cookie(cookie_value_key + i);
			
		// Create history item
		li = document.createElement('li');
		a = document.createElement('a');
		a.setAttribute('href', search_URL + cookie_value);
		a_text = document.createTextNode(cookie_value);
		
		// Attach nodes
		a.appendChild(a_text);
		li.appendChild(a);
		ul.appendChild(li);
	}
	
	div.appendChild(h3);
	div.appendChild(ul);
}

function swapCSS ()
{
	var widgetsCSS = rsStaticRoot + '/c/widgets.css';
	var printPreviewCSS = rsStaticRoot + '/c/print_preview.css';
	var links = document.getElementsByTagName ('link');
	var linksLength = links.length;
	for (var i = 0; i < linksLength; i++)
	{
		link = links.item (i);
		var href = link.href;
		if (href == widgetsCSS) { link.href = printPreviewCSS; link.media = 'all'; break; }
		if (href == printPreviewCSS) { link.href = widgetsCSS; link.media = 'screen'; break; }
	}
} 



/*Prevent Null Searches*/
function stopNullSubmit() {
	var input = $j("#hdr_search_input")[0];
	
	while(input.value.substring(0,1) == ' ') {
		input.value = input.value.substring(1,input.value.length);
	}
	while(input.value.substring(input.value.length-1,input.value.length) == ' ') {
		input.value = input.value.substring(0,input.value.length-1);
	}
	
	if(input.value == '') {
		return false;
	}
	return true;
}
tii_addEventHandler($j("#hdr_search_form")[0],'submit',function(event) {
	if(stopNullSubmit() == false) {
		tii_stopDefaultAction(event);
	}
},false);

/*Auto-Suggest Functionality*/
var $sg = {};
$sg.items = new Array ();
$sg.setAutoSuggest = function (index)
{
	$sg.items [index] = {};
	var sgItem = $sg.items [index];
	sgItem.cancelBlurHandler = false;
	sgItem.search = (index == 0 ? document.getElementById ('hdr_search_input') : document.getElementById ('ftr_search_input'));
	sgItem.root = (index == 0 ? document.getElementById ('hdr_search') : (sgItem.search ? sgItem.search.parentNode : null));
	if (sgItem.root)
	{
		var idOrClass = index == 0 ? 'autoSuggest' : 'suggest';
		var divs = sgItem.root.getElementsByTagName ('div');
		var divsLength = divs.length;
		for (var i = 0; i < divsLength; i++)
		{
			var div = divs [i];
			if (index == 0) { if (div.className == idOrClass) { sgItem.div = div;} }
			else { if (div.id == idOrClass) { sgItem.div = div;} }
		}
		if (sgItem.div) { sgItem.suggestions = sgItem.div.getElementsByTagName ('li'); }
	}
	sgItem.tab = -1;
	sgItem.open = false;
	if (sgItem.search && sgItem.div)
	{
		sgItem.search.value = '';
		sgItem.search.setAttribute('autocomplete', 'off');
		tii_addEventHandler(sgItem.search, 'keydown', function(event) { $sg.asControls(event, index); }, false);
		tii_addEventHandler(sgItem.search, 'keyup', function(event) { $sg.getSuggestions(event, index); }, false);
		tii_addEventHandler(sgItem.search, 'blur', function(event) { $sg.closeAutoSuggest(index); }, false);
	}
}

$sg.closeAutoSuggest = function (index)
{
	var delay = setTimeout (function ()
	{
		var sgItem = $sg.items [index];
		if (sgItem.cancelBlurHandler) { sgItem.cancelBlurHandler = false; }
		else
		{
			sgItem.open = false;
			sgItem.div.style.display = 'none';
		}
	}, 250);
}
$sg.openAutoSuggest = function (index) { $sg.items [index].open = true; $sg.items [index].div.style.display = 'block'; }
$sg.setSearchValue = function (element, index)
{	
	$sg.items [index].search.value = element.childNodes [0].nodeValue;
	$sg.items [index].cancelBlurHandler = false;
	$sg.closeAutoSuggest(index);
}
$sg.getSuggestions = function (e, index)
{
	if (e.keyCode == 27) { $sg.closeAutoSuggest (index); }
	else if(e.keyCode != 38 && e.keyCode != 40 && e.keyCode != 13)
	{
		if($sg.items[index].tab != -1)
		{
			$sg.items [index].suggestions [$sg.items [index].tab].className= '';
			$sg.items [index].tab = -1;
		}
		if($sg.items [index].search.value.length>2)
		{
			if (typeof window.rs_asScriptCount == 'undefined') { window.rs_asScriptCount = -1; }
			window.rs_asScriptCount++;
			var id = 'asScript' + window.rs_asScriptCount;
			window [id] = function (jsonData)
			{
				if (jsonData && jsonData.suggestions)
				{
					$sg.items [index].cancelBlurHandler = true;
					var suggestions = jsonData.suggestions;
					var sLength = suggestions.length;
					var content = '<ol>\n';
					for (var i = 0; i < sLength; i++)
					{
						var suggestion = suggestions [i];
						if (suggestion)
						{
							var label = suggestion.name;
							if (label && label != '') { content += ('<li>' + label + '</li>\n'); }
						}
					}
					content += '\n</ol>';
					$sg.items [index].div.innerHTML = content;
					if (!$sg.items [index].open) { $sg.openAutoSuggest (index); }
					$sg.setClicks (index);
				}
				else { $sg.items [index].div.innerHTML = ''; }
			}
			var script = document.createElement ('script');
			script.type = 'text/javascript';
			script.id = id;
			if ($trc.HOST_PREFIX == '') {

				script.src = 'http://search.realsimple.com/suggest.json?N=0&lookAheadFor=' + encodeURIComponent ($sg.items [index].search.value) + '&callback=' + id +'&maxResults=5&wildcard=true';

			} else {
			
				script.src = 'http://' + $trc.HOST_PREFIX + 'esearch.realsimple.com/suggest.json?N=0&lookAheadFor=' + encodeURIComponent ($sg.items [index].search.value) + '&callback=' + id +'&maxResults=5&wildcard=true';
			
			}
			
			$trc.domHook.appendChild (script);
		}
	}
}

$sg.asControls = function (e, index)
{
	var suggestions = $sg.items [index].suggestions;
	var currentTab = $sg.items [index].tab;
	if(suggestions.length > 0) {
		if(e.keyCode == 13 && $sg.items [index].open && currentTab > -1) {
			tii_stopDefaultAction(e);
			$sg.setSearchValue(suggestions [currentTab], index);
		}
		else if(e.keyCode == 40) {
			if(currentTab != -1 && currentTab < suggestions.length-1) {
				suggestions [currentTab].className='';
			}
			if(currentTab < suggestions.length-1) {
				currentTab++;	
				suggestions [currentTab].className='currentTab';
			}
		}
		else if(e.keyCode == 38) {
			if(currentTab != -1) {
				suggestions [currentTab].className='';
				currentTab--;
			}
			if(currentTab != -1) {
				suggestions [currentTab].className='currentTab';	
			}
		}
	} else {
	    $sg.closeAutoSuggest(index);
	}
	$sg.items [index].tab = currentTab;
}

$sg.setClicks = function (index)
{
	var suggestions = $sg.items [index].suggestions;
	for(i=0;i<suggestions.length;i++) {
		tii_addEventHandler (suggestions[i], 'click', function (event)
		{
			$sg.items [index].cancelBlurHandler = true;
			var li = typeof event.target != 'undefined'? event.target : event.srcElement;
			$sg.setSearchValue (li, index);
		}, false);
	}
}

$j(document).ready(function ()
{
	$sg.setAutoSuggest (0);
	$sg.setAutoSuggest (1);
});

/* Make this my homepage */
$j(document).ready(function ()
{
	var performAction = function (event)
	{
		s_gi (s_account).tl (anchor, 'o', 'MakeThisMyHomePage: Clicks');
		var IS_OPERA = typeof window.opera != 'undefined';
		var IS_IE = typeof document.all != 'undefined' && !IS_OPERA && navigator.vendor != 'KDE';
		if (IS_IE)
		{
			anchor.style.behavior='url(#default#homepage)';
			anchor.sethomepage('http://www.realsimple.com');
			tii_stopDefaultAction (event);
		}
	};
	var anchor = $j('#make-homepage a').get(0);
	if (anchor) { tii_addEventHandler(anchor, 'click', performAction, false); }
});

/* Right Rail Include (Editorial Module) */
function rs_setEditorialModule (){

		var contentArr = [];
		/*find all tools-content*/
		jQuery('.tools-content').each(function(){
			contentArr.push(jQuery(this));
		})

		var liArr = [];
		/*find all tools-tab li*/
		jQuery('#tools-tab').find('li').each(function(){
			liArr.push(jQuery(this));
		})

		jQuery('#tools-tab').find('a').each(function(){
			var _this = jQuery(this);
			var _thisParent = _this.parent();
			var id =  _this.attr('href').substring(1);

			_thisParent.click(function(){
				jQuery.each(contentArr,function(){

					var arryThis = jQuery(this);
					if( arryThis.attr('id') === id){
						arryThis.css('display','block');
					} else{
						arryThis.css('display','none');
					}

				})

				jQuery.each(liArr,function(){
					jQuery(this).removeClass();
				})

				_thisParent.addClass('selected');
				_thisParent.addClass(id+'-selected');

				return false;

			}) //click

		}) // each

	}
rs_setEditorialModule ();
