function riaTrackV2(appDCSURI, eventName, eventType, eventId) {
    // NOTE: used for Rich Internet Application Tracking - FlashTrackAction and AJAX Track

    dcsMultiTrack('DCS.dcsuri', appDCSURI, 'DCSext.eventname', eventName, 'DCSext.eventtype', eventType, 'DCSext.eventid', eventId);
}

var $j = jQuery.noConflict();
/****************************************************************
Global JavaScript Document

Global JavaScript Document contains JavaScript functions 
that are used throughout the site.
      
*****************************************************************//* Things to run Onload */
$j(function() {
    // Setup Video Links
    activateVideoLinks();
    // Intialize Menu
    initializeMenu();
    // Intialize Tabs Component
    initializeTabs();

    // Intialize Theater in Homepage

    initializeTheater();

    //Following Takeover call no longer being used:

    // Intialize Theater Takeover in Homepage
    //initializeTheaterTakeover();

    // Add hover events to simulate the :hover not supported by IE6
    setHoverEvents();
    // FAQ Component
    initializeFAQ();
    // SetPrintActions
    setPrintActions();
    //showSignUpconfirmation
    showSignUpConfirmation();
    //Beauty Buzz Deeplinks
    //initializeBeautyBuzz();
    //No results
    initializeNoResults();
});



/****************************************************************
globalEvents sets up events that are global to the entire site
Params: None

relies on video A HREF links having:
1) class of "videoLink"
2) href pointing to the MP4 video file to be progressively downloaded
3) rel attribute with the 3 video params separated by | in the following
	order: videoWidth|videoHeight|videoDuration(in seconds)

.NET example: of link: 
<a href="<%= System.Configuration.ConfigurationManager.AppSettings["baseprefix"] %>videos/vid_filename.mp4" rel="videoParams::320|180|34" class="videoLink">Play Video 1</a>
*****************************************************************/
function activateVideoLinks() {
	var videoLinks =$j("a.videoLink");
	videoLinks.click(function(e) {
	    var vidParams = $j(this).attr("rel").split("::")[1].split("|"),
			videoPath = $j(this).attr('href');
	    videoPlayer = $j('#lbVideo')
	    e.preventDefault();
	    playVideo(videoPath, "lbVideo", vidParams[0], vidParams[1], vidParams[2]);
	})
}




