$(document).ready(function(){
	// page supports javascript
	if(!$(document.body).hasClass('js')) { $(document.body).addClass('js'); }

	// global variables
	var newItem = $('<div class="item loading"><div></div></div>');
	var product;

	/**
	 * Input Labeled function
	 * handles replacing the input text with its label
	 */
	 var labelDefault = [];
	$('input.grab-label').each(function(i, el) {
			labelDefault[i] = $(el).prev().css('display','none').text();
	});
	$('input.grab-label').each(function(i, el) {
		$(el)
		.attr('value',labelDefault[i]).addClass('labeled')
			.focus(function(e) {
				if ($(this).attr('value') == labelDefault[i]) {
					$(this).attr('value','').removeClass('labeled');
				}
			})
			.blur(function(e) {
				if ($(this).attr('value') === '') {
					$(this).attr('value',labelDefault[i]).addClass('labeled');
				}
			});
		});
	$('form').submit(function(e) {
			$('input.grab-label').each(function(i, el) {
				if($(el).hasClass('labeled')) {
						$(el).attr('value','');
				}
			});
			return true;
		});

	/**
	 * drop down menu
	 * Handles the show/hide functionality
	 */
	// function for mouseenter/mousein
	function menu_enter(){
		$(this).addClass('hover');
		if ($(this).next('li.oddLi')) {
			$(this).next('li.oddLi').addClass('hover');
			var currentId = $(this).children('a').attr('title'); 
			
			if (jQuery.browser.msie && parseFloat(jQuery.browser.version) < 7) {
				$(this).next('li.oddLi').css('background','url('+svrPathMain+'/images/nav/rollover-tab-right.gif) no-repeat 0 0');
				//$(this).next('li.oddLi').css('text-indent','-999px');
			}
		}
	}

	// function for mouseleave/mouseout
	function menu_leave() {
		$(this).removeClass('hover');
		if ($(this).next('li.oddLi'))
		{
			$(this).next('li.oddLi').removeClass('hover');
			if (jQuery.browser.msie && parseFloat(jQuery.browser.version) < 7)
			{
				$('#menuShim').css("display", "none");
				$('#menuShimProd').css("display", "none");
				$(this).next('li.oddLi').css('background','none');
				//$(this).next('li.oddLi').css('text-indent','0');
			}
		}
	}
	var navItems = $('#store-nav').children('li');

	// disable on checkout pages except confirmation/cart screens
	if (!$('body#checkout') || $('body.confirmation') || $('body.cart')) {
		navItems.hover(menu_enter, menu_leave);
		$(navItems).each(function(){
			$(this).children('a').focus(menu_enter).blur(menu_leave);
		});
	}

	/**
	 * auto-size subnav
	 * handles the need for a dynamic width of the dropdown
	 */
	$('#store-nav li ul').each(function(subNav) {
		subNav = $(this);
		subNav.css({
				'display': 'block',
				'margin-left': '-9999px'
				
		});
		
		var width = 60;
		subNav.children('li').each(function() {				
				//width += $(this).width();
				//subNav.css('width', width + 'px');
		});
		subNav.css({
				'display': '',
				'margin-left': ''
		});		
	});

	/**
	 * My Honeydo List
	 * handles the user interaction
	 */
	// shopping list variables
	var shopList = $('#shopping-list-container');	// the list itself
	var shopListOriginalY = shopList.css('bottom'); // storing the bottom css
	var shopListHoverY = parseInt(shopList.css('bottom')) + 6 + 'px'; // "peek" amount
	var shopListOpenY = parseInt(shopList.css('bottom')) + 364 + 'px'; // show the list
	var listOpen = false;
	var shopListHover = false;

	// shopping list functions
	function toggleShoppingList(e) {
		shopList.hover(function(e) { shopListHover = true; }, function(e) { shopListHover = false; });

		if (!listOpen) {
			listOpen = true;
			shopList.animate({'bottom': shopListOpenY}, {'queue': false});
		} else {
			shopList.animate({'bottom': shopListOriginalY}, {'queue': false});
			listOpen = false;
			return false;
		}
		return false;
	}

	// tab action
	$('a#shopping-tab')
		.click(toggleShoppingList)
		.mouseenter(function(e){
			if (!listOpen) { shopList.animate({'bottom': shopListHoverY}, {'queue': false}); }
		});

	$('div#shopping-list-container').mouseout(function(e){
		if (!listOpen) { shopList.animate({'bottom': shopListOriginalY}, {'queue': false}); }
	});

	$('a#close-list').click(toggleShoppingList);

	/**
	 * Shopping List Scroller
	 */
	$('span#prev').css('visibility', 'hidden'); // hide it initially
	if($('#list-items')[0]) {
		var shoppingListSlider = $('#list-items').scrollable({
			api: true,
			size: 4,
			nextPage: '#next',
			prevPage: '#prev'
		});
		shoppingListSlider.onReload(function() {
			if (this.getSize() === 0) {
				$('#list .browse').css('visibility', 'hidden');
			}
			else if (this.getSize() > 4) {
				$('a#next').css('visibility', 'visible');
			}
			$('#list-items').pngFix();
		});
		shoppingListSlider.onSeek(function() {
			// if last page, hide next arrow
			if(this.getPageIndex() < (this.getPageAmount() - 1)) {
				$('span#next').css('visibility', 'visible');
			} else {
				$('span#next').css('visibility', 'hidden');
			}
			// if first page, hide prev arrow
			if(this.getPageIndex() === 0) {
				$('span#prev').css('visibility', 'hidden');
			} else {
				$('span#prev').css('visibility', 'visible');
			}
		});
	}

	/**
	 * Add to Honeydo List
	 * Functions and element construction to showcase the "add to my honeydo list"
	 */
	// appends item once the "list" is slid out
	$('a.add-list').live('click', function(e){
		if ($(this).parents('form')[0]) {
			var qtySelect = $(this).parents('form').find('select:first option:selected').val();
			if (!qtySelect || qtySelect === '') {
				alert('Please select a size');
				return false;
			}
		}

		// binding cheat
		thisItem = $(this);
		// add the dummy loader element
		$('#items').prepend(newItem);
		if (!listOpen) { toggleShoppingList(); }

		var wait = setInterval(function() {
			if (!shopList.is(":animated") ) {
				clearInterval(wait);
				appendItemList(thisItem, 'list');
			}
		}, 200);

		var listWait = setInterval(function() {
			if (!shopList.is(":animated") && !shopListHover) {
				clearInterval(listWait);
				toggleShoppingList();
				shopListOpen = false;
			}
		}, 2000);
		return false;
	});

	/**
	 * appendItemList
	 * handles grabbing the product from the page and adding to the list or cart
	 * @param el the clicked product
	 * @param loc the location - either 'cart' or 'list'
	 */
	function appendItemList(el, loc) {
		var item = el.parent();
		if (!item.hasClass('item')) { appendItemList(item, loc); }
		else {
			if ($('#overlay').is(':visible')) { $("#overlay").jqmHide(); }

			// product container
			itemToAdd = $('<div class="item"></div>');

			// constructor
			var itemLink = $('<a>').attr({
				'html': '',
				'href': item.find('a:first').attr('href'),
				'title': item.find('a:first').attr('title')
			});
			var itemImg = $('<img>').attr({
				'alt': item.find('img:first').attr('alt'),
				'height': 172,
				'src': item.find('img:first').attr('src'),
				'width': 172
			});
			var itemRating = item.find('.rating').clone();
			itemRating.find('#reviewcount').remove('#reviewcount');
			itemRating.find('img').each(function(){
				$(this).attr({
					'height': 15,
					'src': $(this).attr('src').replace('lrg.png','sm.gif'),
					'width': 17
				});
			});
			var itemTitle = item.find('h2').clone();
			var itemSizeCount = item.find('.sizecount').clone();
			var itemSKU = item.find('.sku').clone();
			var itemQty = item.find('.qty').clone();
			//var itemPrice = item.find('h3').clone();
			var itemPrice = item.find('.headertitle').clone();
			var itemAddBar = item.find('.addbar').clone().append($('<a href="#" title="Remove" class="list-remove"><img src="img/buttons/remove.png" alt="remove" width="50" height="20" /></a>'));
			itemAddBar.find('.add-list').remove('.add-list');
			itemAddBar.find('.buy-now').remove('.buy-now');
			itemAddBar.find('.learn').remove('.learn');

			if (!item.find('.add-cart')[0]) {
				itemAddBar.prepend('<a class="add-cart" title="Add to Cart" href="#"><img width="87" height="20" alt="Add to Cart" src="img/buttons/add-cart.png"/></a>');
			} else {
				itemSizeCount = $('<p>').addClass('sizecount').text($('#overlay select option:selected').text());
			}

			// pricing variables
			var miniTotal = parseFloat($('#minicart_total em').text().replace('$',''));
			var miniMerch = parseFloat($('#minicart_merch td').text().replace('$',''));
			var miniShip = parseFloat($('#minicart_shipping td').text().replace('$',''));
			var miniTax = $('#minicart_tax td').text().replace('$','')

			// for the homepage
			if ($('body').attr('id') === 'home' && item.parent().attr('id') !== 'items') {
				itemLink.attr({'href': $('#product a:first').attr('href'), 'title': $('#product a:first').attr('title')});
				itemImg.attr({'src': $('#product a img').attr('src').replace('_landing.png','.jpg'), 'alt': $('#product a img').attr('alt'), 'width': 172, 'height': 172});
			}

			if (item.hasClass('detail')) { // the product detail page
				itemLink.attr({'href': window.location, 'title': $('#viewerarea img').attr('alt')});
				itemImg.attr({'src': $('#viewerthumbs img:first').attr('src').replace('_thumb.jpg','.jpg'), 'alt': $('#viewerthumbs img:first').attr('alt'), 'width': 172, 'height': 172});
				itemTitle = $('<h2>').text($('h1').text());
				itemSizeCount = $('<p>').addClass('sizecount').text($('#size_selector option:selected').text());
				itemQty = $('<p>').addClass('qty').text('Quantity: ' + $('#qty').val());
			}

			// adjust image dimensions if it's added to cart
			if (loc === 'cart') { itemImg.attr({'height': 94, 'width': 94}); }
			itemLink.append(itemImg);
			itemToAdd.append(itemLink);

			if (loc === 'list') {
				if ($('body').hasClass('productdetail')) {
					itemToAdd.find('.rating img').each(function(){
						$(this).attr('src',$(this).attr('src').replace('lrg.png','sm.gif'));
					});
				}
				itemToAdd.append(itemRating);
				itemToAdd.append(itemTitle);
				itemToAdd.append(itemSizeCount);
				itemToAdd.append(itemPrice);
				itemToAdd.append(itemAddBar);
			}

			if (loc === 'cart') {
				var itemCartWrapper = $('<div class="detail"></div>');
				itemCartWrapper.append(itemTitle);
				itemCartWrapper.append(itemSizeCount);
				itemCartWrapper.append(itemSKU);
				(itemQty.length >= 1) ? itemCartWrapper.append(itemQty) : itemCartWrapper.append('<p class="qty">Quantity: <strong>1</strong></p>');
				itemCartWrapper.append(itemPrice);
				itemToAdd.append(itemCartWrapper);

				// for price manipulation
				if (itemPrice.text().split(' ').length > 1) {
					miniMerch += parseFloat(itemPrice.text().split(' ')[1].replace('$',''));
				} else {
					miniMerch += parseFloat(itemPrice.text().replace('$',''));
				}

				miniTax = parseInt(.0065 * miniMerch * 100);
				$('#minicart_tax td').text().replace('$','');

				var miniTotal = parseInt((miniMerch + miniShip + miniTax) * 100);

				$('#minicart_tax td').text('$' + miniTax);
				$('#minicart_merch td').text('$' + miniMerch);
				$('#minicart_total em').text('$' + (miniTotal / 100));
			}

			// replace cart loader with new item
			newItem.replaceWith(itemToAdd);

			// if added to list, reload list and add to total
			if (loc === 'list') {
				shoppingListSlider.reload();
				var listTotal = parseInt($('#list-total').text());
				$('#list-total').text(listTotal + 1);
			}
			else if (loc === 'cart') {
				var cartTotal = parseInt($('.cart-link:first a span.cart-total:first').html());
				$('span.cart-total').each(function(e) {
					$(this).html(cartTotal + 1); 
				});
			}
		}
		return false;
	}

	// remove item from honeydo list
	$('a.list-remove').live('click', function(e){
		$(this).parent().parent().remove();
		var listTotal = parseInt($('#list-total').text());
		$('#list-total').text(listTotal - 1);
		shoppingListSlider.reload();
		return false;
	});

	/**
	 * Add to Cart
	 * Handles the actions for adding to the minicart
	 */
	// shopping list variables
	var minicart = $('#minicart-frame');	// the list itself
	var minicartOpen = false;
	var minicartHover = false;

	// shopping list functions
	function setMinicart() {
		var leftOffset;
		minicart.css({
			'top': $('#nav').offset().top
		});
		if (jQuery.browser.msie)
		{
			if (parseFloat(jQuery.browser.version) === 7)
			{
				leftOffset = $('#nav').width() + $('#nav').offset().left - minicart.width() + 9;
			}
			else {
				leftOffset = $('#nav').width() + $('#nav').offset().left - minicart.width();
			}
		}
		else {
			leftOffset = $('#nav').width() - minicart.width() - 26;
		}
		minicart.css({
			'left': parseFloat(leftOffset)
		});
	}

	function toggleMinicart(e) {
		setMinicart();
		if (!minicartOpen) {
			minicartOpen = true;
			minicart.animate({'height': 524}, {'queue': false});
		}
		else {
			minicartOpen = false;
			minicart.animate({'height': 0}, {'queue': false});
		}
		var miniWait = setInterval(function() {
			if (!minicart.is(':animated') && !minicartHover) {
				clearInterval(miniWait);
				minicart.animate({'height': 0}, {'queue': false});
				minicartOpen = false;
			}
		}, 2000);
		minicart.hover(function(e) { minicartHover = true; }, function(e) { minicartHover = false; });
		$(window).bind('resize',setMinicart);
		$('#frame').scroll(setMinicart);
		return false;
	}

	// appends item once the minicart is slid out
	$('a.add-cart').live('click', function(e){
		if ($(this).parents('form')[0]) {
			var qtySelect = $(this).parents('form').find('select:first option:selected').val();
			if (!qtySelect || qtySelect === '') {
				alert('Please select a size');
				return false;
			}
		}

		// scroll to top
		$('#frame').animate({scrollTop:0}, 'slow'); 

		// binding cheat
		thisItem = $(this);
		// add the dummy loader element
		$('#minicart-items').prepend(newItem);

		// if no items exist in cart, create skeleton
		// test against the first cart-link to prevent additional duplicates
		if (!$('#nav .cart-link:first a span')[0]) {
			$('#nav .cart-link:first a').addClass('items-added').append(' ( <span class="cart-total">0</span> )');
			$('<li class="odd">|</li><li class="checkout-link"><a href="checkout_your_cart.php" title="Checkout">Checkout</a></li>').insertAfter('#nav .cart-link:first'); // setup checkout link
		}

		// add cart/checkout hover event
		$('.cart-link a').hover(function(e) { if (!minicartOpen) { toggleMinicart(); } });

		// if the cart isn't open, do so
		if (!minicartOpen) { toggleMinicart(); }

		var wait = setInterval(function() {
			// don't do anything until the animation is complete
			if (!minicart.is(':animated')) {
				clearInterval(wait);
				appendItemList(thisItem, 'cart');
			}
		}, 200);
		return false;
	});

	// close link in minicart
	$('a#close-minicart').click(toggleMinicart);

	// FOR CHECKOUT DEMO
	if ($(document.body).hasClass('cart')) {
		$('.cart-link a').hover(function(e) { if (!minicartOpen) { toggleMinicart(); } });
		$('span.cart-total').each(function(e) {
			$(this).html(3); 
		});
	}

});

