var loading = true;
$(function() {
	$('#nav li:last').find('a').addClass('last');
	$('div.home_images').each(function() {
		$(this).find('img').hide().each(function() {
			var currImg = $(this);
			var img = $(new Image());
			img.load(function() {
				currImg.show().css({opacity: 0});
				if (currImg.attr('src') == $('div.home_images img:first').attr('src')) {
					currImg.animate({opacity: 1}, 500).addClass('current');
					var first = true;
					(function rotateImgs() {
						if (!first) {
							$('div.home_images img').each(function() {
								var $this = $(this);
								if ($this.hasClass('current')) {
									var next = $this.next('img:first');
									if (next.length == 0) next = $('div.home_images img:first');
									next.css({opacity: 1, top: 0});
									$this.animate({opacity: 0, top: 200}, 700, function() { 
										$this.removeClass('current'); 
										next.addClass('current');
									});
									return false;
								}
							});
						} else {
							first = false;
						}
						setTimeout(rotateImgs, 6000);
					})();
				}
			}).attr('src', currImg.attr('src'));
		});
	});
	$('#leftNav ul.subCats').each(function() {
		var $this = $(this);
		if (!$this.parent().hasClass('current')) {
			$this.hide().prev('a').click(function() {
				if ($this.parent().hasClass('expanded')) {
					$this.slideUp(500);
					$this.parent().removeClass('expanded');
				} else {
					$this.slideDown(500);
					$this.parent().addClass('expanded');
				}
				return false;
			});
		} else {
			$this.prev('a').click(function() {
				$this.find('a:first').trigger('click');
				return false;
			});
		}
	});
	$('#search').focus(function() {
		var $this = $(this);
		if ($this.val() == 'SEARCH') $this.val('');
	}).blur(function() {
		var $this = $(this);
		if ($.trim($this.val()) == '') $this.val('SEARCH');
	});
	$('div.productLink a').mouseenter(function() {
		$(this).find('div.prodLinkTitle').stop().animate({backgroundColor: '#c3c3bf'}, 200);
	}).mouseout(function() {
		$(this).find('div.prodLinkTitle').stop().animate({backgroundColor: '#f5f5f2'}, 300);
	});
	$('#leftNav a').mouseenter(function() {
		$(this).stop().animate({backgroundColor: '#f5f5f2'}, 200);
	}).mouseout(function() {
		if ($(this).parentsUntil('#leftNav').filter('.current, .expanded').length == 0) $(this).stop().animate({backgroundColor: '#ffffff'}, 300);
	});
	setTimeout(function() {
		var zoomRatio = 1250 / 450;
		var offsetLeft = 0;
		var offsetTop = 0;
		$('#mainImage').mouseover(function() {
			var $this = $(this);
			offsetLeft = $this.offset()['left'];
			offsetTop = $this.offset()['top'];
			if ($this.find('div.shader').length == 0) {
				$this.append('<div id="topBox" class="shader"/><div id="leftBox" class="shader"/><div id="rightBox" class="shader"/><div id="bottomBox" class="shader"/>');
			}
			if ($.support.opacity) {
				$this.find('div.shader').stop().animate({opacity: 0.6}, 250);
				$('#mainZoom').css('display', 'block').stop().animate({opacity: 1}, 250);
			} else {
				$('#mainZoom').css('display', 'block');
			}
		}).mouseleave(function() {
			if ($.support.opacity) {
				$('#mainImage div.shader').stop().animate({opacity: 0}, 250, function() {$('#mainImage').find('div.shader').remove();});
				$('#mainZoom').stop().animate({opacity: 0}, 250, function() {$(this).css('display', 'none');});
			} else {
				$('#mainImage div.shader').remove();
				$('#mainZoom').css('display', 'none');
			}
		}).mousemove(function(e) {
			var upperX = (e.pageX - offsetLeft) - 81;
			if (upperX < 0) upperX = 0;
			if (upperX + 162 > 450) upperX = 288;
			var lowerX = upperX + 162;
			var upperY = (e.pageY - offsetTop) - 81;
			if (upperY < 0) upperY = 0;
			if (upperY + 162 > 450) upperY = 288;
			var lowerY = upperY + 162;
			$('#topBox').css({bottom: 450 - upperY, right: 450 - lowerX});
			$('#leftBox').css({top: upperY, right: 450 - upperX});
			$('#rightBox').css({left: lowerX, bottom: 450 - lowerY});
			$('#bottomBox').css({left: upperX, top: lowerY});
			$('#mainZoom img').css({left: upperX * -zoomRatio, top: upperY * -zoomRatio});
			if (showingInfo) {
				$('#prodInfo').css({top: lowerY, left: upperX});
			}
		});
	}, 1000);

	$('a.button').mouseenter(function() {
		$(this).find('span').stop().animate({backgroundColor: '#000000'}, 300);
	}).mouseleave(function() {
		$(this).find('span').stop().animate({backgroundColor: '#5b5b5b'}, 300);
	});

	$('#addToCart').click(function() {
		if ($(this).find('span').text() == 'Updating...') {
			alert('Updating cart.  Please wait until finished processing.');
			return false;
		}
		var items = [];
		var overStock = false;
		$('#productTable').find('input[type=text]').each(function() {
			var $this = $(this);
			if ($.trim($this.val()) != '' && parseInt($this.val()) > 0) {
				var minQty = parseInt($this.attr('min_qty'));
				var qty = parseInt($this.val());
				if (minQty > 1 && qty % minQty != 0 && wholesaleCust) {
					var prodName = $this.parent().prevAll('.productName').text();
					var addQty = minQty - (qty % minQty);
					if (confirm(prodName + ' must be ordered in quantities of ' + minQty + ' change quantity to ' + (qty + addQty) + '?')) {
						$this.val(qty + addQty);
					} else {
						overStock = true;
					}
				}
				items.push($this);
			}
		});

		if (overStock) return false;

		if (items.length > 0) {
			var url = $(this).attr('href');
			$(this).find('span').text('Updating...');
			function addItem() {
				var $this = items.shift();
				var data = {quantity: parseInt($this.val()),
					prod_rn: $this.attr('id').split('_')[1],
					js: 'true'
				};
				$.get(url, data, function(rslt) {
					eval(rslt);
					$this.attr('stock', parseInt($this.attr('stock')) - parseInt($this.val()));
					$this.val('');
					if (items.length > 0) {
						addItem();
					} else {
						$('#shopStatus').css('background-color', '#c3c3bf').animate({backgroundColor: '#ffffff'}, 1000);
						$('#addToCart').find('span').text('Add to Cart');
					}
				});
			}
			addItem();
		} else {
			alert('Please enter quantities of products first.');
		}
		return false;
	});
	$('form.productForm').submit(function() {
		var hasProduct = false;
		$('#productTable').find('input').each(function() {
			var val = $.trim($(this).val());
			if (val != '' && parseInt(val) > 0)  {
				hasProduct = true;
				return false;
			}
		});
		if (!hasProduct) alert('Nothing to add to the cart.  Please add a quantity to at least one item.');
		return hasProduct;
	});
	$('#productTable input').numeric();
	var showingInfo = false;
	var prodOverCount = 0;
	$('div.prodId').mouseover(function() {
		prodOverCount++;
		if (!showingInfo) {
			$('#mainImage').append('<div id="prodInfo">' + $(this).attr('rel') + '</div>');
			$('#prodInfo').css({top: $('#bottomBox').css('top'), left: $('#bottomBox').css('left')});
			showingInfo = true;
		} else {
			$('#prodInfo').text($(this).attr('rel'));
		}
		if ($.support.opacity) {
			$('#prodInfo').stop().animate({opacity: 1}, 150);
		}
	}).mouseout(function() {
		prodOverCount--;
		setTimeout(function() {
			if (prodOverCount <= 0) {
				prodOverCount = 0;
				if ($.support.opacity) {
					$('#prodInfo').animate({opacity: 0}, 250, function() {
						if (prodOverCount == 0) {
							$(this).remove();
							showingInfo = false;
						}
					});
				} else {
					$('#prodInfo').remove();
					showingInfo = false;
				}
			}
		}, 150);
	});
	$('table.cart_table').find('tbody').find('tr').mouseenter(function() {
		var $this = $(this);
		$this.addClass('hover');
	}).mouseleave(function() {
		var $this = $(this);
		$this.removeClass('hover');
	});

	$('#pay_cc').hide();
	$('#pay_purchase_order').hide();
	$('div.pay_method_row').find('input').click(function() {
		if ($(this).attr('rel') == 'cc') {
			$('#pay_cc').slideDown(400);
		} else {
			$('#pay_cc').slideUp(400);
		}
		if ($(this).attr('rel') == 'other') {
			$('#pay_purchase_order').slideDown(400);
		} else {
			$('#pay_purchase_order').slideUp(400);
		}
	}).filter(':checked').each(function() {
		if ($(this).attr('rel') == 'cc') {
			$('#pay_cc').show();
		} else if ($(this).attr('rel') == 'other') {
			$('#pay_purchase_order').show();
		}
	});
	if ($.trim($('#nav li.selected').text()) != 'Towels') {
		$('#colorDropbox').hide();
	} else {
		$('#colorDropbox').click(function() {
			var $this = $(this);
			if ($this.hasClass('showing')) {
				slideUpBox(true);
			} else {
				var dropList = $this.find('div.dropList');
				dropList.animate({height: dropList.find('ul').height()}, 200);
				$this.addClass('showing');
			}
		}).mouseenter(function() {
			$(this).attr('_over', parseInt($(this).attr('_over')) + 1);
			clearTimeout($(this).attr('_timer'));
		}).mouseleave(function() {
			var over = parseInt($(this).attr('_over')) - 1;
			if (over <= 0) {
				$(this).attr({'_over': 0, '_timer': setTimeout(slideUpBox, 1000)});
			}
		}).attr('_over', 0);
		$('#colorDropbox a').click(function() {
			var $this = $(this);
			var html = $this.html();
			var text = $this.text();
			if (text == 'Clear Filter') {
				html = 'Filter by Color';
			} else {
				html = html.replace(new RegExp(text + '$'), 'Filter by ' + text);
			}
			$('#colorDropbox div.title').html(html);
			slideUpBox(true);
			filterColorsBy(text);
			return false;
		});
//		if ($.cookie('av_color')) {
//			$('#color' + $.cookie('av_color')).find('a').trigger('click');
//		}
	}
	$('#retailLoginLink').click(function() {
		var moveTo = 26;
		if ($.browser.msie && $.browser.version == '7.0') {
			moveTo = -5;
		}
		$('#retailLogin').css({'display': 'block', 'opacity': 0, top: 0}).animate({'opacity': 1, 'top': moveTo}, 300);
		return false;
	});
	$('#retailClose').click(function() {
		$('#retailLogin').animate({'opacity': 0, 'top': 0}, 300, function() {
			$(this).css('display', 'none');
		});
		return false;
	});
	loading = false;
	$('#method_1').click();

	$('#submitRetail').click(function() {
		$('#retailSignup').submit();
		return false;
	}).css('display', 'inline-block');
	$('#retailSignup').submit(function() {
		var ok = true;
		$('input.required').each(function() {
			if ($.trim($(this).val()) == '') {
				ok = false;
			}
		});
		if (! ok) {
			alert('You must enter values for all required fields. (marked by asterisks *).');
			return false;
		}
		return true;
	});
	$import('http://static.addtoany.com/menu/page.js');
	$('#simple_search_btn').click(function() {
		$('#simple_search_form').submit();
		return false;
	});
});

