/* 2008 HowStuffWorks, Inc. */

/**
 * HSW Javascript Namespace
 */

//Create function to create virtual local namespace,
//and immediately run it.
(function(){

	//Init hsw object
	var HSW =
	{
	};

	//Assign hsw to global namespace
	window.HSW = HSW;
})();

HSW.RealMedia = {
	adImpressions: new Array,
	referrer: {
		refCount: 0,
		setCookie: function() {
			if (this.refCount === 0)
			{
				setCookie('r', document.URL, false, false, 'howstuffworks.com');
				this.refCount = 1;
			}
		}
	}
}

var adBackgroundColor = '';

// Sets up the primary navigation in IE6
//if(($.browser.msie)&&(parseInt($.browser.version)<7))
var browser = navigator.appName;
var b_version = navigator.appVersion;
var version = parseFloat(b_version);
if ((browser=="Microsoft Internet Explorer") && (version < 7))
{
	$(document).ready(function()
	{
		$('#nav1>ul>li').each(function()
		{
			if(this.getAttribute('id')=="nav1HomeLink")
			{
				if(!$(this).hasClass("on"))
				{
					$(this).bind('mouseenter',function()
					{
						$(this).addClass("on");
					});
					$(this).bind('mouseleave',function()
					{
						$(this).removeClass("on");
					});
				}
			}
			else
			{
				if(!$(this).hasClass('divider'))
				{
					$(this).bind('mouseenter', function()
					{
						if(!$(this).hasClass("on"))
						{
							$(this).addClass($(this).hasClass("nosub")?"nosubhover":"hover");
						}
					});
					$(this).bind('mouseleave', function()
					{
						if(!$(this).hasClass("on"))
						{
							$(this).removeClass($(this).hasClass("nosub")?"nosubhover":"hover");
						}
					});
				}
			}
		});
		$('#nav2 > ul > li').each(function()
		{
			if(!$(this).hasClass('divider'))
			{
				$(this).bind('mouseenter', function()
				{
					$(this).addClass($(this).hasClass("nosub")?"nosubhover":"hover");
				});
				$(this).bind('mouseleave', function()
				{
					$(this).removeClass($(this).hasClass("nosub")?"nosubhover":"hover");
				});
			}
		});
		$('.moreBox').each(function()
		{
			$(this).bind('mouseenter', function()
			{
				$(".morePop").css(
				{
					display: 'block'
				});
			});
			$(this).bind('mouseleave', function()
			{
				$(".morePop").css(
				{
					display: 'none'
				});
			});
		});
		$('.shareBox').each(function()
		{
			$(this).bind('mouseenter', function()
			{
				$(".sharePop").css(
				{
					display: 'block'
				});
			});
			$(this).bind('mouseleave', function()
			{
				$(".sharePop").css(
				{
					display: 'none'
				});
			});
		});
		$('.shareVideo').each(function()
		{
			$(this).bind('mouseenter', function()
			{
				$(".sharePop").css(
				{
					display: 'block'
				});
			});
			$(this).bind('mouseleave', function()
			{
				$(".sharePop").css(
				{
					display: 'none'
				});
			});
		});
	});
}


/* tabbed modules functionality */

function getTabType1Content(str)
{
	return str.replace('tab-','tab-content-');
}

var tabSets=
{
	whatsHot:
	{
		css: '.vTabbed .tabs li a',
		tab2content: getTabType1Content,
		isCarousel: false
	},
	featuredItems:
	{
		css: '#featuredItems .tabs li a',
		tab2content: getTabType1Content,
		isCarousel: false
	},
	featuredSubTabs:
	{
		css: '#featured-articles .stabs li a',
		tab2content: getTabType1Content,
		isCarousel: true
	},
	popularSubTabs:
	{
		css: '#popular-articles .stabs li a',
		tab2content: getTabType1Content,
		isCarousel: true
	},
	doitSubTabs:
	{
		css: '#doit-articles .stabs li a',
		tab2content: getTabType1Content,
		isCarousel: true
	}
}

// does the initial tab set up of turning on/off the appropriate content and attaches the event listener to the tab link
function setUpTabs(key)
{
	var st=tabSets[key];
	st.currentTab=null;
	st.tabs = $(st.css);
	if(st.tabs.length>0)
	{
		st.tabs.each(function()
		{
			var subs=$('#'+st.tab2content(this.id)+' .stabs');
			if(subs.length>0)
			{
				var nd = $('ul', subs[0])[0];
				carousel.setUp(nd);
				if($(this).hasClass('on'))
				{
					carousel.setActive(nd, true);
				}
				$(this).bind('click', function()
				{
					carousel.setActive(nd);
				});
			}
			// if tab is flagged as "on" make sure the tab content is showing
			if($(this).hasClass('on'))
			{
				st.currentTab=this.id;
				$('#'+st.tab2content(this.id)).removeClass('off');
			}
			else
			{ // otherwise make sure it is not showing
				var cId=st.tab2content(this.id);
				if(!$('#'+cId).hasClass('off'))
				{
					$('#'+cId).addClass('off');
				}
			}

			// This comment does not adequately describe what is going on here (MCB)
			// attach onclick event listener to handle switching
			$(this).bind('click',function(e)
			{
				if(this.id!=st.currentTab)
				{
					$(this).addClass('on');
					$('#'+st.tab2content(this.id)).removeClass('off');
					$('#'+st.currentTab).removeClass('on');
					$('#'+st.tab2content(st.currentTab)).addClass('off');
					st.currentTab=this.id;
					if (this.id.substr(0,3) != 'tab')
					{
						carousel.stop();
					}
				}
				return false;
			});

		});
		if(st.isCarousel)
		{
			var gp=st.tabs[0].parentNode.parentNode.parentNode;
		}
		// if no tab was flagged as "on" at load time, flag the first one
		if(st.currentTab==null)
		{
			var cnt=0;
			$(st.tabs[cnt]).addClass('on');
			$('#'+st.tab2content(st.tabs[cnt].id)).removeClass('off');
			st.currentTab=st.tabs[cnt].id;
			var subs=$('#'+st.tab2content(st.currentTab)+' .stabs');
			if(subs.length>0)
			{
				var nd=$('ul',subs[0]);
				carousel.setActive(nd[0],true);
			}
		}
	}
}

