
/*	Global Utilites
*/

//$(document).ready(function () {
//    $('<a/>', {
//        'href': "#moneyback"
//    })
//        .click(function () {
//            window.location.hash = '#moneyback';
//        })
//        .css({
//            'display': 'block',
//            'width': '110px',
//            'height': '15px',
//            'position': 'relative',
//            'bottom': '313px',
//            'left': '688px',
//            'z-index': '250',
//            'float': 'left'
//        })
//        .appendTo(
//                "#ctl00_PlaceHolderMasterPage_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField"
//        )
//})

//$(document).ready(function () {
//        $('<div/>', {
//        })
//        .click(function() {
//                 window.location.hash='moneyback';
//                })
//        .css({
//                'width' : '110px',
//                'height' : '15px',
//                'position' : 'relative',
//                'bottom' : '313px',
//                'left' : '688px',
//                'z-index' : '250',
//                'float' : 'left'})
//        .appendTo(
//                "#ctl00_PlaceHolderMasterPage_PlaceHolderMain_RichHtmlField1__ControlWrapper_RichHtmlField"
//        )})


/*added the below two for regenerist new landing */
$(document).ready(function () {
$('a.ga_track_AdLobs').each(function () {
        $(this).bind('click', function () {

            if ($(this).text() == "Find out why") {
                try {
                    var pageTracker = _gat._getTracker("UA-2768145-4");
                    pageTracker._trackPageview("/click/adlobpromo/regeneristprivatelabel");

                } catch (err) { }

 }
          })

    });
});
$(document).ready(function () {
    $('img.ga_track_AdLobs').each(function () {
        $(this).bind('click', function () {

            if ($(this).parent().attr("href") == "/RegeneristNewLanding.aspx?lang=en-US") {
                try {
                    var pageTracker = _gat._getTracker("UA-2768145-4");
                    pageTracker._trackPageview("/click/adlobpromo/regeneristprivatelabel");

                } catch (err) { }

            }
        })

    });
});
/*added the below two for moneybackguarantee promo */
$(document).ready(function () {
    $('a.ga_track_AdLobs').each(function () {
        $(this).bind('click', function () {

            if ($(this).attr("href") == "#moneybackguarantee?lang=en-US") {
                try {
                    var pageTracker = _gat._getTracker("UA-2768145-4");
                    pageTracker._trackPageview("/click/adlob/moneybackguarantee");

                } catch (err) { }

            }
        })

    });
});
$(document).ready(function () {
    $('img.ga_track_AdLobs').each(function () {
        $(this).bind('click', function () {

            if ($(this).parent().attr("href") == "#moneybackguarantee?lang=en-US") {
                try {
                    var pageTracker = _gat._getTracker("UA-2768145-4");
                    pageTracker._trackPageview("/click/adlob/moneybackguarantee");

                } catch (err) { }

            }
        })

    });
});


