$(function() {
	// apply png fix

	// watch for close of product zoom
	$('#productzoom').click(function() {
		$("#productdetail").css("visibility", "visible");
		$('#productdisplay').show();
		$(this).fadeOut('normal');
	});

	$('#spin360close').click(function() {
		$("#productdetail").css("visibility", "visible");
		$('#productdisplay').show();
		$("#spin360").fadeOut('normal');
	});



	// cross browser toggle for color swatches
	$(".color").hover(
		function() { $(this).css('backgroundPosition', 'top left'); },
		function() { $(this).css('backgroundPosition', 'bottom left');
	});

	// watch for product thumbnail click
	$('#selectview').find('td a').click(changeProductImage);
	$(".color").click(changeProductContent);
	$('.color').click(changeProductImage);

	// watch for changes in product states
	productNav();

	// watch for read more review
	$('.reviewtxt .read-more').live('click', expandReview);
	$('.nb-response .read-more').live('click', expandResponse);

	// watch for helpful click
	$('.helpful a').live('click', submitHelpfulReview);

	// watch for toggle between helpful and recent
	$('.sortby a').live('click', sortReviews);

	// watch for pagination
	$('.reviewblock .pagination a').live('click', paginateReviews);

	$('.add-review').click(showAddReview);
	$('.add-review-text').click(showAddReview);

	$(".read-all-reviews").click(function() {
		$("a[rel=customer-reviews]").click();
	});
});

/**
 * Changes a product image.
 */
soleActive = false;
function changeProductImage() {

	$this = $(this);

	// get the image type
	var type = $this.attr('rel');

	if ($this.hasClass('color')) {
		$('.productcolors').find('.selected').removeClass('selected');
		$('#selectview td').removeClass('selected');
		$('#selectview td:first').addClass('selected');
		$this.addClass('selected');
	} else {
		$this.parent().parent().find('td').removeClass('selected');
		$this.parent().addClass('selected');
	}

	// handle type
	if (type == 'spin') {
		$("#productdetail").css("visibility", "hidden");
		$("#productdisplay").fadeOut('fast');
		$('#productzoom').fadeOut('fast');
		$('#spin360').fadeIn('fast');
	} else if (type == 'zoom') {

		$("#productzoomflash").html('<div class="zoomload">' +
									'<img src="'+STATIC_SERVER+'public/img/preloaders/large.gif" alt="loading"/>' +
									'<p class="loading">Loading</p>' +
									'</div>');
		if (soleActive == true) {
			loadDynamicImage(currentColor['zoomview_sole'], onProductZoomImageLoadComplete, 600);
			$('#productzoomfooter').html($('#productzoomfooter').html().replace(/PROFILE/ig, "SOLE"));
			$('#productzoomflash').addClass('solePadding');
		}else{
			loadDynamicImage(currentColor['zoomview'], onProductZoomImageLoadComplete, 600);
			$('#productzoomfooter').html($('#productzoomfooter').html().replace(/SOLE/ig, "PROFILE"));
			$('#productzoomflash').removeClass('solePadding');
		}

		$("#productdetail").css("visibility", "hidden");
		$("#productdisplay").fadeOut('fast');
		$('#spin360').fadeOut('fast');
		$('#productzoom').fadeIn('fast');

	} else {

		// remove pngfix

		// switch to preloader
		$('#productimage td img').remove();
		$('#productimage td').prepend('<img src="'+STATIC_SERVER+'public/img/preloaders/large.gif" />').append('<p class="loading">Loading</p>');

		var imgPropertyName = "";
		if (colorData[type] != undefined) {
			// update the currently selected color
			currentColor = colorData[type];
			imgPropertyName = 'profilelargeview';
			soleActive = false;
		} else {
			if(type == "sole"){soleActive = true;}else{soleActive = false;}
			imgPropertyName = type + 'largeview';
		}
		// preload image
		loadDynamicImage(currentColor[imgPropertyName], onProductImageLoadComplete, 600);
	}

	return false;
}

/**
 * Dynamically loads in image before display.
 */
function loadDynamicImage(data, onCompleteCallback, timeout) {
	var img = new Image();
	$(img).load(function () {
		setTimeout(function() { onCompleteCallback(data) }, timeout);
		delete img;
	}).error(function () {
		// notify the user that the image could not be loaded
		alert('An error occurred attempting to load the image.');
	}).attr('src', data);
}

