
Event.observe ( window, 'load', function() {
	// ***** jump to a spot on a page *****
	// if a query string contains a parameter named jump and an element (of any sort) contains an id
	// defined by the jump parameter this function will jump to that element on the page
	function jumpcheck(){
		var checkfor = parent.document.URL.toQueryParams ();
		if(checkfor.jump){
			if(checkfor.jump == 'skinconsultation'){launchSkinConsultation();}
			else if(checkfor.jump == 'foundationfinder'){launchFoundationFinder();}
			else{
				onElement(checkfor.jump, function(){
					var element = $(checkfor.jump);
			//		alert(element.cumulativeOffset());
			//		alert('found ' + checkfor.jump);
					Effect.ScrollTo(checkfor.jump);
					}, 2, 60)
				}
			}
		};
	jumpcheck.defer();
	});

document.observe('user:loaded', function () {

	var reference = $('accountbar') ? $('accountbar').down('ul').down('li.last') : null;
	if (reference) {
		// clear all siblings and rebuild top-right nav
		var sibs = reference.siblings();
		$A(sibs).each(function(sib){
			sib.remove();
		});
		
		new ViewBagButton($('accountbar').down('li.last'));
		
		if (user.recognized_user && user.registered_user){
			reference.insert({before: '<li><a href="/templates/user/account/index.tmpl" style="padding-right: 0px">Welcome Back #{first_name}</a><a id="welcome-link" style="padding-left: 3px" href="/signout/index.tmpl">(not #{first_name}?)</a></li>'.interpolate(user)});
			reference.insert({before: '<li><a href="/templates/user/account/index.tmpl">My Account</a></li>'});
			reference.insert({before: '<li><a id="signout-link" href="/signout/index.tmpl">Sign Out</a></li>'});
		} else {
			reference.insert({before: '<li><a id="signin-link" href="#">Sign In</a></li>'});		
		}
		if ( !user.email_optin) {
			reference.insert({before: '<li><a id="email-link" href="#">Email Sign Up</a></li>'});
		}

		reference.insert({before: '<li><a id="help-link" href="#">Need Help?</a></li>'});

		// WDR: PLEASE NOTE: Jennie Bell, Jess Madrid, and Anika have all asked
		// me to remove the "alert" warning and the "there was an error" message.
		// If anyone asks you to put it back, then please let's all talk and figure out
		// what we are supposed to do.  This seems to keep going back and forth...!!
		/*
		new ModRPCForm('top-nav-signin',{
			msgLoading: 'Logging in...',
			msgComplete: 'Reloading...',
			msgFailure: '', // (see above) 'There was an error.',
			onSuccess: function(r){
				// (see above) if (r.WARNINGS.length) alert(r.WARNINGS.join('\n\n'));
				user.initialize();
				cart.initialize();
				dashboard.handleSignin();
				$('signin-box').hide();
            	$('signin-box').fire('signin:submitted');
			}
		});
		*/

		new JsonRPCForm('top-nav-optin',{
			method: 'email.signup',
			msgLoading: 'Submitting...',
			msgComplete: 'Reloading...',
			msgFailure: '',			
			onSuccess: function(data){
				var frm = $('top-nav-optin').serialize(true);
				Object.extend(frm, data.result);
				user.initialize();
				cart.initialize();
				//$('email-box').hide();
				$('email-box').fire('email_signup:submitted', frm);
				location.href = '/cms/customer_service/signup_thanks.tmpl';
			}
		});
		
		// Do we have a dashboard on this page?
		/*
		$$('.dashboard-signin-form').each( function(dform) {
			new ModRPCForm(dform,{
				msgLoading: 'Logging in...',
				msgComplete: 'Reloading...',
				msgFailure: '', //'There was an error.',
				onSuccess: function(){
					//location.reload(true)
					user.initialize();
					cart.initialize();
					dashboard.handleSignin(true);
					//$('signin-box').hide();
				}
			});
		});
		*/
		
	    if (typeof FloatingPaneLink !== 'undefined') {
	        var panelink_args = {active_state: 'active'};
	        var nav_panes = [
	            new FloatingPaneLink(["email-link"], "email-box", panelink_args),
	            new FloatingPaneLink(["signin-link"], "signin-box", panelink_args),
				new FloatingPaneLink(["cart-link"], "cart-box", panelink_args),
				new FloatingPaneLink(["help-link"], "help-box", panelink_args)
	        ];
	    }
	    
        var emailLink = $("email-link");
        if (emailLink) {
            emailLink.observe('mouseover', function(evt) {
              emailLink.fire('email_signup:opened');
            });
        }

       var signinLink = $("signin-link");
       if (signinLink) {
         signinLink.observe('mouseover', function(evt) {
           signinLink.fire('signin:opened');
         });
       }
		
	}
});