function slideUpBox(force) {
	function _slideUp() {
		$('#colorDropbox').removeClass('showing').find('div.dropList').animate({height: 0}, 200);
	}
	if (force) {
		_slideUp();
	} else {
		if (parseInt($('#colorDropbox').attr('_over')) <= 0) {
			$('#colorDropbox').attr('_over', 0);
			_slideUp();
		}
	}
}
function filterColorsBy(color) {
	var smallColor = color.toLowerCase();
	var timeout = 200;
	if (loading) timeout = 0;
	var fullCount = $('div.productLink').each(function() {
		if (smallColor == 'clear filter' || $(this).attr('rel').indexOf(smallColor) > -1) {
			$(this).show(timeout).removeClass('outOfColor');
		} else {
			$(this).hide(timeout).addClass('outOfColor');
		}
	}).length;
	if (fullCount == $('div.productLink.outOfColor').length) {
		$('#noMatch').css('display', 'block');
	} else {
		$('#noMatch').css('display', 'none');
	}
	if (smallColor == 'clear filter') {
		$.cookie('av_color', null, {path: '/'});
	} else {
		$.cookie('av_color', color, {path: '/'});
	}
}

function $import(src){
  var scriptElem = document.createElement('script');
  scriptElem.setAttribute('src',src);
  scriptElem.setAttribute('type','text/javascript');
  document.getElementsByTagName('head')[0].appendChild(scriptElem);
}

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */
(function(e){function g(c){var a;if(c&&c.constructor==Array&&c.length==3)return c;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return[parseInt(a[1]),parseInt(a[2]),parseInt(a[3])];if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return[parseFloat(a[1])*2.55,parseFloat(a[2])*2.55,parseFloat(a[3])*2.55];if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return[parseInt(a[1],16),parseInt(a[2],
16),parseInt(a[3],16)];if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return[parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16)];if(/rgba\(0, 0, 0, 0\)/.exec(c))return h.transparent;return h[e.trim(c).toLowerCase()]}e.each(["backgroundColor","borderBottomColor","borderLeftColor","borderRightColor","borderTopColor","color","outlineColor"],function(c,a){e.fx.step[a]=function(b){if(!b.colorInit){var d;d=b.elem;var i=a,f;do{f=e.curCSS(d,i);if(f!=""&&f!="transparent"||e.nodeName(d,
"body"))break;i="backgroundColor"}while(d=d.parentNode);d=g(f);b.start=d;b.end=g(b.end);b.colorInit=true}b.elem.style[a]="rgb("+[Math.max(Math.min(parseInt(b.pos*(b.end[0]-b.start[0])+b.start[0]),255),0),Math.max(Math.min(parseInt(b.pos*(b.end[1]-b.start[1])+b.start[1]),255),0),Math.max(Math.min(parseInt(b.pos*(b.end[2]-b.start[2])+b.start[2]),255),0)].join(",")+")"}});var h={transparent:[255,255,255]}})(jQuery);


