var filterList = [];
var availableFilters = [];
var ratingsLoaded = false;
var intervalHolder = null;
var directoryContent;
var categoryId = null;
var playerLoaded = false;
var pageLoaded = false;
var playerReady;

// Config for metadata, only for directory page
jQuery(function($){
	var tracking = typeof(pageTracker) != 'undefined';
	
	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;
		});
	}

	$('#nav > li').hoverIntent(function(){
		$(this).addClass('over');
		$('ul', this).fadeIn(200);
	}, function(){
		$(this).removeClass('over');
		$('ul', this).fadeOut(200);
	});
	
	$('#nav > li > ul').prepend('<li class="shade"></li>');
		
	// HOME STUFF
	
	if ($('#main-home').length) {
		$('#main-home > img:nth-child('+Math.ceil(Math.random()*$('#main-home > img').length)+')').css('display', 'block');
	}
	
	if ($('#email-signup-form').length) {
		$('#email-signup-form').ajaxForm({
			url: 'http://marketlive.us1.list-manage.com/subscribe/post-json?u=4c4fae7dc67ebb7babf27dc7d&id=3d74ca210c&c=?',
			type: 'GET',
			dataType: 'json',
			contentType: "application/json; charset=utf-8",
			beforeSubmit: function(){
				$('#email-signup-form').fadeOut();
			},
			success: function(r){
				$('#email-signup-form').fadeIn();
				if (r.result == 'success') {
					$('#email-signup-form').parents('ul').html('<li><p>'+r.msg+'</p></li>');
				} else {
					var p = $('#email-signup-form').get(0);
					var $$ = $('.errorblock', p);
					if (!$$.length) {
						$(p).append('<p class="errorblock"></p>');
						$$ = $('.errorblock', p);
					}
					
					$$.text(r.msg.replace(/^0 - /, ''));
				}
			}
		});
	}
	
	// END HOME STUFF
		
	$('body > img').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);
		});
		
		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(); });
		});
	}
	
	// Category Stuff //
	if ($('#cat-head').length) {
		$('#content-close').click(function(){
			$(this).fadeOut('slow');
			$('.botrplayer embed, .botrplayer object').each(function(){
				if (typeof(this.sendEvent) != 'undefined') {
					this.sendEvent('PLAY', false);
				}
			});
			$('#cat-head .video:visible, #cat-head .html-content:visible').fadeOut('slow', function(){
				$('#cat-head').animate({
					height: $('#cat-head > img').height()
				}, 'slow', function(){
					$('#cat-head > img').fadeIn('slow');
				});
			});
		});
		
		$('#cat-head li').click(function(){
			if (tracking) pageTracker._trackEvent('Features', $(':header', this).text(), 'play');
			var loadContent;
			var data = $(this).metadata({type: 'elem', name: 'script'});
			if (data.action == 'video') {
				if ($('html.ie7').length && !playerLoaded) {
					// Reload video
					eval('botr_'+data.content+'_66759_52531.loadSWF();');
				}
				loadContent = function(){
					playerReady = function(obj) {
						playerLoaded = true;
						document.getElementById(obj['id']).sendEvent('PLAY');
					};
					
					$('#cat-head').animate({
						height: ($('#video-'+data.content).height()+$('#cat-head-foot').height())+"px"
					}, 'slow', function(){
						$('#video-'+data.content).fadeIn('slow');
						$('#content-close').fadeIn('slow');
					});
				};
			} else {
				// ajax content here
				loadContent = function(){
					$('#cat-head .html-content').load(data.content, function(){
						$('#cat-head .html-content').append('<div class="clear"></div>');
						$('#cat-head').animate({
							height: ($('#cat-head .html-content').height()+$('#cat-head-foot').height())+"px"
						}, 'slow', function(){
							$('#content-close').fadeIn('slow');
							$('#cat-head .html-content').fadeIn('slow');
						});
					});
				};
			}
			
			if ($('#cat-head > img:visible').length) {
				$('#cat-head').height($('#cat-head > img').height());
				$('#cat-head > img:visible').fadeOut('slow', loadContent);
			} else {
				$('#cat-head .video:visible, #cat-head .html-content:visible').fadeOut('slow', loadContent);
			}
			
			return false;
		});

		if (window.location.hash.length) {
			switch (window.location.hash) {
				case '#openfeature=1':
					$(window).load(function(){
						$('#cat-head li:first-child').click();
					});
					break;
				case '#openfeature=2':
					$(window).load(function(){
						$('#cat-head li:last-child').click();
					});
					break;
				default:
					break;
			}
		}
		
		// find products only in last row
		var count = $('#product-list > li').length;
		var maxIndex = (Math.floor(count/4) * 4) - 1;
		$('#product-list > li:gt('+maxIndex+')').css('background-image', 'none');
	}
	
	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>';
					
					content = ' <span class="breadcrumb-sep"></span> ' + content;
					$('#breadcrumb').append(content);
				}
			});
		}
		
		var $tabs;
		if ($('html.ie7').length) {
			$tabs = $('#product-details').tabs();
		} else {
			$tabs = $('#product-details').tabs({ fx: { opacity: 'toggle' } });
		}
		$('.tabs a').mousedown(function(){
			if ($(this).parent().hasClass('ui-state-active')) {
				$.scrollTo('#product-details', {
					easing: 'easeInOutQuart',
					duration: 1500,
					offset: {top: -20}
				});
			}
		});
		$('.tabs a').corners('2px transparent top').addClass('rounded');
		$(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').removeClass('open').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: '#cbc7c1'});
						}, function(){
							$(this).css({ backgroundColor: '#ddd9d3'});
						});
					});
				});

				$('.selector-options').hover(function(){
					$(this).css({ backgroundColor: '#cbc7c1'});
				}, function(){
					$(this).css({ backgroundColor: '#ddd9d3'});
				}).click(function(){
					$(this).addClass('open');
					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);
	}

	// 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;
		if ($('.prodThumbPrice .pricesale', this).length) {
			price = parseFloat($.trim($('.prodThumbPrice .pricesale', this).text().replace(/^\s*\$/, '')));
		} else {
			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>');
			});
		}
	}
	
	// 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 (hiddenFilter == cFilter) return;
			
			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(){
					$(this).addClass('over');
					$('ul', this).not(':animated').slideDown('fast');
					$('div', this).addClass('over');
				},
				out: function(){
					$$ = $(this);
					$('ul', this).slideUp('fast', function(){
						$$.removeClass('over');
					});
					$('div', this).removeClass('over');
				}
			});
		
		$('#filter-list dl, #sort-wrap dt').corners('3px');
	
		$('#filter-list ul li')
			.click(processClick);
		
		$('#sort-wrap li')
			.click(function(){
				$('#sort-wrap dl.over').removeClass('over');
				$(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').stop().animate({
					color: '#fff'
				}, 200);
				// $(this).css('color', '#fff');
			}, function(){
				$(this).not('.active').stop().animate({
					color: '#4C4B4A'
				}, 300, function(){
					$(this).attr('style', '');
				});
				// $(this).css('color', '#4C4B4A');
			});
	}
		
	if (!$('#filter-list li').length) $('#directory-filter').hide();
	
	
	if ($('#product-area').length) {
		jQuery.address.change(function(event) {
			$('#filter-list li.over').removeClass('over');
			
			var params = {};
			if (event.queryString.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+'';
					}
				});
			}
			
			if (pageLoaded || event.queryString.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('dd 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() {
							$('#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 > li').css({
						display: '',
						width: '',
						opacity: ''
					});
					$('#filter-list dd div').remove();
			
					$('#clear-filters').hide();
			
					doSort(false);
					doFilter();
			
					if ($('html.ie7').length) {
						$('#footer').toggleClass('foo');
					}

					$('#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;
				$.cookie('filter_query', $.address.queryString(), {expires: 10, path: '/'});
			}
		});
	}
	
	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: $.address.queryString();
		var params = {};
		
		var newParam = filterName+'='+optionName;
		var paramRegExp = new RegExp('&?'+newParam);
		var glue = query.length? '&': '';
		
		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();

		$('#filter-breadcrumb').empty();
		if ($.address.queryString().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).parent().not(':hidden').animate({
					width: 0,
					opacity: 0
				}, 'fast', function(){
					$('dl', this).addClass('disabled');
					$(this).attr('style', '');
					$(this).hide();
				});
			} else {
				$(this).parent().attr('style', '');
				$(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').html($('#sort-wrap dt').html().replace(new RegExp($('#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 parseInt(out, 10);
					};
					break;
					
			}

			if (sortFunc) {
				pIds.sort(sortFunc);
			
				$.each(pIds, function(){
					$('#product-list').append($('#'+this));
				});
			}

			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');
			});
		}
		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="http://www.danner.com/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();
}