/************ This doesn't seem to be in use *********************/

// doesn't the jquery dimensions library do this? (MCB)
// are we just trying to reduce bandwith by not including it? (MCB)
/*
function getOffsetLeft(nd)
{
	var par=nd;
	var ofp=0;
	do
	{
		ofp += par["offsetLeft"]||0;
		par =  par.offsetParent;
		if(par&&par.style.position=='relative')
		{
			par=null;
		}
	} while(par);
	return ofp;
};
*/
////////////////////////////////////////////////////////////////////

var nonWhiteSpace = /\S/;

function DOMCleanGecko (node)
{
        for (var i = 0; i < node.childNodes.length; i++)
        {
                var childNode = node.childNodes[i];
                // if it is a text node and only contains spaces
                if ((childNode.nodeType == 3) && (!nonWhiteSpace.test(childNode.nodeValue)))
                {
                        node.removeChild(node.childNodes[i]);
                        // it is generally considered bad style to alter control variable in a for loop.. (self dis) (MCB)
                        i--;
                }
                if (childNode.nodeType == 1) // normal node
                {
                        DOMCleanGecko(childNode);
                }
        }
}

// set up tabs on document ready
$(document).ready(function()
{
	// lets get rid of any / all the whitespace that could break the layout and complicate the DOM

	//try catch here because there is no nav2 on the homepage -> caused failure
	try
	{
		DOMCleanGecko(document.getElementById('nav1'));
		DOMCleanGecko(document.getElementById('nav2'));
	}
	catch (e)
	{

	}



	try
	{
		// we need to move the secondary top menu over (MCB)
		// so that it is touching whatever is selected from the nav1 menu (MCB)

		// first lets get into the top menu, all the way down to the first LI (MCB)
		var menuItemCurrent = document.getElementById('nav1').childNodes[0].childNodes[0];
		// loop through until we find the one that is selected (MCB)

		var selectedMenuItemOffset = 0;
		var count = 0;
		do
		{
			if (menuItemCurrent.className == 'on')
			{
				// we want to know where the right side of the selected menu item is
				selectedMenuItemOffset = menuItemCurrent.offsetLeft + menuItemCurrent.offsetWidth;
			}

			count++;
		} while (menuItemCurrent = menuItemCurrent.nextSibling)

		var menu2Width=document.getElementById('nav2').childNodes[0].offsetWidth;
		$("#nav2 > ul").css(
		{
			position: 'relative',
			left: Math.max((selectedMenuItemOffset - menu2Width), document.getElementById('nav1').childNodes[0].offsetLeft) + 'px'
		});

		$("#nav2").css(
		{
			visibility: 'visible',
			zIndex: '80'
		});

		$("#nav2 > ul").css(
		{
			zIndex: '80'
		});

		$("#nav2 > ul > li").css(
		{
			zIndex: '80'
		});

		$("#nav2 > li > .popNav").css(
		{
			zIndex: '80'
		});

	}
	catch (e)
	{
		//alert(e);
		// I guess their browser doesn't support something we were trying to do (MCB)
		// no matter... (MCB)
	}

	// loop through the tabbed modules list and run "setUpTabs" on each key
	for(var x in tabSets)
	{
		setUpTabs(x);
	}
	if(carousel.node==null)
	{
		var subs=$('#notab-content .stabs');
		if(subs.length>0)
		{
			var nd=$('ul',subs[0]);
			carousel.setActive(nd[0],true);
		}
	}
	$(window).load(function ()
	{
		carousel.start();
	});

	// Unbind all other click events for the prev/next tabs
	$('.tab-more a').unbind('click');
	$('.tab-less a').unbind('click');

	// Bind new click event for next/prev
	$('.tab-more a').click(next);
	$('.tab-less a').click(previous);

	// Count tabs and add a 'see more' if necessary
	if ($('#whatsInside .vTabbed .tabs ul li').length > 10)
	{
		$('#whatsInside .vTabbed .tabs ul').append('<li class="tab-more"><a href="#" class="tab-more-btn">More Topics</a></li>');
		$('.tab-more').click(next);
	}

	// Function for next
	function next(e)
	{
		e.preventDefault();
		$('#whatsInside .vTabbed .tabs ul li:visible:not(.tab-more):not(.tab-less)').each(function(i)
		{
			$(this).slideUp();
		});
		$('#whatsInside .vTabbed .tabs ul li.tab-more, #whatsInside .vTabbed .tabs ul li.tab-less').remove();
		$('#whatsInside .vTabbed .tabs ul li:hidden').each(function(i)
		{
			$(this).slideDown();
		});
		$('#whatsInside .vTabbed .tabs ul').prepend('<li class="tab-less"><a href="#" class="tab-less-btn">Previous Topics</a></li>');
		$('.tab-less').click(previous);
	}

	// Function for previous
	function previous(e)
	{
		e.preventDefault();
		$('#whatsInside .vTabbed .tabs ul li:visible:not(.tab-more):not(.tab-less)').each(function(i)
		{
			$(this).slideUp();
		});
		$('#whatsInside .vTabbed .tabs ul li.tab-more, #whatsInside .vTabbed .tabs ul li.tab-less').remove();
		$('#whatsInside .vTabbed .tabs ul').append('<li class="tab-more"><a href="#" class="tab-more-btn">More Topics</a></li>');
		$('.tab-more').click(next);
		$('#whatsInside .vTabbed .tabs ul li:hidden').each(function(i)
		{
			$(this).slideDown();
		});
	}
});

