
var REDKEN = new Site();


/* -- BEGIN: DHTMLMenu ---------------------------------------------------- */

var DHTMLMenu = Class.create(PageWidget, {
	initialize : function(menu_id, config) {
		this.node = $(menu_id);

		// bail out if the menu doesn't exist on this page
		if (!this.node || this.initialized) return;

		this.setOptions(config);

		this.submenus = { };

		// get all the top-level LIs in the menu and iterate over them, adding event handlers
		$(menu_id).immediateDescendants().each(function(item){
			item.observe("mouseover", this.mouseoverHandler.bindAsEventListener(this, item));
			item.observe("mouseout", this.mouseoutHandler.bindAsEventListener(this, item));

			this.submenus[item.id] = item.down().next();
		}.bind(this));

	},

	initialized : false,
	node : null,              // holds the DOM node of the menu
	menu_hide_timeout : null, // the JS timeout ID for hiding the menu
	menu_show_timeout : null, // the JS timeout ID for showing the menu
	last_menu_on : null,      // the DOM object of the waiting to close

	mouseoverHandler : function(e, item) {
		// stop the menu from closing/opening (this gets called a lot)
		clearTimeout(this.menu_hide_timeout);
		clearTimeout(this.menu_show_timeout);

		// if we're mousing over the menu for the first time, set a timeout so the menu doesn't show up accidentally.
		if (this.last_menu_on == null) {
			this.menu_show_timeout = setTimeout(this.showMenu.bind(this, item),	this.CONFIG["menu_show_time"]);

		// if there's already a menu on, then we know the user is expecting to see another one, so show it immediately.
		} else if (this.last_menu_on != item) {
			this.showMenu(item);
		}
	},

	mouseoutHandler : function(e, item) {
		// clear the existing show/hide timeouts (this gets called a lot)
		clearTimeout(this.menu_hide_timeout);
		clearTimeout(this.menu_show_timeout);

		// only "close" the menu in a little bit if we're over a menu with submenus, otherwise, close it right now
		if (this.submenus[item.id]) {
			this.menu_hide_timeout = setTimeout(this.hideMenu.bind(this, item),	this.CONFIG["menu_hide_time"]);

		} else {
			this.hideMenu(item);
		}
	},

	// shows the menu
	showMenu : function(item) {
		// hide the last menu shown
		if (this.last_menu_on != null) { this.hideMenu(this.last_menu_on); }

		// adding the "hover" class turns on the menu
		item.addClassName(this.CONFIG['hover_class']);

		// insert the IFRAME for IE
		if (Prototype.Browser.IE6) {
			// get at the submenu for dimension info
			var submenu = this.submenus[item.id];
			if (submenu) {
				var iframe = submenu.next();

				if (submenu && !iframe) {
					this.createIframe(item, {
						'left'   : submenu.offsetLeft + "px",
						'height' : submenu.offsetHeight + "px",
						'width'  : submenu.offsetWidth + "px"
					});
				}
			}
		}

		// store the last item on
		this.last_menu_on = item;

	}, // END: showMenu()

	// hide the menu
	hideMenu : function(item) {
		// nothing to hide
		if (item == null) return;

		// removing the "hover" class turns off the menu
		item.removeClassName(this.CONFIG['hover_class']);

		// remove the IFRAME for IE
		if (Prototype.Browser.IE6) {
			var submenu = this.submenus[item.id];
			if (submenu) {
				var iframe = submenu.next();
				if (submenu && iframe) {
					item.removeChild(iframe);
				}
			}
		}

		this.last_menu_on = null;
	}, // END: hideMenu()

	// makes an IFRAME the exact size of the menu so elements underneath it are covered
	// (IE-only)
	createIframe : function(node, style) {
		new Insertion.Bottom(node, (new Template('<iframe class="' + this.CONFIG['iframe_class'] + '" frameborder="0" scrolling="no" style="width: #{width}; height: #{height}; left: #{left};"><\/iframe>')).evaluate(style));
	}
});

DHTMLMenu.CONFIG = {
	submenu_class : "SubMenu", // the DOM class of the menu container
	hover_class : "Hover", // the class to give the top-level LI to "activate" the menu
	menu_hide_time : 500, // time to keep the menus on after mouseout; in ms
	menu_show_time : 100, // threshold o
	iframe_class : "IframeFix"
};

fixWebKitInheritanceBug(DHTMLMenu);