(function(b){b.fn.alphanumeric=function(a){a=b.extend({ichars:"!@#$%^&*()+=[]\\';,/{}|\":<>?~`.- ",nchars:"",allow:""},a);return this.each(function(){if(a.nocaps)a.nchars+="ABCDEFGHIJKLMNOPQRSTUVWXYZ";if(a.allcaps)a.nchars+="abcdefghijklmnopqrstuvwxyz";s=a.allow.split("");for(i=0;i<s.length;i++)if(a.ichars.indexOf(s[i])!=-1)s[i]="\\"+s[i];a.allow=s.join("|");var c=a.ichars+a.nchars;c=c.replace(RegExp(a.allow,"gi"),"");b(this).keypress(function(d){k=d.charCode?String.fromCharCode(d.charCode):String.fromCharCode(d.which);
c.indexOf(k)!=-1&&d.preventDefault();d.ctrlKey&&k=="v"&&d.preventDefault()});b(this).bind("contextmenu",function(){return false})})};b.fn.numeric=function(a){var c="abcdefghijklmnopqrstuvwxyz";c+=c.toUpperCase();a=b.extend({nchars:c},a);return this.each(function(){b(this).alphanumeric(a)})};b.fn.alpha=function(a){a=b.extend({nchars:"1234567890"},a);return this.each(function(){b(this).alphanumeric(a)})}})(jQuery);

