/*
	Global Utilites
*/




/**
 *
 * Validation Application
 *
 */

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;
	}
	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) {}
			
		          
			})
		
		
		
		
		
		}
      
    })
}

$(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();
 
 
});


$.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');
		$('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();
	$('.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=\"/Pages/LearnAboutSkin.aspx\">learn about skin care</a>" ); }
		else if ( $('#olayArticleLayoutCategoryContent').html().match(/inside\s+olay/i)  ) { $('#olayArticleCategoryLinkContent').html( "<a href=\"/Pages/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 ? '&' : '?';
	$('#olayArticleEmailer a').attr('href', str + joint + 'email=True');
});

$(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 ? '&' : '?';
	$('#olayProductDetailEmailer a').attr('href', str + joint + 'email=True');
});



/* 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();
	});
});


/*
	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" ) {
			$('#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: '/PublishingImages/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;
}