// ---------------------------------------------------------------------------

REDKEN.addFeature('DHTMLMenus', {
	setupElements : function(scope) {
		$$S(scope, ".DHTMLMenu").each(function(menu) {
			this.storeWidgetInstance(menu.id, new DHTMLMenu(menu.id));
		}.bind(this));
	}
});

/* ------------------------------------------------------ END: DHTMLMenu -- */


/* -- BEGIN: FormFieldTitle ----------------------------------------------- */

// FIXME: refactor this to be Class-based

REDKEN.addFeature('FormFieldTitle', {

	CONFIG : {
		show_title_class : "ShowTitle",
		disabled_class : 'Disabled'
	},

	setupElements : function(scope) {

		// set up the INPUT tags
		$$S(scope, 'INPUT.' + this.CONFIG['show_title_class']).each(function(input_el){

			// skip this whole thing if the element is disabled or if there's no title attribute
			if ( input_el.disabled || 
			    (typeof(input_el.title) == 'undefined') || 
			    (input_el.title == '') ) {
				return;
			}

			this.restoreHelperText(input_el);

			// hook up the events
			input_el.observe('focus', this.clearHelperText.bind(this, input_el));
			input_el.observe('blur', this.restoreHelperText.bind(this, input_el));

		}.bind(this)); // END: inputs


		// set up the SELECT tags
		$$S(scope, 'SELECT.' + this.CONFIG['show_title_class']).each(function(select_el){
			// warning: kinda ugly

			// create new option and prepend it tot the options array
			var new_option = "<option value=\"\"" + ((select_el.selectedIndex == 0)	 ? " selected=\"selected\"": "") + ">" + select_el.title + "<\/option>";

			new Insertion.Top(select_el, new_option);
		}); // END: selects


		// set up the TEXTAREA tags
		// FIXME: same as INPUT tags right now... may change
		$$S(scope, 'TEXTAREA.' + this.CONFIG['show_title_class']).each(function(textarea_el){

			// skip this whole thing if the element is disabled or if there's no title attribute
			if ( textarea_el.disabled || 
			    (typeof(textarea_el.title) == 'undefined') || 
			    (textarea_el.title == '') ) {
				return;
			}

			this.restoreHelperText(textarea_el);

			// hook up the events
			textarea_el.observe('focus', this.clearHelperText.bind(this, textarea_el));
			textarea_el.observe('blur', this.restoreHelperText.bind(this, textarea_el));

		}.bind(this)); // END: textareas


		// set up the FORM to clear out our titles onsubmit
		$$S(scope, 'FORM').each(function(form_el){
			form_el.observe('submit', this.clearHelperTextOnSubmit.bindAsEventListener(this), false);
		}.bind(this));

	}, // END: setupElements

	clearHelperText : function(el) {
		if (el.value == el.title) {
			el.value = '';
			el.removeClassName(this.CONFIG['disabled_class']);
		}
	},

	restoreHelperText : function(el) {
		if (el.value == '' || el.value == el.title) {
			el.value = el.title;
			el.addClassName(this.CONFIG['disabled_class']);
		}
	},

	clearHelperTextOnSubmit : function() {
		var f = Event.element(arguments[0]);

		// loop through all of the inputs in this FORM
		$A($$S(f, 'INPUT')).each(function(input_el) {
			// only process inputs which are ShowTitle enabled
			if (!input_el.hasClassName(this.CONFIG['show_title_class'])) { return; }

			// reset the value if it's equal to the title
			if (input_el.value == input_el.title) { input_el.value = ""; }
		}.bind(this));
	} // END: clearDefaultValues()

});

/* ------------------------------------------------- END: FormFieldTitle -- */


/* -- BEGIN: sIFR --------------------------------------------------------- */