/* Triplet balloon toggle function */
function swapToggles(onId,offId)
{
	$('#'+onId).toggleClass('hidden');
	$('#'+offId).toggleClass('hidden');
}

/* featured module carousel functionality */
var carousel=
{
	defaultTiming: 10000, /*default timing for carousel in ms */
	direction: -1, /* direction the carousel is moving -1 for sliding left (right arrow, normal movement) 0 for sliding right (left arrow) */
	tracker: null, /* setTimeout tracking */
	node: null, /* tracks which carousel is currently active */
	items: null, /*tracks the LIs in the currently active carousel */
	moveUnit: 149, /* the amount to move per activation, the width of 1 item, set in the CSS (layout.css, #featuredItems .stabs ul li, width+padding) */
	continual: false,/* flag for continual animation */
	lastMoveDirection: -1,/* tracks the last movement in case there was a change during animation*/
	inMotion: false, /* tracks whether currently animating*/
	changedNodes: null, /* tracks whether the carousel was changed in mid-animation */
	finishScrolling: false,
	stop: function()
	{
		clearTimeout(carousel.tracker);
	},
	start: function()
	{
		if(!carousel.inMotion)
		{
			carousel.tracker=setTimeout(function(){carousel.move()},(carousel.continual?100:carousel.defaultTiming));
		}
	},
	move: function()
	{
		var nd=$(carousel.node);
		carousel.inMotion=true;
		carousel.endAnimation();
	},
	setActive: function(nd,setup)
	{
		carousel.stop();
		if(carousel.inMotion)
		{
			carousel.changedNodes=nd;
			return;
		}
		carousel.node=nd;
		carousel.items=$('li',this.node);
		if(!setup)
		{
			carousel.start();
		}
	},
	endAnimation: function()
	{
		carousel.inMotion=false;
		carousel.lastMoveDirection=carousel.direction;
		if(!carousel.continual)
		{
			if(carousel.finishScrolling)
			{
				carousel.finishScrolling=false;
			}
			else
			{
				if (carousel.items != null)
				{
					var nxt=false;
					carousel.items.each(function(idx)
					{
						var nds=$('a',this)[0];
						if($(nds).hasClass('on'))
						{
							nxt=true;
							if((idx + 1) == carousel.items.length)
							{
								var nd=$('a',carousel.items.get(0))[0];
								$(nd).triggerHandler('click');
							}
						}
						else if(nxt)
						{
							$(nds).triggerHandler('click');
							nxt=false;
						}
					});
				}
			}
		}
		if(carousel.changedNodes)
		{
			carousel.setActive(carousel.changedNodes);
			carousel.changedNodes=null;
		}
		else
		{
			carousel.start();
		}
	},
	/* set the direction for the next movement of the carousel (-1 or 0) */
	setDirection: function(dir)
	{
		carousel.direction=dir;
		if(!carousel.inMotion)
		{
			carousel.lastMoveDirection=dir;
		}
	},
	/* does the initial setup of the carousels during page load */
	setUp: function(nd)
	{
		// Stub function for now
	}
}

function textCounter(field,cntfield,maxlimit)
{
	// if too long...trim it!
	var countField = document.getElementById(field);
	var counterField = document.getElementById(cntfield);
	if (countField.value.length > maxlimit)
	{
		countField.value = countField.value.substring(0, maxlimit);
	}
	// otherwise, update 'characters left' counter
	else
	{
		counterField.value = maxlimit - countField.value.length;
	}
}

function inject_code(str)
{
	document.write(str);
}

function omnitureClick(str)
{
	var s=s_gi(s_account);
	void(s.tl(this,'o',str));
}

function getKeepAskingForm()
{
	$.ajax(
	{
		type: 'GET',
		url:  '/keep-asking-ajax.htm',
		dataType: 'html',
		cache: false,
		error: function ()
		{
		},
		success: function(msg)
		{
			$("#question").html(msg);
			swapToggles('answers','question');

			var s=s_gi(s_account);
			void(s.tl(this,'o','Home Pg : Keep Asking : Answer'));
		}
	});
}

