/* � 2008 HowStuffWorks, Inc. */

// 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()
			{
				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;
				}
				return false;
			});

		});
		if(st.isCarousel)
		{
			var gp=st.tabs[0].parentNode.parentNode.parentNode;
			$(gp).bind('mouseenter',function()
			{
				carousel.pause();
			});
			$(gp).bind('mouseleave',function()
			{
				carousel.unpause();
			});
		}
		// if no tab was flagged as "on" at load time, flag the first one
		if(st.currentTab==null)
		{
			var cnt=st.isCarousel?1: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)
	{
		//alert(e);
		// Invoked on a page that has no navigation, nav1/nav2
	}

	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);
		}
	}
	// set up left arrows in featured module
	$('#featuredItems .arrow-left').each(function()
	{
		$(this).bind('mouseenter',function()
		{
			carousel.setDirection(0);
			carousel.stop();
			carousel.continual=true;
			carousel.start();
		});
		$(this).bind('mouseleave',function()
		{
			carousel.setDirection(-1);
			carousel.stop();
			carousel.continual=false;
			carousel.finishScrolling=true;
			carousel.start();
		});

	});
	// set up right arrows in featured module
	$('#featuredItems .arrow-right').each(function()
	{
		$(this).bind('mouseenter',function()
		{
			carousel.stop();
			carousel.continual=true;
			carousel.start();
		});
		$(this).bind('mouseleave',function()
		{
			carousel.stop();
			carousel.continual=false;
			carousel.finishScrolling=true;
			carousel.start();
		});
	});
	$(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 > .tabs ul li').length > 10)
	{
		$('#whatsInside > .tabs ul').append('<li class="tab-more"><a href="#">More Topics &#9660;</a></li>');
		$('.tab-more').click(next);
	}

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

	// Function for previous
	function previous(e)
	{
		e.preventDefault();
		$('#whatsInside > .tabs ul li:visible:not(.tab-more):not(.tab-less)').each(function(i)
		{
			$(this).slideUp();
		});
		$('#whatsInside > .tabs ul li.tab-more, #whatsInside > .tabs ul li.tab-less').remove();
		$('#whatsInside > .tabs ul').append('<li class="tab-more"><a href="#">More Topics &#9660;</a></li>');
		$('.tab-more').click(next);
		$('#whatsInside > .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: 9000, /*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) */
	paused: false, /* flag to pause the animations */
	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.paused&&!carousel.inMotion)
		{
			carousel.tracker=setTimeout(function(){carousel.move()},(carousel.continual?100:carousel.defaultTiming));
		}
	},
	move: function()
	{
		var nd=$(carousel.node);
		carousel.inMotion=true;
		nd.animate(
		{
			left: carousel.moveUnit * 2 * carousel.direction
		},
		1000,
		"linear",
		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();
		}
	},
	swapNodes: function()
	{
		if(carousel.lastMoveDirection==-1)
		{
			carousel.node.appendChild(carousel.node.removeChild(carousel.items[0]));
		}
		else
		{
			carousel.node.insertBefore(carousel.node.removeChild(carousel.items[carousel.items.length-1]),carousel.items[0]);
		}
		$(carousel.node).css('left',carousel.moveUnit*(-1));
		carousel.items=$('li',carousel.node);
	},
	endAnimation: function()
	{
		carousel.inMotion=false;
		carousel.swapNodes();
		carousel.lastMoveDirection=carousel.direction;
		if(!carousel.continual)
		{
			if(carousel.finishScrolling)
			{
				carousel.finishScrolling=false;
			}
			else
			{
				var nxt=false;
				carousel.items.each(function()
				{
					var nds=$('a',this)[0];
					if($(nds).hasClass('on'))
					{
						nxt=true;
					}
					else if(nxt)
					{
						$(nds).triggerHandler('click');
						nxt=false;
					}
				});
			}
		}
		if(carousel.changedNodes)
		{
			carousel.setActive(carousel.changedNodes);
			carousel.changedNodes=null;
		}
		else
		{
			carousel.start();
		}
	},
	/* shows the "paused" message and stops the carousel*/
	pause: function()
	{
		$('.message div',carousel.node.parentNode).toggleClass('hidden');
		carousel.paused=true;
		carousel.stop();
	},
	/* unpauses the carousel, hides the message,  and starts the timer */
	unpause: function()
	{
		$('.message div',carousel.node.parentNode).toggleClass('hidden');
		carousel.paused=false;
		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)
	{
		var itms=$('li',nd);
		if($(itms[itms.length-1]).hasClass('on'))
		{
			$(itms[itms.length-1]).removeClass('on');
		}
		$(nd).css('left',carousel.moveUnit*(-1));
		nd.insertBefore(nd.removeChild(itms[itms.length-1]),itms[0]);
	}
}

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(true,'o',str));
}

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

			var s=s_gi(s_account);
			void(s.tl(true,'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;
}