REDKEN.addFeature('sIFR', {
	// these get passed as the first argument to sIFR.replace
	fonts : {
		'tradegothic' : {
			'src': '/javascripts/sifr.tradegothic.swf',
			'ratios': [12,1, 13,1, 14,1, 15,1, 16,1, 17,1, 18,1, 19,1, 20,1, 21,1, 22,1, 23,1, 24,1, 25,1]
		},

		'gothic_13' : {
			'src': '/javascripts/sifr.gothic-13.swf',
			'ratios': [64, 1]
		},

		'helvetica' : {
			'src': '/javascripts/sifr.helvetica.swf',
			'ratios': [64, 1]
		}
	},

	// these get passed as the second argument to sIFR.replace
	rules : {
		'tradegothic' : [
			{ selector: [
					"#professional-homepage #SideColumn H2",
					"#product-toolbox H3"
				].join(","),
				css :[
					'.sIFR-root { font-size: 15px; text-transform: uppercase; background-color: #000000; color: #FFFFFF; }'
				],
				wmode: 'transparent',
				tuneHeight : -5
			},

			{ selector: [
					"#MainColumn #related-content H3",
					"#consumer-homepage H2",
					"#SupplementalFeatures H3",
					".HomeBox H2"
				].join(","),
				css :[
					'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #000000; background-color: #FFFFFF; }',
					'b, strong { color: #999999; }' // FIXME: the B tag doesn't work
				],
				fitExactly : true,
				preventWrap : true,
				tuneHeight : -5,
				tuneWidth : 10,
				offsetLeft: 5
			},

			{ selector: [
					"#MainColumn.product H2",
					"#MainColumn H2.VerySmall"
				].join(","),
				css :[
					'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #000000; background-color: #FFFFFF; }'
				],
				tuneHeight : -5
			},

			{ selector: [
					".hair-profile-recommendations H2"
				].join(","),
				css :[
					'.sIFR-root { font-size: 24px; text-transform: uppercase; color: #000000; background-color: #FFFFFF; text-align: right; }'
				],
				tuneHeight : -5
			},

			{ selector: [
					"#MainColumn H2.green"
				].join(","),
				css :[
					'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #0E7C6D; }'
				],
				wmode: 'transparent',
				tuneHeight : -5
			},

			{ selector: [
					"#MainColumn H2.fineTitle"
				].join(","),
				css :[
					'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #666666; }'
				],
				wmode: 'transparent',
				tuneHeight : -6
			}
		],

		'gothic_13' : [
			{ selector: [
					"#MainColumn H1.Large"
				].join(","),
				css :[
					'.sIFR-root { font-size: 81px; leading: -17px; text-transform: uppercase; color: #000000; }'
				],
				wmode: 'transparent',
				tuneHeight : -10,
				kerning : true,
				offsetLeft : 3
			},
			
			{ selector: [
					"#MainColumn H1.Medium",
					"#your-hair-profile-header"
				].join(","),
				css :[
					'.sIFR-root { font-size: 64px; leading: -11px; text-transform: uppercase; color: #000000; }'
				],
				wmode: 'transparent',
				tuneHeight : -10,
				kerning : true,
				offsetLeft : 3
			},
			
			{ selector: [
					"#MainColumn H1.Small"
				].join(","),
				css :[
					'.sIFR-root { font-size: 58px; leading: -10px; text-transform: uppercase; color: #000000; }'
				],
				wmode: 'transparent',
				tuneHeight : -10,
				kerning : true,
				offsetLeft : 3
			},
			
				{ selector: [
						"H4.BlackHeader"
					].join(","),
					css :[
						'.sIFR-root { font-size: 20px; text-transform: uppercase; color: #000000; }'
					],
					wmode: 'transparent',
					tuneHeight : -8,
					kerning : true,
					offsetLeft : 0
				},

				{ selector: [
						"H3.BlackHeader"
					].join(","),
					css :[
						'.sIFR-root { font-size: 26px; text-transform: uppercase; color: #000000; }'
					],
					wmode: 'transparent',
					tuneHeight : -8,
					kerning : true,
					offsetLeft : 0
				},

				{ selector: [
						"H4.GrayHeader"
					].join(","),
					css :[
						'.sIFR-root { font-size: 28px; text-transform: uppercase; color: #b2b2b2; }'
					],
					wmode : 'opaque',
					tuneHeight : -4,
					kerning : true,
					offsetLeft : 0
				},

				{ selector: [
						"H3.GrayHeader"
					].join(","),
					css :[
						'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #838383; }'
					],
					wmode : 'opaque',
					tuneHeight : 0,
					kerning : true,
					offsetLeft : 0
				},

				{ selector: [
						"H3.GrayLabel"
					].join(","),
					css :[
						'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #838383; }'
					],
					wmode : 'opaque',
					tuneHeight : -8,
					kerning : true,
					offsetLeft : 0
				},
				
				{ selector: [
						"#your_hair_profile H2"
					].join(","),
					css :[
						'.sIFR-root { font-size: 28px; text-transform: uppercase; color: #A31700; }'
					],
					wmode : 'transparent',
					tuneHeight : -8,
					kerning : true,
					offsetLeft : 0
				},
				
				 { selector : [
						".Recommendation H3",
						"#recommended-services"
					].join(","),
					css :[
						'.sIFR-root { font-size: 22px; text-transform: uppercase; color: #333333; }'
					],
					wmode: 'transparent',
					kerning: true,
					offsetLeft : 3
				},
				
				{ selector: [
						"#recommended-salon-services-for-you H4",
						"#stylists-table H3"
					].join(","),
					css :[
						'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #A20500; }'
					],
					wmode : 'transparent',
					tuneHeight : -8,
					kerning : true,
					offsetLeft : 0
				},
				
				 { selector : [
						"#your-recommended-haircare-products H4"
					].join(","),
					css :[
						'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #1451BB; }'
					],
					wmode: 'transparent',
					kerning: true,
					offsetLeft : 3
				},
				
				 { selector : [
						"#your-recommended-styling-product H4",
						"#try-this-blended-styling-formula H4",
						"#try-this-blended-styling-formula2 H4"
					].join(","),
					css :[
						'.sIFR-root { font-size: 18px; text-transform: uppercase; color: #0383AA; }'
					],
					wmode: 'transparent',
					kerning: true,
					offsetLeft : 3
				},
				
				{ selector : [
						".Tip H6"
					].join(","),
					css :[
						'.sIFR-root { font-size: 20px; text-transform: uppercase; color: #A31700; }'
					],
					wmode: 'transparent',
					kerning: true,
					offsetLeft : 3
				},
				
				{ selector : [
						".Tip H5"
					].join(","),
					css :[
						'.sIFR-root { font-size: 15px; text-transform: uppercase; color: #A31700; text-align: center; }'
					],
					wmode: 'transparent',
					kerning: true,
					offsetLeft : 3
				}
				
			],

		'helvetica' : [
			{ selector : [
					"#question-wrapper H3"
				].join(","),
				css :[
					'.sIFR-root { font-size: 18px; font-weight: bold; color: #000000; }'
				],
				wmode: 'transparent',
				kerning: true,
				offsetLeft : 3
			},

			{ selector : [
					"#question-wrapper P.Question"
				].join(","),
				css :[
					'.sIFR-root { font-size: 13px; color: #000000; }'
				],
				wmode: 'transparent',
				kerning: true,
				offsetLeft : 3
			}
		]
	},

	initialize : function() {
		if (typeof(sIFR) == 'undefined') { return; }

		for (var font_name in this.fonts) {
			sIFR.activate(this.fonts[font_name]);

			if (!this.rules[font_name]) { continue; }

			for (var i=0; i < this.rules[font_name].length; i++) {
				sIFR.replace(this.fonts[font_name], this.rules[font_name][i]);
			}
		}

	}
});