$(document).ready(function () {
    $('a.ga_FC_buynow').each(function () {

        $(this).bind('click', function () {
            try {

                var pageTracker = _gat._getTracker("UA-2768145-4");

                pageTracker._trackPageview("/click/refreshFC/buynow/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});


$(document).ready(function () {
    $('a.ba_learn_more').each(function () {


        $(this).bind('click', function () {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/refreshFC/learnnow/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});

/*
TE landing page tracking
*/

$(document).ready(function () {
    $('a.ga_TEproductschanging_buynow').each(function () {

        $(this).bind('click', function () {
            try {

                var pageTracker = _gat._getTracker("UA-2768145-4");

                pageTracker._trackPageview("/click/tetone/productschanging_buynow/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});

$(document).ready(function () {
    $('a.ba_learn_more3').each(function () {

        $(this).bind('click', function () {
            try {

                var pageTracker = _gat._getTracker("UA-2768145-4");

                pageTracker._trackPageview("/click/tetone/productschanging_learnnow/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});


$(document).ready(function () {
    $('a.ga_TEdiscontinued_buynow').each(function () {

        $(this).bind('click', function () {
            try {

                var pageTracker = _gat._getTracker("UA-2768145-4");

                pageTracker._trackPageview("/click/tetone/discontinued_buynow/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});


$(document).ready(function () {
    $('a.ba_learn_more2').each(function () {

        $(this).bind('click', function () {
            try {

                var pageTracker = _gat._getTracker("UA-2768145-4");

                pageTracker._trackPageview("/click/tetone/discontinued_learnnow/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});

$(document).ready(function () {
    $('a.ga_TE_adlob').each(function () {

        $(this).bind('click', function () {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/tetone/adlob/comingin2012/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});

$(document).ready(function () {
    if ($.cookie("IE6Allowed") == null || $.cookie("IE6Allowed") != 1) {
        var browserName = $.browser.msie;
        var browserVer = $.browser.version;
        if (browserName == true && browserVer == 6) {

            var message = '<table width="600" border="0" cellspacing="2" cellpadding="2" align="center">'
  + '<tr>'
  + '<td style="font-weight: bold; font-size: 16px; border-bottom: 1px solid #fff; line-height: 40px;">Did   you know that your Internet Explorer is out of date? <a href="javascript:void(0);" style="margin-left: 190px;" class="close">X</a></td>'
  + '</tr>'
  + '<tr>'
  + '<td>To get the best possible experience using our website we recommend that you   upgrade to a newer version or other web browser. A list of the most popular web   browsers can be found below.</td>'
  + '</tr>'
  + '<tr>'
  + '<td>Just click on the icons to get to the download page</td>'
  + '</tr>'
  + '<tr>'
  + '<td><table width="100%" border="0" cellspacing="2" cellpadding="2">'
  + '<tr>'
  + '<td><a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx" target="_blank"><img src="/en-US/Images/IE6alert/ie-latest.jpg" width="122" height="123" /></a></td>'
  + '<td><a href="http://www.mozilla.com/firefox/" target="_blank"><img src="/en-US/Images/IE6alert/ff-latest.jpg" width="122" height="123" /></a></td>'
  + '<td><a href="http://www.apple.com/safari/download/" target="_blank"><img src="/en-US/Images/IE6alert/safari-latest.jpg" width="122" height="123" /></a></td>'
  + '<td><a href="http://www.opera.com/download/" target="_blank"><img src="/en-US/Images/IE6alert/opera-latest.jpg" width="122" height="123" /></a></td>'
  + '<td><a href="http://www.google.com/chrome" target="_blank"><img src="/en-US/Images/IE6alert/chreome-latest.jpg" width="122" height="123" /></a></td>'
  + '</tr>'
+ '</table></td>'
+ '</tr>'
+ '</table>',

      div = $('<div id="ie-warning"></div>').html(message).hide();
            div.prependTo(document.body).slideDown(500);
            $('.close').click(function () {
                $.cookie("IE6Allowed", "1", { path: '/' });
                div.prependTo(document.body).slideUp(500);
            });
        }
    }
})


/*
Primary Nav SEO Fixes to embed noscript tags
*/
$(document).ready(function () {
    /**** Insert SEO Fixes to the Top Level Primary Nav ****/
    $("ul.pri_menu").find("li:eq(0)").after('<noscript><a href="/browsebyneed.aspx">browse by need</a></noscript>');
    /* Insert a noscript tag into Explore Products */
    $("ul.pri_menu").find("li:eq(1)").after('<noscript><a href="/AllBoutiques.aspx">skin care products</a></noscript>');

    /* Insert a noscript tag into Learn About Skin Care */
    $("ul.pri_menu").find("li:eq(2)").after('<noscript><a href="/LearnAboutSkin.aspx">skin care</a></noscript>');

    /* Insert a noscript tag into Inside Olay */
    $("ul.pri_menu").find("li:eq(3)").after('<noscript><a href="/InsideOlay.aspx">inside Olay</a></noscript>');

    /* Insert a noscript tag into Offers */
    $("ul.pri_menu").find("li:eq(4)").after('<noscript><a href="/Offers.aspx">olay coupon</a></noscript>');

    /**** Insert SEO Fixes to the 2nd Level of Explore Products ****/

    /* Add noscript tags for some of the boutiques */

    /* Insert after Body Lotion link */
//    $("#DvContentPopup2").find("div.row1:eq(9)").after('<noscript><a href="http://www.olay.com/skin-care-products/body-lotion">body lotion</a></noscript>');

//    /* Insert after Olay Body Cleansing link */
//    $("#DvContentPopup2").find("div.row1:eq(3)").after('<noscript><a href="http://www.olay.com/skin-care-products/body-cleansing">body cleansing</a></noscript><noscript><a href="http://www.olay.com/skin-care-products/body-cleansing/body-wash">body wash</a></noscript>');

//    /* Insert after Browse All link */
//    $("#DvContentPopup2").find("div.row1:eq(10)").after('<noscript><a href="http://www.olay.com/SpfSkinCare.aspx">spf skin care</a></noscript><noscript><a href="http://www.olay.com/skin-care-products/bath-and-body-products">bath and body products</a></noscript>');

});



/**
 *
 * Validation Application
 *
 */
/*These two functions are for Primary navigation */



function show(num) {/* ECOM & REGIMEN SCRIPT CHANGE */
    pageH = $(document).height()-100;
    pageW = $(document).width();
   

    $("#DvOpaqueLayer1").show();
    $('#DvOpaqueLayer1').height(pageH);
    $('#DvOpaqueLayer1').width(pageW);
    for (i = 1; i < 7; i++) {
        var div = "#DvContentPopup" + i;

        if (i == num) {

            $(div).show();
        }
        else {
            $(div).hide();
        }

    }

}
function hide() {/* ECOM & REGIMEN SCRIPT CHANGE */
    //            var div = "#DvContentPopup" + num;
    //            var div1 = "#DvOpaqueLayer1";
    //            $(div).hide();
    //            $(div1).hide();
    $("#DvOpaqueLayer1").hide();

    for (i = 1; i < 7; i++) {
        var div1 = "#DvContentPopup" + i;

        $(div1).hide();
    }

    $('#shoppingcart').hide();
    $('#light-box-shoppingcart').hide();

}


/*Above two functions are for Primary navigation */


   




var emcValidator = {
	
	// Define empty array for error objects
	errors: [],
	
	//  CSS predefined styles
	css: { 
		// Styles for input when error(s) are found
		active: {
			current: {borderColor:'#F00'},
			parent: {borderColor:'#F00'}
		}, 
		// Styles for input on "normal" state
		inactive: {
			current: {borderColor:'#000'},
			parent: {borderColor:'#F2E4C7'}
		} 
	},
	
	// String selectors for jQuery's message elements
	selectors: {
		messageWrapper: '.validationArea',
		messageList: '.validationList'
	},
	
	// Wrapper function for errors array.
	length: function() { return this.errors.length },
	
	// Create an errorObject, and append it to the error array.
	createError: function(i,m) {
		var e = { id: i, message: m };
		this.errors.push(e);
	},
	
	// Create a wrapper for jQuery's id selector.
	// 
	// This Sharepoint creates random element id's based on UUID prefix.
	getElementById: function(id) {
		return $("[id$='"+id+"']");
	},
	
	
	// Compare all elements in an array.
	//
	// $idArray$ an array of element IDs
	// $errorMessage$ a string to be displayed on error
	match: function(idArray, errorMessage) {
		var _A = "";
		for(var j = 0; j < idArray.length ; j++ )
		{
			if ( j == 0 )
			{
				_A = this.getElementById(idArray[j]).val();
			} else {
				var tmp = this.getElementById(idArray[j]);
				if ( _A != tmp.val() )
				{
					this.createError(idArray[j],errorMessage);
				}
			}
		}
	},
	
	
	func: function(idArray, execFunction, errorMessage) {
		if ( typeof execFunction != "function" ) { return false; }
		for (var j = 0 ; j < idArray.length ; j++ )
		{
			if ( ! execFunction.call( this.getElementById( idArray[j] ) ) ) {
				this.createError(idArray[j],errorMessage);
			}
		}
	},
	/*
	eval: function(idArray,evalFunction,errorMessage) {
		if ( typeof evalFunction != "function" ) {
			return false;
		}
		for ( var j = 0; j < idArray.length ; j++ )
		{
			var v = evalFunction.call(this.getElementById(idArray[j]))
			if ( v == false ) 
			{
				this.createError(idArray[j],errorMessage);
			}
		}
	},
	*/
	// Evaluate if element values is present.
	// Strips whitespace, and counts strings length
	//
	// $idArray$ an array of element IDs
	// $errorMessage$ a string to be displayed on error
	require: function(idArray, errorMessage) {
		for(var j = 0; j < idArray.length ; j++ )
		{	
			var element = this.getElementById(idArray[j])
			switch ( element.attr('type') ) {
				case "checkbox" :
					if ( !element.is(':checked') )
					{
						this.createError(idArray[j],errorMessage);
					}
					break;
				
				case "select-one":
					if ( element.val() == "0" )
					{
						this.createError(idArray[j],errorMessage);
					}
					break;
				case "text" :
				case "hidden" :
					var valueString = element .val().replace(/(\s)/,'');
					if ( valueString.length < 1 )
					{
						this.createError(idArray[j],errorMessage);
					}
					break;
				default : ;
			}
		}
	},
	age: function(idArray, ageRequire, errorMessage) {
		var currentTime = new Date();
		for(var j = 0; j < idArray.length ; j++ )
		{
			if(currentTime.getFullYear()-ageRequire < this.getElementById(idArray[j]).val())
			{
				this.createError(idArray[j],errorMessage);
			}
			
		}
		
	
	},
	
	// Pass element value through RegEx. Display error on null-match
	//
	// $idArray$ an array of element IDs
	// $errorMessage$ a string to be displayed on error
	reg: function(idArray,regEx,errorMessage) {
		for(var j = 0; j < idArray.length ; j++ )
		{				
			var valueString = this.getElementById(idArray[j]).val();
			if ( !valueString.match(regEx) )
			{
				this.createError(idArray[j],errorMessage);
			}
		}
	},
	
	// Resets all forms error messages
	// 
	// $callBack$ Executes a function if passed
	clear: function(callBack) {
		$(this.selectors.messageWrapper).hide();
		$(this.selectors.messageList).html(' ');
		for (var j = emcValidator.length() ; j > 0  ; j--)
		{
			this.getElementById(this.errors[j - 1].id).css(this.css.inactive.current).parent().css(this.css.inactive.parent);
			this.errors.pop();
		}
		if ( typeof callBack == "function" ) {
			callBack.call();
		}
	},
	
	// Displays all error messages
	// 
	// $onError$ Executes a function if passed, and errors where discovered
	render: function(onError) {
		if ( this.length() == 0 ) { return false; }
		$(this.selectors.messageWrapper).show();
		for ( var j = 0 ; j < this.length() ; j++ )
		{
			this.getElementById(this.errors[j].id).css(this.css.active.current).parent().css(this.css.active.parent);
			$(this.selectors.messageList).append('<p>'+this.errors[j].message+'</p>');
		}
		if ( this.length() > 0 && typeof onError == "function" )
		{
			onError.call();
		}
	}
}


		
/* 
	Toggle Country window
*/
function toggle_country_selection() {
    
    var _id_selector = 'countryOverlay';
	var _div_element  = document.getElementById(_id_selector);
	if (_div_element === null) {
	    try { console.log("Unable to find element with id \"" + _id_selector + "\"") } catch (err) { /* silent */ }
	    return false;
	}
	else {
	    showCountryList()
	}



	switch ( _div_element.style.display) {
		case "block" :
			_div_element.style.display = "none";
			break;
		default :
			_div_element.style.display = "block";
	}
	
}

/* 
	Toggle Language window
*/
function toggle_language_selection() {
	var _id_selector = 'languageOverlay';
	var _div_element  = document.getElementById(_id_selector);
	if (  _div_element === null ) 
	{
			try { console.log("Unable to find element with id \"" + _id_selector + "\"") } catch(err) { /* silent */ }
			return false;
	}
	switch ( _div_element.style.display) {
		case "block" :
			_div_element.style.display = "none";
			break;
		default :
			_div_element.style.display = "block";
	}
	
}


(function($) {
	/*
		Extended function to find nearest ancestor HTML Element.
	*/
    $.fn.ancestor = function(selector) {
        
        var $elem = $( this ).parent();
        while( $elem.size() > 0 ) {
            if( $elem.is( selector ) ) 
            {
                return $elem;
            } else {
                $elem = $elem.parent();
            }
        }
        return null;
    }

	/*
		`Extended function to strip leading/trailing whitespace from string
	*/
	$.fn.trim = function(string) {
			return string.replace(/^\s+/,'').replace(/\s+$/,'')
	}

	$.fn.cloneWithPassword = function() {
		var i = document.createElement('input');
		i.type = 'password'
		$(i).attr('value', $(this).attr('value'));
		$(i).attr('id', $(this).attr('id'));
		$(i).attr('name', $(this).attr('name'));
		$(i).addClass($(this).attr('class'));
		$(i).attr('rel',$(this).attr('rel'));
		return $(this).replaceWith(i);
	}
    $.fn.activeTextInput = function(args) {
		var options = $.extend({
			ancestorSelector	: '.active_nav_widget',
			isActiveClass		: 'is_active',
			inActiveClass		: 'is_inactive',
			parentSelector		: 'li'
		}, args);
	    return this.each(function() {
	        // Use REL attribute as reference
	        $(this).addClass(options.inActiveClass).attr('rel',$(this).val());
	        // Bind FOCUS event
	        $(this).bind('focus',function(){
	            /* */
	            if ($(this).val() == $(this).attr('rel'))
	            {
	                $(this).removeClass(options.inActiveClass).addClass(options.isActiveClass).val('');
	            }
	        });
	        // Bind BLUR event
	        
	        $(this).bind('blur',function(){
	            var _val = $.trim($(this).val());
	            if(_val == null || _val == '' )
	            {
	                $(this).removeClass(options.isActiveClass).addClass(options.inActiveClass).val($(this).attr('rel'));
	            } else {
	                $(this).removeClass(options.inActiveClass).addClass(options.isActiveClass).val(_val);
	            }
	        });
	        
    	});
    }
    
})(jQuery);

$(document).ready(function(){
	$('input.loginControlUserName, input.loginControlPassword').activeTextInput();
	$('.searchForm .search input').activeTextInput();
	
});

$.fn.gaTrackOlayForYou = function() {
 return $(this).each(function(){
  $(this).bind('click', function(){
   try {
		var pageTracker = _gat._getTracker("UA-2768145-4");
		pageTracker._trackPageview("/GoToOlayForYou");
		} catch(err) {}
  })
 })
}

$.fn.gaTrack = function(val) {
 return $(this).each(function(){
  $(this).bind('click', function(){
   try {  
     var pageTracker = _gat._getTracker("UA-2768145-4");
     pageTracker._trackPageview("/click/<"+ window.location.href.toLowerCase() + ">/<"+val+">/<Click>");
   } catch (err) {  }
  })
 })
}

$.fn.gaTrackSearch = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/<" + window.location.href.toLowerCase() + ">/<" + val + ">/<Search>");
            } catch (err) { }
        })
    })
}

$.fn.gaTrackSubmit = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/<" + window.location.href.toLowerCase() + ">/<" + val + ">/<Submit>");
            } catch (err) { }
        })
    })
}

$.fn.gaTrackSubmitAnswer = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/<" + window.location.href.toLowerCase() + ">/<" + val + ">/<SubmitAnswer>");
            } catch (err) { }
        })
    })
}

$.fn.gaTrackSelect = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/<" + window.location.href.toLowerCase() + ">/<" + val + ">/<Select>");
            } catch (err) { }
        })
    })
}

$.fn.gaTrackAddComment = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/<" + window.location.href.toLowerCase() + ">/<AddComment>");
            } catch (err) { }
        })
    })
}


$.fn.gaTrackLogin = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/<" + window.location.href.toLowerCase() + ">/<" + val + ">/<Login>");
            } catch (err) { }
        })
    })
}

$.fn.gaTrackAdLobs = function(val) {
    return $(this).each(function() {
        $(this).bind('click', function() {
		
			if($(this).text() == "find out")
			{
				 try {
						var pageTracker = _gat._getTracker("UA-2768145-4");
						pageTracker._trackPageview("/GoToOlayForYou");
		
					} catch(err) {}
			
			
			}
          
        })
    })
}

$.fn.gaTrackAdLobsImg = function(val) {
    return $(this).each(function() {
	
		if($(this).parent().attr("href") == "http://www.OlayForYou.com")
		{
			  $(this).parent().bind('click', function() {
		
				
				 try {
						var pageTracker = _gat._getTracker("UA-2768145-4");
						pageTracker._trackPageview("/GoToOlayForYou");
				
					} catch(err) {}
			
		          
			})
		
		
		
		
		
		}
      
    })
}

$.fn.gaTrackFierce = function (val) {
    return $(this).each(function () {
        $(this).bind('click', function (e) {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("click/fierce/regimenreco/" + val);
            } catch (err) { }
        })
    })
}
$.fn.gaTrackMonteCarlo = function (val) {
    return $(this).each(function () {
        $(this).bind('click', function(){
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/montecarlo/buynow/" + val);
               
            } catch (err) {  }
        })
    })
}


$.fn.gaTrackMonteCarloName = function (val) {
    return $(this).each(function () {
        $(this).bind('click', function () {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/montecarlo/" + val);
            } catch (err) { }
        })
    })
}




$(document).ready(function () {
    $('a.ga_FC_textlink').each(function () {

        $(this).bind('click', function () {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/refreshFC/textlink/findyourfavorite/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});

$(document).ready(function () {
    $('a.ga_FC_adlob').each(function () {

        $(this).bind('click', function () {
            try {
                var pageTracker = _gat._getTracker("UA-2768145-4");
                pageTracker._trackPageview("/click/refreshFC/adlob/findyourfavorite/" + $(this).attr('href'));

            } catch (err) { }
        })

    });
});

$(document).ready(function () {

    $('a.ga_track_buynow').gaTrack('BuyNow');
    $('#addToShopping').gaTrack('AddShoppingList');
    $('a.ga_track_onlineRetailer').gaTrackSearch('OnlineRetailer');
    $('.find_button').gaTrackSearch('NearStore');
    $('#ga_track_nearstore').gaTrackSearch('NearStore');
    $('input.joinClubOlayBtn').gaTrackSubmit('Registration');
    $('a.ga_track_pollName').gaTrackSubmitAnswer('PollName');
    $('a.ga_track_videoName').gaTrackSelect('VideoName');
    $('a.ga_track_liveConsultation').gaTrack('LiveConsultation');
    $('a.loginLink').gaTrackLogin('ClubOlay');
    $('a.ga_track_olayforyou').gaTrackOlayForYou();
    $('a.ga_track_AdLobs').gaTrackAdLobs();
    $('img.ga_track_AdLobs').gaTrackAdLobsImg();
    $('a.ga_track_Fierce1').gaTrackFierce('step1_regeneratingcreamcleanser');
    $('a.ga_track_Fierce2').gaTrackFierce('step2_microsculptingcream');
    $('a.ga_track_Fierce4').gaTrackFierce('step4_antiagingeyeroller');
    $('a.ga_track_Fierce5').gaTrackFierce('step5_nightresurfacingelixir');
    $('a.ga_track_facial-moisturizer').gaTrackMonteCarlo('http://olay.com/skin-care-products/anti-aging-products/facial-moisturizer?pid=075609032981');
    $('a.ga_track_micro-sculpting').gaTrackMonteCarlo('http://olay.com/skin-care-products/anti-aging-products/micro-sculpting-cream?pid=075609019326');
    $('a.ga_track_facial-moisturizer_name').gaTrackMonteCarloName('regenerist_uvdefense');
    $('a.ga_track_micro-sculpting_name').gaTrackMonteCarloName('regenerist_microsculptingcream');
    
});


$.fn.treeView = function(){
    return $(this).each(function () {
    
		/*try {
			var current_href = window.location.href.split('?')[0].split('/').pop().toLowerCase()
		} catch (er) { var current_href = "#" }
		$('> li > a:not(.expand)', this).each(function(){
			if ( $(this).attr('href').toLowerCase() == current_href )
			{
				$(this).siblings('ul').show();
				$(this).siblings('a.expand').addClass('active');
			} else {
				$(this).siblings('ul').hide();
			}
		});
		*/
		//$('li > ul', this).hide();
		$('li:first-child', this).addClass('first_child');
		$('li:last-child', this).addClass('last_child');
		$('li.SubCategoryListItem a.expand', this).each(function () {
				$(this).attr('href','#');
			}).toggle(
			function() {
				$(this).addClass('active').siblings('ul').slideDown('fast');
				},
			function() {
				$(this).removeClass('active').siblings('ul').slideUp('fast');
				}
		);
		$('li.SubCategory_current a.expand', this).addClass('active').toggle(
			function() {
				$(this).removeClass('active').siblings('ul').slideUp('fast');
				},
			function() {
				$(this).addClass('active').siblings('ul').slideDown('fast');
			}
		)
	});
}

/*
	Terms and Conditions
*/
$(document).ready(function () {
    $('#terms_and_conditions').bind('click', function () {
        var termElement = $('#terms_and_conditions_content');
        if (termElement.length > 0) {
            $('#DvOpaqueLayer1').show()
            termElement.show()
            termElement.click(function () {
                $(this).hide();
                $('#DvOpaqueLayer1').show();
            });
        }
        return false;
    });

    $('ul.SubCategoryList').treeView();
    $('li.SubCategory_current').treeView();
    $('li.SubCategoryListItem').treeView();

    $('.FilterTermsMenu ul.FilterMenu').treeView();
    $('.filterGroup .filterProperty').click(
		function () {
		    $(this).toggleClass('active').siblings('.filterValues').eq(0).slideToggle();
		    return false;
		}
	).siblings('.filterValues').hide();
    try {
        $('li.filterItem-current').parent('ul.filterValues').show().siblings('a.filterProperty').addClass('active');
    } catch (err) { }
});

/*
	Populate SELECT with OPTION node
*/
function newOptionsWithInteger(integer) {
	return $('<option></option>').html(integer).val(integer);
}

/*
	Hide input fields
*/
$(document).ready(function(){
	$('.hiddenFields, .hiddenControls').hide(); 
});

function GetElementByIdEndsWith(tagName, txtValue){
	return $(tagName+'[id$='+txtValue+']')[0] || false
}

/* Article control bar functions */
/* build back to category link */
$(document).ready(function(){

	if (  $('#olayArticleLayoutCategoryContent, #olayArticleCategoryLinkContent').length == 2 )
	{
		if ( $('#olayArticleLayoutCategoryContent').html().match(/learn\s+about\s+skin/i)  ) { $('#olayArticleCategoryLinkContent').html( "<a href=\"/LearnAboutSkin.aspx\">learn about skin care</a>" ); }
		else if ( $('#olayArticleLayoutCategoryContent').html().match(/inside\s+olay/i)  ) { $('#olayArticleCategoryLinkContent').html( "<a href=\"/insideolay.aspx\">inside Olay</a>" ); }
	}
	
});

/* bind print link */
$(document).ready(function(){
	$('#olayArticlePrinter, #olayProductDetailPrinter').bind('click', function(){
		window.print();
		return false;
		});
});

/* Email */
$(document).ready(function(){
	var str = window.location.href;
	if (str.indexOf('email=True') > -1) 
	{ 
		$('#olayProductDetailEmailer a').attr('href', str);
		return true;

	}
	var joint = str.indexOf('?') > -1 ? '&' : '?';
	/* commented by M&O team */
	/*$('#olayArticleEmailer a').attr('href', str + joint + 'email=True');*/

	$('#olayArticleEmailer a').attr('href', '/EmailFriend.aspx');
});

$(document).ready(function(){
	var str = window.location.href;
	if (str.indexOf('email=True') > -1) 
	{ 
		$('#olayProductDetailEmailer a').attr('href', str);
		return true;

	}
	var joint = str.indexOf('?') > -1 ? '&' : '?';
	/* comented by M&O team */
	/*$('#olayProductDetailEmailer a').attr('href', str + joint + 'email=True');*/
	$('#olayProductDetailEmailer a').attr('href', '/EmailFriend.aspx');
});



/* bind contrast links */
$(document).ready(function(){
	$('#olayArticleHighContraster').attr('href','#').bind('click', function(){
		$('.olayArticleLayoutPageContent, .olayQuizPollMainRightSection').css({backgroundColor:'#fff',color:'#000'});
		$('.olayArticleLayoutPageContent li, .olayQuizPollMainRightSection li').css({backgroundColor:'#fff',color:'#000'});
		$('#olayArticleLowContraster').show();
		$('#olayArticleHighContraster').hide();
		
		return false;
		});
	
	$('#olayArticleLowContraster').attr('href','#').bind('click', function(){
		$('.olayArticleLayoutPageContent, .olayQuizPollMainRightSection').css({backgroundColor:'#000',color:'#fff'});
		$('.olayArticleLayoutPageContent li, .olayQuizPollMainRightSection li').css({backgroundColor:'#000',color:'#fff'});
		$('#olayArticleHighContraster').show();
		$('#olayArticleLowContraster').hide();
		return false;
		});
});


$.fn.getFontSize = function(){	
	return parseInt(
		$(this).eq(0).css("font-size").replace(/px$/,"") || 0
	);
}
$.fn.getPaddingBottom = function(){	
	return parseInt(
		$(this).eq(0).css("padding-bottom").replace(/px$/,"") || 0
	);
}

$.fn.getPaddingTop= function(){	
	return parseInt(
		$(this).eq(0).css("padding-top").replace(/px$/,"") || 0
	);
}

$.fn.shiftText = function(adj, opts) {
	var range = $.extend({min:10,max:60},opts);
	var adj = parseInt(adj || 0);
	return $(this).each(function(){
		var cursorSize = parseInt( $(this).css('font-size') || 14 );
		var cursorLineHeight = parseInt( $(this).css('line-height') || 14 );
		cursorLineHeight = cursorLineHeight < cursorSize ? cursorSize : cursorLineHeight;
		if ( $.browser.msie && cursorLineHeight <= cursorSize )
		{
			cursorLineHeight = cursorLineHeight > 0 ? cursorLineHeight + 2 : cursorLineHeight;
		}
		if ( ( cursorSize > range.min && adj < 0) || ( cursorSize < range.max && adj > 0 ) ) {
			$(this).css({
				fontSize: (cursorSize + adj) + 'px',
				lineHeight: (cursorLineHeight + adj) + 'px'
			});
		} 
		return $(this);
	});
}

$.fn.shiftFontTag = function(direction_boolean) {
	return $(this).each(function(){
		var cursor = parseInt( $(this).attr('size') || 1 );
		switch (true) {
			case ( cursor < 7 && direction_boolean ) :
				$(this).attr('size', cursor + 1 );
			break;
			case ( cursor > 1 && !direction_boolean ) :
				$(this).attr('size', cursor - 1 );
			break;
		}
		return this;
	});
}

function isPositive(number) {
	return ( parseInt(number) > 0 )
}
/* create and bind text adjustment functions */
function adjustArticleTextSize(adj)
{
	/*
	// normal text
	log('adjusting text')
	var size = $('.olayArticleLayoutMainContent').getFontSize();
	if ( ( size < 28 || !isPositive(adj) ) && ( size > 10 || isPositive(adj) ) ) {
		var newSize = size + adj;
		$('.olayArticleLayoutPageContent').css("font-size", newSize + "px");
		$('.olayArticleLayoutMainContent').css("font-size", newSize + "px");
		$('.olayArticleLayoutMainContent p').css("font-size", newSize + "px");
		
		// paragraph break
		size = $('.olayArticleLayoutMainContent p').getPaddingBottom();
		newSize = parseInt(size.replace(/px/, "")) + adj;
		$('.olayArticleLayoutMainContent p').css("padding-bottom", newSize + "px");
	}
	// h1 text & breaks
	if($('.olayArticleLayoutMainContent h1').length)
	{	
		log('adjusting h1')
		size = $('.olayArticleLayoutMainContent h1').getFontSize();
		if ( ( size < 88 || !isPositive(adj) ) && ( size > 15 || isPositive(adj) ) ) {
			newSize = size + adj;
			$('.olayArticleLayoutMainContent h1').css("font-size", newSize + "px");
			$('.ms-rteCustom-ArticleTitle').css("font-size", newSize + "px");
			
			size = $('.olayArticleLayoutMainContent h1').getPaddingBottom();
			newSize = parseInt(size.replace(/px/, "")) + (2 * adj);
			$('.olayArticleLayoutMainContent h1').css("padding-bottom", newSize + "px");
			$('.ms-rteCustom-ArticleTitle').css("padding-bottom", newSize + "px");
		}
	}
	
	// h2 text & breaks
	if($('.olayArticleLayoutMainContent h2').length)
	{
		log('adjusting h2')
		size = $('.olayArticleLayoutMainContent h2').getFontSize();
		if ( ( size < 88 || !isPositive(adj) ) && ( size > 15 || isPositive(adj) ) ) {
			newSize = siz + adj;
			$('.olayArticleLayoutMainContent h2').css("font-size", newSize + "px");
		
			size = $('.olayArticleLayoutMainContent h2').getPaddingBottom();
			newSize = parseInt(size.replace(/px/, "")) + adj;
			$('.olayArticleLayoutMainContent h2').css("padding-bottom", newSize + "px");
		
		
			size = $('.olayArticleLayoutMainContent h2').getPaddingTop();
			newSize = parseInt(size.replace(/px/, "")) + adj;
			$('.olayArticleLayoutMainContent h2').css("padding-top", newSize + "px");
		}
	}
	*/
	try {
		var _selector = '.olayArticleLayoutContentRight p, .olayArticleLayoutContentRight h1, .olayArticleLayoutContentRight h2, .olayArticleLayoutContentRight li, ';
		    _selector += '.olayQuizPollMainRightSection p, .olayQuizPollMainRightSection h1, .olayQuizPollMainRightSection h2, .olayQuizPollMainRightSection li, ';
		    _selector += '.olayQuizPollHtmlSection p';
		$(_selector).shiftText(adj * 2);
		$('font').shiftFontTag(isPositive(adj));
	} catch (err) { /* */ }
}

$(document).ready(function(){
	$('#olayArticleTextSizePlus').attr('href','#').bind('click', function(){
		try {
			adjustArticleTextSize(1);
		} catch (err) { throw(err) /* */ }
		return false;
		});
	
	$('#olayArticleTextSizeMinus').attr('href','#').bind('click', function(){
		try {
			adjustArticleTextSize(-1);
		} catch (err) { throw(err) /* */ }
		return false;
		});
});

/*
	Popup Close Button
*/
$(document).ready(function(){
	$('a#popUpClosepopup').bind('click',function(){
	    $('#popUpOverlaypopup').hide();
        $('#popUpBackGroundpopup').hide();
	});
});

$(document).ready(function () {
    $('a#popUpCloseprofilepopup').bind('click', function () {
        $('#popUpOverlayprofilepopup').hide();
        $('#popUpBackGroundprofilepopup').hide();
    });
});

$(document).ready(function () {
    $('a#popUpCloseChangePasswordpopup').bind('click', function () {
        $('#popUpOverlaycpPopup').hide();
        $('#popUpBackGroundcpPopup').hide();
    });
});

$(document).ready(function () {
    $('a#popUpCloseresetRequest').bind('click', function () {
        $('#popUpOverlayresetRequest').hide();
        $('#popUpBackGroundresetRequest').hide();
    });
});

$(document).ready(function () {
    $('a#popUpCloseResetPasswordpopup').bind('click', function () {
        $('#popUpOverlayResetPopup').hide();
        $('#popUpBackGroundResetPopup').hide();
    });
});


/*
	BV Set offset
*/
$.fn.adjustBV = function(args){
	var options = $.extend({
		base_selector: '.olayWideLayoutWebpartZoneMain',
		top_offset: 50,
		bottom_offset: 50
	},args);
	return this.each(function(){
		var rootOffset = $(options.base_selector).offset();
		if ( typeof rootOffset == "undefined" ) { var rootOffset = { left : "auto", top : "auto" } ; }
		$(this).css({
			left: rootOffset.left,
			top: rootOffset.top + options.top_offset
		});
		$(options.base_selector).css({
			minHeight: $(this).height() + options.bottom_offset
		});
	});
}	
/*
$(document).ready(function(){
	if ( $('div[id=BVSubmissionContainer], #BVSYContainer').length > 0 ) { 
		$('div[id=BVSubmissionContainer], #BVSYContainer').adjustBV();
		var timer = setInterval(function(){ $('div[id=BVSubmissionContainer], #BVSYContainer').adjustBV(); }, 632);
		$(window).resize(function(){ $('div[id=BVSubmissionContainer], #BVSYContainer').adjustBV(); });
	}
});
*/
/* maintain dropdown state for sort*/
$(document).ready(function(){

	if(getParameterByName('sortby') != "")
	{
	   $('#GridSort').val(getParameterByName('sortby'));
	}
    
});


/*
	Print Preview
*/
function printPreview(){
	$('link[href$=print.css]').each(function(){
		$(this).attr('media',($(this).attr('media') == 'print' ? 'screen' : 'print'));
	});
}

/*
	Bind email close button
*/
$(document).ready(function(){
	$('#popUpCloseemail').click(function(){
		$('#popUpOverlayemail, #popUpBackGroundemail').remove()
	});
});

function change_parent_url(url){
	document.location=url;
}

// Demo two style(s|ing) for myClubOlay
/*
$(document).ready(function(){
	$('.olayThreeZoneLayoutLeft .newslettersClubOlay').bind('dblclick',function(){
		$('.image, .description', this).slideToggle();
	});
});
*/


$.fn.restrictLength = function(max_length) {
	return $(this).each(function(){
		if (max_length === undefined) {
			var alt = $(this).attr('rel')
			max_length = isNaN(alt) ? 500 : alt
		}
		var str = $(this).val();
		if (str.length > max_length) 
		{
			$(this).val(str.substring(0,max_length));
		}
	});	
}
/*
$(document).ready(function(){
	$('.hasMaxLength').bind('keyup',function(){
		$(this).restrictLength(500);
	});
});
*/

/* 
Binds the Buy All Link on the dynamic landing page to the goToBuyAllPage() function.
*/
$(document).ready(function(){ $('#buyAllLink').click(function(){goToBuyAllPage();})});


/*
	BV Article Corrections
	
	Function that returns the width and height of the given selctor.
*/
function getBVdims(selector) {
	return { 
		width:  $(selector).outerWidth(true),
		height: $(selector).outerHeight(true)
	}
}
//#BVSYContainer
function createElementPlaceholder(afterElement, dims)
{
	dims = typeof dims != "object" ? {} : dims ;
	var _attr = {
		id:'BVPlaceHolder'
	};
	var _css = $.extend({
		clear: 'left',
		width: 100,
		height: 100,
		float: 'left'
	}, dims);
	var _neu_element = $('<div></div>').attr(_attr).css(_css)
	$(afterElement).after(_neu_element);
	return $(_neu_element).offset();
}



function emcIsLoaded() {
	return typeof BVisLoaded == "undefined" ? false : BVisLoaded ;
}

function log(msg)
{
	try { console.log(msg); } catch (err) { /* Silence */ }
}




/*
	Hide element of Cookie is empty
*/
$.fn.hideIfCookieIsEmpty = function(cookieName) {
	if ( typeof cookieName != "string" ) { return this ; }
	var regex = new RegExp(cookieName + "=([^\s;]+)");
	if ( !regex.test(document.cookie ) ) {
		$(this).each(function(){
			$(this).hide();
		});
	}
	return $(this);
}

$(document).ready(function(){
	$('#olayShoppingListViewLink a').attr('href','#').bind('click',function(){
		$('.wishListItemRowGrid').removeClass('wishListItemRowGrid').addClass('wishListItemRow');
		$('.shopping_white_icon').removeClass('shopping_white_icon');
		$(this).parent().addClass('shopping_white_icon');
		return false;
	});
	$('#olayShoppingGridViewLink a').attr('href','#').bind('click',function(){
		$('.wishListItemRow').removeClass('wishListItemRow').addClass('wishListItemRowGrid');
		$('.shopping_white_icon').removeClass('shopping_white_icon');
		$(this).parent().addClass('shopping_white_icon');
		return false;
	});
	$('#olayShoppingListToolbar').hideIfCookieIsEmpty('olayWishList')
});


/* Checks if the given object is empty */
$.fn.isEmpty = function(){
    var _html = "";
    $(this).each(function(){
        _html += $(this).html();
    });
    return _html.length > 0 ? false : true
};




var emcWatcherString="";
var emcWatcherInterval;

function emcWatcher() {
	log('emcWatcher called');
	window.emcWatcherInterval = setInterval(function(){
			var watchingScope = '#BVSYContainer, #BVCustomerRatings, #BVSubmissionContainer';
			if ( $(watchingScope).length > 0 && !$(watchingScope).isEmpty() ) {
			
				/*These two lines belongs to the google onclick code above.*/
			    $('#BVRRSubmitReviewButtonID').gaTrack('SubmitReview');
	            $('#BVSYDisplayContentLinkWriteID').gaTrackAddComment('AddComment');

				switch(true) {
					/*
						Video
					*/
					case $('.olayVideoLayoutVideoContent, #BVSYContainer').length == 2:
						log('updating video');
						$('#BVSYContainer, #BVSYSummaryBoxHeaderID, #BVSYSummaryBoxLinksID').css({
							position: "relative",
							marginLeft: "261px"
						});
						//var d = $.extend({clear:'right',marginTop: '100px',float:'none'},getBVdims('#BVSYContainer'));
						//$('#BVSYContainer').css(createElementPlaceholder('.olayVideoLayoutVideoContent',d)).css('width','654px');
												
						// Adjust the footer relative to this section
						
						// Get the dimensions to use for the footer.  Get the height and top of the 
						// BVSYContainer
						//var containerTop = $('#BVSYContainer').outerHeight(true) + $('#BVPlaceHolder').outerHeight(true);

						// Update the footer with these dimensions
						//$('.Footer').css('margin-left','261px').css('margin-top','100px').css('position','absolute').css('top',containerTop);												
					break;
					/*
						Slide Show
					*/
					case $('.OlayPageSlideshowContent, #BVSYContainer').length == 2:
						log('updating sldeshow');
						$('#BVSYContainer, #BVSYSummaryBoxHeaderID, #BVSYSummaryBoxLinksID').css({
							position: "relative",
							marginLeft: "261px"
						});
						//var d = $.extend({clear:'right',marginTop: '100px',float:'none'},getBVdims('#BVSYContainer'));
						//$('#BVSYContainer').css(createElementPlaceholder('.OlayPageSlideshowContent',d)).css('width','654px');
												
						// Adjust the footer relative to this section
						
						// Get the dimensions to use for the footer.  Get the height and top of the 
						// BVSYContainer
						//var containerTop = $('#BVSYContainer').outerHeight(true) + $('#BVPlaceHolder').outerHeight(true);

						// Update the footer with these dimensions
						//$('.Footer').css('margin-left','261px').css('margin-top','100px').css('position','absolute').css('top',containerTop);												
					break;
					/*
						Quiz Pages
					*/
					case $('.olayQuizPollMainRightSection, #BVSYContainer').length == 2:
						log('updating quiz');
						$('#BVSYContainer, #BVSYSummaryBoxHeaderID, #BVSYSummaryBoxLinksID').css({
							position: "relative",
							marginLeft: "261px"
						});
						//var d = $.extend({clear:'right',marginTop: '10px', marginLeft:'261px',float:'none'},getBVdims('#BVSYContainer'));
						//$('#BVSYContainer').css(createElementPlaceholder('.olayQuizPollMainRightSection',d)).css('width','654px');
												
						// Adjust the footer relative to this section
						
						// Get the dimensions to use for the footer.  Get the height and top of the 
						// BVSYContainer
						//var containerTop = $('#BVSYContainer').outerHeight(true) + $('#BVPlaceHolder').outerHeight(true);

						// Update the footer with these dimensions
						//$('.Footer').css('margin-left','261px').css('margin-top','100px').css('position','absolute').css('top',containerTop);												
					break;
					/*
						Generic Article
					*/
					case $('.olayArticleLayoutContentRight, #BVSYContainer').length == 2:
						log('updating article');
						//var d = $.extend({clear:'right',marginTop: '10px', marginLeft:'261px',float:'none'},getBVdims('#BVSYContainer'));
						//$('#BVSYContainer').css(createElementPlaceholder('.olayArticleLayoutContentRight',d)).css('width','654px');
						$('#BVSYContainer, #BVSYSummaryBoxHeaderID, #BVSYSummaryBoxLinksID').css({
							position: "relative",
							marginLeft: "261px"
						});
						// Adjust the footer relative to this section
						
						// Get the dimensions to use for the footer.  Get the height and top of the 
						// BVSYContainer
						// var containerTop = $('#BVSYContainer').outerHeight(true) + $('#BVPlaceHolder').outerHeight(true);

						// Update the footer with these dimensions
						// $('.Footer').css('margin-left','261px').css('margin-top','100px').css('position','absolute').css('top',containerTop);												
					break;
					/*
						Product Detail - First Review
					*/
					case $('#BVRRRatingSummaryLinkWriteFirstID').length == 1:
						log('updating first review');
						// Position the ReadAllReviews link relative to the Write First Review Link
						$('.ReadAllReviewsLink').hide() //.css({marginTop: '-31px', marginLeft:'290px'});
						// Remove 
					break;
					/*
						Product Detail - Existing Reviews
					*/
					case $('#BVRRRatingSummaryLinkWriteID').length == 1:
						log('updating reviews');
						// Position the ReadAllReviews link relative to the Write Review Link
						var _left = ($.browser.msie && $.browser.version.substr(0,1)<7) ? '160px' : '278px';
						$('.ReadAllReviewsLink').css({marginTop: '-25px', marginLeft: _left });
					break;
					/*
						Form Submit
					*/
					case !!$('body').children('#BVSYContainerDN').length :
						log('updating form overlay');
						// Get Dimensions  of BV container
						var d = $.extend({clear:'right',marginTop: '10px',float:'none'},getBVdims('#BVSYContainerDN'));
						// Move BV over placeholder
						$('#BVSYContainerDN').css(createElementPlaceholder('.olayWideLayoutHtmlMain',d)).css('width','915px');
						setInterval(function(){
							$('#BVPlaceHolder').height($('#BVSYContainerDN').height());
						},333);
					break;
					/*
						Form Submit
					*/
					case !!$('body').children('#BVSubmissionContainerDN').length :
						log('updating form overlay');
						// Get Dimensions  of BV container
						var d = $.extend({clear:'right',marginTop: '50px',float:'none'},getBVdims('#BVSubmissionContainerDN'));
						// Move BV over placeholder
						$('#BVSubmissionContainerDN').css(createElementPlaceholder('.olayWideLayoutHtmlMain',d)).css('width','915px');
						setInterval(function(){
							$('#BVPlaceHolder').height($('#BVSubmissionContainerDN').height());
						},333);
					break;
				} 
				/* Clean loop */
				clearInterval(window.emcWatcherInterval);
			}
	},333);
}


/*
	Navigation behavior
	~emc
*/
$(document).ready(function(){
	$('.Dvtotal_header .top_panel ul.pri_menu li').bind('mouseenter',function(){
		$('.Dvtotal_header .top_panel ul.pri_menu a').addClass('inactive');
		$('a', this).removeClass('inactive');
	});
	$('#DvOpaqueLayer1, #DvOpaqueLayer2, #DvOpaqueLayer3, #DvOpaqueLayer4').bind('mouseenter',function(){
		$('.Dvtotal_header .top_panel ul.pri_menu a').removeClass('inactive');
	});
	/* Bind behavior of dropdowns */
	/* Causes epileptic seizures ------ Removed 20100511
	$('#DvContentPopup1, #DvContentPopup2, #DvContentPopup3, #DvContentPopup4').bind('mouseleave',function(){ 
		$(this).hide();
		$('div[id^=DvOpaqueLayer]').hide();
		$('.Dvtotal_header .top_panel ul.pri_menu a').removeClass('inactive');
	});
	*/
	$('ul.pri_menu').bind('mouseleave',function(evt){
	var limit = 65 - (window.pageYOffset || 0);
	if (evt.clientY < limit) {
		$('div[id^=DvOpaqueLayer], div[id^=DvContentPopup]').hide();
		$('.Dvtotal_header .top_panel ul.pri_menu a').removeClass('inactive');
	}
	});
});


/*
	Stip comments from Awards & Press pages
	And Adjust searchbar valignment for Win/Mozilla
*/
$(document).ready(function(){
	try {
		var _s = $('.olayArticleLayoutSubcategory').text().replace(/(\s)/g,'').toLowerCase();
		if ( _s == "awardsandpress" ||"theolaystory") {
			$('#olayArticleCommenter').css('visibility','hidden');
		}
	} catch (er) { /* silence */ }
	if ( ( navigator.appVersion.indexOf('Win') > 0 ) && $.browser.mozilla ) {
		if ( $.browser.version < "1.9.2.3" ) {
			$('.IDPSearchTextBox').css('padding-top','6px');
		}
	}
	
	
	// Fix IE PNG FIX
	
	if ($.browser.msie && $.browser.version.substr(0,1)<7) {
		try {
			/*
			var s = $('<script></script>').attr({
				type: 'text/javascript',
				src: '/Style Library/jquery.pngFix.pack.js'
			});
			$('body').append(s);
			*/
			eval(function(p,a,c,k,e,r){e=function(c){return(c<62?'':e(parseInt(c/62)))+((c=c%62)>35?String.fromCharCode(c+29):c.toString(36))};if('0'.replace(0,e)==0){while(c--)r[e(c)]=k[c];k=[function(e){return r[e]||e}];e=function(){return'([237-9n-zA-Z]|1\\w)'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('(s(m){3.fn.pngFix=s(c){c=3.extend({P:\'blank.gif\'},c);8 e=(o.Q=="t R S"&&T(o.u)==4&&o.u.A("U 5.5")!=-1);8 f=(o.Q=="t R S"&&T(o.u)==4&&o.u.A("U 6.0")!=-1);p(3.browser.msie&&(e||f)){3(2).B("img[n$=.C]").D(s(){3(2).7(\'q\',3(2).q());3(2).7(\'r\',3(2).r());8 a=\'\';8 b=\'\';8 g=(3(2).7(\'E\'))?\'E="\'+3(2).7(\'E\')+\'" \':\'\';8 h=(3(2).7(\'F\'))?\'F="\'+3(2).7(\'F\')+\'" \':\'\';8 i=(3(2).7(\'G\'))?\'G="\'+3(2).7(\'G\')+\'" \':\'\';8 j=(3(2).7(\'H\'))?\'H="\'+3(2).7(\'H\')+\'" \':\'\';8 k=(3(2).7(\'V\'))?\'float:\'+3(2).7(\'V\')+\';\':\'\';8 d=(3(2).parent().7(\'href\'))?\'cursor:hand;\':\'\';p(2.9.v){a+=\'v:\'+2.9.v+\';\';2.9.v=\'\'}p(2.9.w){a+=\'w:\'+2.9.w+\';\';2.9.w=\'\'}p(2.9.x){a+=\'x:\'+2.9.x+\';\';2.9.x=\'\'}8 l=(2.9.cssText);b+=\'<y \'+g+h+i+j;b+=\'9="W:X;white-space:pre-line;Y:Z-10;I:transparent;\'+k+d;b+=\'q:\'+3(2).q()+\'z;r:\'+3(2).r()+\'z;\';b+=\'J:K:L.t.M(n=\\\'\'+3(2).7(\'n\')+\'\\\', N=\\\'O\\\');\';b+=l+\'"></y>\';p(a!=\'\'){b=\'<y 9="W:X;Y:Z-10;\'+a+d+\'q:\'+3(2).q()+\'z;r:\'+3(2).r()+\'z;">\'+b+\'</y>\'}3(2).hide();3(2).after(b)});3(2).B("*").D(s(){8 a=3(2).11(\'I-12\');p(a.A(".C")!=-1){8 b=a.13(\'url("\')[1].13(\'")\')[0];3(2).11(\'I-12\',\'none\');3(2).14(0).15.J="K:L.t.M(n=\'"+b+"\',N=\'O\')"}});3(2).B("input[n$=.C]").D(s(){8 a=3(2).7(\'n\');3(2).14(0).15.J=\'K:L.t.M(n=\\\'\'+a+\'\\\', N=\\\'O\\\');\';3(2).7(\'n\',c.P)})}return 3}})(3);',[],68,'||this|jQuery||||attr|var|style||||||||||||||src|navigator|if|width|height|function|Microsoft|appVersion|border|padding|margin|span|px|indexOf|find|png|each|id|class|title|alt|background|filter|progid|DXImageTransform|AlphaImageLoader|sizingMethod|scale|blankgif|appName|Internet|Explorer|parseInt|MSIE|align|position|relative|display|inline|block|css|image|split|get|runtimeStyle'.split('|'),0,{}))
			$(document).pngFix({
				blankgif: '/en-US/Images/blank.gif'
			});
			$('div[id^=DvContentPopup] .left span').css({width: '40px', height: '40px'});
			
			// inject clear tag on boutique
			$('.olayBoutiqueLayoutWebpartSection').append($('<div></div>').attr('class','clear'));
			
			
			$('.olayBoutiqueLayoutWebpartSectionRight .image-area-left span').remove();
			$('.olayBoutiqueLayoutWebpartSectionRight .image-area-left img').css({display:'block'});
			
			
		} catch (er) {  } 
	}

});
// this function used for OlayGlossaryOverlaywebpart
function generateURL(glossaryterm) {

    var currentURL = document.location.href;
    var arrUrlStrings = currentURL.split("&");
    var targetURL = arrUrlStrings[0] + "&popup=true&glossaryterm=" + glossaryterm;

    window.location.href = targetURL;
}

//flash tracker for google analytics
function trackClick(description) {

                try {
                                var pageTracker = _gat._getTracker("UA-2768145-4");
                                pageTracker._trackPageview(description);
                } catch(err) {}
}


$(document).ready(function(){

        var scJsTag = (("https:" == document.location.protocol) ? "https://www." : "http://www.");

        $("body").append( unescape("%3Cscript src='" + scJsTag + "customerconversio.com/us/pgworld/olaysc10/sitecrm/sitecrm.aspx' type='text/javascript'%3E%3C/script%3E") );

});

    function showCountryList() {
       

    
        if (window.XMLHttpRequest) {
            xmlhttp = new XMLHttpRequest();
        }
        else {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

        }
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                //alert(xmlhttp.responseText);
                $("#countryOverlay").html(xmlhttp.responseText);
                
               // document.getElementById("countryOverlay").innerHTML =
                
            }
        }

        xmlhttp.open("POST", "/PopupWebForm.aspx?lang=en-US", true);
        xmlhttp.send(null);

    }
    // calling RegistrationPopUpOverlay
    function callRegistrationPopUpOverlay() {
        $('#popUpOverlaypopup').show();
        $('#popUpBackGroundpopup').show();
    }

    // calling UpdateProfilePopUpOverlay
    function callUpdateProfilePopUpOverlay() {
        $('#popUpOverlayprofilepopup').show();
        $('#popUpBackGroundprofilepopup').show();
    }

    // calling ChangePasswordPopUpOverlay
    function callChangePasswordPopUpOverlay() {
        $('#popUpOverlaycpPopup').show();
        $('#popUpBackGroundcpPopup').show();
    }

    // calling ChangePasswordPopUpOverlay
    function callForgotPasswordPopUpOverlay() {
        $('#popUpOverlayresetRequest').show();
        $('#popUpBackGroundresetRequest').show();
    }

    // calling ResetPasswordPopUpOverlay
    function callResetPasswordPopUpOverlay() {
        $('#popUpOverlayResetPopup').show();
        $('#popUpBackGroundResetPopup').show();
    }
    
    

 //jquery start for ChangeUserEmail Page

    $(document).ready(function () {
        $("input[id$='_submitImageButton']").click(function () {

            newEmail = $('input[id$="PlaceHolderMain_txtNewEmail"]').val();
            if (newEmail == "") {
                $('#DivChangeUserName_NotValidAddress').show();
                return false;
            }

            var emailPattern = /^\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/;
            if (emailPattern.test(newEmail) != true) {
                $('#DivChangeUserName_NotValidAddress').show();
                return false;
            }

        });

    });

    // calling ChangeUserNameAlreadyExisted Div
    function callChangeUserNameAlreadyExisted() {
        $('#DivChangeUserName_EmailAlreadyUsed').show();
        return false;
    }

    // calling callLoginFailureText Div
    function callLoginFailureTextDiv() {
        $('.loginFailure').show();
        return false;
    }

    function callLoginLockoutTextDiv() {
        $('.loginLockout').show();
        return false;
    }
    //Hiding viewFullIngredientsList Div
    function viewFullIngredientsList() {
       
        $('.keyIngredientsListPanel').hide();
        $('.fullIngredientsListPanel').show();
    }

    //Hiding InactiveRegimen Div
    function viewKeyIngredientsList() {
       
        $('.keyIngredientsListPanel').show();
        $('.fullIngredientsListPanel').hide();

    }
    
     //Hiding InactiveRegimen Div
    function callHideInactiveRegimen() {
        $('div.myRegimenInActiveModule').hide();
    }

    //Displaying InactiveRegimen Div
    function callShowInactiveRegimen() {
        $('div.myRegimenInActiveModule').show();
    }

   //Displaying OlayIngredientsOverlay Div
    function callShowIngredientsPopUpOverlay() {
      
        $('#popUpOverlaypopup').show();
        $('#popUpBackGroundpopup').show()

    }

    $(document).ready(function () {
        $("input[id$='_FindButton']").click(function () {
            if (!$("#FindNearbyStore").attr('checked')) {
                return false;
            }
        });
    });

    function appendToWishList(pid) {

        var olayWishList = $.cookie("olayWishList");

        if (olayWishList == null)
            $.cookie("olayWishList", pid + ";", { path: '/', expires: '14' });

        else
            $.cookie("olayWishList", olayWishList + pid + ";", { path: '/', expires: '14' });
    }

    $(document).ready(function () {
       
        var iMedia = (("https:" == document.location.protocol) ? "https://" : "http://");

        $("body").append(unescape("%3Cscript src='" + iMedia + "js.revsci.net/gateway/gw.js?csid=F09828&auto=t' type='text/javascript'%3E%3C/script%3E"));

    });

   $(document).ready(function () {

       $('select[id$="_cboDay"]').val("28");

   });

   /* ECOM & REGIMEN SCRIPT START */
   /*    Added By: Manish Chunawala - 21 Nov 11    Wishlist Script Start    */

   function appendToWishList(pid) { // IN USE. This function is called from the Overlay Add to wish list link
       var olayWishList = $.cookie("olayWishList");
       if (olayWishList == null)
           $.cookie("olayWishList", pid + ";", { path: '/', expires: '14' });
       else if (!(olayWishList.indexOf(pid + ';') > -1))
           $.cookie("olayWishList", olayWishList + pid + ";", { path: '/', expires: '14' });

       UpdateWishListSummaryCount();
       var addtowishlistpageurl = '/addtowishlist.aspx?pid={0}';
       Displayoverlay(addtowishlistpageurl.replace("{0}", pid), "true");
   }

   function appendToWishListEcom(pid, linkid, inShoppingListText, lang) { // IN USE

       var olayWishList = $.cookie("olayWishList");

       if (olayWishList == null)
           $.cookie("olayWishList", pid + ";", { path: '/', expires: '14' });

       else if (!(olayWishList.indexOf(pid + ';') > -1))
           $.cookie("olayWishList", olayWishList + pid + ";", { path: '/', expires: '14' });


       addWishListText = $("a[id$='" + linkid + "']");
       var Wishlist_Page_Url = "/wishlist.aspx?lang=" + lang;

       var addWishListText; // change the text to the "In wish list";

       addWishListText.text("" + inShoppingListText + "");
       var addtowishlistpageurl = '/addtowishlist.aspx?pid={0}&lang=' + lang;
       Displayoverlay(addtowishlistpageurl.replace("{0}", pid), "false")
       UpdateWishListSummaryCount();
       return false;
   }

   function RemoveWishListItem(productCode) {
       if ($.cookie('olayWishList') != null) {
           var cookieValue = $.cookie('olayWishList');
           if (cookieValue.indexOf(productCode + ';') > -1) {
               cookieValue = cookieValue.replace(productCode + ';', "");
               $.cookie('olayWishList', cookieValue, { expires: 14, path: '/' });
           }
       }
   }

   /*    Added By: Manish Chunawala - 21 Nov 11    Wishlist Script End    */

   /*    Added By: Manish Chunawala - 21 Nov 11    ShoopingCart Script Start    */
   function appendToShoopingCart(pid) {

       var olayShoppingCart = $.cookie("olayShoppingCart");
       if (olayShoppingCart == null)  // if the shopping cart cookie does not exist
           $.cookie("olayShoppingCart", pid + "#1" + ";", { path: '/', expires: '14' });
       else if (!(olayShoppingCart.indexOf(pid + '#') > -1))  // if the product to add is not present in shopping cart cookie 
           $.cookie("olayShoppingCart", olayShoppingCart + pid + "#1" + ";", { path: '/', expires: '14' });
       else // if the product to add is present in the Shopping cart cookie
       {
           ShoppingCart_Arr = new Array(olayShoppingCart.split(";").length);
           ShoppingCart_Arr = olayShoppingCart.split(";");
           var UpdatedShoppingCart = "";
           var ProductId, Quantity;
           for (cnt = 0; cnt < ShoppingCart_Arr.length; cnt++) {
               if (ShoppingCart_Arr[cnt].indexOf('#') > 0) {
                   ProductId = (ShoppingCart_Arr[cnt].split("#"))[0];
                   if (ProductId == pid) {
                       Quantity = (ShoppingCart_Arr[cnt].split("#"))[1];
                       Quantity = parseInt(Quantity) + 1;
                       ShoppingCart_Arr[cnt] = ProductId + "#" + Quantity;
                   }
                   UpdatedShoppingCart = UpdatedShoppingCart + ShoppingCart_Arr[cnt] + ";";
               }
           }
           $.cookie("olayShoppingCart", UpdatedShoppingCart, { path: '/', expires: '14' });

       }
       return false;
   }

   function appendMultipleProductsToShoopingCart(pids) {
       // Pass comma seperated Product UPC codes.
       Product_Arr = new Array(pids.split(";").length);
       Product_Arr = pids.split(";");
       for (cntIndex = 0; cntIndex < Product_Arr.length; cntIndex++) {
           if (Product_Arr[cntIndex].length > 0) {
               appendToShoopingCart(Product_Arr[cntIndex]);
           }
       }
   }

   function RemoveShoppingCartItem(pid) {
       if ($.cookie('olayShoppingCart') != null) {
           var olayShoppingCart = $.cookie('olayShoppingCart');
           if (olayShoppingCart.indexOf(pid + '#') > -1) {
               ShoppingCart_Arr = new Array(olayShoppingCart.split(";").length);
               ShoppingCart_Arr = olayShoppingCart.split(";");
               var UpdatedShoppingCart = "";
               var ProductId, Quantity;
               for (cnt = 0; cnt < ShoppingCart_Arr.length; cnt++) {
                   if (ShoppingCart_Arr[cnt].indexOf('#') > 0) {
                       ProductId = (ShoppingCart_Arr[cnt].split("#"))[0];
                       if (ProductId != pid) {
                           UpdatedShoppingCart = UpdatedShoppingCart + ShoppingCart_Arr[cnt] + ";";
                       }
                   }
               }
               $.cookie("olayShoppingCart", UpdatedShoppingCart, { path: '/', expires: '14' });
           }
       }
   }

   function SetShoppingCartProductQuantity(pid, qty) {
       //alert(pid + " in fun " + qty);
       if (qty.indexOf('-') > -1)
           return false; //alert("-"); //
       else if (qty.indexOf('.') > -1)
           return false; //alert("."); //
       else if (qty.indexOf(',') > -1)
           return false; //alert(","); //
       else if (isNaN(qty))
           return false; // alert("NAN"); //

       if ($.cookie('olayShoppingCart') != null) {
           var olayShoppingCart = $.cookie('olayShoppingCart');
           if (olayShoppingCart.indexOf(pid + '#') > -1) {
               ShoppingCart_Arr = new Array(olayShoppingCart.split(";").length);
               ShoppingCart_Arr = olayShoppingCart.split(";");
               var UpdatedShoppingCart = "";
               var ProductId, Quantity;
               for (cnt = 0; cnt < ShoppingCart_Arr.length; cnt++) {
                   if (ShoppingCart_Arr[cnt].indexOf('#') > 0) {
                       ProductId = (ShoppingCart_Arr[cnt].split("#"))[0];
                       if (ProductId == pid) {
                           if (qty > 0)
                               ShoppingCart_Arr[cnt] = ProductId + "#" + qty;
                           else
                               ShoppingCart_Arr[cnt] = "";
                       }
                       if (ShoppingCart_Arr[cnt] != "")
                           UpdatedShoppingCart = UpdatedShoppingCart + ShoppingCart_Arr[cnt] + ";";
                   }
               }
               $.cookie("olayShoppingCart", UpdatedShoppingCart, { path: '/', expires: '14' });
               UpdateShoppingCartSummary();
               UpdateShoppingCartSummaryCount();
           }
       }
   }
   /*    Added By: Manish Chunawala    ShoopingCart Script End    */

   /* Added By: Manish Chunawala Add to cart Popup Script Start */
   $(document).ready(function () {
       pageH = $(document).height();
       pageW = $(document).width();
       $("a.show-panel").click(function (e) {
           $(".lightbox, .lightbox-panel-addtocart").fadeIn(300);
           $('a.retailer').attr('href', this.href);

           e.preventDefault();
           $('.lightbox').height(pageH);
           $('.lightbox').width(pageW);
           $('.lightbox').fadeTo(0, 0.5);
       })

       $("a.close-panel").click(function () {
           $(".lightbox, .lightbox-panel-addtocart").fadeOut(300);
       })
   })


   /* Added By: Manish Chunawala Add to cart Popup Script End */
   function addpopupproducttoCart(pid, lang) { // IN USE : used from the Grid and list listing pages
       appendToShoopingCart(pid);
       UpdateShoppingCartSummaryCount();
       var addtocartpageurl = '/addtocart.aspx?pid={0}&lang=' + lang;
       Displayoverlay(addtocartpageurl.replace("{0}", pid), "true");
   }
   function addpopupproducttoCartfromWishlist(pid, lang) {
       appendToShoopingCart(pid);
       UpdateShoppingCartSummaryCount();
       RemoveWishListItem(pid);
       UpdateWishListSummaryCount();
       var addtocartpageurl = '/addtocart.aspx?pid={0}&lang=' + lang;
       Displayoverlay(addtocartpageurl.replace("{0}", pid), "false");
   }
   /*
   function addpopupproducttoWishList(pid) {
   appendToWishList(pid);
   var addtowishlistpageurl = '/pages/addtowishlist.aspx?pid={0}';
   document.getElementById('PopupAddtocart').src = addtowishlistpageurl.replace("{0}", pid);
   }*/
   function addwishlistproductsToShopoingCart(pids, url, ExpireCookie) {
       appendMultipleProductsToShoopingCart(pids);
       //UpdateShoppingCartSummaryCount();
       window.parent.location.href = url;
       //var olayWishList = $.cookie("olayWishList");
       if (ExpireCookie.length > 0) {
           $.cookie('olayWishList', '', { expires: 14, path: '/' });
       }

   }

   /* Added By: Manish Chunawala googlemap Popup Script Start */
   function openMap(GoogleMapPageUrl) {
       Displayoverlay(GoogleMapPageUrl, "false");
   }

   /* Added By: Manish Chunawala googlemap Popup Script End */

   /* Added by: Hiren for dynamic overlay for shoppingcart START */
   function calcHeight() {
       var d = "10";
       var iframe = document.getElementById('PopupAddtocart');
       var the_height;
       if (typeof (iframe) != 'undefined' && iframe != null) {
           if (iframe.contentWindow.document.readyState == 'complete') {
               if (iframe.contentWindow.document.body.offsetHeight) {
                   the_height = iframe.contentWindow.document.body.offsetHeight;
               }
               else (iframe.contentWindow.document.body.scrollHeight)
               {
                   the_height = iframe.contentWindow.document.body.scrollHeight;
               }
               var TotalHeight = Number(the_height) + Number(d);
               if (TotalHeight < 20)
                   TotalHeight = 400;

               iframe.style.height = String(TotalHeight) + "px";
           }
           else {
               setTimeout("calcHeight()", 50);
           }
       }
   }

   function calcHeightFromPopup() {
       var d = "10";
       var iframe = window.parent.document.getElementById('PopupAddtocart');
       var the_height; alert(iframe);
       if (typeof (iframe) != 'undefined' && iframe != null) {
           if (iframe.contentWindow.document.readyState == 'complete') {
               if (iframe.contentWindow.document.body.offsetHeight) {
                   the_height = iframe.contentWindow.document.body.offsetHeight;
               }
               else (iframe.contentWindow.document.body.scrollHeight)
               {
                   the_height = iframe.contentWindow.document.body.scrollHeight;
               }
               var TotalHeight = Number(the_height) + Number(d);
               if (TotalHeight < 20)
                   TotalHeight = 400;
               window.parent.document.getElementById('lightbox-panel-addtocart').style.height = String(TotalHeight) + "px";
           }
           else {
               setTimeout("calcHeightFromPopup()", 50);
           }
       }
   }

   function closeoverlay(reload) {
       var iframe = document.getElementById('PopupAddtocart');
       if (reload == 'true') {
           window.parent.location.reload();
       }
       else {
           iframe.src = '';
           $(".lightbox, .lightbox-panel-addtocart").fadeOut(300);
       }

       $("#lightbox-panel").mCustomScrollbar("vertical", 400, "easeOutCirc", 1.05, "auto", "yes", "yes", 10);
   }


   function UpdateShoppingCartSummary() {
       //  IF THIS FUNCTION IS CALLED FROM THE OVERLAY
       //  {}
       //  ELSE (i.e. if this function is called from the Shopping Cart Page
       //  {}
       if (window.parent.document.getElementById('divShoppingCartSummary') != null) {
           if (document.getElementById("diviframeShoppingCartSummary") != null)
               window.parent.document.getElementById('divShoppingCartSummary').innerHTML = document.getElementById("diviframeShoppingCartSummary").innerHTML;
       }
       else {
           if (document.getElementById("diviframeShoppingCartSummary") != null)
               window.document.getElementById('divShoppingCartSummary').innerHTML = document.getElementById("diviframeShoppingCartSummary").innerHTML;
       }

       if (window.parent.document.getElementById('shortcut_shopping_cart') != null) {
           if (document.getElementById("diviframeShoppingCartSummaryCount") != null)
               window.parent.document.getElementById('shortcut_shopping_cart').innerHTML = document.getElementById("diviframeShoppingCartSummaryCount").innerHTML;
       }
       else {
           if (document.getElementById("diviframeShoppingCartSummaryCount") != null)
               window.document.getElementById('shortcut_shopping_cart').innerHTML = document.getElementById("diviframeShoppingCartSummaryCount").innerHTML;
       }

       if (window.parent.document.getElementById('spanShoppingCartSummaryCountTotal') != null) {
           if (document.getElementById("diviframeShoppingCartSummaryCountTotal") != null)
               window.parent.document.getElementById('spanShoppingCartSummaryCountTotal').innerHTML = document.getElementById("diviframeShoppingCartSummaryCountTotal").innerHTML;
       }
       else {
           if (document.getElementById("diviframeShoppingCartSummaryCountTotal") != null)
               window.document.getElementById('spanShoppingCartSummaryCountTotal').innerHTML = document.getElementById("diviframeShoppingCartSummaryCountTotal").innerHTML;
       }
   }

   function UpdateWishListSummaryCount() {
       var count = 0;
       if ($.cookie('olayWishList') != null && $('#header_wish_list' != null)) {
           var cookieValue = $.cookie('olayWishList');
           var pieces; // = qListString.split(';');
           if (cookieValue.indexOf(';') > -1) {
               pieces = cookieValue.split(';');
               count = pieces.length - 1;
           }
       }
       if (count >= 0) {
           // append count
           var opening = ' (';
           var closing = ')';
           var strsc = $('#shortcut_wish_list').text();
           if (strsc.indexOf('(') > 0) {
               if (count == 0) { opening = ''; closing = ''; count = ''; strsc = strsc.substring(0, strsc.indexOf('(')); }
               else {
                   strsc = strsc.substring(0, strsc.indexOf('(') + 1);
               }
           }
           else {
               if (count == 0)
               { opening = ''; closing = ''; count = ''; }
               strsc = strsc + opening;
           }
           $('#shortcut_wish_list').empty().append(strsc + count + closing);
           $('#header_wish_list').removeAttr('style');
       }
   }

   function UpdateShoppingCartSummaryCount() {
       var count = 0;
       var quantitycnt = 0;
       if ($.cookie('olayShoppingCart') != null && $('#header_shopping_cart' != null)) {
           var cookieValue = $.cookie('olayShoppingCart');
           var pieces; // = qListString.split(';');
           if (cookieValue.indexOf(';') > -1) {
               pieces = cookieValue.split(';');
               count = pieces.length - 1;
               for (i = 0; i < count; i++) {
                   var cookieval = pieces[i];
                   cookieval = cookieval.substring(pieces[i].indexOf('#') + 1, pieces[i].length)
                   quantitycnt = parseInt(quantitycnt, 10) + parseInt(cookieval, 10);
               }
           }
       }
       if (count > 0) {

           var strsc = $('#shortcut_shopping_cart').text();
           if (strsc.indexOf('(') > 0) {
               strsc = strsc.substring(0, strsc.indexOf('(') + 1);
           }
           else {
               strsc = strsc + ' (';
           }
           $('#shortcut_shopping_cart').empty().append(strsc + quantitycnt + ')');
           $('#header_shopping_cart').removeAttr('style');
       }
   }

   function Displayoverlay(pageurl, frompopup) {
       var objdiv;
       if (frompopup == "false")
           objdiv = document.getElementById("lightbox-panel-addtocart");
       else
           objdiv = window.parent.document.getElementById("lightbox-panel-addtocart");

       var iframewidth = "583";
       var iframeheight = "500";
       /**/var regExp = /showgooglemap.aspx/g;
       if (regExp.test(pageurl)) {
           iframewidth = "536";
           iframeheight = "470";
       }
       objdiv.innerHTML = "<iFrame frameBorder='0' src='" + pageurl + "' onload='calcHeight()' id='PopupAddtocart'  scrolling='no' style='width:" + iframewidth + "px;height:" + iframeheight + "px;background:none !important;' allowtransparency='true' frameborder='0' ></iFrame><div class='clear'></div>";
   }

   function GoToProductDetailPageIframe(pageurl) {
       window.parent.location.href = pageurl;
   }
   /* ECOM & REGIMEN SCRIPT END */
