
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: [
					"#c5aAccount H2"
				].join(","),
				css :[
					'.sIFR-root { font-size: 24px; text-transform: uppercase; color: #000000; background-color: #FFFFFF; text-align: left; }'
				],
				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 -- */

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

/* ---------------------------------------------------------------------- */ 

var ProductNavigation = Class.create({
	
	initialize : function(nav, families, filters) {
		this.maincol = $("MainColumn");
		this.nav = nav;
		this.families = families;
		this.filters = filters;
		this.no_results = $("no-results");
		if (!this.nav || !this.families || !this.filters)
			return;
		
		var nav_lists = this.nav.getElementsByTagName("ul");
		this.top_level_families = nav_lists[0].getElementsByTagName("input");
		this.secondary_lists = $A(nav_lists).without(nav_lists[0]);
		
		this.filter_inputs = [];
		this.all_filter_inputs = [];
		for (var i = 0, filter, inputs; filter = this.secondary_lists[i]; i++) {
			inputs = filter.getElementsByTagName("input");
				for (var ii = 0, all = "all_tag", input; input = inputs[ii]; ii++)
					if (input.id.indexOf(all) == -1) {
						this.filter_inputs.push(input);
					} else {
						this.all_filter_inputs.push(input);
					}
		}
		
		this.secondary_batches = $H();
		for (var i = 0, list; list = this.secondary_lists[i]; i++)
			this.secondary_batches.set($(list).identify(), $A(list.getElementsByTagName("input")));
		
		this.family_categories = this.families.getElementsByClassName("family-wrapper");
		this.filter_categories = this.filters.getElementsByClassName("family-wrapper");
		
		this.wrapper_batches = $H();
		for (var i = 0, batches = this.maincol.getElementsByClassName("family-wrapper"); batch = batches[i]; i++)
			this.wrapper_batches.set(batch.id, batch.getElementsByClassName("ProductWrapper"));
		
		var loc = document.location.href, match;
		if ((match = loc.match(/category=(.+)$/)) !== null) {
			var checkbox = $("tag_" + match[1]);
			if (checkbox)
				checkbox.checked = true;
		} else {
			for (var i = 0, l = this.top_level_families.length, c; c = this.top_level_families[i]; i++)
				c.checked = false;
		}
		this.active_families = this.getCheckedElementsFromBatch(this.top_level_families);
		this.active_filters = this.getCheckedElementsFromBatch(this.filter_inputs);
		
		// First refresh, but not if we're vanilla loading
		if (this.active_families.length > 0) {
			this.determineFamilyVisibility();
		} else {
			if (!Prototype.Browser.IE)
				replaceProductFamilySifrs();
			this.filters.hide();
		}

		this.nav.observe("click", this.navigationClickHandler.bindAsEventListener(this));

		var all_products = $("all-products-button");
		if (all_products)
			all_products.observe("click", this.modifyAllCheckboxes.bind(this));

		this.all_products = this.maincol.getElementsByClassName("ProductWrapper");
		for (var i = 0, product; product = this.all_products[i]; i++)
			this.initializeProductPopup(product);

	},
	
	initializeProductPopup : function(product) {
		var popup = $(product).down(".ProductPopup");
		if (popup) {
			product.observe("mouseover", this.toggleProductPopup.bind(this, popup, true));
			product.observe("mouseout", this.toggleProductPopup.bind(this, popup, false));
		}
	},
	
	toggleProductPopup : function(popup, visible) {
		popup.style.cssText = visible? "display:inline;" : "display:none";
	},
	
	navigationClickHandler : function(e) {
		var el = e.findElement("input");
		if (el) {
			var type = el.getAttribute("type");
			if (type === "checkbox") {
				if (el.checked) {
					this.active_families.push(el);
				} else {
					this.active_families = this.active_families.without(el);
				}
			} else {
				this.active_filters = this.getCheckedElementsFromBatch(this.filter_inputs);
			}
			this.determineFamilyVisibility();
		}
	},
	
	modifyAllCheckboxes : function() {
		var all_toggled = this.getCheckedElementsFromBatch(this.top_level_families).length === this.top_level_families.length;
		for (var i = 0, l = this.top_level_families.length, element; element = this.top_level_families[i]; i++)
			element.checked = !all_toggled;
		for (i = 0, l = this.all_filter_inputs.length; element = this.all_filter_inputs[i]; i++)
			element.checked = true;
		this.active_families = this.getCheckedElementsFromBatch(this.top_level_families);
		this.active_filters = this.getCheckedElementsFromBatch(this.filter_inputs);
		this.determineFamilyVisibility();
	},
	
	getCheckedElementsFromBatch : function(batch) {
		var results = [];
		for (var i = 0, l = batch.length, element; element = batch[i]; i++)
			if (element.checked)
				results.push(element);
		return results;
	},
	
	determineFamilyVisibility : function() {
		this.no_results.hide();
		if (this.active_families.length === 0) {
			this.filters.hide();
			this.families.show();
			this.visible_families = this.family_categories;
			for (var i = 0, family; family = this.visible_families[i]; i++)
				family.show();
		} else {
			this.visible_families = [];
			this.families.hide();
			this.filters.show();
			for (var i = 0, section; section = this.top_level_families[i]; i++) {
				var target = $(section.value);
				if (section.checked) {
					target.show();
					this.visible_families.push(target);
				} else {
					target.hide();
				}
			}
		}
		this.determineFilterVisibility();
	},
	
	determineFilterVisibility : function(){
		var visible_products = [];
		
		for (var i = 0, product; product = this.all_products[i]; i++) {
			product.show();
			product.status = 0;
		}
		
		for (var i = 0, family; family = this.visible_families[i]; i++)
			family.status = this.wrapper_batches.get(family.id).length;
		
		for (var i = 0, filter; filter = this.active_filters[i]; i++) {
			var filter_id = filter.id;
			for (var x = 0, family; family = this.visible_families[x]; x++) {
				var products = this.wrapper_batches.get(family.id);
				for (var y = 0, product; product = products[y]; y++) {
					if (product.status !== 2) {
						if (product.className.indexOf(filter_id) > -1) {
							visible_products.push(product);
							product.status = 1;
						} else {
							if (product.status === 1) {
								visible_products = visible_products.without(product);
							}
							family.status -= 1;
							product.status = 2;
							product.hide();
						}
					}
				}
			}
		}
		
		var could_be_hidden = this.visible_families.length, will_be_hidden = 0;
		for (var i = 0, family; family = this.visible_families[i]; i++) {
			if (family.status === 0) {
				will_be_hidden += 1;
				family.hide();
			}
		}
		
		if (this.active_filters.length !== 0 || could_be_hidden === will_be_hidden)
			this.no_results.style.display = visible_products.length === 0 || could_be_hidden === will_be_hidden ? "block" : "none";	
	
	}
	
});