/* ----------------------------------------------------------- END: sIFR -- */



/* -- BEGIN: product navigation ------------------------------------------- */

var ProductNavigationFacet = Class.create(PageWidget, {
	initialize : function(facet) {
		this.node = $(facet);

		if (!this.node) { return; }

		this.nodes = { };
		this.nodes['facet_title'] = this.node.down("H4");
		if (this.node.down("UL")) {
			this.nodes['facet_nav'] = this.node.down("UL");
		}

		this.title_has_link = !!this.nodes['facet_title'].down("A");
		this.in_selected_nav = this.node.hasClassName('Selected');

		this.current_section = null;

		// attach an event listener to the H4
		this.nodes['facet_title'].observe('click', this.facetClickHandler.bindAsEventListener(this));

		if (this.in_selected_nav) {
			this.constructor.last_open_facet = this.constructor.current_section = this;
		} else {
			if (this.nodes['facet_nav']) {
				this.nodes['facet_nav'].hide();
			}
		}
	},

	facetClickHandler : function(e) {
		if (this.nodes['facet_nav'] && this.node.down("UL.result-nav")) {
			if ( (!this.nodes['facet_nav'].visible()) || 
					 (!this.nodes['facet_nav'].visible() && (this.constructor.current_section == this))
			) {
				if (this.constructor.last_open_facet) { this.constructor.last_open_facet.toggleFacet(); }
				this.toggleFacet();
				this.constructor.last_open_facet = this;

				Event.element(e).blur();
				Event.stop(e);
			}
		}
	},

	toggleFacet : function() {
		this.nodes['facet_nav'].toggle();
		this.node.toggleClassName('Selected');
	}
});