function submitKeepAskingForm()
{
	var returnValue = true;
	if ($("#kaQuestion").val() == "")
	{
		$("#responseRequired").html("Please fill in missing required fields indicated in red above.");
		$("#kaQuestionLabel").css(
		{
			color: '#B00000'
		});
		returnValue = false;
	}
	else
	{
		$("#kaQuestionLabel").css(
		{
			color: '#000000'
		});
	}
	if ($("#kaName").val() == "")
	{
		$("#kaNameLabel").css(
		{
			color: '#B00000'
		});
		$("#responseRequired").html("Please fill in missing required fields indicated in red above.");
		returnValue = false;
	}
	else
	{
		$("#kaNameLabel").css(
		{
			color: '#000000'
		});
	}
	if ($("#kaCity").val() == "")
	{
		$("#kaCityLabel").css(
		{
			color: '#B00000'
		});
		$("#responseRequired").html("Please fill in missing required fields indicated in red above.");
		returnValue = false;
	}
	else
	{
		$("#kaCityLabel").css(
		{
			color: '#000000'
		});
	}
	if ($("#kaCountry").val() == "")
	{
		$("#kaCountryLabel").css(
		{
			color: '#B00000'
		});
		$("#responseRequired").html("Please fill in missing required fields indicated in red above.");
		returnValue = false;
	}
	else
	{
		$("#kaCountryLabel").css(
		{
			color: '#000000'
		});
	}
	if ($("#kaCountry").val() == "United States"  && $("#kaState").val() == "")
	{
		$("#kaStateLabel").css(
		{
			color: '#B00000'
		});
		$("#responseRequired").html("Please fill in missing required fields indicated in red above.");
		returnValue = false;
	}
	else
	{
		$("#kaStateLabel").css(
		{
			color: '#000000'
		});
	}
	$.ajax(
	{
		type: "POST",
		url: "keep-asking-ajax-response.htm",
		data: "kaQuestion=" + $("#kaQuestion").val() + "&kaName=" + $("#kaName").val() + "&kaCity=" + $("#kaCity").val() + "&kaCountry=" + $("#kaCountry").val() + "&kaState=" + $("#kaState").val() + "&kaCaptcha=" + $("#kaCaptcha").val(),
		success: function(msg)
		{
			//alert( msg );
			$("#responseRequired").html("");
			if (msg != "")
			{
				$("#responseRequired").html(msg);
				document.getElementById("keepAskingCaptcha").src = "captcha.png" + '?unique=' + new Date().valueOf();
			}
			else
			{
				message = "<p><b>Thank you for submitting your question!</b></p><br>";
				message += "<p>Please keep checking the home page over the next few days to see if  your question has been selected and posted with an answer.</p><br>";
				message += "<a class=\"keepAskingSuccessLink\" onclick=\"swapToggles(\'answers\',\'question\')\">Click here to go back home</a>\n";
				$("#keepAskingAnswers").css(
				{
					display: 'none'
				});
				$("#keepAskingSuccess").html(message);
			}
		}
	});
	return returnValue;
}

/* Bubble library code */

function bubble (options)
{
	this.subject      = null;
	this.text         = 'test';
	this.bubble1      = null;
	this.bubble2      = null;
	this.bubble3      = null;
	this.bubbleMain   = null;
	this.arrow        = null;
	this.style        = 'bubbleExpanding';
	this.direction    = 'right';
	this.align        = 'left';
	this.width        = 200;
	this.timeout      = null;

	if (typeof options.text != 'undefined')
	{
		this.text = options.text;
	}
	if (typeof options.subject != 'undefined')
	{
		this.subject = options.subject;
	}
	if (typeof options.style != 'undefined')
	{
		this.style = options.style;
	}
	if (typeof options.direction != 'undefined')
	{
		this.direction = options.direction;
	}
	if (typeof options.align != 'undefined')
	{
		this.align = options.align;
	}

	this.show();
}

bubble.prototype.show = function ()
{
		// offsetLeft only works on absolute or relative positioned elemented
		this.subject.style.position = 'relative';

		if (this.style == 'bubbleExpanding')
		{
			this.bubble1              = this.addDiv (this.subject.offsetLeft + this.subject.offsetWidth - 21, this.subject.offsetTop - 1, 13, 8);
			this.bubble2              = this.addDiv (this.subject.offsetLeft + this.subject.offsetWidth - 15, this.subject.offsetTop - 10, 20, 15);
			this.bubble3              = this.addDiv (this.subject.offsetLeft + this.subject.offsetWidth - 7, this.subject.offsetTop - 20, 30, 22);
			this.bubbleMain           = this.addDiv (this.subject.offsetLeft + this.subject.offsetWidth + 4, this.subject.offsetTop - 35, null, null, this.text);
		}
		else if (this.style == 'block')
		{
			if (this.align == 'left')
			{
				this.bubbleMain           = this.addDiv (this.subject.offsetLeft, this.subject.offsetTop + this.subject.offsetHeight, this.width, null, this.text);
			}
			else
			{
				this.bubbleMain           = this.addDiv ((document.documentElement.clientWidth) - (this.subject.offsetLeft + this.subject.offsetWidth), this.subject.offsetTop + this.subject.offsetHeight + 10, this.width, null, this.text);
				this.arrow = document.createElement('IMG');
				this.bubbleMain.parentNode.insertBefore(this.arrow, null);
				this.arrow.src = 'http://static.howstuffworks.com/en-us/www/style/bubblePointerUp.gif';
				this.arrow.style.position = 'absolute';
				this.arrow.style.left = this.bubbleMain.offsetLeft + parseInt(this.width * 5/6) + 'px';
				this.arrow.style.top = (this.bubbleMain.offsetTop - 9) + 'px';
				this.arrow.style.zIndex = 1000;
			}
		}
};

bubble.prototype.showSupportingBubble = function (depth)
{
	var tempHeight = this.bubbleMain.offsetHeight * 0.8;
	var offsetTop = this.bubbleMain.offsetHeight * 0.1;
	this.addDiv (this.bubbleMain.offsetLeft - (this.bubbleMain.offsetLeft - this.subject.offsetLeft) * 0.1, (this.bubbleMain.offsetHeight * 0.8));

//Width - 7, this.subject.offsetTop - 20, 30, 22);
}