var ProductTabs = Class.create({
	initialize : function(tabset) {

		// add the JS-enabled class and grab the tabs...
		tabset.show().up().addClassName("ActiveTabSet");
		this.tab_targets = {};
		var tabs = tabset.getElementsByTagName("li");
		
		// figure out if there is a current page, if so, we want to show it be default..
		var page = document.location.href.match(/[\?|\&]page=(\d+)/);
		this.current_page = page ? parseInt(page[1]) : false;

		// initialize the tab behaviors..
		for (var i = 0, target; target = tabs[i]; i++)
			this.initializeTab(tabs[i], i);
			
		// grab the reviews wrappers...
		this.reviews_wrapper = $("reviews-wrapper");
		this.product_id = $("product_id");
		this.initializeReviewsWrapper();

		// hook up the smaller link at the top of the reviews
		var total_reviews = $("total-review-count");
		this.product_review_target = $("tab-customer-reviews-target");
		this.product_review_tab = $("tab-customer-reviews");
		if (total_reviews && this.product_review_tab && this.product_review_target)
			total_reviews.observe("click", this.showProductReviews.bind(this));

		this.ajax_captcha_wrapper = $("ajax-captcha-wrapper");
		this.captcha_verified = $("captcha_verified");
		// hide the captcha if we've got the cookie
		if (this.captcha_verified.value == "true") {
			this.ajax_captcha_wrapper.hide();
		} else {
			// otherwise, set the review submit form to use the ajax captcha
			// there is only one captcha on the page at any given time - if we need
			// to use the captcha for the review ratings we move it from the submit
			// review form.
			this.review_submit_button = $("submit_product_review");
			this.review_form = $("product-review-form");
			if (this.review_submit_button && this.review_form)
				this.review_submit_button.observe("click", this.reviewClickHandler.bindAsEventListener(this));
		}
		
		$(document.body).scrollTo();
	},
		
	initializeTab : function(tab, i) {
		// if the tab is "tab-reviews", the reviews area is "tab-reviews-target"
		var tab_target = $($(tab).id + "-target");
		if (tab_target) {
			// stash it in the tab targets hash
			this.tab_targets[tab.id] = tab_target;
			// if reviews tab is requested, activate the correct tab
			// otherwise the active tab is the first
			if ((location.hash != '#tab-customer-reviews-target' && i == 0) || (location.hash == '#tab-customer-reviews-target' && i == 2)) {
				this.active_tab = tab;
				tab.addClassName("Selected");
			} else {
				tab_target.hide();
			}
			if (!tab.hasClassName("NoBuzz"))
				tab.observe("click", this.tabClickHandler.bind(this, tab));
		} else {
			tab.hide();
		}
	},
	
	initializeReviewsWrapper : function() {
		// rating_links are all the helpful, unhelpful, and flag links.
		var rating_links = $$(".rate-this-review A");
		for (var i = 0, target; target = rating_links[i]; i++)
			this.initializeRemoteLink(target);
		// show the rating links wrappers (hidden for non-JS people)
		$$S(this.reviews_wrapper, ".rate-this-review").invoke("show");
	},
		
	// visibility, swaps the current tab for whatever tab was clicked
	tabClickHandler : function(tab) {
		if (tab.hasClassName("Selected")) return;
		this.tab_targets[this.active_tab.removeClassName("Selected").id].hide();
		this.tab_targets[tab.id].show();
		this.active_tab = tab.addClassName("Selected");
		this.active_tab.scrollTo();
	},
	
	// used specifically by the reviews link at the top
	showProductReviews : function() {
		this.tab_targets[this.active_tab.removeClassName("Selected").id].hide();
		this.product_review_target.show();
		this.active_tab = this.product_review_tab.addClassName("Selected");
	},
	
	// for all the review rating links (helpful, unhelpful) and flagging links.
	initializeRemoteLink : function(link) {
		link.observe("click", this.rateThisReview.bindAsEventListener(this, link));
	},
	
	rateThisReview : function(e, link) {
		e.stop();
		var target = link.href;
		this.requested_rating = link;
		if (this.active_target) {
			this.active_target.show();
			this.active_target = null;
		}
		this.active_target = link.up(".rate-this-review");
		// check the cookie - if its set, we can just jump right to the rating...
		if (this.captcha_verified.value == "true") {
			this.submitRating(target);
		} else {
			// otherwise, we move the captcha up to the rating area and wait for
			// a successful entry by adding a submit button underneath it
			// that will fire off the ajax handler...
			this.active_target.hide();
			this.active_target.insert({ after : this.ajax_captcha_wrapper });
			// clean up the previous submit button if it exists...
			if (this.submit_button) {
				Event.stopObserving(this.submit_button);
				this.submit_button.remove();
			}
			this.ajax_captcha_wrapper.show();
			this.submit_button = new Element("input", { "type" : "image", "src" : "/images/btn.submit.gif", "class" : "captcha-submit-button" });
			this.ajax_captcha_wrapper.insert({ after : this.submit_button });
			this.submit_button.observe("click", this.verifyCaptchaResponse.bindAsEventListener(this));
		}
	},
	
	// the main captcha check for the review submission form
	reviewClickHandler : function(e) {
		e.stop();
		if (this.review_form.down("#ajax-captcha-wrapper")) {
			this.verifyCaptchaResponse();
		} else {
			this.review_form.select(".Field").last().insert({ after : this.ajax_captcha_wrapper });
		}
	},
	
	// talks to the rails controller that will check with the recaptcha API- will
	// return "true" or "false"
	verifyCaptchaResponse : function(e) {
		new Ajax.Request("/verify-captcha", {
			parameters : { "response" : Recaptcha.get_response(), "challenge" : Recaptcha.get_challenge() },
			onSuccess : this.checkCaptchaResponse.bind(this)
		});
	},
	
	checkCaptchaResponse : function(transport) {
		if (transport.responseText == "true") {
			// are we rating a review or did we add a review?
			// if we're rating a review, we need to know which one we were working on...
			if (this.requested_rating) {
				this.captchaSuccessHandler(this.requested_rating.href);
				this.active_target.show();
				this.ajax_captcha_wrapper.hide();
				this.submit_button.hide();
			} else {
				this.captchaSuccessHandler();
			}
		} else {
			this.resetCaptcha();
		}
	},
	
	captchaSuccessHandler : function(href) {
		// remove the captcha from the page
		Recaptcha.destroy();
		// create the cookie so that we dont need to captcha anymore
		this.captcha_verified.value = "true";
		// was this on a review rating, or are we submitting the actual form?
		if (href) {
			this.submitRating(href);
		} else {
			this.review_form.submit();
		}
	},
	
	// this gets called when the user fails the captcha
	resetCaptcha : function(){
		Recaptcha.reload();
	},
	
	// fires off the helpful, unhelpful, flag links to the product reviews
	// controller - the href determines whats going on...
	submitRating : function(target) {
		new Ajax.Request(target, {
			onSuccess : this.ratingReviewSuccessHandler.bind(this)
		});
	},
	
	// replaces the links to mark the review with the response from the server.
	ratingReviewSuccessHandler : function(transport) {
		this.active_target.update(transport.responseText);
	}
	
});