ProductNavigationFacet.last_open_facet = null;
ProductNavigationFacet.current_section = null;

fixWebKitInheritanceBug(ProductNavigationFacet);

// ---------------------------------------------------------------------------

REDKEN.addFeature('ProductNavigation', {
	setupElements : function(scope) {
		$$S(scope, '#product-family-nav > LI').each(function(facet){
			this.storeWidgetInstance(facet.identify(), new ProductNavigationFacet(facet));
		}.bind(this));

	}
});

/* --------------------------------------------- END: product navigation -- */


/* -- BEGIN: buzz & events ------------------------------------------------ */
// 
// var BuzzEventsListing = Class.create(PageWidget, {
// 	initialize : function(wrapper) {
// 		this.node = $(wrapper);
// 		if (!this.node) { return; }
// 		this.months = this.node.select('.HotContent');
// 		this.months.each(function(m, i){
// 			var header = m.down('h3');
// 			var content = m.down('ul');
// 			if (!header || !content) { return; }
// 			header.addClassName('Link');
// 			if (i != 0) {
// 				header.removeClassName('Active');
// 				content.setStyle({ display : 'none' });
// 			}
// 			header.observe('click', this.headerClickHandler.bindAsEventListener(this));
// 		}, this);
// 		this.archives = $('archived-whats-hot');
// 		if (!this.archives) { return; }
// 		var archived_header = this.archives.down('h2');
// 		if (archived_header) {
// 			archived_header.addClassName('Link');
// 			archived_header.observe('click', this.archivedClickHandler.bindAsEventListener(this));
// 			archived_header.select('h3','ul').each(function(ele){ ele.setStyle({ display : 'none' }); });
// 			archived_header.select('h3').invoke('removeClassName','Active');
// 		}
// 	},
// 	
// 	headerClickHandler : function(e){
// 		var header = e.element();
// 		header = (header.tagName.toLowerCase() == 'h3') ? header : header.up('h3');
// 		if (header.hasClassName('Active')) {
// 			header.removeClassName('Active');
// 			header.next('ul').setStyle({ display : 'none' });
// 		} else {
// 			header.addClassName('Active');
// 			header.next('ul').setStyle({ display : 'block' });
// 		}
// 	},
// 	
// 	archivedClickHandler : function(e){
// 		var header = e.element();
// 		header = (header.tagName.toLowerCase() == 'h2') ? header : header.up('h2');
// 		if (header.up().hasClassName('ArchivedActive')) {
// 			header.up().removeClassName('ArchivedActive');
// 			this.archives.select('ul','h3').each(function(ele){ ele.setStyle({ display : 'none' }); });
// 			this.archives.select('.Active').invoke('removeClassName','Active');
// 		} else {
// 			header.up().addClassName('ArchivedActive');
// 			this.archives.select('h3').each(function(ele){ ele.setStyle({ display : 'block' }); });
// 		}
// 	}
// 
// });
// 
// // ---------------------------------------------------------------------------
// 
// REDKEN.addFeature('buzz-events', {
// 	setupElements : function() {
// 		if ($('buzz-events-listing')) {
// 			this.storeWidgetInstance('buzz-events-listing', new BuzzEventsListing('buzz-events-listing'));
// 		}
// 	}
// });

/* -------------------------------------------------- END: buzz & events -- */


REDKEN.addFeature('PrintLink', {
	setupElements : function(source) {
		$$('.print-link, #print-link').each(function(print_link){
			print_link.observe('click', function(e) {
				Event.stop(e);
				if (window.print) { window.print(); }
			});
		});
	}
});


REDKEN.addFeature('SectionNavFixer', {
	setupElements : function(source) {
		var nav_items = $$('#SectionNav > LI');

		nav_items.each(function(item, i){
			if (i == 0) { return; }
			if (item.hasClassName('Active')) {
				item.previous().setStyle({ 'backgroundImage' : 'none' });
			}

			if ( (i == nav_items.length - 1) && !item.hasClassName('Active')) {
				item.setStyle({ 'backgroundImage' : 'none' });
			}

		});
	}
});


REDKEN.addFeature('DistributorLocatorFixer', {
	setupElements : function() {
		$$('#nav_grow-business LI A, #SectionNav > LI A').each(function(anchor){
			if (/\/distributor\-locator\/$/.match(anchor.href)) {
				anchor.href = "\/distributor-locator\/";
			}
		});

	}
});