document.observe('cart:loaded', function () {
	cart.updateGlobalQty();
});

document.observe('dom:loaded', function () {

	dashboard = new UserDashboard();

	user = new User();
	cart = new Cart();	
	
	if (window.attachEvent && navigator.appVersion.substr(22,3)=="6.0")
		sfHover(); // For IE6
	
	typeaheadsearch = new TypeAheadSearch ({
		inputElementId: 'search',
		outputContainerId: 'global-typeahead-search-box',
		positionTop: 4,
		positionLeft: -126,
		activeLink: function() { $('searchbar').addClassName('searchbar-active'); },
		deactiveLink: function() { $('searchbar').removeClassName('searchbar-active'); }
	});
		
	if($('scroll-container')) {
		new Control.Scroller( 'scrollcontent', 'handle', 'track', {
			up: "button-up",
			down: "button-down",
			onScroll: function(value, scroller) {}
		});
	};
	
	loadLiveChatButtons();

	// My Skin Consultation 
	$$('.skinConsultationButton').each(function(button) {
		button.observe('click', function(event){
			var element = Event.element(event);
			// KFR: CoreMetrics taggng. This will send the element along with the name of the anchor
			// to checkNavLink() to manually throw a link promotions tag
			checkNavLink(element.parentNode,element.parentNode.name);
			launchSkinConsultation();
		});
	});// end of My Skin Consultation
	
	// Foundation Finder 
	$$('.foundationFinderButton').each(function(button) {
		button.observe('click', function(event){
			var element = Event.element(event);
			// KFR: CoreMetrics taggng. This will send the element along with a flag to tell
			// checkNavLink to manually throw a link promotions tag
			checkNavLink(element.parentNode,element.parentNode.name);
			launchFoundationFinder();
		});
	}); // end of Foundation Finder
});

launchFoundationFinder = function() {
	templatefactory.get('foundation_finder_overlay').evaluateCallback({
		callback: function (html){
			overlay.launch({
				content  : html,
				cssStyle : {width:'798px', height:'444px'}
			});
			$('lighterwindow_close_link').observe('click',function(){
				overlay.hide();
			});
		}
	});
};

launchSkinConsultation = function() {
		// bug 28585
		if ( $('sppVideo') ) {
			$('sppVideo') .javascriptToFlash('pauseVideo');
		}
		templatefactory.get('skin_consultation_overlay').evaluateCallback({
			callback: function (html){
				overlay.launch({
					content  : html,
					cssStyle : {width:'798px', height:'448px'}
				});
				$('lighterwindow_close_link').observe('click',function(){
					overlay.hide();
					// bug 28585
					if ( $('sppVideo') ) {
						$('sppVideo') .javascriptToFlash('resumeVideo');
					}							
				});
			}
		});
	};

/////////////////////////////////////////////////////////////////////
// Create a lighterwindow popup button out of anything
// with the class "lwPopupButton" applied.
// Ex:
//	<a href="/this/is/a/path.tmpl" class="lwPopupButton"
//		popupHeight="500" popupWidth="300" printButton="true"
//		>this is a link</a>
function createLwPopupLinks() {
	$$('.lwPopupButton').each ( function(el) {
		if ( !el.lwPopup ) {
			var h = el.readAttribute('popupHeight') || 615;
			var w = el.readAttribute('popupWidth') || 800;
			var href = el.readAttribute('href');
			var prn = el.readAttribute('printButton') || false;
			
			el.lwPopup = new PopupButton ( el, {
								url: href,
								divHeight: h,
								divWidth: w,
								printButton: prn
			});
		}
	});
}

// Watch for dom-load and window-load to create our popup links.
document.observe("dom:loaded", function() {  createLwPopupLinks(); });
Event.observe ( window, 'load', function() { createLwPopupLinks(); });
/////////////////////////////////////////////////////////////////////


// For IE 6
sfHover = function() {
	try
	{
		var sfEls = document.getElementById("navigation").getElementsByTagName("LI");
		for (var i=0; i<sfEls.length; i++) {
			sfEls[i].onmouseover=function() {
				this.className+=" sfhover";
			}
			sfEls[i].onmouseout=function() {
			    var self = this;
			    var hideSubmenu = function() {
    				self.className=self.className.replace(new RegExp(" sfhover\\b"), "");
			    }
			    var t=setTimeout(hideSubmenu,100);
//				this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
			}
		}
	}
	catch(err)
	{
		console.log('err on sfHover')
	}
};

