﻿/****************************************************************
Utils JavaScript Document for John Frieda Global

Global Utils JS document contains JavaScript functions 
that are used throughout the site.
      
*****************************************************************/
/* Things to run Onload */
$(function() {

	// Setup Global Events
	globalEvents();

	// Activate Tabs (if needed)
	activateTabs();

	// Tell webpage JS is available
	$("body").removeClass("noJS").addClass("JS");

	if (tb_detectMacXFF()) { // added because the line height is off for mac ff
		$("body").addClass("macff");
	}

	// Initialize Superfish menu, center nav
	if ($("#nav ul.sf-menu").length > 0) {
		centerNav();

		if ($.browser.msie) {  //Removes fade in from IE to get rid of opacity jump
			$("#nav ul.sf-menu").superfish({
				'autoArrows': false,
				'speed': 0
			});
			if ($.browser.version.substr(0, 1) < 7) { $("#nav li li:first-child").css('padding-top', '10px'); }
			$("#nav li li:last-child").css({ 'padding-bottom': '10px', 'border-width': '0px 1px 1px' });
		} else {
			$("#nav ul.sf-menu").superfish({
				'autoArrows': false,
				'speed': 400
			});
		}
	}

	// Setup image swapper if on Product Channel Landing
	imgSwapper();

	// Setup hovers for Where to Buy page
	imgHover();

	// Setup collapsable FAQs and the open/close events associated with them
	setupFAQs();

	// Create Print Links and append below #wrapper
	createPrintLinks('External Website Addresses in the Document')
});


/****************************************************************
globalEvents sets up events that are global to the entire site
Params: None
*****************************************************************/
function globalEvents() {
	// open all links with rel='ext' in a new window
	$("a[rel='ext']").attr('target', '_blank');

	$("a.videoLink").click(function(e) {
	    e.preventDefault();
        // Cancel Homepage Theater AutoRotation if necessary
	    cancelTheaterAutoRotation();
		var vidParams = $(this).attr("rel").split("::")[1].split("|");
		playVideo($(this).attr("href"), "lbVideo", vidParams[0], vidParams[1], vidParams[2], flashPrefix + "FlashVideoPlayer_scale.swf", '');
	});

	if ($("a.top").length > 0) {
		$("a.top").hoverIntent(function() {
			$(this).parent("li").css("z-index", 199).siblings("li").css("z-index", 99);
			$(this).parent("li").parent("ul").css("z-index", 199).siblings("ul").css("z-index", 99);
		}, function() {
			$(this).parent("li").siblings("li").css("z-index", 99);
			$(this).parent("li").parent("ul").siblings("ul").css("z-index", 99);
		});
	}
	
	$(".print_button").click(function(e) {
		e.preventDefault();
		window.print();
	});

	if ($(".productCallout, .productUsed").length > 0) {
		$(".productCallout, .productUsed").equalHeights();
	}
}

/****************************************************************
Activate Tabs sets up tabs for pages that have tabbed content
Params: None
*****************************************************************/
function activateTabs() {
	// activate tabs for product detail page
	if ($("#productDetail").length > 0) {
		var tabs = $("#productDetail");
		tabs.tabs();

		SWFAddress.onChange = function() {
			handleChange(tabs);
		}

		// set up swfaddress so the back button works
		tabs.tabs({
			select: function(event, ui) {
				var theHash = ui.tab.hash;
				theHash = theHash.replace("#", "/") + "/";
				SWFAddress.setValue(theHash);
			}
		});
	}
}

/****************************************************************
handleChange works with SWFAddress to keep the 
correct back/forward button functionality with tabs UI
Params: tabObj (object Tabs UI was called on)
*****************************************************************/
function handleChange(tabObj) {
	// show the correct tab, based on the hash value from swfaddress
	//var tabObj = $("productDetail");
	//theHash = theHash.replace("#", "");
	var theHash = SWFAddress.getPath();

	switch (theHash) {
		case "/"+ tabIDs[0] +"/":
			tabObj.tabs("select", 0);
			$("#shareBuyLinks").show();
			$("#productDetail .imgWrapper img").show();
			$("#productDetail h3").show();
			break;
		case "/" + tabIDs[1] + "/":
			tabObj.tabs("select", 1);
			$("#shareBuyLinks").show();
			$("#productDetail .imgWrapper img").show();
			$("#productDetail h3").show();
			break;
		case "/" + tabIDs[2] + "/":
			tabObj.tabs("select", 2);
			$("#shareBuyLinks").show();
			$("#productDetail .imgWrapper img").show();
			$("#productDetail h3").show();
			break;
		case "/" + tabIDs[3] + "/":
			tabObj.tabs("select", 3);
			$("#shareBuyLinks").hide();
			$("#productDetail .imgWrapper img").hide();
			$("#productDetail h3").hide();
			break;
		default:
			tabObj.tabs("select", 0);
			$("#shareBuyLinks").show();
			$("#productDetail .imgWrapper img").show();
			$("#productDetail h3").show();
			break;
	}
}

/****************************************************************
parentWidth - returns the computed width of the parent 
element based on the outerwidth of the elements within it
Params: an element with children elements
*****************************************************************/
function parentWidth(parentElement) {
	var totalWidth = 0;
	if (parentElement.children().length > 0)
		parentElement.children().each(function() { totalWidth += $(this).outerWidth(); });
	else
		totalWidth = parentElement.outerWidth();
	return totalWidth;
}