// ---------------------------------------------------------------------------
// <select>-based navigation script

var SelectNavigation = Class.create({
  initialize: function(element){
    element.observe('change', this.onchange);
  },
  
  onchange: function(){
    if (this.value.blank() || (this.value == "#") ) { return; }

		if (/^http\:\/\//.match(this.value)) {
      window.location.href = this.value;
    } else {
	    window.location.pathname = this.value;
  	}
  }
});

SelectNavigation.attach = function(){
  $$('select.SelectNavigation').each(function(element){
    new SelectNavigation(element);
  });
};
document.observe("dom:loaded", SelectNavigation.attach);

// ---------------------------------------------------------------------------
// Email page / Send to a friend functionality

var EmailPageLink = Class.create({
	initialize: function(el) {
		this.node = $(el);
		if (!this.node) { return; }

		this.node.observe('click', this.showWindow.bindAsEventListener(this));
	},

	window_ref : null,

	showWindow: function(e) {
		e.stop();

		var url = "http://" + window.location.host + "/send_page?url=" + encodeURIComponent(window.location.href) + "&page_name=" + encodeURIComponent(document.title.gsub(/^Redken\s(Consumer|Professional)\s-\s*/, ''));

		this.window_ref = window.open(url,'email_page_window','height=590,width=450,scrollbars=yes,location=no,menubar=no,toolbar=no,status=no,directories=no');
		this.window_ref.focus();
	}
});

document.observe("dom:loaded", function(){ new EmailPageLink($('email-link')); });

// ---------------------------------------------------------------------------
// What's Hot Page