bubble.prototype.addDiv = function (x, y, width, height, text)
{
	var tempDiv = document.createElement('DIV');
	tempDiv.style.position = 'absolute';
	tempDiv.style.zIndex = 999;
	if (text)
	{
		var my = this;
		tempDiv.innerHTML = text;
		tempDiv.style.padding = '9px';
		tempDiv.style.borderWidth = '2px';
		tempDiv.style.MozBorderRadius = '5px';
		tempDiv.style.webkitBorderRadius = '5px';
		tempDiv.style.width = width + 'px';
		$(tempDiv).click(function ()
		{
			my.remove();
		});
		$(this.subject).mouseout(function (e)
		{
			my.timeout = setTimeout(function ()
			{
				my.remove();
			}, 500);
		});
		$(tempDiv).mouseover(function (e)
		{
			clearTimeout(my.timeout);
		});
		$(tempDiv).mouseout(function (e)
		{
			// if firefox (MCB)
			// AND not moving out of childNode into the original (MCB)
			// AND the node they moved to is inside the original (MCB)
			if(e.relatedTarget && (e.relatedTarget != this) && (e.relatedTarget.parentNode != this))
			{
				my.remove();
			}
		});
	}
	else
	{
		tempDiv.style.width = width + 'px';
		tempDiv.style.height = height + 'px';
		tempDiv.style.borderWidth = '1px';
		tempDiv.style.MozBorderRadius = '15px';
		tempDiv.style.webkitBorderRadius = '15px';
	}
	tempDiv.style.borderStyle = 'solid';
	tempDiv.style.borderColor = '#AAA';
	tempDiv.style.backgroundColor = '#fff';
	tempDiv.style.MozBorderRadius = '5px';
	tempDiv.style.webkitBorderRadius = '5px';
	tempDiv.style.borderRadius = '10px';
	if (this.align == 'left')
	{
		tempDiv.style.left = x + 'px';
	}
	else
	{
		tempDiv.style.right = x + 'px';
	}
	tempDiv.style.top = y + 'px';
	document.body.appendChild (tempDiv);
	return tempDiv;
};

bubble.prototype.remove = function ()
{
	if (this.bubbleMain)
	{
		this.bubbleMain.parentNode.removeChild(this.bubbleMain);
		this.bubbleMain = null;
	}
	if (this.bubble1)
	{
		document.body.removeChild(this.bubble1);
	}
	if (this.bubble2)
	{
		document.body.removeChild(this.bubble2);
	}
	if (this.bubble3)
	{
		document.body.removeChild(this.bubble3);
	}
	if (this.arrow)
	{
		this.arrow.parentNode.removeChild(this.arrow);
		this.arrow = null;
	}
}

//Here is an example of how to use this
/*
setTimeout("doit();", 1500);
function doit ()
{
	myBubble = new bubble (document.getElementById('urlLandingPage'), 'blah blah blah');
}
*/

$(document).ready(function()
{
	$("#random-article").bind("mouseover", function(e)
	{
		setTimeout(function ()
		{
			new bubble (
			{
				subject : document.getElementById('random-article'),
				style   : 'block',
				align   : 'right',
				text    : '<h3 style=\"color: #005288;\">Random Article</h3>The Random Article tool gives you a completely random article with every click.  Try it and discover something new every time.<br/><a id=\"random-article-link\" href=\"/random-article\" style=\"float: right;\">try it &raquo;</a>'
			});

			$("#random-article-link").attr('onclick', $("#random-article").attr('onclick'));
		}, 1000);
	});

	$("#random-video").bind("mouseover", function(e)
	{
		setTimeout(function ()
		{
			new bubble (
			{
				subject : document.getElementById('random-video'),
				style   : 'block',
				align   : 'right',
				text    : '<h3 style=\"color: #005288;\">Random Video</h3>The Random Video tool gives you a completely random video with every click.  Try it and discover something new every time.<br/><a id=\"random-video-link\" href=\"/random-video\" style=\"float: right;\">try it &raquo;</a>'
			});

			$("#random-video-link").attr('onclick', $("#random-video").attr('onclick'));
		}, 1000);
	});
});

/* © 2008 HowStuffWorks, Inc. */
// Start cookie handling functions

function getCookie(name)
{
	var start = document.cookie.indexOf(name + "=");
	var len = start + name.length + 1;
	if ((!start) && (name != document.cookie.substring(0, name.length))) {
		return null;
	}
	if (start == -1) return null;
	var end = document.cookie.indexOf(";", len);
	if (end == -1) end = document.cookie.length;
	return unescape(document.cookie.substring(len, end));
}