/****************************************************************
makeAnotherNav - creates a new nav UL and appends it after
the one passed in if the original is greater than the max 
width.  It calls itself recursively until the resulting
div is smaller than the max width.
*****************************************************************/
function makeAnotherNav(navUl, maxWid) {

	var totalWidth = parentWidth(navUl);

	var newNavUL;
	newNavUL = $("<ul class='navline'></ul>");

	while (totalWidth > maxWid) {
		var liToMove = navUl.children("li").eq(-1).prependTo(newNavUL);
		totalWidth = parentWidth(navUl);
	}
	newNavUL.insertAfter(navUl);
	navUl.children("li").add(newNavUL.children("li")).children("a").removeClass("top").removeClass("topLast").addClass("top");
	navUl.children("li").eq(-1).add(newNavUL.children("li").eq(-1)).children("a.top").removeClass("top").addClass("topLast");
	
	if (!($.browser.msie && $.browser.version.substr(0, 1) < 7)) {
		if (parentWidth(newNavUL) > maxWid) {
			makeAnotherNav(newNavUL, maxWid);
		}
	}
}

/****************************************************************
Center the main nav if less than 876 pixels,
set to 875px and wrap if bigger than that
Params: None
*****************************************************************/
function centerNav() {
	var initNavUL = $("#nav ul:first-child");

	var maxNavWidth = 885;
	if (parentWidth(initNavUL) > maxNavWidth) {
		makeAnotherNav(initNavUL, maxNavWidth);
	}

	if ($("#nav").children("ul").length > 1) {
		$("#nav").children("ul").addClass($("#nav > ul:first-child").attr("class"));
	}
	for (var i = 1; i <= $("#nav").children("ul").length; i++) {
		$("#nav").children("ul").eq(-i).css("z-index", i * 100).children("li").css("z-index", i * 100);
	}
	// Center Navigation
	$("#nav > ul").each(function() {
		var navulwidth = $(this).outerWidth();
		if (navulwidth < maxNavWidth + 1) {
			$(this).css({ "width": navulwidth + "px", "float": "none" });
		} else {
			$(this).css({ "width": maxNavWidth + "px", "float": "none" });
		}
	});
}

/****************************************************************
replaceDropdown() swaps the dropdown for a Select List.
Params: Select ID
ID for Containing div = Select ID + "LinkList"
ID for Target link = Select identifier + "Link"
Text for Link = First Value in Select List
*****************************************************************/
function replaceDropdown(SelectID) {
	var divID = SelectID.substring(1) + "LinkList";
	var linkID = SelectID.substring(1) + "Link";
	var prodOptions = $(SelectID + " option");
	var prodList = '<div id="' + divID + '" class="ddlist">\n<a href="#" id="' + linkID + '">' + prodOptions.eq(0).text() + '</a>\n<ul>\n';
	for (var i = 1; i < prodOptions.length; i++) {
		prodList += '<li><a href="' + prodOptions.eq(i).val() + '">' + prodOptions.eq(i).text() + '</a></li>\n';
	}
	prodList += '</ul>\n</div>\n';
	$(SelectID).next("button").remove();
	$(SelectID).after(prodList);
	$(SelectID).remove();

	// Setup Click event for dropdown
	var ddTimer;
	var openDiv = $("#" + divID);
	$("#" + linkID).click(function(e) {
		e.preventDefault();
		if ($("#" + divID + " ul").is(":visible")) {
			$("#" + divID + " ul").slideUp("fast");
			$(this).toggleClass("open");
			clearTimeout(ddTimer);
		} else {
			$("#" + divID + " ul").slideDown("fast");
			$(this).toggleClass("open");
		}
	});
	openDiv.mouseleave(function() {
		if (openDiv.children("ul").is(":visible")) {
			ddTimer = setTimeout(function() { closeDropdown(openDiv); }, 1000);
		}
	});
	openDiv.mouseenter(function() {
		clearTimeout(ddTimer);
	});
	/* The following code would be used rather than the click function if the dropdowns are changed to hover rather than click */
	/*$("#" + linkID).hoverIntent({
	over: function() { $("#" + divID + " ul").slideDown("fast"); },
	timeout: 300,
	out: function() { $("#" + divID + " ul").slideUp("fast"); }
	});*/
}
/****************************************************************
closeDropdown() closes the dropdown menu that is open after a 
set amount of time
Params:
jQuery Object that is the div that is currently open
*****************************************************************/
function closeDropdown(openDiv) {
	if (openDiv.children("ul").is(":visible")) {
		openDiv.children("ul").slideUp("fast");
		openDiv.children("a").toggleClass("open");
	}
}