var WhatsHotListing = Class.create({
	initialize : function(wrapper){
		WhatsHotListingNode = this;
		this.node= $(wrapper);
		this.mainfeature = $('MainFeature');
		if (!this.node || !this.mainfeature) { return; }
		this.category = String(document.location).split("?").last();
		this.category = this.category.include("hot") ? 'all' : parseInt(this.category.split("=").last());

		// Initialize Current Content
		this.listings = this.node.select('.HotContent');
		if (this.listings.length < 1) { return; }
		this.listings.each(function(month){ this.initializeHotContent(month); }, this);

		// Initialize Archived Content
		this.archives = $('archived-whats-hot-wrapper');
		if (this.archives) { this.initializeArchivedContent(); }

		// Display most recent feature image and thumbnail
		this.currentcontent = $('current-whats-hot-wrapper');
		if (!this.currentcontent) { return; }
		var first_image = this.node.down('.MainImage').down('img');
		if (first_image) { this.mainfeature.setStyle({ backgroundImage : 'url(' + first_image.src + ')', backgroundRepeat : 'no-repeat', backgroundPosition: 'top left' }); }
		var first_featureLink = this.node.down('.MainImage').href;
		if (first_featureLink) { this.mainfeature.update('<a href="'+ first_featureLink +'" class="mainFeatureLink"></a>'); }
		var firstThumb = this.node.down('li');
		this.lastHover = firstThumb;
		firstThumb.addClassName('Hover');

	},
	initializeHotContent : function(month){
		var header = month.down('h3');
		var list = header.next('ul');
		if (header && list) {
			header.addClassName('Link');
			header.observe('click', this.toggleHotContentVisibility.bindAsEventListener(this));
			if (!header.hasClassName('Active')) { list.setStyle({ display : 'none' }); }
			this.initializeHotContentList(list);
		}
	},
	initializeArchivedContent : function(){
		this.archived_months = this.archives.select('.HotContent');
		this.archived_months.invoke('setStyle',{display:'none'});
		this.archived_header = this.archives.down('h3');
		if (this.archived_header) {
			this.archived_header.addClassName('Link');
			this.expanded_archives = false;
			this.archived_header.observe('click', this.archivedHotContentHeaderClickHandler.bindAsEventListener(this));
		}
		this.archived_months.each(function(month){
			var header = month.down('h3');
			if (header) {
				header.addClassName('Link');
				var month = parseInt(this.integerFromMonth(header.down('img',0).title.split(" ").first()));
				var year = parseInt(header.down('img',1).title.split(" ").last());
				header.observe('click', this.archivedContentClickHandler.bindAsEventListener(this, month, year, this.category));
			}
		}, this);
	},
	initializeHotContentList : function(ul){
		var items = ul.select('li');
		if (items.length == 0) { ul.remove(); } else {
			items.each(function(li){
				li.down('a').addClassName('Link').removeAttribute('href');
				li.observe('mouseover', this.hotContentMouseOverHandler.bindAsEventListener(this));
				li.observe('mouseout', this.hotContentMouseOutHandler.bindAsEventListener(this));
				li.observe('click', this.hotContentClickHandler.bindAsEventListener(this));
				li.observe('click', this.hotContentFeatureLink.bindAsEventListener(this));
			}, this);
		}
	},
	hotContentMouseOverHandler : function(e){
		if (this.lastHover){ this.lastHover.removeClassName('Hover'); }
		var ele = e.element();
		if (ele.tagName.toLowerCase() != 'li') { ele = ele.up('li'); }
		ele.addClassName('Hover');
		this.lastHover = null;
	},
	hotContentMouseOutHandler : function(e){
		var ele = e.element();
		if (ele.tagName.toLowerCase() != 'li') { ele = ele.up('li'); }
		this.lastHover = ele;
	},
	hotContentClickHandler : function(e){
		var ele = e.element();
		if (ele.tagName.toLowerCase() != 'li') { ele = ele.up('li'); }
		var image = ele.down('.MainImage').down('img');
		if (image) { this.mainfeature.setStyle({ backgroundImage : 'url(' + image.src + ')', backgroundRepeat : 'no-repeat', backgroundPosition: 'top left' }); }
	},
	hotContentFeatureLink : function(e){
		var ele = e.element();
		if (ele.tagName.toLowerCase() != 'li') { ele = ele.up('li'); }
		var featureLink = ele.down('.MainImage').href;
		if (featureLink) { this.mainfeature.update('<a href="'+ featureLink +'" class="mainFeatureLink"></a>'); }
		if (!featureLink) { this.mainfeature.update('<a class="mainFeatureLink"></a>'); }
	},
	toggleHotContentVisibility : function(e){
		var ele = e.element();
		if (ele.tagName.toLowerCase() != 'h3') { ele = ele.up('h3'); } // avoid img clicks
		var list = ele.next('ul');
		if (ele && list) {
			if (ele.hasClassName('Active')) {
				ele.removeClassName('Active');
				list.setStyle({ display : 'none' });
			} else {
				ele.addClassName('Active');
				list.setStyle({ display : 'block' });
			}
		}
	},
	archivedHotContentHeaderClickHandler : function(){
		if (this.archived_header.hasClassName('ActiveArchives')) {
			this.archived_header.removeClassName('ActiveArchives');
			this.archived_months.invoke('setStyle',{display:'none'});
		} else {
			this.archived_header.addClassName('ActiveArchives');
			this.archived_months.invoke('setStyle',{display:'block'});
		}
	},
	archivedContentClickHandler : function(e, month, year, category){
		var ele = e.element();
		if (ele.tagName.toLowerCase() != 'h3') { ele = ele.up('h3'); }
		var list = ele.next('ul');
		if (!list) {
			this.fetchArchivedMonth(month,year,category,ele);
		}	else {
			if (ele.hasClassName('Active')) {
				ele.removeClassName('Active');
				list.setStyle({ display : 'none' });
			} else {
				ele.addClassName('Active');
				list.setStyle({ display : 'block' });
			}
		}
	},
	fetchArchivedMonth : function(month, year, category, target){
		new Ajax.Request('/whats-hot', {
			asynchronous : false,
			method : 'get',
			parameters : { 'month' : month, 'year' : year, 'category' : category },
			onSuccess : this.fetchArchivedMonthSuccessHandler.bind(this.responseText, target),
			onFailure : this.fetchArchivedMonthFailureHandler.bind(this, target)
		});
	},
	fetchArchivedMonthSuccessHandler : function(target, transport){
		var json = transport.responseText.evalJSON();
		var month_list = new Element('UL');
		$H(json).each(function(item){
			switch(parseInt(item[1][1])) { case 0: var cat='all';break; case 1: var cat='haircare';break; case 2: var cat='styling';break; case 3: var cat='color';break; case 4: var cat='men';break; case 5: var cat='events';break; }
			var type = (parseInt(item[1][2]) == 1) ? 'article' : 'event';
			if (item[1][5] == 'true') { var linkability = ' href="' + item[1][0] + '"'; } else { var linkability = ''; }
			var li = new Element('li', { 'class' : type+' '+cat }).update('<span class="Icon"></span><a class="Link" href="' + item[1][0] + '">' + item[0] + '</a><img src="' + item[1][3] + '" class="Thumbnail" alt="" /><a class="MainImage"' + linkability + '><img src="' + item[1][4] + '" alt="" /></a>');
			month_list.insert({ bottom:li});
		});
		target.insert({after:month_list});
		if (Prototype.Browser.IE) { 
			Event.stopObserving(target, 'click');
		} else {
			month_list.previous('h3').addClassName("Active");
		}
		WhatsHotListingNode.initializeHotContent(month_list.up('.HotContent'));
	},
	fetchArchivedMonthFailureHandler : function(transport){ return false; },
	integerFromMonth : function(month) {
		switch(month) {
			case "Janurary" : var month_int = 1; break;
			case "February" : var month_int = 2; break;
			case "March" : var month_int = 3; break;
			case "April" : var month_int = 4; break;
			case "May" : var month_int = 5; break;
			case "June" : var month_int = 6; break;
			case "July" : var month_int = 7; break;
			case "August" : var month_int = 8; break;
			case "September" : var month_int = 9; break;
			case "October" : var month_int = 10; break;
			case "November" : var month_int = 11; break;
			case "December" : var month_int = 12; break;
		}
		return month_int;
	}
});