var ProductZoom = Class.create({
	initialize : function(button, image){
		this.image = image;
		this.button = button.show();
		this.button.observe("click", this.displayImageZoom.bind(this));
		this.overlay = new Element("div", { "id" : "ZoomOverlay", "style" : "display: none;" });
		$(document.body).insert({ bottom : this.overlay });
	},
	
	displayImageZoom : function(){
		this.image.show();
		var total_height = document.viewport.getHeight();
		var total_width = document.viewport.getWidth();
		this.overlay.setStyle({ width : (total_width - 20)+"px", height : total_height+"px", display : "block" });
		this.overlay.observe("click", this.hideImageZoom.bind(this));
	},
	
	hideImageZoom : function(){
		this.image.hide();
		this.overlay.hide();
		Event.stopObserving(this.overlay);
	}
	
});

document.observe("dom:loaded", function(){
	var filters = $("CategoryFilters");
	var families = $("CategoriesToFilter");
	var categories = $("FilteredCategories");
	if (filters && families && categories)
		new ProductNavigation(filters, families, categories);
	var tabs = $("product-information-tabset");
	if (tabs)
		new ProductTabs(tabs);
	
	var button = $("zoom-img-in");
	var zoom_target = $("product-zoom-target");
	if (button && zoom_target)
		new ProductZoom(button, zoom_target);
});