/***********************************************************************
playVideo initializes the SWFObject for video play and
sets up the parameters of the video
required: videoURL
params:
***********************************************************************/
function playVideo(videoURL, lbid, vidWidth, vidHeight, vidDuration, playerURL, optionalParamStr, dontOpenInLightbox) {
	// SWFplayer and ContainerDiv sizes are dynamic based on vidWidth & vidHeight


	//Check if video is larger than the viewport, if so, resize video proportionally to fit
	var viewportY = $(window).height();
	var viewportX = $(window).width();
	var dimChanged = false;

	vidWidth = parseInt(vidWidth);
	vidHeight = parseInt(vidHeight);
	if (vidWidth + 20 > viewportX || vidHeight + 20 > viewportY) {
		dimChanged = true;
		var vidPorportions = vidWidth / vidHeight;
		var orgW = vidWidth;
		var orgH = vidHeight;
		if (vidHeight + 20 > viewportY) {
			vidHeight = viewportY * .75;
			vidWidth = orgW > orgH ? vidHeight * vidPorportions : vidHeight / vidPorportions;
			if (vidWidth + 20 > viewportX) {
				vidWidth = viewportX * .75;
				vidHeight = orgW > orgH ? vidWidth / vidPorportions : vidWidth * vidPorportions;
			}
		} else {
			vidWidth = viewportX * .75;
			vidHeight = orgW > orgH ? vidWidth / vidPorportions : vidWidth * vidPorportions;
			if (vidHeight + 20 > viewportY) {
				vidHeight = viewportY * .75;
				vidWidth = orgW > orgH ? vidHeight * vidPorportions : vidHeight / vidPorportions;
			}
		}
	}

	// test function variables
	if (videoURL == "") { return false; }
	if (lbid == "") { lbid = "lbVideo"; }
	if (vidWidth == "") { vidWidth = "532"; }
	if (vidHeight == "") { vidHeight = "420"; }
	if (vidDuration == "") { vidDuration = "9999"; }
	if (playerURL == null || playerURL == "") { playerURL = flashPrefix + "FlashVideoPlayer_scale.swf"; }

	var playerWidth = parseInt(vidWidth);
	// Add 22 for the height of the control bar in the Flash player, edit if the control bar height changes
	var playerHeight = parseInt(vidHeight) + 22; 
	if (optionalParamStr == null || optionalParamStr == "") {
		optionalParamStr = "";
	}
	var flash1_contentVersion = "9.0.115";


	// get div if exists, create if it doesn't
	var lightboxDiv = $("#" + lbid);
	if (lightboxDiv.length == 0) {
		lightboxDiv = createLBdiv(lbid, 'body');
	}

	// setup SWFObject
	if (swfobject.hasFlashPlayerVersion(flash1_contentVersion)) {
		//EMBED SWFObject Flash Player
		var vidDiv = lbid + "noflash";
		var flashvars = {};
		flashvars.videoUrl = videoURL;
		flashvars.videoWidth = vidWidth;
		flashvars.videoHeight = vidHeight;
		flashvars.videoDuration = vidDuration;
		var flashparams = {};
		flashparams.menu = "false";
		flashparams.quality = "high";
		flashparams.wmode = "opaque";
		flashparams.bgcolor = "#3E3C3C";
		var flashattributes = {};

		swfobject.embedSWF(playerURL, vidDiv, playerWidth, playerHeight, flash1_contentVersion, null, flashvars, flashparams, flashattributes);

	} else if (supports_html5_h264_video()) {
		//EMBED HTML5 Video Player
		// NOTE that iPhone OS2 does not support HTML5 Video
		var videoattributes = {};
		videoattributes.src = videoURL;
		videoattributes.width = vidWidth;
		videoattributes.height = vidHeight;
		videoattributes.controls = "true";
		var video = $("<video></video>").attr(videoattributes);
		lightboxDiv.html('');
		lightboxDiv.append(video);

	}

	//var topMargin =

	if (!dontOpenInLightbox) {
	    if (!dimChanged) {
	        // open lightbox to display
	        // ScrollFreeze is used for Firefox only because it repositions the page to the top when 
	        // overflow: hidden is applied to the HTML element
	        $.fn.colorbox({
	            innerWidth: playerWidth,
	            innerHeight: playerHeight,
	            inline: true,
	            href: "#" + lbid,
	            onOpen: function() { if ($.browser.mozilla) ScrollFreeze.on(); $('html').css({ overflow: 'hidden' }); }, //prevent scrolling
	            onCleanup: function() { lightboxDiv.hide(); $('html').css({ overflow: 'auto' }); }, //re-enable scrolling
	            onClosed: function() { lightboxDiv.remove(); if ($.browser.mozilla) ScrollFreeze.off(); },
	            opacity: 0.5
	        });
	    } else {  // Don't disable scrolling if video had to be resized to fit
	        // open lightbox to display
	        $.fn.colorbox({
	            innerWidth: playerWidth,
	            innerHeight: playerHeight,
	            inline: true,
	            href: "#" + lbid,
	            onOpen: function() { },
	            onCleanup: function() { lightboxDiv.hide(); },
	            onClosed: function() { lightboxDiv.remove(); },
	            opacity: 0.5
	        });
	    }
	}
}

/***********************************************************************
supports_html5_h264_video tests the browser to see if it can
play HTML5_h264 video natively
***********************************************************************/
function supports_html5_h264_video() {
    //if browser can't play video tag at all (IE), return false:
    if (!document.createElement('video').canPlayType) { return false; }
    //if it can, check for mp4 type:
    else {
        var v = document.createElement("video");
        return v.canPlayType('video/mp4');
    }
}


