// ===========================================================================
// ### Style Carousel ###
// Assumes the carousel will be a <ul> with a fixed width and height, and 
// overflow: hidden.  Adjusts scroll position by morphing the left position.
// Automatically creates left/right links and attaches event listeners to them.

var StyleCarousel = Class.create({
  initialize: function(element){
    this.element = element;
		this.currentPosition = 0;
		this.leftPosition = 0;
    this.perPage = 6;
    this.thumbnails = element.select("li.StyleThumbnail");
    this.thumbnails.each(function(child){
      new StyleThumbnail(child);
    });
		this.thumbnailWidth = 127;
    this.createCarouselControls();
    this.scrollToCurrentStyle();
  },
  
  createCarouselControls: function(){
    var container = this.element.up().up();
		if(!container.down('a.RightArrow')){
			container.insert({top: '<div class="StyleCarouselControl Right"><span id="RightArrow" class="RightArrow Link" title="View next set of styles"></span></div>'});
      container.down('span.RightArrow').observe('click', this.scrollRight.bindAsEventListener(this));
			container.down('span.RightArrow').observe('mouseover', this.addHoverClass);
	    container.down('span.RightArrow').observe('mouseout', this.removeHoverClass);
    }
    if(!container.down('a.LeftArrow'))
    {
			container.insert({top: '<div class="StyleCarouselControl Left"><span id="LeftArrow" class="LeftArrow Link" title="View previous set of styles"></span></div>'});
      container.down('span.LeftArrow').observe('click', this.scrollLeft.bindAsEventListener(this));
			container.down('span.LeftArrow').observe('mouseover', this.addHoverClass);
	    container.down('span.LeftArrow').observe('mouseout', this.removeHoverClass);
    }
		
		$("LeftArrow").addClassName("Disabled");
  },
  
  scrollLeft: function(e){
		if(this.currentPosition > 0 && this.leftPosition < 0){
			var newPosition = this.currentPosition - this.perPage;
			
			if(newPosition > 0){
				this.scrollToStyle(newPosition,1);
			}else{
				this.scrollToStyle(0,1);
				newPosition = 0;
			}
			this.currentPosition = newPosition;
		}
		
		Event.element(e).blur();
    e.stop();
  },
  
  scrollRight: function(e){
		if(this.currentPosition < this.thumbnails.size()){
			var newPosition = this.currentPosition + this.perPage;
			var maxPosition = this.thumbnails.size()-this.perPage;
		
			if(newPosition > maxPosition){
				this.scrollToStyle(maxPosition,1);
				newPosition = maxPosition;
			}else{
				this.scrollToStyle(newPosition,1);
			}
			this.currentPosition = newPosition;
		}
		
		Event.element(e).blur();
    e.stop();
  },

	addHoverClass: function(e){
    this.addClassName("ArrowHover");  
  },
  
  removeHoverClass: function(e){
    this.removeClassName("ArrowHover");
  },
  
  scrollToCurrentStyle: function(){
    var currentThumb = this.element.down("li.selected");
		var currentIndex = this.thumbnails.indexOf(currentThumb);
		var newPosition = 0;
	
    if(currentThumb){
		  var thumbPage = (currentIndex / this.perPage).floor();
			var partialPage = currentIndex % this.perPage;
			if(partialPage > 0){
				thumbPage += 1;
			}
			
			if(currentIndex > this.perPage){
				newPosition = (thumbPage-1) * this.perPage + 1;
			}
			if(currentIndex == this.perPage){
				newPosition = thumbPage * this.perPage;
			}
			
			this.scrollToStyle(newPosition,0);
		  this.currentPosition = newPosition;
    }
  },

  scrollToStyle: function(position, speed){
		var maxPosition = this.thumbnails.size()-this.perPage;
		
		if(position > maxPosition){
			this.leftPosition = -this.thumbnailWidth * maxPosition;
		}else{
			this.leftPosition = -this.thumbnailWidth * position;
		}
		
		//enable_disable arrow navigation based on position
		if(this.leftPosition == 0){
			$("LeftArrow").addClassName("Disabled");
		}else{
			$("LeftArrow").removeClassName("Disabled");
		}
		if(position >= maxPosition){
			$("RightArrow").addClassName("Disabled");
		}else{
			$("RightArrow").removeClassName("Disabled");
		}
		
		
	
		new Effect.Morph(this.element,{
			style:'left: '+ this.leftPosition + 'px;',
			duration:speed
		});
  }
  
});

