jQuery.preloadImages = function()
{
  for(var i = 0; i<arguments.length; i++)
  {
    jQuery("<img>").attr("src", arguments[i]);
  }
}

$.preloadImages(
		"images/dynamic-window-images/dynabox_pop_img_tl.png", 
		"images/dynamic-window-images/dynabox_pop_img_tc.png",
		"images/dynamic-window-images/dynabox_pop_img_tr.png",
		"images/dynamic-window-images/dynabox_pop_img_ml.png",
		"images/dynamic-window-images/dynabox_pop_img_mc.png",
		"images/dynamic-window-images/dynabox_pop_img_mr.png",
		"images/dynamic-window-images/dynabox_pop_img_bl.png",
		"images/dynamic-window-images/dynabox_pop_img_bc.png",
		"images/dynamic-window-images/dynabox_pop_img_br.png",
		"images/dynamic-window-images/dynabox_pop_vid_ml.png",
		"images/dynamic-window-images/dynabox_pop_vid_mc.png",
		"images/dynamic-window-images/dynabox_pop_vid_mr.png",
		"images/dynamic-window-images/dynabox_pop_vid_bl.png",
		"images/dynamic-window-images/dynabox_pop_vid_bc.png",
		"images/dynamic-window-images/dynabox_pop_vid_br.png",
		"images/dynamic-window-images/dynabox_pop_capt_lft.gif",
		"images/dynamic-window-images/dynabox_pop_capt_rgt.gif",
		"images/dynamic-window-images/dynabox_icn_close.png",
		"images/dynamic-window-images/dynabox_loading.gif",
		"images/dynamic-window-images/dynabox_macFFBgHack.png",
		"images/dynamic-window-images/dynabox_appearover-background.png",
		"images/dynamic-window-images/dynabox_appearover-bottom-cap.png",
		"images/dynamic-window-images/dynabox_appearover-bullet.gif",
		"images/dynamic-window-images/dynabox_appearover-divider.png",
		"images/dynamic-window-images/dynabox_appearover-gradient.png",
		"images/dynamic-window-images/dynabox_appearover-gradient-short.png",
		"images/dynamic-window-images/dynabox_appearover-highlight.png",
		"images/dynamic-window-images/dynabox_appearover-menu-item.png",
		"images/dynamic-window-images/dynabox_appearover-top-cap.png"
);
/*--------------------------- dynamicBox ----------------------------*/

/**
 * if an argument is sent, this close functionality will confirm the user wants to close
 * the window before closing it
 */
function dynamicBoxEnd() {
	var closeIt = true; // default to automatic closing
	if (arguments.length > 0 ) { closeIt = false; }
	
	// confirm before closing
	if (!closeIt) {
		var msg = "Are you sure you want to close this window?\nAny information you have entered will be lost.";
		if (confirm(msg)) {
			closeIt = true;
		}
	}
	
	if (closeIt) {
		$("#dynamicBox, #popLoading, #popShadow").remove();
		$("#blur-overlay").fadeOut("fast", function() { $(this).remove(); });
		$('embed, object, select').css({ 'visibility' : 'visible' });
	}	
	
}

function featureLocOverlay() {
	var arrPageSizes = getPageSize();
	$('#blur-overlay').css({
		width: arrPageSizes[0],
		height: arrPageSizes[1]
	});
}

function featureLocBox() {
	var arrPageSizes = getPageSize();
	var arrayPageScroll = getPageScroll();
	var fromLeft = ((arrPageSizes[2]-$('#dynamicBox').width())/2)+arrayPageScroll[0];
	var fromTop = ((arrPageSizes[3]-$('#dynamicBox').height())/2)+arrayPageScroll[1];
	$('#dynamicBox').css({
		left:	fromLeft < 0 ? 0 : fromLeft,
		top: fromTop < 0 ? 10 : fromTop
	}).show();
}