function onProductImageLoadComplete(imageSrc)
{
	$('#productimage td .loading').fadeOut(function() {
		$(this).remove();
	});

	$("#productimage td img").fadeOut(function() {
		var $this = $(this);
		if ($('#spin360').not(':hidden')) {
			$('#spin360').fadeOut('fast', function() {
				$this.attr('src', imageSrc).css({ height: '', width: '' });
				setTimeout(function() {  $this.fadeIn();  }, 100);
			});
		} else {
			$this.attr('src', imageSrc).css({ height: '', width: '' });
			setTimeout(function() { $this.fadeIn();  }, 100);
		}
	});
}

function onProductZoomImageLoadComplete(imageSrc)
{
	$("#productzoomflash").fadeOut(function() {
		var $this = $(this);
		$this.html('<img id="zoomViewImg" src="' + imageSrc + '">');
		$this.fadeIn('fast', function() {
			//setTimeout(function() { $this.find('img').ifixpng(); }, 250);
		});
	});
}

/**
 * Handles the right navigation for products.
 */
function productNav() {

	$.address.init(function(e) {
		$('.productnav .item').click(function() {
			$.address.value($(this).attr("rel"));
			return false;
		});
	}).change(function(e) {

		var pathNames = $.address.pathNames();
		var navItem;

		// set the navigation element
		if (pathNames.length > 0) {
			thisPath = pathNames[0];
		//}else{
			//thisPath = "highlights-and-features";
			//navItem = $(".productnav .item[rel=highlights-and-features]");
			navItem = $('.productnav .item[rel=' + thisPath + ']');
			var title = navItem.text();
	
			// define scripts for each section
			var sectionScripts = {
				'highlights-and-features': "",
				'customer-reviews': DATA_SERVER+"public/js/products/addreview.js",
				'product-videos': "",
				'editorial-reviews': "",
				'related-content': ""
			};
	
			var scriptName = sectionScripts[navItem.attr("rel")];
			var contentId = "#content-" + navItem.attr("rel");
	
			// switch selected element
			navItem.siblings('.selected').removeClass('selected');
			navItem.addClass('selected');
	
			if (scriptName) {
				// dynamically load the required javascript
				//$.getScript(DATA_SERVER+'/public/js/' + scriptName, function() {
					// switch div and titles
					$('.contentblock:not(:hidden)').fadeOut('normal', function() {
						//needs to be fixed for ipad////////sIFR.getReplacementByFlashElement($('#productheader').children('.sIFR-flash')[0]).replaceText(title);
						$(contentId).fadeIn('normal');
					});
				//	});
			} else {
				$('.contentblock:not(:hidden)').fadeOut('normal', function() {
					//needs to be fixed for ipad////////replacements['h2.sifr-red'][0].replaceText(title);
					$(contentId).fadeIn('normal');
				});
			}
		}


	});
}

function expandReview(){
	var $review = $(this).parents('.review');
	//alert(reviewItem.attr("review_id"));
	//var $review = $('.review_id_'+reviewItem.attr("review_id"));
	$review.find('.reviewtxt').slideUp();
	$review.find('.extendedreview').slideDown('normal', function() {
		var $collapseBtn = $review.find('.btn-collapse');
		$collapseBtn.css('visibility', 'visible');
		$collapseBtn.one('click', collapseReview);
	});
	return false;
}

function collapseReview(thisItem) {
	var $collapseBtn = $(this);
	var $review = $(this).parents('.review');
	$review.find('.reviewtxt').slideDown();
	$review.find('.extendedreview').slideUp('normal', function() {
		$collapseBtn.css('visibility', 'hidden');
	});
	return false;
}

function expandResponse() {
	var $response = $(this).parents('.response-content');
	$response.find('.expandedresponse').slideDown('normal');
	return false;
}