function setCookie(name, value, expires, path, domain, secure)
{
	var today = new Date();
	today.setTime(today.getTime());
	if (expires) {
	expires = expires * 1000 * 60 * 60 * 24;
	}
	var expires_date = new Date(today.getTime() + (expires));
	document.cookie = name + "=" + escape(value) +
	((expires) ? ";expires=" + expires_date.toGMTString() : "") + //expires.toGMTString()
	((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "") +
	((secure) ? ";secure" : "");
}

function deleteCookie(name, path, domain)
{
	if (getCookie(name)) document.cookie = name + "=" +
	((path) ? ";path=" + path : "") +
	((domain) ? ";domain=" + domain : "" ) +
	";expires=Thu, 01-Jan-1970 00:00:01 GMT";
}

// This function checks to see if the HSW cookie is set.  If so, it returns
// true. If not, false.
function getHSWCookie()
{
	var results = document.cookie.match('HSWCookie' + '=(.*?)(;|$)');

	if (results) {
		return true;
	} else {
		return null;
	}
}

// If the HSWCookie is not set, then display the log in/register link.  If it
// is, then display the logout link.  This is used in the Opinion block of the
// left navbar.
function checkHSWCookie()
{
	if (!getHSWCookie()) {
		document.write('<li id="rccStatus">&nbsp;&nbsp;<a href="/login.php">Log In/Register</a></li>')
	}
	else {
		document.write('<li id="rccStatus">&nbsp;&nbsp;<a href="/logout.php">Log Out</a></li>');
	}
}

// End cookie handling


// A little Web 2.0 for ya...
function createRequestObject()
{
	var ro;
	var browser = navigator.appName;
	if(browser == "Microsoft Internet Explorer"){
		ro = new ActiveXObject("Microsoft.XMLHTTP");
	} else {
		ro = new XMLHttpRequest();
	}
	return ro;
}

// Functions to handle pulling in cobranded headers if applicable
var cobrand = createRequestObject();
var cobrand_firstpageonly = false;

function sendCobrandRequest()
{
	var ref = document.referrer;
	if(cobrand_firstpageonly != true) {
		var refcookie = getCookie('HSWPartner');
		if(refcookie != "" && refcookie != null && refcookie != undefined) {
			ref = refcookie;
		}
	}
	// Be sure we have a valid partner so we don't make unnecessary HTTP calls
	var partner = getPartner(ref);
	if(partner == "" || partner == undefined || partner == null) {
		return;
	}
	if(cobrand_firstpageonly != true) {
		if(refcookie == "" || refcookie == null || refcookie == undefined) {
			setCookie('HSWPartner', ref, '', '/', '.howstuffworks.com');
		}
	}
	var cobrand_url = 'cobrand.htm?partner='+partner;
	cobrand.open('get', cobrand_url);
	cobrand.onreadystatechange = handleResponse;
	cobrand.send(null);
}

function getPartner(ref)
{
	if(ref.indexOf('www.forbestraveler.com') >= 0) {
		return 'forbestravel';
	} else {
		return '';
	}
}

function handleResponse()
{
	switch(cobrand.readyState)
	{
		case 1:
		case 2:
		case 3:
			break;
		case 4:
			if(cobrand.responseText != '' && cobrand.responseText != null) {
				document.getElementById('coBrand').style.display='';
				document.getElementById('coBrandContents').innerHTML=cobrand.responseText;
			}
			break;
		default:
			break;
	}
}

// End cobrand code

// Function for in-page video player
function embedVideo(videofile)
{
	var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage.php?pageID='+videofile+'" name="vidFrame" frameborder=0 width=420 hscroll=no vscroll=no height=410>Your Browser Does Not Support iFrames</iframe>';
	document.write(msg);
}
function embedVideoSmall(videofile)
{
	var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage_s.php?pageID='+videofile+'" name="vidFrame" frameborder=0 width=225 hscroll=no vscroll=no height=195>Your Browser Does Not Support iFrames</iframe>';
	document.write(msg);
}
function embedVideoPlain(videofile)
{
	var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage_plain.php?pageID='+videofile+'" name="vidFrame" frameborder="0" width="420" hscroll="no" vscroll="no" height="410">Your Browser Does Not Support iFrames</iframe>';
	document.write(msg);
}
function embedVideo280(videofile)
{
	var msg = '<iframe src="http://videos.howstuffworks.com/vid_inpage_280.php?pageID='+videofile+'" name="vidFrame" frameborder=0 width=290 hscroll=no vscroll=no height=300>Your Browser Does Not Support iFrames</iframe>';
	document.write(msg);
}


// New video 2.0 javascript calls
function inPagePlayer (videoId, args)
{
	args = args ? args : {};

	var url       = 'http://videos.howstuffworks.com/inline-player.htm';
	var winWidth  = 460;
	var winHeight = 496;
	var noSkin    = 0;

	options = new Array;
	options.push('videoId=' + videoId);
	options.push('adCode=' + escape(OAS_sitepage));

	if (args.noSkin)
	{
		options.push('noSkin=' + (args.noSkin ? noSkin = 1 : 0));
	}

	if (args.width != null)
	{
		options.push('width=' + args.width);

		if (noSkin)
		{
			winWidth = args.width;
		}
	}

	if (args.height)
	{
		options.push('height=' + args.height);

		if (noSkin)
		{
			winHeight = args.height;
		}
	}

	if (args.autostart)
	{
		options.push('autostart=' + (args.autostart ? 1 : 0));
	}

	var msg = '<br><iframe  style="clear: both;"  src="' +  url + '?' + options.join('&') + '" name="vidFrame" frameborder="0" width="' + winWidth + '" hscroll="no" vscroll="no" scrolling="no" height="' +  winHeight + '">'
	        + 'Your Browser Does Not Support iFrames'
	        + '</iframe>';

	document.write(msg);
}

function inject_code(str) {
	document.write(str);
}

function browserAcceptsCookies() {
	var HSW_acceptsCookies = false;
	if (document.cookie == '') {
		document.cookie = 'HSW_acceptsCookies=yes';
		if (document.cookie.indexOf('HSW_acceptsCookies=yes') != -1) {
			HSW_acceptsCookies = true;
		}
	}
	else {
		HSW_acceptsCookies = true;
	}
	return (HSW_acceptsCookies);
}

function recordStats(webpage,referer) {
}

function tsStats(parms)
{
  var _bs = '<img height=1 width=1 border=0 src="http://www.howstuffworks.com/tsform.php?'+parms+'">';
  document.write(_bs);
}

function OpenWindow(url)
{
	newwindow = window.open ("/" + url, 'HowStuffWorks', 'status=no,toolbar=no,location=no,menubar=no,scrollbars=yes,resizable=yes,width=485,height=675');
}

function OpenWindow2(url,h,w)
{
	newwindow = window.open ("/" + url, 'HowStuffWorks', 'status=no,toolbar=no,location=no,menubar=no,scrollbars=no,resizable=no,width=' + w + ',height=' + h);
}

var RN = new String (Math.random());
var RNS = RN.substring(2,11);
//var RNS = "1290781908475";

function DisplayAds (sitepage, position, width, height)
{
	var oas = 'http://ad.howstuffworks.com/RealMedia/ads/';
	var oaspage = sitepage + '/1' + RNS + '@' + position;

	if (_version < 11) {
		document.write ('<A HREF="' + oas + 'click_nx.ads/' + oaspage + '" TARGET="_top"><IMG SRC="' + oas + 'adstream_nx.ads/' + oaspage + '" BORDER="0" WIDTH="' + width + '" HEIGHT="' + height + '"></a>');
	} else {
		document.write ('<SCRIPT LANGUAGE="JavaScript1.1" SRC="' + oas + 'adstream_jx.ads/' + oaspage + '">');
		document.write ('\<\!-- --\>');
		document.write ('\<\/SCRIPT\>');
		document.write ('\<\!-- --\>');
	}
}

function showImage(html)
{
	windowOps = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes," +
			  "width=500,height=500,left=250,top=50";
	ImageWindow = window.open("","ImageWindow",windowOps);
	windowHTML = '<html><body><base href="http://www.howstuffworks.com/"><center><font face="arial,helvetica">' + html +
			   '<p><font face="arial,helvetica">' +
			   '<a href="javascript:window.close();">Click here</a> to close this window.</font></center>' +
			   '</body></html>';
	self.ImageWindow.document.clear();
	self.ImageWindow.document.write(windowHTML);
	self.ImageWindow.focus();
	self.ImageWindow.document.close();
}

function tryIt(HTML)
{
	windowOps = "toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=yes," +
			  "width=500,height=500,left=250,top=50";
	ImageWindow = window.open("","ImageWindow",windowOps);
	windowHTML = '<html><body>' + HTML +
			   '<p><font face="arial,helvetica">' +
			   '<A HREF="javascript:window.close();">Click here</a> to close this window.</font>' +
			   '</body></html>';
	self.ImageWindow.document.clear();
	self.ImageWindow.document.write(windowHTML);
	self.ImageWindow.focus();
	self.ImageWindow.document.close();
}

function shopTI(url,lid)
{
	if (url.indexOf("LINKIN_ID") == -1) {
		url="http://"+escape(url.substring(7))+"/LINKIN_ID-"+lid;
	}

	return url;
}

function videoWin(id)
{
	window.open('mediacenter/mcPlayerFull.php?vidID='+id,'mcPlayer','width=740,height=440,menubar=no,status=no,location=no,toolbar=no,scrollbars=yes,resizable=yes');
}

function getRccStatus()
{
	// this hasn't been optimized for IE7 (MCB)
	// as of IE7, ActiveXObjects should be the fallback, not the default (MCB)
	// really, we should just be using jquery's ajax (MCB)

	var xmlhttp=false;

	try {
		xmlhttp = new ActiveXObject('Msxml2.XMLHTTP');
	} catch (e) {
		try {
			xmlhttp = new
			ActiveXObject('Microsoft.XMLHTTP');
		} catch (E) {
			xmlhttp = false;
		}
	}

	if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
		xmlhttp = new XMLHttpRequest();
	}

	var file = '/rccStatus.php';
	xmlhttp.open('GET', file, true);

	xmlhttp.onreadystatechange=function() {

		if (xmlhttp.readyState == 4) {
			if (xmlhttp.status == 200 && xmlhttp.responseText){
				document.getElementById ("rccStatus").innerHTML = xmlhttp.responseText;
			}
		}
	}

	xmlhttp.send(null)
	return;
}