function parseFeatureQuery ( query ) {
  	var Params = {};
  	if ( ! query ) {return Params;}// return empty object
  	var Pairs = query.split(/[;&]/);
  	for ( var i = 0; i < Pairs.length; i++ ) {
    	var KeyVal = Pairs[i].split('=');
    	if ( ! KeyVal || KeyVal.length != 2 ) {continue;}
      var key = unescape( KeyVal[0] );
      var val = unescape( KeyVal[1] );
      val = val.replace(/\+/g, ' ');
      Params[key] = val;
  	}
  	return Params;
}
	
function featureWinLoaded(obj) {
	var objWidth = $(obj).width() - 6;
	var objHeight = $(obj).height() + 10;

	var arrPageSizes = getPageSize();
	var arrayPageScroll = getPageScroll();
	var fromLeft = ((arrPageSizes[2]-objWidth)/2)+arrayPageScroll[0];
	var fromTop = ((arrPageSizes[3]-objHeight)/2)+arrayPageScroll[1];
	fromLeft = fromLeft < 0 ? 0 : fromLeft;
	fromTop = fromTop < 0 ? 0 : fromTop;

	$("#popLoading").fadeOut("fast",function() { 
		$("#popLoading").remove(); 
		$("#dynamicBox, #dynamicBox .container").width(objWidth).height(objHeight);		
		
		$('#dynamicBox').animate({ top: fromTop, left:	fromLeft }, 500);
		$("#popShadow .mc").animate({ height: objHeight+"px", width: objWidth+"px" }, 500, function() {
			
			if (obj.attr("id")=="popImg")
				$("#popImg, #dynamicBox .imgCaption").css({display:"block"});
			else
				$("#popIframeContent").css({display:"block"});

			$("#popClose").css({ top: "-10px", left: objWidth + "px" }).show();
			/*
			if (obj.hasClass("taxCalc")||obj.hasClass("helpMeChoose")) {
				$("#popShadow").hide();
			}	else if (!(obj.attr("id")=="popImg")){
				$("#dynamicBox .fadeTop").css({ top: "18px", left: "10px", width: objWidth - 15 + "px" }).show();
				$("#dynamicBox .fadeBtm").css({ top: objHeight - 12 + "px", left: "10px", width: objWidth - 15 + "px" }).show();
			}
			*/				
			
		});
		$("#popShadow .ml, #popShadow .mr").animate({ height: objHeight+"px" }, 500);
		$("#popShadow .tc, #popShadow .bc").animate({ width: objWidth+"px" }, 500);
	});
	
}

/*--------------------------- Page Sizes ----------------------------*/

function getPageSize(){
	var xScroll = (window.innerHeight && window.scrollMaxY) && window.innerWidth + window.scrollMaxX || (document.body.scrollHeight > document.body.offsetHeight) && document.body.scrollWidth || document.body.offsetWidth;
	var yScroll = (window.innerHeight && window.scrollMaxY) && window.innerHeight + window.scrollMaxY || (document.body.scrollHeight > document.body.offsetHeight) && document.body.scrollHeight || document.body.offsetHeight;

	var windowWidth = self.innerHeight && (document.documentElement.clientWidth ? document.documentElement.clientWidth : self.innerWidth) || (document.documentElement && document.documentElement.clientHeight) && document.documentElement.clientWidth || document.body && document.body.clientWidth;
	var windowHeight = self.innerHeight && self.innerHeight || (document.documentElement && document.documentElement.clientHeight) && document.documentElement.clientHeight || document.body && document.body.clientHeight;

	// for small pages with total height less then height of the viewport
	var pageHeight = yScroll < windowHeight ? windowHeight : yScroll;
	
	// for small pages with total width less then width of the viewport
	var pageWidth = xScroll > windowWidth ? xScroll : windowWidth;

	var arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
}