function changeProductContent() {
	var colorrel = $(this).attr('rel');

	// unbind pngfix
	if(colorData[colorrel].typeOf != '2') {
		$('#buynowlink').attr("href", 'http://www.nbwebexpress.com/detail.asp?s1=NBAS&s2=buynow&style=' + colorData[colorrel].style);
	}

	$("#selectview a[rel=profile] img").attr('src', colorData[colorrel].profileview);
	$("#selectview a[rel=sole] img").attr('src', colorData[colorrel].soleview);
	
	if (colorData[colorrel].spinview != "") {
		$("#spinThumbHolder1").show();
		$("#spinThumbHolder2").show();
		$("#selectview a[rel=spin] img").attr('src', colorData[colorrel].spinview);
		
		var flashvars = {};
	    var params = {};
	        //params.scale = "exactfit";
	        params.wmode = "transparent";
	        params.bgcolor = "#000000";
			params.base = colorData[colorrel].spinviewLocation;
	    var attributes = {};
	    swfobject.embedSWF(colorData[colorrel].spinviewLocation+"/360.swf", "spin360content", "500", "415", "9", null, flashvars, params, attributes);

		
	}else{
		$("#spinThumbHolder1").hide();
		$("#spinThumbHolder2").hide();
		
		$("#selectview a[rel=spin] img").attr('src', "/images/pixel.gif");
	}

	// rebind pngfix
	//setTimeout(function() { $("#selectview img").ifixpng(); }, 250);

	var shoeSizeMarkup = "";
	var shoeWidths = [];
	for (var width in colorData[colorrel].shoesizes) {
		shoeWidths.push(width);
		shoeSizeMarkup += '<tr class="alt">' +
			'<td class="thirtysix center">' + width + '</td>' +
			'<td>' + colorData[colorrel].shoesizes[width] + '</td>' +
		'</tr>';
	}

	$("#widthchart a").html(shoeWidths.join(", ") + ' (shoe sizes)');
	$("#tt_widthchart tbody").html(shoeSizeMarkup);
}

function submitHelpfulReview() {
	var $this = $(this);
	var isHelpful = ($this.hasClass('btn-no')) ? 0 : 1;
	var $parent = $this.parent().parent();
	var reviewId = $parent.attr('rel');
	$.post(DATA_SERVER+'ajax/actions.php?action=reviewFeedback', { reviewID: reviewId, productID: PRODUCT_ID, feedback : isHelpful }, function(data) {
		$parent.html('<span>Thank you for your feedback.</span>');
	});
	return false;
}

function sortReviews() {
	var $this 	= $(this);
	if ($this.hasClass('active')) return false;
	var sortby 	= ($this.hasClass('most-helpful')) ? 'helpful' : 'recent';
	if (sortby == 'helpful') {
		$('.sortby .most-recent').removeClass('active');
		$('.sortby .most-helpful').addClass('active');
	} else {
		$('.sortby .most-helpful').removeClass('active');
		$('.sortby .most-recent').addClass('active');
	}
	productPagination(0, sortby);
	return false;
}

function paginateReviews() {
	var $this	= $(this);
	var page	= $this.attr('rel');
	var $sortby	= $('.sortby a.active');
	$sortby.removeClass('active');
	var sortby	= ($sortby.hasClass('most-helpful')) ? 'helpful' : 'recent';
	if (sortby == 'helpful') $('.sortby .most-helpful').addClass('active');
	else $('.sortby .most-recent').addClass('active');
	productPagination(page, sortby);
	return false;
}

function productPagination(page, sortby) {

	$productreviews = $('#productreviews');
	window.scrollTo(0,$productreviews.offset().top);
	$productreviews.block({ message: '<img src="'+STATIC_SERVER+'public/img/preloaders/large.gif" /><br />Loading',
							css: {
								width: '100%',
								height: '88%',
								top: '12%',
								left: 0,
								border: 'none',
								padding: '0',
								backgroundColor: '#fff',
								opacity: .3,
								color: '#000'
							},
							overlayCSS:  {
								backgroundColor: '#fff',
								opacity: 0.6
							}
						  });

	$.post(DATA_SERVER+'ajax/reviews.php?productID='+PRODUCT_ID, { orderby: sortby, page: page }, function(data) {
		$productreviews.find('.review').remove();
		$productreviews.find('.pagination-container').remove();
		$productreviews.append(data);
		$productreviews.fadeIn('fast');
		$productreviews.unblock();
	});

	return false;
}

function showAddReview() {

	initReviewFormState();

	$('.contentblock:not(:hidden)').fadeOut('normal', function() {
		$('.addareviewblock').fadeIn(function() {
			$('.cancelreview').one('click', function() {
				$(this).parents('.contentblock').fadeOut(function() {
					$('.reviewblock').fadeIn();
				});
				return false;
			});
		});
	});
	return false;
}

function initReviewFormState()
{
	var $form = $("#reviewform");
	$('input:checked', $form).attr('checked', '');
	$('textarea', $form).val("");

	$('.starcontainer', $form).each(function() {
		$('input:last', this).click();
	});

	$('.slidercontainer input[name=size]:eq(2)', $form).click();
	$('.slidercontainer input[name=width]:eq(2)', $form).click();
	$('.slidercontainer input[name=repurchase]:eq(4)', $form).click();
}