/***********************************************************************
createsLBdiv creates a div for the video to go into
params: id for the lightbox div, width of the video, where to append it
returns the jQuery div object
***********************************************************************/
function createLBdiv(lbid, appendIdent) {
	var lightboxDiv = $("<div></div>").attr({ id: lbid });

	//create noflash div and insert
	var noflashDiv = $("<div></div>").attr("id", lbid + "noflash").addClass("no-flash");
	var noflashP1 = $("<p></p>").text(nonflashVideoContentPart1).attr("style", "padding-top:30px");
	var noflashP2link = $("<a></a>").attr({ href: nonflashVideoContentPart2LinkUrl, target: "_blank" }).text(nonflashVideoContentPart2LinkText);
	var noflashP2 = $("<p></p>").text(nonflashVideoContentPart2Text);
	noflashP2.prepend(noflashP2link);
	noflashDiv.append(noflashP1).append(noflashP2);
	lightboxDiv.append(noflashDiv);

	//Insert lightboxDiv
	$(appendIdent).append(lightboxDiv);
	return lightboxDiv;
}

/***********************************************************************
setupGTLCarousel initializes the carousel for the Get The Looks page  
***********************************************************************/
function setupGTLCarousel() {
	var circ = false; //Default state is false if there are less elements than the shownElements
	var btns = false; //No navigation arrows on the page unless they are inserted
	var shownElements = 6;

	if ($("#gtlSlider ul li").length > shownElements) {
		var btnPrev = $("<p>Prev</p>").attr("id", "sliderPrev").insertAfter("#gtlSlider");
		var btnNext = $("<p>Next</p>").attr("id", "sliderNext").insertAfter("#gtlSlider");
		btns = true; 		
		circ = true;		
	}

	var currentIndex = 1;
	if ($("#gtlSlider a.current").length > 0) currentIndex = $("#gtlSlider a.current").parent("li").index();
	
	$("#gtlSlider").jCarouselLite({
		btnPrev: btns ? "#" + btnPrev.attr("id") : "",
		btnNext: btns ? "#" + btnNext.attr("id") : "",
		mouseWheel: true,
		circular: circ,
		visible: shownElements,
		auto: 0,
		speed: 300,
		start: currentIndex
	});
	$("#gtlSlider li a").click(function() {
		if ($(this).hasClass("current")) return false;
		$(this).parent("li").siblings().children("a").removeClass("current"); $(this).addClass("current");
	});
}


/***********************************************************************
Homepage theater
***********************************************************************/
var homepageTheaterCurrentIndex = -1;
var homepageTheaterAutoRotationIntervalId = 0;
var homepageTheaterAutoRotationWaitTime = 8000; //milliseconds
var homepageJCarouselliteShownElements = 5;
function setupHomepageTheater() {
	var circ = false; //Default state is false if there are less elements than the shownElements
	var btns = false; //No navigation arrows on the page unless they are inserted
	var shownElements = homepageJCarouselliteShownElements;

	if ($("#theaterNavSlider ul li").length > shownElements) {
		var btnPrev = $("<p>Prev</p>").attr("id", "sliderPrev").insertAfter("#theaterNavSlider");
		var btnNext = $("<p>Next</p>").attr("id", "sliderNext").insertAfter("#theaterNavSlider");
		btns = true;
		//circ = true; // Homepage theater should NOT cycle
	}

	$("#sliderPrev").click(function() {
	    cancelTheaterAutoRotation();
	});
	$("#sliderNext").click(function() {
	    cancelTheaterAutoRotation();
	});
	$("#theaterNavSlider").jCarouselLite({
		btnPrev: btns ? "#" + btnPrev.attr("id") : "",
		btnNext: btns ? "#" + btnNext.attr("id") : "",
		mouseWheel: true,
		circular: circ, 
		visible: shownElements,
		auto: 0,
		speed: 300
	});
	$(".theaterDiv").hide();
	$("#theaterDefault").show();
	//$("#theaterNavSlider li a").live("click", function(e) {
	$("#theaterNavSlider li a").hoverIntent(function() {
		//e.preventDefault();
		cancelTheaterAutoRotation();
		showTheaterNavItem(this, true);
	}, function() {
		startHomepageTheaterAutorotation($(this).parent("li").index(), homepageTheaterAutoRotationWaitTime);
	});

	//startHomepageTheaterAutorotation(homepageTheaterCurrentIndex, homepageTheaterAutoRotationWaitTime);

	$("a#navSliderClose").click(function(e) {
	    e.preventDefault();
	    if ($(this).hasClass("open")) {
	        $("#sliderWrap").animate({ "bottom": -80 }, 1250, 'easeOutBack');
	        $("#theaterNavSlider ul li a img").animate({ top: -66 }, 1250);
	        $(this).css({ "background-position": "top right" }).toggleClass("open");
	    } else {
	        $("#sliderWrap").animate({ "bottom": -1 }, 1250, 'easeInBack');
	        $("#theaterNavSlider ul li a img").animate({ top: 0 }, 1250);
	        $(this).css({ "background-position": "top left" }).toggleClass("open");
	    }
	    cancelTheaterAutoRotation();
	});
}