var StyleThumbnail = Class.create({
  initialize: function(element){
      if (element.down()) {
        element.down().observe('mouseover', this.addHoverClass);
        element.down().observe('mouseout', this.removeHoverClass);
    }
  },
  
  addHoverClass: function(e){
    this.addClassName("Hover");  
  },
  
  removeHoverClass: function(e){
    this.removeClassName("Hover");  
  }
});

document.observe("dom:loaded", function(){
  var carousel = $('StyleCarousel');
  if(carousel)
    new StyleCarousel(carousel);
});

// ---------------------------------------------------------------------------
// Site Search / Salon Locator form toggling

var SiteSalonSearchToggle = Class.create({
	initialize : function(toggler){
		this.node = $(toggler);
		if (!this.node) { return; }
		this.inputs = this.node.select('INPUT');
		this.salon_form = $('salon_finder_search_form');
		this.search_form = $('redken_search_form');
		if (this.inputs.length < 2 || !this.salon_form || !this.search_form)
			{ return; }
		this.inputs.each(function(radio){
			radio.observe('click', this.toggleForm.bindAsEventListener(this));
		}, this);
	},
	toggleForm : function(e){
		var id = e.element().id;
		if (id.match(/salon/)) {
			this.salon_form.setStyle({ display : 'block' });
			this.search_form.setStyle({ display : 'none' });
		} else {
			this.search_form.setStyle({ display : 'block' });
			this.salon_form.setStyle({ display : 'none' });
		}
	}
});

document.observe("dom:loaded", function(){
	new SiteSalonSearchToggle('search-toggler');
});

// ---------------------------------------------------------------------------
// Your Hair Profile