/***********************************************************************
playVideo initializes the SWFObject for video play and
sets up the parameters of the video
required: videoURL
params: 
videoURL
lightbox/colorbox div id (defaults to "lbVideo")
vidWidth
vidHeight
vidDuration (in seconds)

.NET example: of link: 
<a href="<%= System.Configuration.ConfigurationManager.AppSettings["baseprefix"] %>videos/vid_filename.mp4" rel="videoParams::320|180|34" class="videoLink">Play Video 1</a>
***********************************************************************/
function playVideo(videoURL, lbid, vidWidth, vidHeight, vidDuration, playerURL, dontOpenInLightbox) {
    // SWFplayer and ContainerDiv sizes are dynamic based on vidWidth & vidHeight

    if (videoURL == "") { return false; }

    /*****************************************/
    /* IMPORTANT PARAMS TO CONFIGURE - START */
    /*****************************************/
    var flashVideoPlayerURL = playerURL;
    if (playerURL == null || playerURL == "") { flashVideoPlayerURL = flashPrefix + "FlashVideoPlayer_scale_v2.swf"; }

    var videoURLForFlashPlayer = videoURL;

    var flash1_contentVersion = "9.0.115"; // Flash 9.0.115 or higher required for H.264 video codec support
    
    
    //Check if video is larger than the viewport, if so, resize video proportionally to fit
    var viewportY = $j(window).height();
    var viewportX = $j(window).width();
    var dimChanged = false;

    vidWidth = parseInt(vidWidth);
    vidHeight = parseInt(vidHeight);
    /* DISABLE RESIZING FOR NOW
    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;
            }
        }
    }
    */

    // CHOOSE SOME DEFAULT HEIGHTS AND WIDTHS IF THEY ARE NOT EXPLICITLY DEFINED IN CALL TO playVideo
    var defaultVideoWidth = "532";
    var defaultVideoHeight = "420";
    /*****************************************/
    /* IMPORTANT PARAMS TO CONFIGURE - END */
    /*****************************************/

    // test function variables
    if (lbid == "") { lbid = "lbVideo"; }
    if (vidWidth == "") { vidWidth = defaultVideoWidth; }
    if (vidHeight == "") { vidHeight = defaultVideoHeight; }
    if (vidDuration == "") { vidDuration = "9999"; }
    if (playerURL == null || playerURL == "") { playerURL = flashPrefix + "JergensGlowAdvisorVideoPlayer.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;
        
    var flash1_contentVersion = "9.0.115";


    // get div if exists, create if it doesn't
    var lightboxDiv = $j("#" + 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;
        flashvars.videoAutoPlay = "true";
        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 = $j("<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
            $j.fn.colorbox({
                innerWidth: playerWidth,
                innerHeight: playerHeight,
                inline: true,
                href: "#" + lbid,
                onOpen: function() { if ($j.browser.mozilla) ScrollFreeze.on(); $j('html').css({ overflow: 'hidden' }); }, //prevent scrolling
                onComplete: function() { // setup SWFObject
                    createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, flashVideoPlayerURL, playerWidth, playerHeight, lightboxDiv);
                },
                onCleanup: function() { lightboxDiv.hide(); $j('html').css({ overflow: 'auto' }); }, //re-enable scrolling
                onClosed: function() { lightboxDiv.remove(); if ($j.browser.mozilla) ScrollFreeze.off(); },
                opacity: 0.5
            });
        } else {  // Don't disable scrolling if video had to be resized to fit
            // open lightbox to display
            $j.fn.colorbox({
                innerWidth: playerWidth,
                innerHeight: playerHeight,
                inline: true,
                href: "#" + lbid,
                onOpen: function() { },
                onComplete: function() { // setup SWFObject
                    createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, flashVideoPlayerURL, playerWidth, playerHeight, lightboxDiv);
                },
                onCleanup: function() { lightboxDiv.hide(); },
                onClosed: function() { lightboxDiv.remove(); },
                opacity: 0.5
            });
        }
    } else {
        createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, flashVideoPlayerURL, playerWidth, playerHeight, lightboxDiv);
    }

    if (detectAndroid()) {
        $j("video").live("click", function() {
            this.play();
        });
    }
}

/***********************************************************************
supports_html5_h264_video tests the browser to see if it can
play HTML5_h264 video natively
***********************************************************************/
function supports_html5_h264_video() {
    //if Android, return true
    if (detectAndroid()) return true;
    //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 = $j("<div></div>").attr({ id: lbid });

    //create noflash div and insert
    var noflashDiv = $j("<div></div>").attr("id", lbid + "noflash").addClass("no-flash");
    var noflashP1 = $j("<p></p>").text(nonflashVideoContentPart1).attr("style", "padding-top:30px");
    var noflashP2link = $j("<a></a>").attr({ href: nonflashVideoContentPart2LinkUrl, target: "_blank" }).text(nonflashVideoContentPart2LinkText);
    var noflashP2 = $j("<p></p>").text(nonflashVideoContentPart2Text);
    noflashP2.prepend(noflashP2link);
    noflashDiv.append(noflashP1).append(noflashP2);
    lightboxDiv.append(noflashDiv);

    //Insert lightboxDiv
    $j(appendIdent).append(lightboxDiv);
    return lightboxDiv;
}

/***********************************************************************
createVideoObject creates either the SWFObject or Video tag as appropriate
params: flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight,
vidDuration, playerWidth, playerHeight, lightboxDiv
***********************************************************************/
function createVideoObject(flash1_contentVersion, lbid, videoURL, vidWidth, vidHeight, vidDuration, playerURL, playerWidth, playerHeight, lightboxDiv) {
    // 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;
        //if (detectAndroid() && videoURL.substring(0,3) == "../" && videoUrlPrefixForRelativeRootUsed) videoattributes.src = videoURL.substring(3);
        videoattributes.width = vidWidth;
        videoattributes.height = vidHeight;
        videoattributes.controls = "true";
        videoattributes.autoplay = "true";
        var video = $j("<video></video>").attr(videoattributes);
        lightboxDiv.html('');
        lightboxDiv.append(video);
    }
}