function callJCarouselLiteGoFunction(indexToShow) {
    var paramToSetCarouselTo = 0;
    // todo: following is good enough but could do a better job of determining if desired index is already visible
    if (indexToShow >= homepageJCarouselliteShownElements) {
        paramToSetCarouselTo = indexToShow - homepageJCarouselliteShownElements + 1;
        // NOTE: Following function is mapped in jcarousellite_1.0.1.customized.js
        parent.jcarousellitegofunction(paramToSetCarouselTo);
    }
}
function startHomepageTheaterAutorotation(startingIndex, timeInMilliseconds) {
	homepageTheaterAutoRotationIntervalId = setTimeout(function() { autoRotationShowNextHomepageTheaterIndex(startingIndex); }, timeInMilliseconds);
}
function autoRotationShowNextHomepageTheaterIndex(sIndex) {
    // Increment to next index
	if (sIndex != homepageTheaterCurrentIndex) {
		homepageTheaterCurrentIndex = sIndex + 1;
	} else {
		homepageTheaterCurrentIndex++;
	}
    // If this next index is the last one then cancel future autorotation calls
    if (homepageTheaterCurrentIndex > ($("#theaterNavSlider ul li").length - 1)) showDefaultImageAndCancelAutoRotation();
    else {
        // Tell main theater to show next index
        showTheaterNavIndex(homepageTheaterCurrentIndex);
        // Tell jCarouselLite to slide if necessary (next index is not currently in jCarouselLite view)
        callJCarouselLiteGoFunction(homepageTheaterCurrentIndex);
       }
       homepageTheaterAutoRotationIntervalId = setTimeout(function() { autoRotationShowNextHomepageTheaterIndex(homepageTheaterCurrentIndex); }, homepageTheaterAutoRotationWaitTime);
}
function showDefaultImageAndCancelAutoRotation() {
    cancelTheaterAutoRotation();
    homepageTheaterCurrentIndex = -1;
    $(".theaterDiv").fadeOut(1200);
    $("#theaterDefault").fadeIn(1200);
    $("#theaterNavSlider ul li a").each(function(index, domEle) {
        $(domEle).removeClass("current");
    });
    // ONLY CALL THE parent.jcarousellitegofunction(0) IF THERE ARE MORE ITEMS THAN 
    //   CAN BE SHOWN AT ONCE (REQUIRING SLIDING BACK TO BEGINNING)
    if ($("#theaterNavSlider ul li").length > homepageJCarouselliteShownElements) {
        parent.jcarousellitegofunction(0);
    }
}
function cancelTheaterAutoRotation() {
    if (homepageTheaterAutoRotationIntervalId != undefined && homepageTheaterAutoRotationIntervalId != 0) {
        clearTimeout(homepageTheaterAutoRotationIntervalId);
        homepageTheaterAutoRotationIntervalId = 0;
    }
}
function showTheaterNavIndex(hpIndex) {
// TODO: THIS IS CURRENTLY HARDCODED TO .NET GENERATED IDS
    showTheaterNavItem($("#ctl00_ContentPlaceHolder1_lvFilmStrip_ctrl" + hpIndex + "_hlFilmStripLink"), false);
}
function showTheaterNavItem(item, forceClose) {

    if ($(item).hasClass("current")) return;

    $(item).parent("li").siblings().children("a").removeClass("current");

    var divtoshow = "#theater";
    var linkClass = $(item).attr("className").split(' ');
    if (linkClass.length >= 1) {
        for (var i = 0; i < linkClass.length; i++) {
            if (linkClass[i].match(/sNav/i)) {
                divtoshow += linkClass[i].replace(/sNav/i, "");
                break;
            }
        }
    } else {
        divtoshow += "Default";
    }

    $(item).addClass("current");

    $(".theaterDiv").fadeOut(1200);
    $(divtoshow).fadeIn(1200);

//    if (forceClose == null || forceClose == true) {
//        if ($("a#navSliderClose").hasClass("open")) {
//            $("a#navSliderClose").click();
//        }
//    }
}

/***********************************************************************
Home Page Theater Takeover Functions
***********************************************************************/

function theaterTakeover(delay, promoIndex, promoWidth) {
	// NEED to stop autorotation if there is a theater Takeover
	setTimeout(function() { animateTheaterTakeover(promoIndex, promoWidth); }, delay);
}

function animateTheaterTakeover(promoIndex, promoWidth) {
	var animateLeftTo = -1;
	switch (promoWidth) {
		case 920:
			// no need for promoIndex, just 1 promo
			animateLeftTo = -6;
			break;
		case 444:
			switch (promoIndex) {
				case 0:
					animateLeftTo = -6;
					break;
				case 1:
					animateLeftTo = 470;
					break;
			}
			break;
		case 286:
			switch (promoIndex) {
				case 0:
					animateLeftTo = -6;
					break;
				case 1:
					animateLeftTo = 311;
					break;
				case 2:
					animateLeftTo = 629;
					break;
			}
			break;
	}
	if (animateLeftTo != -1) {
		$(".homepageTakeover")
					.parents("#hpTheater").css("overflow", "visible").end()
					.animate({ height: [106, 'swing'], top: [389, 'linear'], width: [promoWidth, 'swing'], left: [animateLeftTo, 'easeOutSine'], opacity: [.5, 'easeInQuint'] }, 1500, function() {
							$(this).parents("#hpTheater").css("overflow", "hidden").end().hide("slow", function() {
							startHomepageTheaterAutorotation(homepageTheaterCurrentIndex, homepageTheaterAutoRotationWaitTime);
						});
					});
		$(".homepageTakeover img").animate({ height: [106, 'swing'], width: [promoWidth, 'swing'] }, 1500);
	} else {
		$("#homepageTakeover").fadeOut("slow", function() {
			startHomepageTheaterAutorotation(homepageTheaterCurrentIndex, homepageTheaterAutoRotationWaitTime);
		});
	}
	// NEED to start the autorotation - maybe as callback function from animation?
}