function D_findPosX(obj)
{
	var curleft = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

function D_findPosY(obj)
{
	var curtop = 0;
	if (obj.offsetParent)
	{
		while (obj.offsetParent)
		{
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}


// Locates a div, moves it to its parent's bottom right and
// displays it
function revealDiv (divID, parentID)
{
	this._timeout = 0;
	this._element = document.getElementById (divID);
	this._parent  = document.getElementById (parentID);
}

revealDiv.prototype.show = function ()
{
	this._clear ();
	var y    = D_findPosY (this._parent) + this._parent.clientHeight;
	var doc  = document.getElementById ('doc');
	var docX = D_findPosX (doc);

	this._element.style.top   = y;
	this._element.style.left  = (docX + doc.clientWidth - this._element.offsetWidth) + 'px';
	this._element.style.visibility = 'visible';
}

revealDiv.prototype.hide = function (divID)
{
	element = this._element;
	this._timeout = setTimeout (function () {
		element.style.visibility = 'hidden';
	}, 500);
}

revealDiv.prototype._clear = function ()
{
	if (this._timeout == 0)
		return;

	window.clearTimeout (this._timeout);
	this._timeout = 0;
}


//Video player
hswVideoOverlay =
{
	//Private members
	_documentWrite: null,
	_bufferContent: '',
	_bufferStatus:  false,
	_randomNumber:  null,

	//Public methods
	displayAds: function ()
	{
		//Empty element
		$('#inlinePlayerAds').html('');

		//Save old document.write
		this._documentWrite = document.write;

		//Create new document.write, buffer all writes
		document.write = function (string)
		{
			//Start buffer if starting script
			if (string.match(/^<script/))
			{
				hswVideoOverlay._bufferStatus = true;

				return;
			}

			//End buffer if ending script
			if (string.match(/^<\/script/))
			{
				eval(hswVideoOverlay._bufferContent);

				hswVideoOverlay._bufferStatus  = false;
				hswVideoOverlay._bufferContent = '';

				return;
			}

			if (hswVideoOverlay._bufferStatus)
			{
				hswVideoOverlay._bufferContent += string;

				return;
			}

			$('#inlinePlayerAds').append(string);
		}

		//Throw in ad html in element
		$('#inlinePlayerAds').append(
			this.getAdString("x58,x59!x58", "400", "75") +
			this.getAdString("x58,x59!x59", "150", "700")
		);
	},

	getAdString: function (position, width, height)
	{
		//Init
		var oas      = OAS_url;
		var oaspage  = OAS_sitepage + '/1' + this.getRandomNumber() + '@' + position;
		var adString = '';

		//Return correct string depending on b rowser
		if (OAS_version < 11)
		{
			adString += '<A HREF="' + oas + 'click_nx.ads/' + oaspage + '" TARGET="_top"><IMG SRC="' + oas + 'adstream_nx.ads/' + oaspage + '" BORDER="0" WIDTH="' + width + '" HEIGHT="' + height + '"></a>';
		}
		else
		{
			adString += '<SCRIPT LANGUAGE="JavaScript1.1" SRC="' + oas + 'adstream_jx.ads/' + oaspage + '">';
			adString += '\<\!-- --\>';
			adString += '\<\/SCRIPT\>';
			//adString += '<SCRIPT>';
			//adString += '\hswVideoOverlay.fillBuffer(\'' + element + '\');';
			//adString += '\<\/SCRIPT\>';
			adString += '\<\!-- --\>';
		}

		return adString;
	},

	getRandomNumber: function ()
	{
		if (this._randomNumber == null)
		{
			var rn = new String(Math.random());
			this._randomNumber = rn.substring(2,11);
		}

		return this._randomNumber;
	}
}

/**************
RealMedia page manipulator.
This is a static class: no prototyping required
**************/
var realMediaPM =
{
	_cssRules: (document.all ? 'rules' : 'cssRules'),

	_classChange: new Array (
		//'.header .nav',
		//'.scrollerFeature',
		//'.scrollerFeature .today'
	),

	changeColor: function (color)
	{
		adBackgroundColor = color;
	},

	setColor: function (color)
	{
		document.body.style.background = color;

		for (i in this._classChange)
		{
			for (var S = 0; S < document.styleSheets.length; ++S)
			{
				for (var R = 0; R < document.styleSheets[S][this._cssRules].length; R++)
				{
					if (document.styleSheets[S][this._cssRules][R].selectorText == this._classChange[i])
					{
						document.styleSheets[S][this._cssRules][R].style['background'] = color;
					}
				}
			}
		}
	},

	changeVideoOverlayBackground: function (url)
	{
		$(document).ready(function(){
			$.fn.hswModal._defaultOptions.backgroundImage = "url('" + url + "')";
			$.fn.hswModal._args.backgroundImage = "url('" + url + "')";
			$.fn.hswModal.changeModalBg({backgroundImage: "url('" + url + "')"});
		});
	},

	changeVideoOverlayTransparency: function (transparency)
	{
		$(document).ready(function(){
			$.fn.hswModal._defaultOptions.opacity = transparency;
			$.fn.hswModal._args.opacity = transparency;
			$.fn.hswModal.changeModalBg({opacity: transparency});
		});
	}
}

function makeHomePage(domain)
{
	var obj = document.getElementById("hplink");

	if (!domain)
		domain = "http://www.howstuffworks.com";

	//special case for FireFox
	if(window.sidebar)
	{
		window.sidebar.addPanel('HowStuffWorks', domain, "");
	}
	else
	{
		if(navigator.appName == "Microsoft Internet Explorer" && (parseInt(navigator.appVersion) >= 4)) { // IE 4+
			obj.style.behavior="url(#default#homepage)";
			obj.setHomePage(domain);
		}
		else {
			// anything else
			sethp = window.open("/sethomepage.php", "sethp", "toolbar=0,location=0,status=0,menubar=0,scrollbars=0,resizable=0,width=500,height=300,alwaysRaised=yes,screenX=250,screenY=250,top=250,left=250,alwaysRaised=yes");
		}
	}
}


/**
 * Function to swap active tabs on the healthbox (appears in all health content
 */
function swapHealthBox(display) {
	switch(display) {
		case "symptom":
			document.getElementById("diseases").style.visibility = "hidden";
			document.getElementById(display).style.visibility = "visible";
		break;
		case "diseases":
			document.getElementById("symptom").style.visibility = "hidden";
			document.getElementById(display).style.visibility = "visible";
		break;
	}
}


/**
 * Stub for annoying video player invalid function
 */

function onFSCommand ()
{
}