var YourHairProfile = Class.create({
	
	styling_pairs : {
		more_control : "real-control-recovery",
		strength_repair : "strength-recovery",
		smooth_straight : "smooth-recovery",
		color_protection : "color-recovery",
		dandruff_control : "dandruff-defense",
		more_softness : "soft-recovery",
		lightening_highlights : "blonde-icing-highlights",
		darker : "shades-eq-glaze",
		lighter : "permanent-color",
		cover_gray : "single-process-color-service",
		subtle_change : "lowlights",
		more_shine : "seq-shine-service",
		corrective_color : "see-your-stylist",
		touch_up : "professional-haircolor",
		something_low_maintenance : "shimmer-one"
	},
	
	chemistry_pairs : {
		more_control : "real-control-recovery",
		strength_repair : "strength-recovery",
		smooth_straight : "smooth-recovery",
		color_protection : "color-recovery",
		dandruff_control : "dandruff-defense",
		more_softness : "soft-recovery"
	},
	
	haircolor_pairs : {
		lightening_highlights : "blonde-icing-highlights",
		darker : "shades-eq-glaze",
		lighter : "permanent-color",
		cover_gray : "single-process-color-service",
		subtle_change : "lowlights",
		more_shine : "seq-shine-service",
		corrective_color : "see-your-stylist",
		touch_up : "professional-haircolor",
		something_low_maintenance : "shimmer-one"
	},
	
	haircare_pairs : {
		more_volume : "body-full",
		more_control : "real-control",
		more_curls : "fresh-curls",
		less_dry : "clear-moisture",
		strength_repair : "extreme",
		smooth_straight : "smooth-down",
		color_protection : "color-extend",
		dandruff_control : "scalp-relief",
		sun_protection : "color-extend-sun",
		more_softness : "all-soft"
	},
	
	improvement_styling_pairs : {
		more_volume : "volume",
		more_curls : "curl-wave",
		less_dry : "shine", 
		smooth_straight : "straight-collection"
	},
	
	styling_product_pairs : {
		long_lasting_hold : "hairsprays",
		hot_heat_protection : "heat-styling",
		piecey_looks : "texture",
		more_shine : "shine"
	},
	
	initialize : function(element) {
		this.element = element;
		this.query_ids = window['ProductsIDs'];
		if (!this.query_ids)
			return;
			
		this.element.setStyle({ display : "block" });
		this.select_a_stylist = $("select-your-stylist");
		this.form_element = $("your_hair_profile_submission");
		this.haircare_input = $("haircare_input");
		this.styling_input = $("styling_input");
		this.services_input = $("services_input");
		this.stylist_input = $("stylist_input");
		this.stylist_nav = $("HairProfileNav");
		this.first_step = $("hair-type");
		this.second_step = $("hair-color-services");
		this.third_step = $("the-next-level");
		this.haircolor_input_wrapper = $("natural-haircolor-field");
		this.thickness_slider = $("ThicknessSlider");
		this.thickness_button = $("ThicknessButton");
		if (!this.form_element || !this.haircare_input || !this.styling_input || !this.services_input || !this.stylist_input || !this.stylist_nav || !this.haircolor_input_wrapper || !this.thickness_slider || !this.thickness_button)
			return;
		this.initializeStylistSelection();
		REDKEN.Features.sIFR.initialize();
		// Finished loading first step... continue loading the rest
		this.initializeFinalSteps();
		this.initializeHaircolorServices();
		this.initializeDesiredEnhancements();
	},
	
	initializeStylistSelection : function() {
		this.element.down("FIELDSET").addClassName("Active");
		var choose_expert = $("choose-an-expert-for-me");
		var stylists_table = $("stylists-table");
		var stylist_photos = $("stylist-select");
		if (!choose_expert || !stylists_table || !stylist_photos)
			return;
		var random_expert = Math.floor((Math.random() * 5) + 1);
		choose_expert.observe("click", this.selectStylist.bind(this, random_expert));
		var photos = stylist_photos.select("IMG");
		var buttons = stylists_table.select(".Button");
		for (var i=0,l=stylist_photos.childElements().length;i<l;i++) {
			photos[i].observe("click", this.selectStylist.bind(this, i+1));
			buttons[i].observe("click", this.selectStylist.bind(this, i+1));
			photos[i].observe("mouseover", this.stylistMouseOverHandler.bindAsEventListener(this, photos[i], buttons[i]));
			photos[i].observe("mouseout", this.stylistMouseOutHandler.bindAsEventListener(this, photos[i], buttons[i]));
			buttons[i].observe("mouseover", this.stylistMouseOverHandler.bindAsEventListener(this, photos[i], buttons[i]));
			buttons[i].observe("mouseout", this.stylistMouseOutHandler.bindAsEventListener(this, photos[i], buttons[i]));
		}
	},
	
	stylistMouseOverHandler : function(e, photo, button) {
		photo.addClassName("Hover");
		button.src = "/images/your_hair_profile/btn.get-started.hover.gif";
	},
	
	stylistMouseOutHandler : function(e, photo, button) {
		photo.removeClassName("Hover");
		button.src = "/images/your_hair_profile/btn.get-started.gif";
	},
	
	initializeFinalSteps : function() {
		this.proceed_to_step_2 = $("proceed-to-step-2");
		this.skip_to_step_3 = $("skip-to-step-3");
		this.proceed_to_step_3 = $("proceed-to-step-3");
		this.not_interested_in_services = $("hair_color_services_no");
		this.is_interested_in_services = $("hair_color_services_yes");
		this.not_interested_text = $("not-interested-in-services-p");
		this.get_results = $("get-customized-results");
		this.back_to_step_2 = $("back-to-step-2");
		this.back_to_stylist_selection = $("back-to-stylist-selection");
		this.back_to_step_1 = $("back-to-step-1");
		this.back_to_step_1.observe("click", this.backToStep1.bindAsEventListener(this));
		this.back_to_stylist_selection.observe("click", this.backToStylistSelection.bindAsEventListener(this));
		this.proceed_to_step_3.observe("click", this.skipToStep3ClickHandler.bindAsEventListener(this));
		this.not_interested_in_services.observe("click", this.updateHaircolorServicesInterest.bind(this));
		this.is_interested_in_services.observe("click", this.updateHaircolorServicesInterest.bind(this));
		this.is_interested_in_services.checked = true;
		this.proceed_to_step_2.observe("click", this.step2ClickHandler.bindAsEventListener(this));
		this.skip_to_step_3.observe("click", this.skipToStep3ClickHandler.bindAsEventListener(this));
		this.get_results.observe("click", this.submitYourHairProfile.bindAsEventListener(this));
		this.back_to_step_2.observe("click", this.step2ClickHandler.bindAsEventListener(this));
		this.looking_for_stylist_product = false;
	},
	
	initializeThicknessSlider : function() {
		// global!
		slider = new Control.Slider("ThicknessButton", "ThicknessSlider", {
			minimum : 1,
			maximum : 385,
			range : $R(1,375),
			snap_values : [1,96,192,288,375],
			snap_ranges : [
				$R(1,47),
				$R(48,143),
				$R(144,239),
				$R(240,335),
				$R(336,375)
			],
			onChange : function(value){
				var update = false;
				var v = Math.floor(value);
				var opts = slider.options;
				var r = opts.snap_ranges;
				switch (true) {
					case r[0].include(v) : update = opts.snap_values[0]; break;
					case r[1].include(v) : update = opts.snap_values[1]; break;
					case r[2].include(v) : update = opts.snap_values[2]; break;
					case r[3].include(v) : update = opts.snap_values[3]; break;
					case r[4].include(v) : update = opts.snap_values[4]; break;
				}
				if (update)
					$("ThicknessButton").style.left = update + "px";
			}
		});
	},
	
	initializeHaircolorServices : function() {
		this.haircolor_services = this.second_step.down("ul");
		if (this.haircolor_services) {
			this.haircolor_service_inputs = this.haircolor_services.select("input");
			this.haircolor_service_inputs.invoke("enable");
			this.haircolor_service_inputs.each(function(service){
				service.observe("click", this.twoAllowedCheckboxHandler.bindAsEventListener(this, service, this.haircolor_service_inputs));
			}, this);
		}
	},
	
	initializeDesiredEnhancements : function() {
		this.desired_enhancements = $("two-col-improvements");
		if (this.desired_enhancements) {
			this.styling_products = $("look-for-in-styling-product");
			this.desired_enhancements.select("input").each(function(input){
				input.observe("click", this.toggleHaircolorStylingProducts.bindAsEventListener(this, input));
			}, this);
		}
	},
		
	selectStylist : function(stylist) {
		this.stylist_input.value = this.stylist = stylist;
		this.stylist_nav.down(0).addClassName("Active");
		this.element.select(".LeftColumn").each(function(box){
			box.childElements()[this.stylist - 1].addClassName("ActiveStylist");
		}, this);
		this.toggleCurrentStep(this.first_step);
		this.initializeThicknessSlider();
		if (Prototype.Browser.IE)
			this.thickness_button.setStyle({ zoom : "100%" });
	},
		
	twoAllowedCheckboxHandler : function(e, service, inputs) {
		if (!this.checked_services)
			this.checked_services = [];
		if (service.checked) {
			this.checked_services.push(service);
		} else {
			this.checked_services = this.checked_services.without(service);
		}
		if (this.checked_services.length > 2) {
			this.checked_services[0].checked = false;
			this.checked_services = this.checked_services.without(this.checked_services[0]);
		}
	},
	
	toggleHaircolorStylingProducts : function(e, element) {
		if (element.hasClassName("StylingProduct")) {
			this.looking_for_stylist_product = true;
			this.styling_products.removeClassName("Invisible");
		} else {
			this.looking_for_stylist_product = false;
			this.styling_products.addClassName("Invisible");
		}
	},
	
	updateHaircolorServicesInterest : function(e) {
		var element = e.element();
		if (element.tagName.toLowerCase() == "label")
			element = element.previous();
		if (element.id.match(/no/)) {
			this.proceed_to_step_2.setStyle({ display : "none" });
			this.skip_to_step_3.setStyle({ display : "block" });
			this.not_interested_text.setStyle({ display : "block" });
		} else {
			this.proceed_to_step_2.setStyle({ display : "block" });
			this.skip_to_step_3.setStyle({ display : "none" });
			this.not_interested_text.setStyle({ display : "none" });
		}
	},
	
	backToStylistSelection : function(e) {
		this.stylist_nav.down(".Active").removeClassName("Active");
		this.stylist_nav.down().addClassName("Active");
		$$(".ActiveStylist").invoke("removeClassName", "ActiveStylist");
		this.toggleCurrentStep(this.select_a_stylist);
	},
	
	backToStep1 : function(e) {
		this.stylist_nav.down(".Active").removeClassName("Active").addClassName("Finished");
		this.stylist_nav.down(1).addClassName("Active");
		this.toggleCurrentStep(this.first_step);
	},
	
	step2ClickHandler : function(e) {
		this.stylist_nav.down(".Active").removeClassName("Active").addClassName("Finished");
		this.stylist_nav.down(1).addClassName("Active");
		this.toggleCurrentStep(this.second_step);
	},
	
	skipToStep3ClickHandler : function(e) {
		this.stylist_nav.down(".Active").removeClassName("Active").addClassName("Finished");
		this.stylist_nav.down(1).addClassName("Finished");
		this.stylist_nav.down(2).addClassName("Active");
		this.toggleCurrentStep(this.third_step);
	},
	
	submitYourHairProfile : function(e) {
		// Set all to false initially
		this.recommended_chemistry_service = false;
		this.recommended_haircare_product = false;
		this.recommended_haircolor_product1 = false;
		this.recommended_haircolor_product2 = false;
		this.recommended_chemistry_product = false;
		this.recommended_styling_product = false;
		
		// If blonde, recommend blonde glam
		if ($("haircolor_blonde").checked)
			this.recommended_haircare_product = "blonde-glam";
		
		// Chemistry System Service
		for (var i in this.chemistry_pairs) {
			if (!this.recommended_chemistry_service) {
				var input = $("like_to_improve_"+i);
				if (input.checked)
					this.recommended_chemistry_service = this.styling_pairs[i];
			}
		}
		
		// Haircolor Service 1
		for (var i in this.haircolor_pairs) {
			if (!this.recommended_haircolor_product1) {
				var input = $("haircolor_service_interests_"+i);
				if (input.checked)
					this.recommended_haircolor_product1 = this.styling_pairs[i];
			}
		}
		
		// Haircolor Service 2 (up to two...)
		for (var i in this.haircolor_pairs) {
			if (!this.recommended_haircolor_product2) {
				var input = $("haircolor_service_interests_"+i);
				if (input.checked && this.recommended_haircolor_product1 && this.styling_pairs[i] != this.recommended_haircolor_product1)
					this.recommended_haircolor_product2 = this.styling_pairs[i];
			}
		}
		
		// Chemistry Service
		for (var i in this.chemistry_pairs) {
			if (!this.recommended_chemistry_service) {
				var input = $("like_to_improve_"+i);
				if (input.checked)
					this.recommended_chemistry_service = this.chemistry_pairs[i];
			}
		}
		
		// Haircare Product
		for (var i in this.haircare_pairs) {
			if (!this.recommended_haircare_product) {
				var input = $("like_to_improve_"+i);
				if (input.checked)
					this.recommended_haircare_product = this.haircare_pairs[i];
			}
		}
		
		// Styling Product
		for (var i in this.improvement_styling_pairs) {
			if (!this.recommended_styling_product) {
				var input = $("like_to_improve_"+i);
				if (input.checked)
					this.recommended_styling_product = this.improvement_styling_pairs[i];
			}
		}
				
		// Styling Product -- from the other input set
		if (this.looking_for_stylist_product && !this.recommended_styling_product) {
			for (var i in this.styling_product_pairs) {
				if (!this.recommended_styling_product) {
					var input = $("look_for_"+i);
					if (input.checked)
						this.recommended_styling_product = this.styling_product_pairs[i];
				}
			}
		}
		
		// Set the values of our form
		this.haircare_input.value = this.query_ids["haircare"][this.recommended_haircare_product];
		this.styling_input.value = this.query_ids["styling"][this.recommended_styling_product];
		this.services_input.value = [this.query_ids["service"][this.recommended_haircolor_product1],this.query_ids["service"][this.recommended_haircolor_product2],this.query_ids["service"][this.recommended_chemistry_service]].without(undefined).join(",");
		
		// and submit it
		this.form_element.submit();
	},
	
	toggleCurrentStep : function(new_active) {
		this.element.down(".ActiveStep").removeClassName("ActiveStep").addClassName("Invisible");
		new_active.removeClassName("Invisible").addClassName("ActiveStep");
		REDKEN.Features.sIFR.initialize();
	}
});