/***********************************************************************
Hair-Care Product Channel Landing Page
***********************************************************************/
var prodHairCareLandingPageAutoRotationCurrentIndex = 0;
var prodHairCareLandingPageAutoRotationIntervalId = 0;
var prodHairCareLandingPageAutoRotationWaitTime = 4000; //milliseconds

/***********************************************************************
imgSwapper adds product family and channel images to the 
document and setups events to swap them on hover
***********************************************************************/
var channelBrandingImgObjs = new Array();
var prodFamImgObjs = new Array();
function imgSwapper() {

    
	if (typeof (prodFamFileNames) != 'undefined' && typeof (channelBrandingFileNames) != 'undefined') {
		var numFams = prodFamFileNames.length;
		var numChans = channelBrandingFileNames.length;
		if (numFams == numChans) {
			for (var i = 0; i < numFams; i++) {
				channelBrandingImgObjs[i] = $("<img />").attr({ 'src': channelBrandingFileNames[i], 'class': 'channelBrandingImg' }).appendTo("#col1").hide();
				// TODO: Height and Width are set explicitly here, could be dynamic from XML
				prodFamImgObjs[i] = $("<img />").attr({ 'src': prodFamFileNames[i], 'class': 'productLineup', 'width': '229', 'height': '204' }).appendTo("#innerPLcol1").hide();
			}
			
			$("#productLinks li").eq(0).addClass("current");
			channelBrandingImgObjs[0].add(prodFamImgObjs[0]).show();
			
			$("#productLinks a").hoverIntent(function() {
			    cancelProdHairCareLandingPageAutoRotation();
			    var hoveredFam = $(this).parent("li").index();
			    $(this).parent("li").addClass("current").siblings().removeClass("current");
			    $(".productLineup,.channelBrandingImg").fadeOut("slow");
			    channelBrandingImgObjs[hoveredFam].add(prodFamImgObjs[hoveredFam]).fadeIn("slow");
			}, function() {
			    // Do nothing on mouseOut 
			});
            startProdHairCareLandingPageAutoRotation(prodHairCareLandingPageAutoRotationWaitTime);
		}
    }

    if (typeof (ourExpertsImageAutoRotation) != 'undefined' && ourExpertsImageAutoRotation == true) {
        // Hide all except the first image in the rotation
        $(".landing #col2 #contentWrap #innerCol1 #imageBlock a").eq(0).siblings().hide();
        // start rotation
        startOurExpertsLandingPageAutoRotation(ourExpertsLandingPageAutoRotationWaitTime);
    }
}
function startProdHairCareLandingPageAutoRotation(timeInMilliseconds) {
    prodHairCareLandingPageAutoRotationIntervalId = setInterval("prodHairCareLandingPageAutoRotationShowNextImgs()", timeInMilliseconds);
}
function prodHairCareLandingPageAutoRotationShowNextImgs() {
    prodHairCareLandingPageAutoRotationCurrentIndex++;
    if (prodHairCareLandingPageAutoRotationCurrentIndex >= ($("#productLinks #innerPLcol2 ul li").length)) {
        cancelProdHairCareLandingPageAutoRotation();
        $("#productLinks li").removeClass("current");
        $("#col1 img").last().siblings().add($("#innerPLcol1 img").last().siblings()).hide();
        $("#col1 img").last().add($("#innerPLcol1 img").last()).fadeOut("slow");
        $("#col1 img").first().add($("#innerPLcol1 img").first()).fadeIn("slow");
        prodHairCareLandingPageAutoRotationCurrentIndex = -1;
    } else {
        $("#productLinks li").eq(prodHairCareLandingPageAutoRotationCurrentIndex).addClass("current").siblings().removeClass("current");
        channelBrandingImgObjs[prodHairCareLandingPageAutoRotationCurrentIndex].add(prodFamImgObjs[prodHairCareLandingPageAutoRotationCurrentIndex]).fadeIn("slow");
    }
}
function cancelProdHairCareLandingPageAutoRotation() {
    if (prodHairCareLandingPageAutoRotationIntervalId != undefined && prodHairCareLandingPageAutoRotationIntervalId != 0) {
        clearInterval(prodHairCareLandingPageAutoRotationIntervalId);
        prodHairCareLandingPageAutoRotationIntervalId = 0;
    }
}

/***********************************************************************
Our Experts Landing Page Auto Image Rotation Code
***********************************************************************/
var ourExpertsLandingPageAutoRotationCurrentIndex = 0;
var ourExpertsLandingPageAutoRotationIntervalId = 0;
var ourExpertsLandingPageAutoRotationWaitTime = 4000; //milliseconds

var ourExpertsRotatingImgObjs = new Array();

function startOurExpertsLandingPageAutoRotation(timeInMilliseconds) {
    ourExpertsLandingPageAutoRotationIntervalId = setInterval("ourExpertsLandingPageAutoRotationShowNextImgs()", timeInMilliseconds);
}
function ourExpertsLandingPageAutoRotationShowNextImgs() {
    ourExpertsLandingPageAutoRotationCurrentIndex++;
    if (ourExpertsLandingPageAutoRotationCurrentIndex >= ($(".landing #col2 #contentWrap #innerCol1 #imageBlock a").length)) {
        ourExpertsLandingPageAutoRotationCurrentIndex = 0;
    }
    $(".landing #col2 #contentWrap #innerCol1 #imageBlock a").eq(ourExpertsLandingPageAutoRotationCurrentIndex).fadeIn("slow").siblings().fadeOut("slow");
}

