/*
	Global Utilites
*/


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;
		});
});