/*********************************************************************************************
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())
            $j(window).bind("scroll", function() { ScrollFreeze.setXY(); });
    },
    off: function() {
        $j(window).unbind("scroll");
        if ($j(window).scrollTop() != $j(window).data("yOffset"))
            setTimeout(this.setXY, 5);
    },
    getProp: function() {
        this.Ydisp = $j(window).scrollTop();
        $j(window).data("yOffset", this.Ydisp);
        return this.propFlag;
    },
    setXY: function() {
        $j(window).scrollTop($j(window).data("yOffset"));
    }
}

/***********************************************************************
detectiOSDevice returns true if the device is an iOS device,
based on the user agent string, false if not
***********************************************************************/
function detectiOSDevice() {
    var iOSdevices = ['ipod', 'itouch', 'ipad', 'iphone'];
    var userAgent = navigator.userAgent.toLowerCase();
    for (var i = 0; i < iOSdevices.length; i++) {
        if (userAgent.indexOf(iOSdevices[i]) != -1) {
            return true;
        }
    }
    return false;
}

/***********************************************************************
detectAndroid returns true if the device is an Android device,
based on the user agent string, false if not
***********************************************************************/
function detectAndroid() {
    var Android = ['android'];
    var userAgent = navigator.userAgent.toLowerCase();
    for (var i = 0; i < Android.length; i++) {
        if (userAgent.indexOf(Android[i]) != -1) {
            return true;
        }
    }
    return false;
}



/*********************************************************************************************
    Site Search Functions
*********************************************************************************************/

// Clear the input box on click if default value is present
function conditionalClear(current, field) {
    if (current == "Search" || current == "Enter Keywords") {
        field.value = " ";
    }
};

// Submit the search input when "Enter" is clicked
function submitEnterSiteSearch(e, link, element) {
    var keycode;
    if (window.event) keycode = window.event.keyCode;
    else if (e) keycode = e.which;
    else return true;
    if (keycode == 13 || keycode == 3) {
        siteSearch(link, element);
        return false;
    }
    else {
        return true;
    }
};

// Site Search
function siteSearch(link, element) {
    //alert(link);
    //alert(element);
    var searchInput = document.getElementById(element).getElementsByTagName('input')[0];
    var regEx = /[^a-z0-9\s.,-]/gi;
    var query = searchInput.value.replace(/^\s*|\s*$/, "");
    // alert("query = **" + query + "**");
    if (query == "Search" || query == "Enter Keywords" || query == "" || query == " ") {
        alert('Please enter search terms.');
        searchInput.focus();
    }
    else if (regEx.test(query)) {
        alert('Please use only alpha-numeric characters');
        searchInput.focus();
    }
    else {
        // Trim white space from both ends of query
        query = query.replace(/^\s+|\s+$/g, '');
        query = query.replace('=', '%3D');
        query = query.replace('&', '%26');
        query = query.replace('?', '%3F');
        query = query.replace('#', '%23');
        window.location = link + "?q=" + query + "&filter=0";
    }
};


/*********************************************************************************************
    initializeTabs()
	Tabs Component
	: Currently working only in the productDetail pages, to avoid DOM over querying
*********************************************************************************************/
function initializeTabs(){
    if ($j('body').hasClass('productDetail') || $j('body').hasClass('faq') || $j('body').hasClass('crema')) { // Section check
        var tabs = $j('.tabsComponent > ul li a');
		var tabContents = $j('.tabsComponent > div > div');
		$j(tabs).click(function(e) {
		    var index = tabs.index(this);
		    if ($j('body').hasClass('crema')) {
		        if ($j(this).hasClass('active')) {
		            tabs.removeClass('active');
		            tabContents.removeClass('active').stop(true, true).slideUp();
		            if($j('#wrapper').hasClass('spanish')){$j(this).text('VER INGREDIENTES +');}
		            else{$j(this).text('View Ingredients +');}
		        }
		        else {
		            tabs.addClass('active');
		            tabContents.addClass('active').stop(true, true).slideDown();
		            if($j('#wrapper').hasClass('spanish')){$j(this).text('Ocultar INGREDIENTES -');}
		            else{$j(this).text('Hide Ingredients -');}
		        }
		    }
		    else {
		        tabContents.removeClass('active').css('display', 'none') //Switches classes
			    .eq(index).addClass('active').css('display', 'block'); //needed for IE6 PNG
		        tabs.removeClass('active').css('border', '0px solid').eq(index).addClass('active'); //0px added for DD Fix Bug in IE6
		    }
		    dcsMultiTrack('DCS.dcsuri', 'tab_' + $j(this).text().replace(/ /g, '_'));
		    e.preventDefault();
		});
	}
}