function getPageScroll(){
	var xScroll = self.pageYOffset && self.pageXOffset || (document.documentElement && document.documentElement.scrollTop) && document.documentElement.scrollLeft || document.body.scrollLeft;
	var yScroll = self.pageYOffset && self.pageYOffset || (document.documentElement && document.documentElement.scrollTop) && document.documentElement.scrollTop || document.body.scrollTop;
	var arrayPageScroll = new Array(xScroll,yScroll);
	return arrayPageScroll;
}

/*--------------------------- INIT ----------------------------*/

$(".popbox, .dynamicbox").click(function() {
	var overlayBgColor = '#FFFFFF';
	var overlayOpacity = '0.80';
	var imgLoc = 'images/dynamic-window-images/';
	var iFrameWidth = 675;
	var iFrameHeight = 450;
	var obj = $(this);
	var url = $(this).attr("href");
	var baseURL = url.indexOf(";")!=-1 && url.substr(0, url.indexOf(";")) || url.indexOf("?")!=-1 && url.substr(0, url.indexOf("?")) || url;
	var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
    var urlType = baseURL.toLowerCase().match(urlString);	   
	var queryString = url.replace(/^[^\?]+\??/,'');
	var params = parseFeatureQuery( queryString );
	
	var pWidth = !params['width'] && iFrameWidth || params['width'];
	var pHeight = !params['height'] && iFrameHeight || params['height'];
	
	var type = "content";
	if (urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp')
		type = "img"
	
	var loadingMsg = type == "img" && "Loading Image..." || "Loading Content...";
	$('body').append('<div id="blur-overlay"></div><div id="dynamicBox"><div class="container"><div id="popLoading"><strong>'+loadingMsg+'</strong><img src="'+imgLoc+'dynabox_loading.gif" border="0"></div></div><a href="javascript:;" id="popClose" class="popClose" title="Close"><img src="'+imgLoc+'dynabox_icn_close.png" class="png" border="0" width="28" height="28" /></a><img src="'+imgLoc+'dynabox_pop_fade_top.png" class="fadeTop png" border="0" width="25" height="10"><img src="'+imgLoc+'dynabox_pop_fade_btm.png" class="fadeBtm png" border="0" width="25" height="20"></div>');
	
	if (type == "img") {
		$("#dynamicBox").append('<div id="popShadow"><table cellspacing="0" cellpadding="0" border="0"><tr><td><img src="'+imgLoc+'dynabox_pop_img_tl.png" class="tl png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_tc.png" class="tc png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_tr.png" class="tr png" border="0" width="18" height="18"></td></tr><tr><td><img src="'+imgLoc+'dynabox_pop_img_ml.png" class="ml png" border="0" width="18" height="18"></td><td style="background-color:#FFF"><img src="'+imgLoc+'dynabox_pop_img_mc.png" class="mc png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_mr.png" class="mr png" border="0" width="18" height="18"></td></tr><tr><td><img src="'+imgLoc+'dynabox_pop_img_bl.png" class="bl png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_bc.png" class="bc png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_br.png" class="br png" border="0" width="18" height="18"></td></tr></table></div>');
	} else { 
		$("#dynamicBox").append('<div id="popShadow"><table cellspacing="0" cellpadding="0" border="0"><tr><td><img src="'+imgLoc+'dynabox_pop_img_tl.png" class="tl png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_tc.png" class="tc png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_img_tr.png" class="tr png" border="0" width="18" height="18"></td></tr><tr><td><img src="'+imgLoc+'dynabox_pop_vid_ml.png" class="ml png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_vid_mc.png" class="mc png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_vid_mr.png" class="mr png" border="0" width="18" height="18"></td></tr><tr><td><img src="'+imgLoc+'dynabox_pop_vid_bl.png" class="bl png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_vid_bc.png" class="bc png" border="0" width="18" height="18"></td><td><img src="'+imgLoc+'dynabox_pop_vid_br.png" class="br png" border="0" width="18" height="18"></td></tr></table></div>');
	}
	
	$("#popShadow .tc, #popShadow .bc, #popShadow .mc").width($("#popLoading").width());
	$("#popShadow .ml, #popShadow .mr, #popShadow .mc").height($("#popLoading").height());				
		
	$('embed, object, select').css({ 'visibility' : 'hidden' });
	
	if($.browser.firefox && $.browser.mac)
		$("#blur-overlay").addClass("overlayMacFFBGHack"); // MacFF Only

	featureLocOverlay();
	$('#blur-overlay').css({
		backgroundColor: overlayBgColor,
		opacity: overlayOpacity
	}).fadeIn("fast", function() {
		$("#popShadow").show();
		$("#popLoading").fadeIn("fast", function() {
			// Content Insert

			if (type=="img") {
				$("#dynamicBox .container").append('<iframe allowtransparency="true" frameborder="0" hspace="0" src="' + baseURL + '?' + queryString + '" id="popIframeContent" name="iframeContent' + Math.round(Math.random()*1000) + '" onload="featureWinLoaded($(this))" style="width:' + pWidth + 'px;height:' + pHeight + 'px;" > </iframe>');
			} else {
				$("#dynamicBox .container").append('<iframe allowtransparency="true" frameborder="0" hspace="0" src="' + baseURL + '?' + queryString + '" id="popIframeContent" name="iframeContent' + Math.round(Math.random()*1000) + '" onload="featureWinLoaded($(this))" style="width:' + pWidth + 'px;height:' + pHeight + 'px;" > </iframe>');
			}

			// Window Resize Adjust
			$(window).resize(function() {	
				$('#blur-overlay').hide();
				featureLocOverlay();
				$('#blur-overlay').show();			
				featureLocBox();			
			});	
			
			// Exit		
			document.onkeyup = function(e){
				var keycode = e==null ? event.keyCode : e.which;
				if(keycode == 27)	dynamicBoxEnd(); // Escape Key
			};
			
			if (obj.hasClass('confirmClose')) {
				$("#popLoading, #popClose, #popImg").click(function() {dynamicBoxEnd();});
				$("#blur-overlay").click(function() { dynamicBoxEnd(true); }); // confirm before closing
			} else {
				$("#blur-overlay, #popLoading, #popClose, #popImg").click(function() {dynamicBoxEnd();});
			}	
			

			
		});
	});
	featureLocBox();


	return false;
	
});
// If Mac, default to Mac carousel item
if (navigator.userAgent.toLowerCase().indexOf("mac") != -1 && $(".carousel .topic.mac").length) {
	// "Home" tab
	$(".home .carousel .topic.isOn").removeClass("isOn");
	$(".home .carousel .topic.mac").prev().addClass("isOn");
	$(".home .carousel .menu .topic:last").prependTo(".home .carousel .menu ul");
	
	// "Set Goals & Save" tab
	$(".plan .carousel .topic.isOn").removeClass("isOn");
	$(".plan .carousel .topic.mac").prev().addClass("isOn");
	$(".plan .carousel .menu .topic:last").prependTo(".plan .carousel .menu ul");
}

$(function() {
	$(".carousel .menu").each(function() {
		if ($(this).siblings(".billboard").html() != null) {
			$(this).animate({opacity:1}, 1000, function() {
				$(this).children().children("li").click(function() {
					if ($(this).prev().hasClass("isOn")) {
						$(this).parent().parent().siblings(".control").children("a.next").click();
					}
					if ($(this).next().hasClass("isOn")) {
						$(this).parent().parent().siblings(".control").children("a.prev").click();
					}
				}).not(".isOn").css("cursor","pointer");
				$(this).children().children("li").not(".isOn").css("opacity", 0.5);
				$(this).children().children("li").not(".isOn").find("a.lm").hide();
				$(this).after('<img src="/images/hub/carousel/dynabox_car-bg-menu.gif" class="bg-menu" border="0" />');
				$(this).siblings(".control").hide().css("visibility","visible").fadeIn(300, function() {
					$(this).children(".next").click();
					$(this).siblings(".bg-menu").fadeIn(100, function() {
						$(".carousel .billboard").children("div").css("top", 0).hide();
						if ($.browser.msie)
							$(".carousel .billboard").children("div.isOn").show();
						else 
							$(".carousel .billboard").children("div.isOn").fadeIn(400);
						$(".carousel .billboard").css("overflow","visible");
					});
				});
				
			});
		}
	});
});

$(".carousel .control a").click(function() {
	var speed = 500;
	var $menu = $(this).parent().siblings(".menu").children("ul");
	var $menuIsOn = $menu.children(".isOn");
	var menuLIwidth = $menu.children(".isOn").outerWidth(true);
	var $bb = $(this).parent().siblings(".billboard");
	var $bbIsOn = $bb.children(".isOn");

	if (!$menu.is(":animated")) {
		if ($bb.html() != null) {
			$menuIsOn.animate({
				opacity: 0.5
			}, speed).css("cursor","pointer").find("a.lm").fadeOut(speed);
		}
		$menuIsOn.removeClass("isOn");
		
		if ($(this).hasClass("next")) {
			if ($menuIsOn.next().next("li").html() == null) { 
				$menu.children("li").hide();
				$menu.children("li:first").appendTo($menu);
				$menu.animate({
					left: '+=' + menuLIwidth + 'px'
				}, 1, function() { $menu.children("li").show(); });
			}
			if ($.browser.msie)
				$bbIsOn.hide().removeClass("isOn");
			else
				$bbIsOn.fadeOut(speed).removeClass("isOn"); 
			if ($bbIsOn.next("div").html() == null) {
				if ($.browser.msie)
					$bb.children("div:first").show().addClass("isOn");
				else
					$bb.children("div:first").fadeIn(speed).addClass("isOn");
			} else {
				if ($.browser.msie)
					$bbIsOn.next("div").show().addClass("isOn");
				else
					$bbIsOn.next("div").fadeIn(speed).addClass("isOn");
			}
			$menuIsOn.next("li").animate({
				opacity: 1
			}, speed).addClass("isOn");
			if ($bb.html() != null)
				$menuIsOn.next("li").css("cursor","default").find("a.lm").fadeIn("slow");
			$menu.animate({
				left: '-=' + menuLIwidth + 'px'
			}, speed);
		}

		if ($(this).hasClass("prev")) {
			if ($menuIsOn.prev().prev("li").html() == null) {
				$menu.children("li").hide();
				$menu.children("li:last").prependTo($menu);
				$menu.animate({
					left: '-=' + menuLIwidth + 'px'
				}, 1, function() { $menu.children("li").show(); });
			}
			if ($.browser.msie)
				$bbIsOn.hide().removeClass("isOn");
			else
				$bbIsOn.fadeOut(speed).removeClass("isOn");
			if ($bbIsOn.prev("div").html() == null) {
				if ($.browser.msie)
					$bb.children("div:last").show().addClass("isOn");
				else
					$bb.children("div:last").fadeIn(speed).addClass("isOn");
			} else {
				if ($.browser.msie)
					$bbIsOn.prev("div").show().addClass("isOn");
				else
					$bbIsOn.prev("div").fadeIn(speed).addClass("isOn");
			}
			$menuIsOn.prev("li").animate({
				opacity: 1
			}, speed).addClass("isOn");
			if ($bb.html() != null)
				$menuIsOn.prev("li").css("cursor","default").find("a.lm").fadeIn("slow");	
			$menu.animate({
				left: '+=' + menuLIwidth + 'px'
			}, speed);
		}
	}

});
/* Search Box */
function searchFeatureFocus(formBox) {
	if(formBox.value == 'Search') {
		formBox.value = '';
	}
}
function searchFeatureBlur(formBox) {
	if((formBox.value == ' ') || (formBox.value == '')) {
		formBox.value = 'Search';
	}
}
function checkFeatureSearchInput(inputVal, defaultTerm) {
	if (inputVal == '' || inputVal == defaultTerm) {
		alert('Please Enter a Search Term');
		return false;
	} else {
		return true;
	}
}	
function supportFeatureFocus(formBox) {
	if(formBox.value == 'Keyword or error code') {
		formBox.value = '';
	}
}
function supportFeatureBlur(formBox) {
	if((formBox.value == ' ') || (formBox.value == '')) {
		formBox.value = 'Keyword or error code';
	}
}

$(document).ready(function(){
	$(".feature-green-callout").each(function(){
		var topHeight = $(this).children('.gc-inner-form').height();
		$(this).find('.gc-gra').css({'height': (topHeight+8)+'px'});	
	});
	
    /* Open links in new window */
    $("a.newWindow").click(function() {
          window.open(this.href, "_blank");
          return false;
    });
});

$(function(){
	$('.shop-online-retailers').each(function(){
		var sorURL = $(this).attr('href');
		$(this).attr('href','javascript:;');
		$(this).click(function(){
			var newwin = window.open(sorURL,"shop_online_retailers","height=600,width=700,resizable=1,location=0,scrollbars=yes");
			newwin.focus();
		});
	});
});
$('.cart-multiple input:radio').click(function(){
	var getInputValue = $(this).attr('value');
	$(this).parents('.cart-multiple').attr('action',getInputValue);	
});
// Init - Tab Content
$(".tabcontent .content").each(function() {
	$(this).find(".topic").css("left",0);
	$(this).find(".topic").not(".isOn").hide();
	$(this).height($(this).find(".isOn").height());
});
$(".tabcontent .menu").each(function() {
	$(this).find("li").each(function(i) {
		$(this).attr("rel",i);
	});
	
	if ($(this).parent().hasClass("hover")) {
		$(this).children("li").hoverIntent(function() {
			$(this).click();
		}, function() {});
	}
});
$(".tabcontent .menu li").click(function() {
	if (!$(this).hasClass("isOn")) {
		var speed = 500;
		var $liOn = $(this);
		var $content = $liOn.parent().siblings(".content");
		var aniH = $content.find(".topic:eq("+ $liOn.attr("rel") +")").height();
		if (aniH < 300) aniH = 300;
		
		$liOn.addClass("isOn").siblings(".isOn").removeClass("isOn")
		$content.find(".isOn").fadeOut(speed).removeClass("isOn");
		$content.find(".topic:eq("+ $liOn.attr("rel") +")").fadeIn(speed).addClass("isOn");
		if ($content.height() != aniH)
			$content.stop().animate({"height": aniH}, speed);
	}
	
});


var thisLocation = location.href;
if (thisLocation.indexOf("#tab-")>0) {
	var thisLocationParts = thisLocation.split("#tab-");
	var thisAnchor = thisLocationParts[1] - 1;
	$(".tabcontent .menu a:eq("+thisAnchor+")").trigger("click");
}

$(".panel-toggle").click(function() {
	$(".tabcontent .menu a:eq(1)").trigger("click");
});
 

// Init - Top Menu Hover
var config = { sensitivity: 1, interval: 100, over: showProductFlyover, timeout: 250, out: hideProductFlyover };
$("#menu-product-link").hoverIntent(config);
var config2 = { sensitivity: 1, interval: 100, over: showSigninFlyover, timeout: 250, out: hideSigninFlyover };
$("#menu-signin-link").hoverIntent(config2);
var config3 = { sensitivity: 1, interval: 100, over: showSupportMoreFlyover, timeout: 250, out: hideSupportMoreFlyover };
$("#menu-support-more-link").hoverIntent(config3);

// Init - Footer Expander
$("#foot-notes-toggle").click(function(){
	$(this).toggleClass("footer-graphic-expanded");
	$("#foot-notes-content").slideToggle("fast");
});