/***********************************************************************
imgHover 
adds -over to the image hovered and preloads it into the doc.
if it is already in the doc it does not load the image again
***********************************************************************/
function imgHover() {
	if ($("div#whereToBuy").length > 0) { //$("div.landing").length > 0 ||
		$("#whereToBuy #col1, #whereToBuy #col2").equalHeights();
		$("#whereToBuy #col1 .innercol ul, #whereToBuy #col2 .innercol ul").equalHeights();

		$("#whereToBuy img").hover(

			function() {
			    var thisImg = $(this);
			    if (thisImg.attr("src").indexOf("-over") != -1) {
			        thisImg.attr("src", thisImg.attr("src").replace("-over", ""));
			    }
			    thisImg.data("origSrc", $(this).attr("src"));
			    var orgSrc = thisImg.attr("src");
			    var srcSplit = orgSrc.split(".");
			    var srcLen = srcSplit.length;
			    var pathSrc = orgSrc.replace(srcSplit[srcLen - 2] + "." + srcSplit[srcLen - 1], "");
			    var src = srcSplit[srcLen - 2] + "-over." + srcSplit[srcLen - 1];

			    if ($("img[src=" + pathSrc + src + "]").length < 1) {
			        thisImg.attr("src", pathSrc + src);
			        $("<img />")
						.attr({ "src": pathSrc + src, "style": "display: none;" })
						.appendTo("body")
						.bind("load", function() {
						    thisImg.attr("src", pathSrc + src);
						});
			    } else {
			        thisImg.attr("src", pathSrc + src);
			    }
			},
			function() {
			    if ($(this).attr("src") != $(this).data("origSrc")) {
			        $(this).attr("src", $(this).data("origSrc"));
			    }
			});
	}
}

/***********************************************************************
setupFAQs - sets up the FAQ page collapsable elements and adds the 
click events needed to open/close them
***********************************************************************/
function setupFAQs() {
	if ($("#faqContent").length > 0) {
		$("dl dd").hide();
		$("dl dt").addClass("closedFAQ");
		$("<a href='#' />").addClass("faqToggle").appendTo("dl dt").click(function(e) {
			e.preventDefault();
			if ($(this).hasClass("open")) {
				$(this).parents("dt").next("dd").slideUp();
				if (!($(this).parents("dt").prevAll("dt").first().children("a").hasClass("open"))) {
					$(this).parents("dt").addClass("closedFAQ").removeClass("openFAQ");
				}
				if (!($(this).parents("dt").nextAll("dt").first().children("a").hasClass("open"))) {
					$(this).parents("dt").nextAll("dt").first().addClass("closedFAQ").removeClass("openFAQ");
				}
			} else {
				$(this).parent("dt").addClass("openFAQ").removeClass("closedFAQ").next("dd").slideDown().next("dt").addClass("openFAQ").removeClass("closedFAQ");
			}
			$(this).toggleClass("open");
		});
	}
}


/***********************************************************************
GET QUERYSTRING JS VERSION
***********************************************************************/
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	query = query.replace("&amp;", ";AMP;")
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return "none";
}

/***********************************************************************
	moveBTTLink
	Moves the Back To Top Links onto the page
***********************************************************************/
function moveBTTLink() {
	var BTTLink = $("a#backToTop").click(function() {
		$('html, body').animate({ scrollTop: '0px' }, 700);
		return false;
	});
	BTTLink.hide();
	if ($(window).scrollTop() > $(window).height()) {
		BTTLink.show();
		$('html, body').animate({ scrollTop: $(window).scrollTop() + 1 }, 1); 
	}
	var wrapTop = ($("#discProdContent").offset()["top"] + $("#discProdContent").height() + 5) + "px";
	var wrapLeft = "10px";
	BTTLink.css({ "position": "absolute", "top": wrapTop, "left": wrapLeft });
	$(window).bind('scroll', function() {
		$(".discProdItem").each(function() {
			if (($(window).scrollTop() + $(window).height() - $(this).height() > $(this).offset()["top"]) && ($(window).scrollTop() > $(window).height() / 2)) {
				BTTLink.show();
				var ie6Adjust = 0;
				if ($.browser.msie && $.browser.version.substr(0, 1) < 7) { ie6Adjust = 10; }
				wrapTop = ($(this).offset()["top"] - $(this).height() + 35 - ie6Adjust) + "px";
				BTTLink.stop().animate({ "top": wrapTop });
			}
		});
	});
}

/***********************************************************************
* Equal Heights Plugin
* Equalize the heights of elements. Great for columns or any elements
* that need to be the same size (floats, etc).
* 
* Version 1.0
* Updated 12/10/2008
*
* Copyright (c) 2008 Rob Glazebrook (cssnewbie.com) 
*
* Usage: $(object).equalHeights([minHeight], [maxHeight]);
* 
* Example 1: $(".cols").equalHeights(); Sets all columns to the same height.
* Example 2: $(".cols").equalHeights(400); Sets all cols to at least 400px tall.
* Example 3: $(".cols").equalHeights(100,300); Cols are at least 100 but no more
* than 300 pixels tall. Elements with too much content will gain a scrollbar.
* 
***********************************************************************/

