$(function() {
	
	// the product container needs a class for different view types
	$('.SI-partial-target').bind('viewchange', function(event, viewType, oldViewType) {
		$(this)
			.removeClass(oldViewType + '-view')
			.addClass(viewType + '-view');
	});
	
	//review pop-up is correct!
	$('a.review-dialog').click(function() {
		var $link = $(this);
		
		$(this).ajaxDialog({
			url			: $link.attr('href') + '?detached=true',
			autoOpen	: true,
			open		: function(event, ui) {
				$(ui.dialog).addClass('reviews');
				
				if ($link.hasClass('review-toggle-link')) {
					$(ui.dialog).addClass('review-first');
				}
			}
		});
		
		return false;
	});
	
	//product gallery asset image swapping
	$('.si-product').not('.si-partial').bind('optionchange', function(event, option) {
		var $product = $(this),
			$target = $product.find('#opt' + option.id);
		//only replace gallery if new one exists
		if($target.length > 0) {
			$product
			.find('.active-gallery')
			.removeClass('active-gallery')
			.fadeOut(function(){
				$target
					.addClass('active-gallery')
					.fadeIn()
					//trigger click on first image link to load new main image
					.find('a:first img').trigger('click');
			});
		}
	});
	
	//product image gallery slider
	$('div.gallery div.carousel img').wrap('<li />');
	
    $('div.gallery div.carousel').jCarouselLite({
        btnNext: '.gallery .next',
        btnPrev: '.gallery .prev',
        visible: 3,
        circular: false
    });
    
    if($('div.gallery div.carousel img').length <= 3) {
    	$('div.gallery span.next').toggleClass('disabled');
    }
    
	// product image switcheroo // TODO: make this better
    $('div.item-photos div.gallery img').click(function() {
			var href = $(this).attr('src').replace('_small', '');
			$('.main-image a').attr('href', href).attr('rel', "position: 'inside'");
			$('.mousetrap').remove();
			$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
    });
	
	//sidebar!
	$('div.sidebar-nav > ul > li > a.si-current-branch').parent().addClass('active-nav');
	
	function init(target) {
		// initialize input hints
		$('input:text', target).hint();
		
		// initialize context dialogs
		$('.context-dialog', target).contextDialog();
		
		// initialize sliders
		$('.callout-products', target).itemSlider({
			nextText:		'Next',
			previousText:	'Previous'
		});
		$('div.subitem-view').itemSlider({
			nextText:		'Next',
			previousText:	'Previous'
		});
		
		// initialize zebra striping on tables and lists
		$('table tr:even', target).addClass('stripe');
		
		// close wishlist context dialogs when a product gets added
		$('.si-wishlist-add-form', target).bind('addtowishlist', function() {
			$(this).parents('.ui-context-dialog').contextDialog('close');
		});
		
		// remove new review form and deactivate button when one is created
		$('.si-review-create-form', target).bind('success', function(event) {
			$('#new-review-toggle')
				.toggler('toggle')
				.toggler('destroy')
				.addClass('disabled');
			
			$('#new-review').remove();
			$('.review-controls').remove();
		});
		
		// review edit form swapping
		$('.review-edit', target).swap({ replacementText: '[cancel]' });
		
		// hide review form when it's saved
		$('.si-review-edit-form', target).bind('success', function() {
			$(this).parents('.si-review').find('.review-edit').swap('restore');
		});
		
		//addtocart custom message
		$('.si-cart-add-form').bind('addtocart', function(event) {
			$('#message').hide();
			$('#custom-message').addClass('display');
			setTimeout(function() {
				$('#custom-message').fadeOut(400, function() {
					$('#custom-message').removeClass('display');
				});
			}, 3000);
		});
		
		// remove review helpful links when clicked
		$('.si-review-helpful-button').click(function() {
			$(this).parents('.review-helpful-wrapper').html('Thank you for voting.&nbsp;');
			return false;
		});

	}
	
	// make sure ui widgets get initialized when elements get added to the dom
	$(document).bind('render', function(event, start, end) {
		var $target = $(event.target).children();
		
		if (typeof end != 'undefined') {
			// firefox 3's implementation of Array.slice cannot be called with two undefined args
			$target = $target.slice(start, end);
		} else if (typeof start != 'undefined') {
			$target = $target.slice(start);
		}
		
		init($target);
	});
	
	//main-nav
	var main_hover_config = {
		over:		main_hover_on,
		out:		main_hover_off,
		timeout:	400
	}
	
	$('li.custom-dialog').hoverIntent(main_hover_config);
	
	var hover_config = {
		over:		hover_on,
		out:		hover_off,
		timeout:	400
	}
	
	$('.main-nav-menu > div > ul > li').hoverIntent(hover_config);
	
	$('div.main-nav-menu div').mouseleave(function() {
		$('li.si-has-children ul', this).fadeOut(200);
		$('.hover').removeClass('hover');
	});
	
	//sidebar accordion nav
	$('div.sidebar-nav > ul > li.si-has-children > a').click(function() {
		var parent = $(this).parent();
		if (parent.hasClass('active-nav')) {
			$('ul', parent)
				.stop(true,true)
				.slideToggle(250);
			parent.toggleClass('active-nav');
		} else {
			$('ul', '.active-nav')
				.stop(true,true)
				.slideToggle(250);
			$('.active-nav')
				.removeClass('active-nav');
			$('ul', parent)
				.stop(true,true)
				.slideToggle(250);
			parent.toggleClass('active-nav');
		}
		return false;
	});
	
	//home slideshow
	$('#slideshow').cycle({
		pager: '#slideshow-nav'
	});
	
	//home welcome-area
	$('#welcome-toggle').toggle(function() {
		$('#welcome-area').animate({marginTop: '-23px'});
		$(this).addClass('down');
	}, function() {
		$('#welcome-area').animate({marginTop: '295px'});
		$(this).removeClass('down');
	});
	
	//testimonials
	$('.testimonial').cycle({
		timeout:	11111,
		random:		1
	}); 
	
	//product detail description tabs
	$('.description-tabs').tabs();
	
	// DUBBLE INPUT MAJICK
	// FOR ADD TO CARTING
	$('.dual-input .prod-purchase .cart-add-button').live('click', function() {
		$('#message').addClass('none');
		
		var $product = $(this).parents('.si-product'),
			productId = $product.data('id'),
			itemCount = 0,
			promises = [];

		$('.cart-quantity-input', $product).each(function() {
			var quantity = +$(this).val(),
			// this is ideal!
				productOptionId = $(this).data('productOptionId');
			
			// don't add to cart if there's no quantity specified
			if (productOptionId && quantity) {
				promises.push(SI.cart.addProduct(productId, productOptionId, quantity));
				itemCount += quantity;
			}
		});
		
		if (itemCount) {
			$.when.apply($, promises).then(function() {
				$('#custom-message').addClass('display');
				setTimeout(function() {
					$('#custom-message').fadeOut(400, function() {
						$('#custom-message').removeClass('display');
					});
					$('#message').removeClass('none').hide();
				}, 3000);
			});
		}
		
		return false;
	});
	// FOR ADD TO WISHLISTING
	$('.dual-input .si-wishlist-add-form input.si-button').live('click', function() {
		var $product 		= $(this).parents('.si-product'),
			productId 		= $product.data('id'),
			itemCount 		= 0,
			promises 		= [],
			wishlistId 		= $('.si-wishlist-id option:selected', $product).attr('value'),
			wishlistName	= $('.si-wishlist-name', $product).val(),
			whichList		= $(this).hasClass('si-add-wishlist') ? 'add' : 'createAndAdd';
		
		if (whichList == 'add') {
			$('.cart-quantity-input', $product).each(function() {
				var quantity = +$(this).val(),
				// this is ideal!
					productOptionId = $(this).data('productOptionId');
				
				// don't add to cart if there's no quantity specified
				if (productOptionId && quantity) {
					promises.push(SI.wishlist.addProduct(wishlistId, productId, productOptionId, quantity));
					itemCount += quantity;
				}
			});
		} else if (whichList == 'createAndAdd') {
			SI.wishlist.create(wishlistName);
		}
		
		if (itemCount) {
		}
		
		return false;
	});
	
	// initialize ui widgets on the initial page load
	init(document);
});

function main_hover_on() {
	$('.main-nav-menu', this)
		.css('z-index', 5)
		.stop(true,true)
		.slideToggle(400);	
}

function main_hover_off() {
	$('.main-nav-menu', this)
		.css('z-index', 1)
		.stop(true,true)
		.fadeOut(50);	
}

function hover_on() {
	$('.hover').removeClass('hover');
	$('.active-main-nav').fadeOut(50).removeClass('active-main-nav');
	$(this).addClass('hover');
	$('ul', this).fadeIn(300).addClass('active-main-nav');
}

function hover_off() {
}