/*********************************************************************************************
    initializeTheater()
	Theather Component
	: Slideshow-like Component for the homepage
*********************************************************************************************/
function initializeTheater(){
	if ($j('body').hasClass('home')){ // Section check
	
		var tabs = $j('#theater li a'),
			tabContents = $j('#theater > div > div'),
			tabSymbols = tabContents.find('sup');
			currentIndex = 0;
			
		//Slide Navigation 
		$j(tabs).click(function(e){
			if(!$j(this).hasClass('active')){ //Prevent animation on already active item
				var index = tabs.index(this);
				switchSlide(index);
				clearInterval(slideShowInterval);				
			}
			e.preventDefault();
		});
		
		//Switch Slide Action
		function switchSlide(index){
			if($j.browser.msie && $j.browser.version=='6.0' ){
				tabContents.removeClass('active').eq(index).addClass('active');
				tabs.removeClass('active').eq(index).addClass('active');
			} else {
				if ($j.browser.msie) tabSymbols.css('visibility','hidden'); //Cleartype fix for IE
				tabContents.filter('.active').stop().animate({opacity: 0.1}, 500, 'swing', function() {
					tabContents.removeClass('active').css('z-index','1')
					.eq(index).addClass('active').css({'opacity':0.1,'z-index':30}).stop().animate({opacity: 1}, 450, 'swing');			
					tabs.removeClass('active').eq(index).addClass('active');
					if ($j.browser.msie) tabSymbols.css('visibility','visible');
	 			});
			}
		}
		
		//Start Slideshow
		var slideShowInterval = setInterval(function(){
			currentIndex = tabContents.filter('.active').index()+1;
			currentIndex = (currentIndex == 3) ? 0 : currentIndex;
			switchSlide(currentIndex);
		}, 5000);

	}
}

/*********************************************************************************************
    initializeTheaterTakeover()
	Homepage Theather Takeover
*********************************************************************************************/
function initializeTheaterTakeover() {
    setTimeout(function() { triggerCameraFlash(200,100); }, 1100);
    setTimeout(function() { triggerCameraFlash(0,0); }, 2600);
    setTimeout(function() { triggerCameraFlash(420,70); }, 3200);
    setTimeout(function() { animateTheaterTakeover(); }, 5000);
}
function triggerCameraFlash(left, top) {
    $j('#flashdiv').stop(true,true).css({ left: left + 'px', top: top + 'px' }).show(0, function() {
        setTimeout(function() {
            if (($j.browser.msie && parseInt($j.browser.version) == 7) || ($j.browser.msie && parseInt($j.browser.version) == 8)) {
                $j('#flashdiv').hide();
            }else{
                $j('#flashdivWHITE').fadeIn(100).stop(true, true).fadeOut(300);
                $j('#flashdiv').fadeOut(100);
            }
        }, 70);
    });
}
function animateTheaterTakeover() {
    $j('#takeover').animate({ width: [749, 'linear'] });
    //height: 235 top: 157 left: 750 easeInQuad
    $j('#seeHowBtn').hide();
    $j('#takeoverImg').animate({ height: [170, 'linear'], width: [205, 'linear'], top: [163, 'easeOutSine'], left: [750, 'easeInQuart'], opacity: [0.5, 'linear'] }, 1500, function() {
        $j('#takeoverImg').fadeOut(700, function() {
            initializeTheater();
            $j('#takeover').hide();
        });
    });
}
	
