$(function(){
	
	$.fn.productDetail = function(){
		
		var productDetail = $(this);
		var productId = productDetail.find('input[name = productId]').val();
		var JSONInventoryURL = productDetail.find('input[name = JSONInventory-link]').val();
		var JSONItemPricingURL = productDetail.find('input[name = JSONItemPricing-link]').val();
		var ValidSizeOptionsURL = productDetail.find('input[name = ValidSizeOptions-link]').val();
		// var form = productDetail.find('form'); don't use this, ajax calls may replace form content
		
		// changed for Powerreviews
		
		//productDetail.parent().parent().find('.tabs').tabs(); //the product description tabs
		$('#tabContainer').find('.tabs').tabs();
		
		// cart form submission
		productDetail.find('.add-to-cart-button').livequery('click', function(e) {
			e.preventDefault();
			var action = productDetail.find('form').attr('action');
			var errorFunction = function() {
				var sizeSelectBox = $('.attribute-size select');
				if (sizeSelectBox.length) {
					$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
				}
				
				$.fn.inventory(productId, false, productDetail, JSONInventoryURL);
			};
			var successFunction = function() {
				//window.location = $('#cartUrl').val();
				//$.fn.colorbox.close()
				//productDetail.find('form').show();
				$.fn.inventory(productId, false, productDetail, JSONInventoryURL);
				$('html, body').animate({scrollTop: 0}, 'slow');
				refreshAndDisplayMiniCart(); // display the minicart on success.
			};
			$.fn.submitCartForm(productDetail, action, errorFunction, successFunction);
		});
		
		// inventory notification form submission
		productDetail.find('a.unavailable-message').livequery('click', function(e) {
			e.preventDefault();
			var action = $(this).attr('href');
			$.fn.submitInventoryForm(productId, productDetail, action, JSONInventoryURL); // see jquery.addtocart.js
		});
		
		// close button for the inventory notification messages
		productDetail.find('.close-button').livequery('click', function(e) {
			e.preventDefault();
			$(this).parent().remove();
		});
		
		// POWERREVIEWS START
		// link in snippet (under the title)
	    // get rid of .parent.parent
		productDetail.parent().parent().find('.pr-snippet-write-review, .pr-snippet-write-first-review').find('a.pr-snippet-link').livequery('click', function(e) {
			e.preventDefault();
			$.fn.colorbox({
				opacity: .3
				//, scrolling: true
				, href: $(this).attr('href')
				, iframe: true
				, fastIframe: false
				, width: 700
				, height: 800
			});
		});

		$('#tabContainer').find('.pr-snapshot-footer').find('a.pr-write-review-link').livequery('click', function(e) {
			e.preventDefault();
			$.fn.colorbox({
				opacity: .3
				//, scrolling: true
				, href: $(this).attr('href')
				, iframe: true
				, fastIframe: false
				, width: 700
				, height: 800
			});
		});

		// POWERREVIEWS END
		
		// defining attribute button
		productDetail.find('button.option, button.color-swatch').livequery('click', function(e) {
			e.preventDefault();
			$(this).attributeButton(); // see jquery.addtocart.js

			//if this is a color swatch, change the product photo and filter the size options
			if ($(this).hasClass('color-swatch')) {
				//var colorcode = $(this).val(); can't use this because IE7/IE6 does not support it
				var colorcode = $(this).find('span').text();
				var sizeSelectBox = $('.attribute-size select');
				
				$.fn.togglePrice(productId, productDetail, JSONItemPricingURL);
				
				changePhoto(colorcode);
				
				if (sizeSelectBox.length) {
					var size = sizeSelectBox.find('option:selected').val();
					$.fn.filterSizeOptions(productId, colorcode, size, sizeSelectBox, ValidSizeOptionsURL);
				}
			}
			$.fn.inventory(productId, true, productDetail, JSONInventoryURL);
		});
		
		// defining attribute selection box option
		productDetail.find('.attribute select').livequery('change', function(e) {
			e.preventDefault();
			$(this).attributeSelectOption(); // see jquery.addtocart.js
			
			if ($(this).hasClass('color-swatch')) {
				var sizeSelectBox = $('.attribute-size select');
				var colorcode = $(this).val();
				
				$.fn.togglePrice(productId, productDetail, JSONItemPricingURL);
				
				//if this is a color selection and is not null, change the product photo
				if (colorcode) {
					changePhoto(colorcode);
				}
				
				//if this is a color selection and multiple sizes are available, filter the size options
				if (sizeSelectBox.length) {
					var size = sizeSelectBox.find('option:selected').val();
					$.fn.filterSizeOptions(productId, colorcode, size, sizeSelectBox, ValidSizeOptionsURL);
				}
			}
			$.fn.inventory(productId, true, productDetail, JSONInventoryURL);
		});
		
		// alternate view thumbnail product photos -- these are not contained inside the productDetail container
		$('.image-set a').click(function(e) {
			e.preventDefault();
			var $this = $(this);
			$('.image-set a.selected').removeClass('selected');
			$this.addClass('selected');
			$this.blur();
			
			// added for ie6
			eval($this.attr('href'));
		});
		
		// email a friend lightbox and form initialization
		var emailAFriendLink = productDetail.find('.email-a-friend-link');
		emailAFriendLink.click(function(e) {
			e.preventDefault();
		});
		emailAFriendLink.colorbox({
			opacity: .3
			, scrolling: false
			, onComplete: function() {
				$.fn.colorbox.resize();
				_gaq.push(['_trackPageview', $(this).val('action')]);
				$('#emailAFriendForm').livequery('submit', function(e) {
					e.preventDefault();
					var form = $(this);
					form.hide();
					var loadingMsg = form.next('.loading-image');
					loadingMsg.css('height', form.height());
					loadingMsg.css('width', form.width());
					loadingMsg.show();
					$.ajax({
						url: form.attr('action'),
						data: form.serialize(),
						complete: function(html) {
							loadingMsg.hide();
							var validatedForm = $(html.responseText).find('form');
							form.after(validatedForm);
							form.remove();
							$.fn.colorbox.resize();
						}
					});
				});
			}
			, maxWidth: '100%'
		});

		// add to wishlist form submission
		productDetail.find('.add-to-wishlist-link').livequery('click', function(e) {
			e.preventDefault();
			var action = $(this).attr('href');
			var wishLink = productDetail.find('#wishListUrl').val();
			var errorFunction = function() {
				var sizeSelectBox = $('.attribute-size select');
				if (sizeSelectBox.length) {
					$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
				}
				
				$.fn.inventory(productId, false, productDetail, JSONInventoryURL);
			};
			var successFunction = function() {
				window.location = wishLink;
			};
			$.fn.submitCartForm(productDetail, action, errorFunction, successFunction);
		});
		
		var sizeSelectBox = $('.attribute-size select');
		if (sizeSelectBox.length) {
			$.fn.loadFilteredSizeOptions(productId, sizeSelectBox, ValidSizeOptionsURL);
		}
		
		$.fn.inventory(productId, false, productDetail, JSONInventoryURL);
	};
	
	//note that this function is duplicated in jquery.quickview.js
	//ajax refresh and display of mini cart
	var refreshAndDisplayMiniCart = function() {
	   var miniCartUrl = $("#ajaxMiniCartURL").attr('href');
	   $("#miniCart").load(miniCartUrl, function() {
		   $("#miniCart").addClass('miniCartExpanded');

			var updatedFreeShipping = "";
			var eSpotURL= $('#header').find('input[name = eSpotImportURL-link]').val();
			var targetAmount= $('#header').find('input[name = targetAmount]').val();
			var orderSubtotal= $('#unformattedOrderSubtotal').val();
			//var orderSubtotal= $('#header').find('input[name = orderSubtotalNoDiscount]').val();
			var remainingAmount = targetAmount - orderSubtotal;
			remainingAmount = "$" + remainingAmount.toFixed(2);
			eSpotURL = eSpotURL.replace('RemainingAmountReplace', remainingAmount);
			
			updatedFreeShipping = $.ajax({
					url: eSpotURL,
					dataType: 'html',
					success: function(data, textStatus, jqXHR)
					{
				 		$('#header').find('#headerEspot').html(data);
					},
					error: function(XMLHttpRequest, textStatus, errorThrown) {
						//alert(textStatus + errorThrown);
						//alert(XMLHttpRequest.responseText);
						return;
					}
				});	
		});
	};
	
	// s7 with colors...
	var changePhoto = function(colorcode) {
		var partnumber = $('#product-detail-partnumber').text();
		
		//change the main photo
		var resetZoom = true;
		s7zoom.setImage(S7ConfigClient.isRoot + '/' + company + partnumber + '_' + colorcode + S7_FILTERS, resetZoom);
		
		//change the main photo that appears in the larger view popup
		$('#larger-view-link').querystring('href', 'photo=/' + company + partnumber + '_' + colorcode, 0);
		
		//change the thumbnail that corresponds to the main photo
		$('#main-image-thumbnail img').attr('src', S7ConfigClient.isRoot + company + partnumber + '_' + colorcode + '?' + S7_THUMBNAIL);
		$('#main-image-thumbnail').attr('href', 'javascript:s7zoom.setImage(\'' + S7ConfigClient.isRoot + company + partnumber + '_' + colorcode + S7_FILTERS + '\', true)');

		//change which thumbnail is highlighted
		$('.image-set a.selected').removeClass('selected');
		$('#main-image-thumbnail').addClass('selected');
	};
})