document.observe('dom:loaded', function(){ new WhatsHotListing($('whats-hot')); });

// ---------------------------------------------------------------------------
// Ask The Experts

var AskTheExperts = Class.create({
	initialize : function(wrapper){
		this.node = $(wrapper);
		if (!this.node) { return; }
		new Ajax.Request('/', {
			method: 'get',
			parameters : { 'time' : new Date().getTime() },
			onSuccess: this.AskTheExpertsSuccessHandler.bind(this),
			onFailure: this.AskTheExpertsFailureHandler.bind(this)
		});
	},
	AskTheExpertsSuccessHandler : function(transport){
		if (transport.responseText) {
			var json = transport.responseText.evalJSON();
			var favorite_info = this.node.down('div.favorite-info');
			if (favorite_info) { 
				var learn_more = favorite_info.down('a.learn-more');
				if (learn_more) {
					learn_more.replace('<h4><a href="' + json['url'] +'">' + json['teaser_header'] + '</a></h4><table class="LayoutTable"><tr><td width="87"><a href="' + json['url'] +'"><img src="' + json['thumbnail'] + '" alt="" /></a></td><td><p>' + json['teaser_body'] + '</p><a href="' + json['url'] + '" class="learn-more">Find Out More</a></td></tr></table>');
				}
			}
		}
	},
	AskTheExpertsFailureHandler : function(transport){
		this.node.update('<span id="ErrorMessage">No Experts Returned</span>');
		return false;
	}
});

document.observe('dom:loaded', function(){ 
	setTimeout(function(){ 
		// IE6 SP1 needs a few moments or else $(wrapper) will return null - not good! -amlw 1/8/08
		new AskTheExperts('ask-the-experts'); 
	}, 100); 
});

/* ---------------------------------------------------------------------- */ 
/**
 * Correctly handle PNG transparency in Win IE 5.5 & 6.
 * http://homepage.ntlworld.com/bobosola. Updated 18-Jan-2006.
 * 
 * Use in <HEAD> with DEFER keyword wrapped in conditional comments:
 * 
 *   <!--[if lt IE 7]>
 *   <script defer type="text/javascript" src="pngfix.js"></script>
 *   <![endif]-->
 * 
 */

var arVersion = navigator.appVersion.split("MSIE"),
    version = parseFloat(arVersion[1]),
    filters = false;
    
try { filters = !!document.body.filters }
catch (e) {}

if (version >= 5.5 && filters) {
  $A(document.images).each(function(img) {
    if (!img.src.toLowerCase().endsWith('png')) return;
    
    var span = new Element('span', { id: img.id, className: img.className, title: (img.title || img.alt) }).
      setStyle({
        display: 'inline-block',
        width: img.width + 'px',
        height: img.height + 'px',
        filter: 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="' + img.src + '", sizingMethod="scale")'
      }).
      setStyle(img.style.cssText);
    
    if (img.align == "left")       span.setStyle("float: left");
    else if (img.align == "right") span.setStyle("float: right");
    if (img.parentElement.href)    span.setStyle("cursor: hand");
    
    $(img).replace(span);
  });
}