/*********************************************************************************************
    initializeMenu()
	Adds "hover" class to LI elements simulating the :hover pseudo-class
	not supported by IE6
*********************************************************************************************/
function initializeMenu(){
	var bodyElement = $j('body'),
		wrapperElement = $j('#wrapper'), 
		wrapperMargin = wrapperElement.css('top'),
		globalNav = $j('#globalNav');
	//Rollover functionality for hidden submenus
	if (bodyElement.hasClass('singleMenu')){ 
		$j('#linkProducts, #linkJergens').parent().hover(function(){
				bodyElement.removeClass('singleMenu').addClass('activeMenu');
				wrapperElement.css('top',(parseFloat(wrapperMargin)-32)+'px');
			},function(){
				bodyElement.addClass('singleMenu').removeClass('activeMenu');
				wrapperElement.css('top',(parseFloat(wrapperMargin))+'px')
			}
		);
	} else { // When a sub-menu is default, manage collision with other menus
		$j('#linkProducts, #linkJergens').parent().hover(function(){
			if (!$j(this).hasClass('active')) { globalNav.addClass('collision'); }
		},function(){
			if (!$j(this).hasClass('active')) { globalNav.removeClass('collision'); }
		});
	}
	
	// Pseudo-class (:hover) replacement for IE6 compatibility
	$j('#globalNav ul > li').hover(function(){ 
			$j(this).addClass('hover');
		},function(){
			$j(this).removeClass('hover');
		}
	);
}
/*********************************************************************************************
setHoverEvents()
Adds "hover" class to tiles anchor simulating the :hover pseudo-class not supported by IE6
when needed.
*********************************************************************************************/
function setHoverEvents() {
    $j('#promoTiles > ul li a, .award, #sideContent .sidePanel, #faqTabs h2, #theater .content > div, .promotions .rightContent div, .promotions .leftContent').hover(function() {
        $j(this).addClass('hover');
    }, function() {
        $j(this).removeClass('hover');
    }
	);
	$j('body.home #sideContent .sidePanel').click(function() { // Restore states for Fifefox FBCache
		$j(this).removeClass('hover');
	});
}

/*********************************************************************************************
    initializeFAQ()
	Initializes FAQ component with collapsible entries
*********************************************************************************************/
function initializeFAQ(){
	if ($j('body').hasClass('faq')){
		var faqEntries = $j('div.faqEntry'),
			faqQuestions = faqEntries.find('h2');
		faqQuestions.click(function(e){
			$j(this).parent().toggleClass('expanded');
			e.preventDefault();			
		});
		$j('#actionPanel .linkExpand a').click(function(e){
			faqEntries.addClass('expanded');		
			e.preventDefault();
		});
		$j('#actionPanel .linkCollapse a').click(function(e){
			faqEntries.removeClass('expanded');
			e.preventDefault();
		});	
	}
}
/*

/*********************************************************************************************
	setPrintActions()
/*********************************************************************************************/
function setPrintActions(){
	$j('#printButton, #print').click(function(){
		window.print();
	});
}



/*********************************************************************************************
showSignUpConfirmation()
/*********************************************************************************************/
function showSignUpConfirmation() {

    $j('#signUpForm, #unsubscribeForm ').submit(function() {
        var action = $j('.formsSignUp').attr('action');
        $j.ajax({
            type: "POST",
            url: action, //action variable is a placeholder instead specify the url where the request should be sent.
            success: function() {
                $j('.formsSignUp').siblings().andSelf().addClass('hidden');
                $j('#submitText').removeClass('hidden');
                $j('#optin #wrapper').addClass('signUpThanks');
            }
        });
        return false;
    });
}

/*********************************************************************************************
initializeNoResults();
Adds a new class to when no results displayed
/*********************************************************************************************/
function initializeNoResults() {
    if (($j('.searchResults').has('div#ctl00_ContentPlaceHolder1_noResultsPanel')).size()>0) {
        $j('.searchResults').addClass('noResults');
     }
}