HairProfileResults = Class.create({
	initialize : function(element) {
		this.element = element;
		this.tips = this.element.select(".tip-link");
		this.element.select(".email-link").each(function(email){
			new EmailPageLink(email);
		});
		this.tips.each(function(tip){
			var tip_window = tip.up(".ContentListing").down(".Tip");
			if (!tip_window) return;
			tip.addClassName("Link").removeAttribute("href");
			tip.observe("click", this.tipClickHandler.bindAsEventListener(this, tip_window));
		}, this);
	},
	tipClickHandler : function(e, tip_window) {
		this.displayOverlay();
		this.positionTip(tip_window);
		tip_window.removeClassName("Invisible");
		REDKEN.Features.sIFR.initialize();
		this.tip_overlay.observe("click", this.removeTip.bindAsEventListener(this, tip_window));
		var close = tip_window.down(".Close");
		if (close)
			close.observe("click", this.removeTip.bindAsEventListener(this, tip_window));
	},
	positionTip : function(tip_window){
	  var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
	  tip_window.style.top = top + 'px';
	  tip_window.style.left = '20px';
	},
	displayOverlay : function(){
		if (!this.tip_overlay) {
			this.tip_overlay = new Element("div", { "id" : "tip-popup-overlay" });
			this.body_wrapper = $("BodyWrapper");
			if (!this.body_wrapper) return; 
			var dims = this.body_wrapper.getDimensions();
			this.body_wrapper.insert({ bottom : this.tip_overlay });
			this.tip_overlay.setStyle({ width : dims.width + "px", height : dims.height + "px" });
		}
	},
	removeTip : function(e, tip_window){
		tip_window.addClassName("Invisible");
		this.tip_overlay.setStyle({ display : "none" });
	}
});

document.observe("dom:loaded", function(){
	var yhp = $("your_hair_profile");
	if (yhp)
		new YourHairProfile(yhp);
	var results = $("hair-profile-results-wrapper");
	if (results)
		new HairProfileResults(results);
});