var RatingWidget = Class.create(PageWidget, {
	initialize : function(ul) {
		this.node = ul;
		this.current_rating = 5; // start off with a good review!
		this.all_items = this.node.select("LI");
		this.all_items.each(function(li){
			var label = li.down('label');
			var input = li.down('input');
			input.setStyle({ 'position' : 'absolute', 'left' : '-9999px' });
			label.observe('click', this.labelClickHandler.bindAsEventListener(this, input));
			label.observe('mouseover', this.labelMouseoverHandler.bindAsEventListener(this, li));
			label.observe('mouseout', this.labelMouseoutHandler.bindAsEventListener(this, li));
		}, this);
		this.highlightRating(5, "Score"); // Visual cue that the rating is great.		
	},

	labelClickHandler : function(e, input) {
		input.checked = true;
		this.current_rating = input.value;
		this.highlightRating(input.up(), "Score");
	},

	highlightRating : function(el_or_rating, class_name) {
		var target, target_index;
		if (Object.isElement(el_or_rating)) {
			target = el_or_rating;
			target_index = this.all_items.indexOf(target);
		} else {
			target_index = el_or_rating - 1;
			target = this.all_items[target_index];
		}
		this.all_items.each(function(li, i){
			(i <= target_index) ? li.addClassName(class_name) : li.removeClassName(class_name);
		});
	},

	labelMouseoverHandler : function(e, li) {
		this.node.addClassName("RatePending");
		this.highlightRating(li, 'Hover');
	},

	labelMouseoutHandler : function(e, li) {
		this.node.removeClassName("RatePending");
		var elements = li.previousSiblings();
		elements.push(li);
		elements.each(function(item){
			item.removeClassName("Hover");
		});
	}
});
  
document.observe('dom:loaded', function(){
	var review_rating_stars = $("add-review-rating");
	if (review_rating_stars)
    new RatingWidget(review_rating_stars);
});

var Cookie = {
	create : function(name, value, days) {
		var expires;
		if (days) {
			var date = new Date();
			date.setTime(date.getTime() + (days*24*60*60*1000));
			expires = "; expires=" + date.toGMTString();
		} else {
			expires = "";
		}
		document.cookie = name + "=" + value + expires + "; path=/";
	},
	
	read : function(name) {
		var nameEQ = name + "=";
		var cookies = document.cookie.split(";");
		for (var i = 0, l = cookies.length; i < l; i++) {
			var c = cookies[i];
			while (c.charAt(0) == " ") c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
		}
	},
	
	remove : function(name) {
		Cookie.create(name, "", -1);
	}
};