/**
*	jQuery.noticeAdd() and jQuery.noticeRemove()
*		
*   Copyright (c) 2009 Tim Benniks
*/
(function(b){b.extend({noticeAdd:function(a){var d,e,c;a=b.extend({},{inEffect:{opacity:"show"},inEffectDuration:600,stayTime:4E3,text:"",stay:false,type:"notice"},a);d=!b(".notice-wrap").length?b("<div></div>").addClass("notice-wrap").appendTo("body"):b(".notice-wrap");e=b("<div></div>").addClass("notice-item-wrapper");c=b("<div></div>").hide().addClass("notice-item "+a.type).appendTo(d).html("<p>"+a.text+"</p>").animate(a.inEffect,a.inEffectDuration).wrap(e);b("<div></div>").addClass("notice-item-close").prependTo(c).html("x").click(function(){b.noticeRemove(c)});
navigator.userAgent.match(/MSIE 6/i)&&d.css({top:document.documentElement.scrollTop});a.stay||setTimeout(function(){b.noticeRemove(c)},a.stayTime)},noticeRemove:function(a){a.animate({opacity:"0"},600,function(){a.parent().animate({height:"0px"},300,function(){a.parent().remove()})})}})})(jQuery);


/**
 * jQuery Cookie plugin
 *
 * Copyright (c) 2010 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie=function(e,b,a){if(arguments.length>1&&(b===null||typeof b!=="object")){a=jQuery.extend({},a);if(b===null)a.expires=-1;if(typeof a.expires==="number"){var d=a.expires,c=a.expires=new Date;c.setDate(c.getDate()+d)}return document.cookie=[encodeURIComponent(e),"=",a.raw?String(b):encodeURIComponent(String(b)),a.expires?"; expires="+a.expires.toUTCString():"",a.path?"; path="+a.path:"",a.domain?"; domain="+a.domain:"",a.secure?"; secure":""].join("")}a=b||{};c=a.raw?function(f){return f}:
decodeURIComponent;return(d=RegExp("(?:^|; )"+encodeURIComponent(e)+"=([^;]*)").exec(document.cookie))?c(d[1]):null};

