var filterList = [];
var availableFilters = [];
var ratingsLoaded = false;
var intervalHolder = null;
var directoryContent, headCopy, headImage, headerTemplate;
var categoryId = null;
var playerLoaded = false;
var pageLoaded = false;
var pageTitle = '';

function playerReady() {
	playerLoaded = true;
	if ($('#video-player').length && !$('#video-box-wrap').hasClass('safeHide')) {
		$('#video-player').get(0).sendEvent('PLAY', true);
	}
};

// Config for metadata, only for directory page
jQuery(function($){
	var isIE = false;
	if ($('html.ie').length) {
		isIE = true;
		if ($.address) pageTitle = $.address.title();
	}
	
	if (typeof(jQuery.metadata) != 'undefined' && jQuery('#product-list').length) {
		jQuery.metadata.setType('elem', 'script');
	}
	
	// compatibility issues with ML admin
	var parent_location = new String(parent.location);
	var top_location = new String(top.location);
	var cur_location = new String(document.location);
	parent_location = parent_location.toLowerCase();
	top_location = top_location.toLowerCase();
	cur_location = cur_location.toLowerCase();

	if ( top_location != cur_location && parent_location.indexOf('$home_url') != 0 )
		return;
		
	if ($('html.ie7').length) {
		$('#product-area > .overlay').hide();
		$('#footer').toggleClass('foo');
	}
	
	$('a.popup, a.outsideLink').click(function(){
		newWin($(this).attr('href'), 500, 500, $(this).text());
		return false;
	});
		
    $('input.autofill').each(function(){
        var $$ = $(this);
        var $l = $('label[for="'+$$.attr('id')+'"]');
        $l.hide();

        $$.focus(function(){
            if ($.trim($$.val()) == $l.text()) {
                $$.val('');
            }

            $$.removeClass('blur');
        });

        $$.blur(function(){
            if ($.trim($$.val()) == '') {
                $$.val($l.text());
            }

            $$.addClass('blur');
        });

        $$.blur();
    });

	if ($('.social').length) {
		$('.social .share').hover(function(){
			addthis_open(this, '', '[URL]', '[TITLE]');
		}, function(){
			addthis_close();
		}).click(function(){
			addthis_sendto();
			return false;
		});
		
		$('.social .print').click(function(){
			window.print();
			return false;
		});
	}
	
	if ($('a.lightbox').length > 0) {
		$.fn.fancybox.build();
		$('a.lightbox').fancybox({
			padding: 50,
			frameWidth: 642
		});
	}

		
	// HOME STUFF
	
	if ($('#main-home').length) {
		$('#main-home .overlay').click(function(){
			if ($('#main-home embed, #main-home object').length) {
				$('#main-home embed, #main-home object').get(0).sendEvent('PLAY');
			}
			$('#main-home .safeHide').removeClass('safeHide');
			$(this).fadeOut();
			if (typeof(pageTracker) != 'undefined') {
				pageTracker._trackEvent('Content', 'Play', 'Home -> Crafting Higher Standards');
			}
			return false;
		});
	}
	
	if ($('#email-signup-form').length) {
		$('#email-signup a').click(function(){
			$('#email-signup-form').fadeIn();
			return false;
		});
		
		$('#email-signup-form').ajaxForm({
			url: 'http://marketlive.us1.list-manage.com/subscribe/post-json?u=4c4fae7dc67ebb7babf27dc7d&id=4019e713eb&c=?',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			success: function(r){
				if (r.result == 'success') {
					$('#signup-success').text(r.msg).parent().css('display', 'block');
					$('#email-signup-form fieldset:first-child').fadeOut();
					
					if (typeof(pageTracker) != 'undefined') {
						pageTracker._trackEvent('Form', 'Signup', 'Email');
						pageTracker._trackPageview('/ancillary/thankyou.do');
					}
				} else {
					$('#email-signup-form label').addClass('error');
				}
			}
		});
	}
	
	// END HOME STUFF
		
	$('img[name="s_i_mllcfdannerrev"], img[name="s_i_mllcfdannerprod"]').addClass('safeHide');
	
	// CHECKOUT STUFF
	
	if ($('#cart-list').length) {
		$('.removeLink').click(function(){
			if (typeof(removeItem) != 'undefined') {
				removeItem($(this).parents('.productAction').parent().metadata({type:'elem',name:'script'}).pk);
			}
			return false;
		});
	
		$('.updateLink').click(function(){
			$('#mainForm').submit();
			return false;
		});
		
		$('#cart-list .detail').change(function(){
			setTimeout(function(){ $('#mainForm').submit(); }, 300);
		});
		
		if ($('html.ie7').length) {
			var index = 99;
			$('#cart-list li').each(function(){
				$(this).css('z-index', index);
				index = index - 1;
			});
		}
	}
		
	// PRODUCT STUFF
	
	// proudct option validation
	var $$ = $('#product-display #mainForm');
	if ($$.length) {
		$$.submit(function(){
			if ($('input[name="option"]', this).val().match(/^\d+=0$/)) {
				if (!$('.errormsg', this).length) {
					$('.prodButtons').prev().before('<div class="errormsg" style="display: none;">Please select an option below...</div>');
					$('.errormsg', this).show('fast');
				}
				return false;
			} else {
				$('.errormsg', this).hide('fast', function(){
					$(this).remove();
				});
			}
			
			return true;
		});
		
		$('.prodQty', $$).blur(function(){
			if (!$(this).val()) $(this).val(1);
		});
		
		$('select.detail', $$).change(function(){
			if ($(this).val()) $('.errormsg', $$).hide('fast', function(){ $(this).remove(); });
		});
	}
	
	if ($('#product-list, #crosssell-list, #recovery-list').length) {
		var foldCheck = function() {
			var threshold = 20;
			var hLimit = $(window).scrollTop() + $(window).height() + threshold;
			var wLimit = $(window).scrollLeft() + $(window).width();
		
			$('#product-list, #crosssell-list, #recovery-list').find('li:visible:not(.fetched, .specialContent)').each(function(){
				var elPos = $(this).position();
				if (elPos.top < hLimit && elPos.left < wLimit) {
					$(this).addClass('fetched');
					$('.prodThumbImage img', this)
						.attr('src', $(this).metadata({type: 'elem', name: 'script'}).image)
						.load(function(){
							$(this).attr('width', $(this).width());
							$(this).attr('height', $(this).height());
						});
				}
			});
		};
		
		foldCheck();
	
		var foldCheckTimeoutId = 0;
		var foldTimeout = function(){
			clearTimeout(foldCheckTimeoutId);
			foldCheckTimeoutId = setTimeout(foldCheck, 100);
		};
		$(window).scroll(foldTimeout).resize(foldTimeout);
	}
	
	if ($('#product-details').length) {
		var q = $.cookie('filter_query');
		if (q) {
			var baseUrl = $('#breadcrumb a:last-child').attr('href')+'#/?';
			
			$.each(q.split('&'), function(i){
				var part = this.split('=');
				var filter = part[0];
				var option = part[1];
				
				if (!i) baseUrl = baseUrl.concat('&');
				
				baseUrl = baseUrl.concat(this+'');
				
				if (typeof(filters[filter]) != 'undefined') {
					var content = '<a href="'+baseUrl+'">'+filters[filter].options[option].title+'</a>';
					
					if (i) content = ' / ' + content;
					$('#breadcrumb').append(content);
				}
			});
		}
		
		var $tabs = $('#product-details').tabs({ fx: { opacity: 'toggle' } });
		$(window).load(function(){
			var intervalHolderReview = setInterval(function(){
				if ($('.prSnippetReadReviews .prSnippetLink').length) {
					clearInterval(intervalHolderReview);
					
					$('.prSnippetReadReviews .prSnippetLink').click(function(){
						$tabs.tabs('select', $tabs.tabs('length') - 1);
						$.scrollTo('#product-details', {
							easing: 'easeInOutQuart',
							duration: 1500,
							offset: {top: -20}
						});
						return false;
					});
				}
			}, 300);
			
		});
	
	}
	
	// END PRODUCT STUFF
	
	if ($('#product-details, #cart-list:not(.availability, .order), #bill-state, #bill-country').length) {
		// set up interval to check for select existance along with function
		var intervalHolderSelect = setInterval(function(){
			if ($('#mainForm select, #bill-state, #bill-country').length) {
				clearInterval(intervalHolderSelect);
				var title;
				
				var blurFunc = function(e){
					if (!$(e.target).parents('.selector-options').length) {
						$('body').unbind('mousedown', blurFunc);
						$('.selector-options').data('bound', false);
						$('.selector-options dd').not(':animated').slideUp('fast');
					}
				};
				
				$('#mainForm select').not('#bill-state, #bill-country').each(function(){
					var $s = $(this);
					var id = 'so-'+$s.attr('name').replace(/\./g, '');
					if ($s.val()) {
						title = $(':selected', $s).text();
					} else {
						title = $('option:first-child', $s).text();
					}
					$s.hide().before('<dl id="'+id+'" class="selector-options"><dt>'+title+'</dt><dd><ul></ul></dd></dl>');
					
					$s.change(function(){
						var title = $(':selected', this).text();
						$(this).prev().find('dt').text(title);
					});
					
					$s.children().each(function(){
						var v = $(this).attr('value');
						var t = $(this).text();
						var s = $('#'+id);
					
						if (v == 0) return;
					
						var content = '<li id="option-'+v+'">'+t+'</li>';
						if (t.search(/Out of Stock\s*$/) !== -1) content = '<li id="option-'+v+'" class="disabled">'+t+'</li>';
						$('ul', s).append(content);
						$('ul li.disabled', s).click(function(){ return false; });

						$('#option-'+v+':not(.disabled)').click(function(){
							$s.val($(this).attr('id').replace(/^option-/, '')).change();
							blurFunc({target: $('body').get(0)});
						}).hover(function(){
							$(this).css({ backgroundColor: '#d5ccbb'});
						}, function(){
							$(this).css({ backgroundColor: '#E4DFD6'});
						});
					});
				});

				$('.selector-options').hover(function(){
					$(this).css({ backgroundColor: '#d5ccbb'});
				}, function(){
					$(this).css({ backgroundColor: '#E4DFD6'});
				}).click(function(){
					if (!$(this).data('bound')) {
						$(this).data('bound', true);
						$('body').bind('mousedown', blurFunc);
					}
					if ($('dd:visible', this).length) {
						$('dd', this).not(':animated').slideUp('fast');
					} else {
						$('dd', this).not(':animated').slideDown('fast');
					}
				});
			}
		}, 300);
	}

	$('body').append('<div id="lights-off"></div>');
	$('#lights-off').css('opacity', 0.8).click(function(){
		$('#video-close').click();
	});
	
	
	// Prep product list
	$('#product-list li:not(.specialContent)').each(function(i){
		// Generate unique ids for products in list
		$(this).attr('id', 'product-'+$(this).metadata().code);
		
		// Add price to data
		var price = parseFloat($.trim($('.prodThumbPrice', this).text().replace(/^\s*\$/, '')));
		var name = $('.prodThumbName', this).text();
		$(this).data('price', price);
		$(this).data('name', name);
		$(this).data('rating', 0);
		$(this).data('image', $(this).metadata().image);
		$(this).data('featured', $(this).metadata().ordinal);
	});
	
	// Get review content
	if ($('#product-area').length) {
		if (typeof(reviewData) != 'undefined') {
			var rating = 0;
			$.each(reviewData, function(){
				rating = parseFloat(this.rating);
				$('#product-'+this.id).data('rating', rating)
					.find('.pr_snippet_category').append('<div class="stars rating'+(rating*10)+'"></div>');
			});
		}
		
		if (typeof(directoryContent[categoryId]) != 'undefined') {
		if (typeof(directoryContent[categoryId].baseImage) != 'undefined') {
			var callout = directoryContent[categoryId];
			var content = '<li class="specialContent"><a href="#"><img src="'+callout.baseImage+'"/></a></li>';
			
			if ($('#product-list li:not(.disabled)').length > 6) {
				$('#product-list li:not(.disabled):eq(6)').before(content);
			} else {
				$('#product-list').append(content);
				$('#product-list .specialContent').hide();
			}
			$('body').append('<div id="video-box-wrap" class="safeHide"><div id="video-bg"><div id="video-box"><a href="." id="video-close"><img src="http://www.danner.com/images/en_us/global/globalgraphics/09/close-btn.png" alt="Close"/></a><div id="video-content"><embed src="http://video.danner.com/players/'+callout.video.id+'-66759-48478.swf" id="video-player" name="video-player" class="videoPlayer" width="722" height="408" allowfullscreen="true" allowscriptaccess="always"/><div id="video-info"><h3 class="videoTitle">'+callout.video.title+'</h3><a href="http://standards.danner.com/">View More Stories</a></div></div></div></div></div>');
			// Preload hover image
			var img = new Image();
			img.src = callout.hoverImage;
			
			// Register hover event
			$('#product-list .specialContent a')
				.live('mouseover', function(){
					$('img', this).attr('src', callout.hoverImage);
				}).live('mouseout', function(){
					$('img', this).attr('src', callout.baseImage);
				}).live('click', function(){
					$('#lights-off').removeClass('safeHide').css('opacity', 0.5);
					
					if ($('html.ie').length) {
						$('#video-box-wrap').removeClass('safeHide');
					} else {
						$('#video-box-wrap').removeClass('safeHide').fadeTo('normal', 1);
					}
					if ($('html.ie').length) {
						$('#video-player').get(0).sendEvent('PLAY', true);
					} else {
						if (playerLoaded) {
							$('#video-player').get(0).sendEvent('PLAY', true);
						}
					}
					
					if (typeof(pageTracker) != 'undefined') {
						pageTracker._trackEvent('Content', 'Play', 'Boots -> Crafting Higher Standards');
					}
					
					return false;
				});
			
			if ($('html.ie').length) {
				$('#lights-off').css({opacity: 0, display: 'block'}).addClass('safeHide');
				$('#video-box-wrap').css({display: 'block'}).addClass('safeHide');
			} else {
				$('#video-box-wrap, #lights-off').css({opacity: 0, display: 'block'}).addClass('safeHide');
			}
			$('#video-close').live('click', function(){
				if ($('html.ie').length) {
					$('#video-box-wrap').addClass('safeHide');
					$('#lights-off').css('opacity', 0).addClass('safeHide');
					if (playerLoaded) {
						$('#video-player').get(0).sendEvent('SEEK', 0);
						$('#video-player').get(0).sendEvent('PLAY', false);
					}
				} else {
					$('#video-box-wrap').fadeTo('normal', 0, function(){
						$(this).addClass('safeHide');
						$('#lights-off').css('opacity', 0).addClass('safeHide');
						if (playerLoaded) {
							$('#video-player').get(0).sendEvent('SEEK', 0);
							$('#video-player').get(0).sendEvent('PLAY', false);
						}
					});
				}
				return false;
			});
		}
		}
	}
	
	// Preload CSS images
	if (typeof(jQuery.preloadCssImages) != 'undefined') $.preloadCssImages();

	$('#product-list li:not(.specialContent)').each(function(){
		var data = $(this).metadata().options;
		if (!data) return;
		
		$.each(data, function(option, value){
			if (typeof(availableFilters[option]) == 'undefined') {
				availableFilters[option] = [];
				filterList.push(option);
			}
			
			if ($.isArray(value)) {
				$.each(value, function(){
					var val = ''+this; // Force string
					if ($.inArray(val, availableFilters[option]) == -1) {
						availableFilters[option].push(val);
					}
				});
			} else {
				if ($.inArray(value, availableFilters[option]) == -1) {
					availableFilters[option].push(value);
				}
			}
		});
	});
	
	// Generate menu
	if ($('#directory-filter').length) {
		$('#directory-filter').append('<ul id="filter-list"></ul>');
		$.each(filterList, function(){
			var cFilter = ''+this; // Force string
			if (availableFilters[cFilter].length > 1 && typeof(filters[cFilter]) != 'undefined') { // Greater than one to get rid of filters that only have one option
				var fId = 'filter-'+cFilter;
				$('#filter-list').append('<li><dl id="'+fId+'"><dt>'+filters[cFilter].title+'</dt><dd><ul></ul></dl></li>');
			
				// Add multi class to DOM
				if (filters[cFilter].multi) {
					$('#'+fId).addClass('multi');
				}
			
				switch (cFilter) {
					default:
						$.each(filters[cFilter].options, function(option, meta){
							if ($.inArray(option, availableFilters[cFilter]) !== -1) {
								$('#'+fId+' ul').append('<li id="option-'+option+'">'+meta.title+'</li>');
							}
						});
				}
			}
		});
	
		$('#clear-filters').click(function(){
			jQuery.address.value('?');
			return false;
		});
	
		// Mouse events for filter menu
		$('#filter-list > li, #sort-wrap dl')
			.mousedown(function(){
				return false; // disables text selection
			}).hoverIntent({
				sensitivity: 10,
				timeout: 300,
				over: function(){
					$('ul', this).not(':animated').slideDown('fast');
					$('div', this).addClass('over');
				},
				out: function(){
					$('ul', this).slideUp('fast');
					$('div', this).removeClass('over');
				}
			});
	
		$('#filter-list ul li')
			.click(processClick);
		
		$('#sort-wrap li')
			.click(function(){
				$(this).parent().css('display', '');
				var param = $(this).attr('id').replace(/^option-/, '');
				var query = jQuery.address.queryString();
			
				// search for "sort" key in url
				if (query.search(new RegExp('^(.*&)?sort=')) != -1) {
					query = query.replace(new RegExp('&?sort=[^&]+'), '').concat('&sort='+param);
				} else {
					query = query.concat('&sort='+param);
				}
			
				query = query.replace(/^&+|&+$/g, '');
			
				jQuery.address.value('?'+query);
			
				// doSort(part[1], part[2]);
				return false;
			});

		$('#filter-list ul li, #sort-wrap li')
			.hover(function(){
				$(this).not('.active, :animated').fadeTo('fast', 0.99);
			}, function(){
				$(this).not('.active').fadeTo('fast', 0.5, function(){
					$(this).attr('style', '');
				});
			});
	}
		
	if (!$('#filter-list li').length) $('#directory-filter').hide();
	
	
	if ($('#product-area').length) {
		jQuery.address.change(function(event) {  
			var params = {};
			var query = getQuery();
			
			if (query.length) {
				$.each(event.queryString.split('&'), function(){
					var part = this.split('=');
					var filter = part[0];
					var option = part[1];
			
					if (typeof(filters[filter]) == 'undefined' && filter != 'sort') return;
			
					if (filter != 'sort' && filters[filter].multi) {
						if (typeof(params[filter]) == 'undefined') {
							params[filter] = [];
						}
		
						params[filter].push(option+'');
					} else {
						params[filter] = option+'';
					}
				});
			}
			
			// Check for specific category header content
			$c = $('#category-header');
			if ($c.not(':animated').css('opacity') < 1 || $c.not(':animated').css('display') == 'none') {
				$c.css({
					display: 'block',
					opacity: 0
				});
			
				if (event.path != '' && event.path != '/') {
					categoryPath = event.path;
			
					if (typeof(directoryContent[categoryPath]) != 'undefined') {
						if (typeof(directoryContent[categoryPath].headImage) != 'undefined' && typeof(directoryContent[categoryPath].headCopy) != 'undefined' && typeof(directoryContent[categoryPath].headTitle) != 'undefined') {
							$c.html(headerTemplate.replace('{title}', directoryContent[categoryPath].headTitle).replace('{copy}', directoryContent[categoryPath].headCopy).replace('{image}', directoryContent[categoryPath].headImage));
							if (isIE) {
								$c.find('*').css('opacity', 0);
							}
						}
					}
				}

				$('#category-header img:eq(0)').load(function(){
					if (isIE) {
						$c.find('*').animate({
							opacity: 1
						}, 'slow');
					} else {
						$c.animate({
							opacity: 1
						}, 'slow');
					}
				});
			}

			setTimeout(function(){
				if ($c.not(':animated').css('opacity') < 1) {
					$c.animate({
						opacity: 1
					}, 'slow');
				}
			}, 1000);
			
			
			if (pageLoaded || query.length) {
				pageLoaded = true;
				$('#product-area > .overlay').fadeIn('fast', function(){
					// Test for empty object
					for (var p in params) {
						var filtered = false;
						// object not empty
	
						// Clear any previous filter
						$('#filter-list .active').removeClass('active');
						$('#filter-list dl .disabled').removeClass('disabled');
	
						$.each(params, function(option, value){
							if (option == 'sort' || typeof(filters[option]) == 'undefined') return;
							if (filters[option].multi) {
								$.each(value, function(){
									$('#option-'+this).enable();
								});
							} else {
								$('#option-'+value).enable();
							}
							filtered = true;
						});
				
						$('#filter-list li.selected').not(':has(.active)')
							.removeClass('selected')
							.find('div').remove();
	
						doFilter();
				
						if (filtered) {
							$('#clear-filters').show();
						} else {
							$('#clear-filters').hide();
						}
				
						// Function needed for delaying final steps for filters dependant on external sources
						var finishUp = function() {
							if ($('#product-list li:not(.specialContent, .disabled)').length < 7) {
								$('#product-list .specialContent').hide();
							} else {
								$('#product-list .specialContent').show().insertBefore('#product-list li:not(.specialContent, .disabled):eq(6)');
							}

							$('#product-area > .overlay').fadeOut('fast', function(){
								foldCheck();
							});
						};


						if (typeof(params['sort']) != 'undefined') {
							var parts = params['sort'].split('-');
					
							doSort(parts[0], parts[1]);
							finishUp();
						} else {
							doSort(false);
							finishUp();
						}
						
						if ($('html.ie7').length) {
							$('#footer').toggleClass('foo');
						}
				
						return; // go no further!
					}
	
					// If we got here, params is empty so clear filter and sort
					$('#filter-list .selected').removeClass('selected');
					$('#filter-list .active').removeClass('active');
					$('#filter-list .disabled').removeClass('disabled');
					$('#filter-list div').remove();
			
					$('#clear-filters').hide();
			
					doSort(false);
					doFilter();
			
					if ($('html.ie7').length) {
						$('#footer').toggleClass('foo');
					}

					if ($('#product-list li:not(.specialContent, .disabled)').length < 7) {
						$('#product-list .specialContent').hide();
					} else {
						$('#product-list .specialContent').show().insertBefore('#product-list li:not(.specialContent, .disabled):eq(6)');
					}

					$('#product-area > .overlay').fadeOut('fast');
				});
	
				$.cookie('filter_query', $.address.queryString(), {expires: 10, path: '/'});
			} else {
				if ($('#product-area > .overlay:visible').length) {
					$('#product-area > .overlay').fadeOut('fast', function(){
						foldCheck();
					});
				} else {
					foldCheck();
				}
				$('#clear-filters').hide();
				pageLoaded = true;
			}
			
			
			if (pageTitle) $.address.title(pageTitle);
		});
	}
	
	function processClick(e) {
		$$ = $(e.target);
		
		// Close menu
		$$.parents('ul:visible').not('#filter-list').css('display', 'none');
		
		
		var option = $$.attr('id').replace(/^option-/, '');
		var filter = $$.parents('dl').attr('id').replace(/^filter-/, '');
		
		var path = toggleOption(filter, option);
		jQuery.address.value('?'+path);
	};
	
	// --------- Common Functions --------- //
	var fadeProductListOut = function(callback) {
		$('#product-area > .overlay').fadeIn(callback);
	};
	
	var fadeProductListIn = function(callback) {
		$('#product-area > .overlay').fadeOut(callback);
	};
	
	var getOptionKey = function(e) {
		if ($(e).length) {
			return $(e).attr('id').replace(/^option-/, '');
		}
	};
	
	var getFilterKey = function(e) {
		if ($(e).parents('dl').length) {
			return $(e).parents('dl').attr('id').replace(/^filter-/, '');
		}
	};
	
	var toggleOption = function(filterName, optionName, path) {
		if (optionName === false) {
			jQuery.address.value('');
			return false;
		}
		
		var query = path? path: getQuery();
		var params = {};
		
		var newParam = filterName+'='+optionName;
		var paramRegExp = new RegExp('&?'+newParam);
		var glue = query.length? '&': '';
		
		var tracking = typeof(pageTracker) != 'undefined';
		
		if (filters[filterName].multi) {
			if (query.search(paramRegExp) == -1) {
				// Adding
				if (tracking) pageTracker._trackEvent('Filters', 'Apply', filters[filterName].title+' > '+filters[filterName].options[optionName].title);
				query = query.concat(glue+newParam);
			} else {
				// Removing
				if (tracking) pageTracker._trackEvent('Filters', 'Remove', filters[filterName].title+' > '+filters[filterName].options[optionName].title);
				query = query.replace(paramRegExp, '');
			}
		} else {
			// Search for filter in query
			if (query.search(new RegExp('^(.*&)?'+filterName+'=')) != -1) {
				if (query.search(new RegExp('^(.*&)?'+newParam)) != -1) {
					// Removing
					if (tracking) pageTracker._trackEvent('Filters', 'Remove', filters[filterName].title+' > '+filters[filterName].options[optionName].title);
					query = query.replace(paramRegExp, '');
				} else {
					// Switching
					if (tracking) pageTracker._trackEvent('Filters', 'Apply', filters[filterName].title+' > '+filters[filterName].options[optionName].title);
					query = query.replace(new RegExp('&?'+filterName+'=[^&]+'), '').concat(glue+newParam);
				}
			} else {
				// Adding
				if (tracking) pageTracker._trackEvent('Filters', 'Apply', filters[filterName].title+' > '+filters[filterName].options[optionName].title);
				query = query.concat(glue+newParam);
			}
		}
		
		return query.replace(/^&+|&+$/g, '');
		
	};
	
	var doFilter = function() {
		var activeFilters = getCurrentFilters();
		var filterCount = $('#filter-list dl:has(.active)').size();

		var query = getQuery();

		$('#filter-breadcrumb').empty();
		if (query.length) {
			$.each($.address.queryString().split('&'), function(){
				var part = this.split('=');
				var filter = part[0];
				var option = part[1];
				if (filter == 'sort' || typeof(filters[filter]) == 'undefined') return;
				$('#filter-breadcrumb').append(' \\ <span class="bread-'+filter+'-'+option+'">'+filters[filter].options[option].title+'</span>');
			});
			
			$('#filter-breadcrumb').html($('#filter-breadcrumb').html().replace(/\\+\s*$/, ''));
		}
		
		$('#filter-breadcrumb span').click(function(){
			var path = $.address.queryString();
			$(this).nextAll().each(function(){
				var filter = $(this).attr('class').replace(/^bread-/, '').split('-', 1);
				var option = $(this).attr('class').replace(/^bread-[^-]+-/, '');
				path = toggleOption(filter, option, path);
			});
			jQuery.address.value('?'+path);
		});

		if (filterCount == 0) {
			$('#product-list li:not(.specialContent)').removeClass('disabled');
		} else {
			// Now compare filter against product list
			$('#product-list li:not(.specialContent)').each(function(){
				var data = $(this).metadata().options;
				var pass = true; // Default to passing validation
				$.each(activeFilters, function(filter, option){
					if ($.isArray(option)) {
						$.each(option, function(){
							var val = ''+this;
							if ($.inArray(val, data[filter]) == -1) {
								pass = false;
							}
						});
					} else {
						if ($.inArray(option, data[filter]) === -1) {
							pass = false;
						}
					}
				});

				if (!pass) {
					$(this).addClass('disabled');
				} else {
					$(this).removeClass('disabled');
				}
			});

		}

		// Disabled filter options in sidebar that don't apply to current filtered products
		// Find and create available filters
		var filteredFilters = [];
		$('#product-list li:not(.specialContent)').not('.disabled').each(function(){
			var data = $(this).metadata().options;

			$.each(data, function(option, value){
				if (typeof(filteredFilters[option]) == 'undefined') {
					filteredFilters[option] = [];
					filterList.push(option);
				}

				if ($.isArray(value)) {
					$.each(value, function(){
						var val = ''+this; // Force string
						if ($.inArray(val, filteredFilters[option]) == -1) {
							filteredFilters[option].push(val);
						}
					});
				} else {
					if ($.inArray(value, filteredFilters[option]) == -1) {
						filteredFilters[option].push(value);
					}
				}
			});
		});

		// Iterate through master filter list
		$.each(filterList, function(){
			var cFilter = ''+this; // Force string
			$.each(availableFilters[cFilter], function(){
				if (typeof(filteredFilters[cFilter]) != "undefined") {
					if ($.inArray(''+this, filteredFilters[cFilter]) === -1) {
						$('#option-'+this).addClass('disabled');
					}
				}
			});
		});
		
		// Look for switchable options in filter lists
		$('#filter-list .optional').removeClass('optional');
		$.each(activeFilters, function(filter, option){
			if (!filters[filter].multi) {
				var tempFilters = {};
				var prodOptions;
				$.each(activeFilters, function(subfilter, suboption){
					if (subfilter != filter) {
						tempFilters[subfilter] = suboption;
					}
				});
				
				prodOptions = getCommonProductOptions(tempFilters);
				
				$.each(prodOptions[filter], function(){
					$('#option-'+this+'.disabled').removeClass('disabled').addClass('optional');
				});
			}
		});


		$('#filter-list dl').each(function(){
			if ($('li', this).not('.disabled').size() < 2 && !$('.active', this).length && !$(this).hasClass('multi')) {
				$(this).parent().not(':hidden').animate({
					width: 0,
					opacity: 0
				}, 'fast', function(){
					$('dl', this).addClass('disabled');
					$(this).attr('style', '');
					$(this).hide();
				});
			} else {
				$(this).parent().show();
				$(this).removeClass('disabled');
			}
		});
	};

	var doSort = function(field, direction) {
		fadeProductListOut(function(){
			var pIds = [];
			var dir = (direction? direction.toUpperCase(): 'ASC'); // or DESC

			// Update the parent element to reflect the selection
			if (field) {
				$('#sort-wrap dt').text($('#option-'+field+(direction? '-'+direction: '')).text());
			}

			// Get array of list ids
			$('#product-list li:not(.specialContent)').each(function(){
				pIds.push($(this).attr('id'));
			});

			var sortFunc;
			switch (field) {
				case 'featured':
				case 'rating':
				case 'price':
					sortFunc = function(a, b){
						if (dir == 'ASC') {
							return $('#'+a).data(field) - $('#'+b).data(field);
						} else {
							return $('#'+b).data(field) - $('#'+a).data(field);
						}
					};
					break;

				case 'name':
					sortFunc = function(a, b){
						var out;
						var keyA = $('#'+a).data(field).toUpperCase();
						var keyB = $('#'+b).data(field).toUpperCase();

						if (keyA < keyB) out = -1;
						if (keyA > keyB) out = 1;

						if (dir == 'DESC') out = out * -1;
						return out;
					};
					break;
					
			}

			if (sortFunc) {
				pIds.sort(sortFunc);
			
				$.each(pIds, function(){
					$('#product-list').append($('#'+this));
				});
			}
			
			if (typeof(pageTracker) != 'undefined') {
				pageTracker._trackEvent('Sort', 'Apply', $('#option-'+field+(direction? '-'+direction: '')).text());
			}

			fadeProductListIn();
		});
	};

	var getCurrentFilters = function() {
		var activeFilters = {};
		// Get filter values
		$('#filter-list dl:has(.active)').each(function(){
			var size = $('.active', this).size();
			var filter = $(this).attr('id').replace(/^filter-/, '');
			var option;
			if (!$(this).hasClass('multi')) {
				option = $('.active', this).attr('id').replace(/^option-/, '');
			} else {
				option = [];
				$('.active', this).each(function(){
					option.push($(this).attr('id').replace(/^option-/, ''));
				});
			}

			activeFilters[filter] = option;
		});

		return activeFilters;
	};
	
	var getCommonProductOptions = function(appliedOptions) {
		var activeProducts = [];
		
		// Compare filter against product list
		$('#product-list li:not(.specialContent)').each(function(){
			var data = $(this).metadata().options;
			var pass = true; // Default to passing validation
			$.each(appliedOptions, function(filter, option){
				if (option != null) {
					if ($.isArray(option)) {
						$.each(option, function(){
							var val = ''+this;
							if ($.inArray(val, data[filter]) == -1) {
								pass = false;
							}
						});
					} else {
						if ($.inArray(option, data[filter])) {
							pass = false;
						}
					}
				}
			});

			if (pass) {
				activeProducts.push(this);
			}
		});
		
		var filteredFilters = {};
		$.each(activeProducts, function(){
			var data = $(this).metadata().options;
		
			$.each(data, function(option, value){
				if ($.isArray(value)) {
					if (typeof(filteredFilters[option]) == 'undefined') {
						filteredFilters[option] = [];
					}

					$.each(value, function(){
						var val = ''+this; // Force string
						if ($.inArray(val, filteredFilters[option]) == -1) {
							filteredFilters[option].push(val);
						}
					});
				} else {
					if ($.inArray(value, filteredFilters[option]) == -1) {
						filteredFilters[option].push(value);
					}
				}
			});
		});
		
		return filteredFilters;
		
	};

	var optionCount = function(filter, option) {
		var count = 0;
		$('#product-list li:not(.specialContent)').each(function(){
			var data = $(this).metadata().options;

			if (($.isArray(data[filter]) && $.inArray(option, data[filter]) != -1) || data[filter] == option) {
				count += 1;
			}
		});

		return count;
	};
	
	jQuery.fn.enable = function() {
		var title;
		
		$(this)
			.toggleClass('active')
			.removeClass('disabled');

		$(this).parents('li').addClass('selected');

		var isMulti = $(this).parents('dl').hasClass('multi');
		if (!isMulti) {
			$(this).siblings().removeClass('active');
		}
		
		var filter = getFilterKey(this);
		var option = getOptionKey(this);
		
		if (typeof(filters[filter]) == 'undefined') return;
		
		// Add selection title to div
		var dd = $(this).parents('dd');
		if (dd.find('.active').length > 1) {
			title = '[Multiple] ...';
		} else {
			title = filters[filter].options[option].title;
		}
		if (!dd.find('div').length) {
			// dd.prepend('<div></div>');
			dd.prepend('<div></div>').find('div').click(function(){
				$p = $(this).parents('dl');
				var path = $.address.queryString();
				$p.find('.active').each(function(){
					path = toggleOption($p.attr('id').replace(/^filter-/, ''), $(this).attr('id').replace(/^option-/, ''), path);
				});
				
				jQuery.address.value('?'+path);
				$p.find('ul').css('display', 'none');
			}).hover(function(){
				$(this).not(':animated').fadeTo('fast', 0.99);
			}, function(){
				$(this).fadeTo('fast', 0.5, function(){
					$(this).attr('style', '');
				});
			});
		}
		dd.find('div').text(title);

	};
	
	// IE7 :after fix
	if ($('html.ie7').length) {
		$('#order-details .smallHeader a, #cart-summary a, #main-home .right a, #cart-help .outsideLink, #kickers-4 div, #cvv2-link')
			.append('<img src="/images/en_US/global/globalgraphics/09/arrow-right.png" style="display: inline; padding-left: 5px;"/>');
	}
	
});

function newWin(url, w, h, winName) {
	l = parseInt((screen.width/2) - (w/2), 10);
	t = parseInt((screen.height/2) - (h/2), 10);
	var win = window.open(url, "popup", 'width='+w+',height='+h+',left='+l+',top='+t+',resizable=yes,status=no,toolbar=no,menubar=no,location=no,scrollbars=yes');
	win.focus();
}

function getQuery() {
	return jQuery.address.queryString()? jQuery.address.queryString() : '';
}