$(function() {
	// set toggler defaults
	$.extend($.ui.toggler.defaults, {
		activeClass	: 'active',
		closeClass	: 'close'
	});
	
	// 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');
	});
	
	// load the review list template via ajax on the product detail page
	$('#review-list-wrapper').load($('#review-page-link').attr('href'), function() {
		$(this)
			.removeClass('loading')
			.trigger('render');
	});
	
	//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');
			});
		}
	});
	
	function init(target) {
		// initialize input hints
		$('input:text', target).hint();
		
		// initialize generic toggles
		$('a.toggle', target).toggler();
		
		// initialize context dialogs
		$('.context-dialog', target).contextDialog();
		
		// initialize sliders
		$('.callout-products', target).itemSlider();
		
		// 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').bind('addtowishlist.si', 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 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');
		});
		
		// remove review helpful links when clicked
		$('.si-review-helpful-button').click(function() {
			$(this).parents('.review-helpful-wrapper').html('Thank you for voting.');
			return false;
		});
	}
	
	// homepage slideshow
	$('.home-slideshow-slides').cycle({
		fx:			'scrollHorz',
		timeout:	4000,
		prev:		'.home-slideshow-prev',
		next:		'.home-slideshow-next',
		pager:		'#home-slideshow-nav'
	});
	
	$('.home-slideshow-nav').hover(function() {
		$(this).stop(true, true).animate({
			opacity: 1
		}, 500);
	}, function() {
		$(this).stop(true, true).animate({
			opacity: 0
		}, 250);
	});

	// homepage featured promo	
	if ($('.home-featured-promo-header .timer').length == 1) {
		var date = $('.home-featured-promo-header .timer').html().split("/");

		$('.home-featured-promo-header .timer').countdown({
			until: new Date(date[2], date[0] - 1, date[1]),
			layout: '{dn}Days, {hn}Hours, {mn}Min, {sn}Sec'
		});
	}
	
	//countdown timer
	if ($('div.timer.enabled h3').length == 1) {
		var date = $('div.timer.enabled h3').html().split("/");

		$('div.timer.enabled h3').countdown({
			until: new Date(date[2], date[0] - 1, date[1]),
			layout: '{dnn}:{hnn}:{mnn}:{snn}',
			onExpiry: pageRefresh
		});
	}
	
	function pageRefresh() {
		location.reload(true);
	}
	
	// jquery drawer effect
	$('.jquery-drawer').hover(function() {
		$(this).children('div').stop(true, true).animate({
			bottom:	'+=54px'
		}, 200)}, function() {
		$(this).children('div').stop(true, true).animate({
			bottom:	'-=54px'
		}, 200)
	});
	
	//almost out of stock messaging
	$('.si-options').change(function() {
		if ($('.si-stock').html() < 11) {
			$('.si-stock-wrapper').show();
		}
		else if ($('.si-stock').html() >= 11) {
			$('.si-stock-wrapper').hide();
			$('.si-out-of-stock-wrapper').hide();
		}
		else if ($('.si-stock').html() == 0) {
			$('.si-out-of-stock-wrapper').show();
		}
	});
	
	//product description tabs
	$('.prod-descriptions').tabs();
	
	//last child fix
	$('.ui-slider-handle:last').addClass('ui-state-last');
	
	//crazy sidebar action
	
	$grandchildren = $('div.sidebar-section li.si-has-children li.si-has-children');
	
	$grandchildren.prepend('<span class="arrow"></span>');
	
	$('ul', $grandchildren).hide();
	
	$('div.sidebar-section span.arrow').click(function() {
		$(this).toggleClass('open');
		$(this).nextAll('ul').slideToggle();
	});
	
	$('div.sidebar-section li.si-has-children li.si-has-children a.si-current')
		.parents().show()
		.end()
		.parent()
			.find('ul:first').show()
			.end()
			.find('span:first').toggleClass('open');
	
	$grandchildren.has('.si-current').find('span:first').toggleClass('open');
	
	$('.si-current', $grandchildren).parent().find('span:first').toggleClass('open');
	
    //product image switcheroo
    $('div.gallery img').click(function() {
    	var lrg = $(this).attr('src').replace('_thumb', '_large');
    	var src = $(this).attr('src').replace('_thumb', '');
    	$.ajax({
    		url:		lrg,
    		type:		'HEAD',
    		error:		function() { 
    			$('.main-image a').attr('href', src);
    			$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
    			},
    		success:	function() { 
    			$('.main-image a').attr('href', lrg);
    			$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
    			}
    	});
    });
    $('div.gallery img.si-current').trigger('click'); //ensures that zoom img is correct for first thumbnail
    
    //lightbox
    $('a[rel="lightbox"]').click(function() {
    	$('#lightbox').empty().append('<img src="">').append('<a href="#" class="close si-invisitext">Close</a>');
    	$('#lightbox img').attr('src', $(this).attr('href'));
    	$('#lightbox').lightbox_me({
    		centered: true
    	});
    	return false;
    });
    $('div.main-image').click(function() {
    	var src = $('.main-image a img').attr('src').replace('_medium', '');
    	$('#lightbox').empty().append('<img src="">').append('<a href="#" class="close si-invisitext">Close</a>');
    	$('#lightbox img').attr('src', src);
    	$('#lightbox').lightbox_me({
    		centered: true
    	});
    });
    
    //fix that price slider
    $('.si-product-price-slider').wrap('<div class="price-ranger" />');
	
	// make sure ui widgets get initialized when elements get added to the dom
	$(document).bind('render.si', function(event) {
		init(event.target);
	});
	
	// initialize ui widgets on the initial page load
	init(document);
	
	// initialize menu dropdowns (this takes a long time, so do it after the rest of the JS has initialized)
	//$('#main-nav > ul').dropDown({ arrows:false });
	$('#main-nav ul ul').addClass('si-clearfix');
	$('#main-nav > ul > li').addClass('loaded');
	$('#main-nav > ul > li.loaded').hover(function() {
		$(this).children('ul').stop(true, true).fadeIn("fast");
	}, function() {
		$(this).children('ul').stop(true, true).fadeOut("fast");
	});
	
	$('div.header-links-inner > ul > li').addClass('loaded');
	$('div.header-links-inner > ul > li.loaded').hover(function() {
		$(this).children('ul').stop(true, true).fadeIn("fast");
	}, function() {
		$(this).children('ul').stop(true, true).fadeOut("fast");
	});
});