(function($) {
	$.fn.equalHeights = function(minHeight, maxHeight) {
		tallest = (minHeight) ? minHeight : 0;
		this.each(function() {
			$(this).height("auto");
		});
		this.each(function() {
			if ($(this).height() > tallest) {
				tallest = $(this).height();
			}
		});
		if ((maxHeight) && tallest > maxHeight) tallest = maxHeight;
		return this.each(function() {
			$(this).height(tallest); //.css("overflow", "auto");
		});
	}
})(jQuery);

/***********************************************************************
validateOnBlur
Assists the .Net form validation by checking if the form element
passed is valid and setting the error span to block if it isn't
		
Page_Validators is a .Net array of the validators on the page
		
This function requires .Net validation to be enabled and the
Display: Dyanamic attribute to be used on the validators
***********************************************************************/
function validateOnBlur(Page_Validators, tElement) {
	for (var i = 0; i < Page_Validators.length; i++) {
		//ValidatorValidate(Page_Validators[i], null, null);
		if (Page_Validators[i].id.indexOf(tElement.attr("id")) != -1) {
			if (!Page_Validators[i].isvalid) {
				var errorSpan = (Page_Validators[i].id.substring(Page_Validators[i].id.length - 1)) - 1;
				tElement.siblings("span").eq(errorSpan).css("display", "block");
				tElement.siblings("span:visible").css("display", "block");
			}
		}
	}
}

function tb_detectMacXFF() {
	var userAgent = navigator.userAgent.toLowerCase();
	if (userAgent.indexOf('mac') != -1 && userAgent.indexOf('firefox') != -1) {
		return true;
	}
}
/***********************************************************************
createPrintLinks 
appends readable links to the footer of the document in a 
print only section
***********************************************************************/
function createPrintLinks(headerLabel) {
	// Get the container and target
	var links = $('a[target="_blank"]');

	if ($(links).length) {
		//create a container and heading for the footnotes
		var footnotesWrapper = $('<fieldset>', {
			css: {
				clear: 'both'
			}
		}).addClass('print_only');
		var footnotesLabel = $('<legend>', {
			text: headerLabel
		}).appendTo(footnotesWrapper);

		//create an OL to hold the footnotes
		var footnoteList = $('<ol>').appendTo(footnotesWrapper);
		var linkArray = new Array();
		var printedLink = 0;

		$.each(links, function(i) {
			var linkText = $(this).text();
			var linkValue = $(this).attr('href');
			if (linkValue.substring(0, 7) != 'http://') {
				if (linkValue.substring(0, 1) != '/')
					linkValue = 'http://' + document.location.host + linkValue;
				else
					linkValue = 'http://' + document.location.host + "/" + linkValue;

			}
			linkArray[i] = linkValue;
			var dup = false;
			var count = 0;
			var matchedIndex = -1;
			for (var link in linkArray) {
				if (linkArray[link] == linkArray[i]) {
					count++;
					matchedIndex++;
					if (count > 1) {
						dup = true;
						break;
					}
				}
			}

			if (matchedIndex <= 0) {
				printedLink++;
			}
			//Add hidden span to links
			$('<span>', {
				text: ' [' + printedLink + ']'
			}).appendTo($(this)).addClass('print_only');

			if (!dup) {
				var listEntry = $('<li>', {
					text: linkValue
				}).appendTo(footnoteList);
			}
		});

		// append the heading and <ol> to the target
		$('body').append(footnotesWrapper);
	}
}


/*********************************************************************************************
	ScrollFreeze stops the page from scrolling while on
	Originally downloaded from 
	http://bytes.com/topic/javascript/answers/498334-document-body-scroll-does-not-work-firefox
			
	Usage: ScrollFreeze.on() , ScrollFreeze.off()
	NOTE: The X freeze is currently not enabled, the script only freezes the Y axis scrolling
*********************************************************************************************/
ScrollFreeze = {
	propFlag: true,
	Ydisp: 0,
	Xdisp: 0,
	on: function() {
		if (this.getProp())
			$(window).bind("scroll", function() { ScrollFreeze.setXY(); });
	},
	off: function() {
		$(window).unbind("scroll");
		if ($(window).scrollTop() != $(window).data("yOffset"))
			setTimeout(this.setXY, 5);
	},
	getProp: function() {
		this.Ydisp = $(window).scrollTop();
		$(window).data("yOffset", this.Ydisp);
		return this.propFlag;
	},
	setXY: function() {
		$(window).scrollTop($(window).data("yOffset"));
	}
}



/* Flash Tracking */

function riaTrack(trackingParam) {
    goToPage(trackingParam);
}

function goToPage(pg) {
    dcsMultiTrack('DCS.dcsuri', pg, 'DCS.dcsqry', '', 'WT.ti', pg);
    firstTracker._trackPageview(pg);
    secondTracker._trackPageview(pg);
}

function getQuerystring(key, default_) {
    if (default_ == null) default_ = "";
    key = key.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regex = new RegExp("[\\?&]" + key + "=([^&#]*)");
    var qs = regex.exec(window.location.href);
    if (qs == null)
        return default_;
    else
        return qs[1];
}
