steveosoule
7/8/2016 - 7:43 PM

Levels Thumbnail Update

Levels Thumbnail Update

jsPROD: function () {
		// ---- Open Product Image Gallery ---- //
		cornerstoneUX.sharedFunctions.productGallery($('#js-main-image-zoom'));

		var mainImageZoom = $('#js-main-image-zoom'),
			thumbnails = $('#js-thumbnails');

		thumbnails.on('click', 'div', function () {
			var thumbnailIndex = $(this).attr('data-index');
			mainImageZoom.attr('data-index', thumbnailIndex);
			var clickedLI = parseFloat($(this).attr('data-index'));
			if ( thumbnailIndex ) {
				$('#js-main-dots li.active').removeClass('active');
				$('#js-main-dots li[data-index="' + thumbnailIndex + '"]').addClass('active');
			}
		});

		var debouncedThumbnailSlider = debounce(function(){
			$('#js-thumbnails').unslick().slick({
				vertical: true,
				draggable: false,
				slidesToScroll: 1,
				slidesToShow: 4
			});
		}, 100);

		$.getScript(theme_path + '/js/jquery.slick.min.js', debouncedThumbnailSlider);
		$(window).resize(debouncedThumbnailSlider);

		// ---- Update Button For "Out Of Stock" ---- //
		function outOfStock () {
			var button = $('#js-add-to-cart'),
				buttonText = button.val();

			if (button.is(':disabled') === true) {
				button.addClass('bg-gray').val('Sold Out');
			}
			else {
				button.removeClass('bg-gray').val(buttonText);
			}
		}
		outOfStock();

		// ---- Set Initial Swatch Name ---- //
		$('#js-swatch-name').text($('#js-swatch-select').find('option:first-child').text());

		// ---- Add Border to Active Swatch ---- //
		function selectedSwatch () {
			$('#js-swatches').find('li').each(function () {
				var swatchElement = $(this),
					swatchColor = swatchElement.attr('data-code');

				swatchElement.removeClass('selected-swatch');
				if (swatchColor === $('#js-swatch-select').find('option:selected').val() ) {
					swatchElement.addClass('selected-swatch');
					// swatchColor = swatchColor.replace(/ /g,'');
					// swatchColor = swatchColor.toLowerCase();

					// var namedColors = {
					// 	aliceblue: 'f0f8ff',antiquewhite: 'faebd7',aqua: '00ffff',aquamarine: '7fffd4',azure: 'f0ffff',beige: 'f5f5dc',bisque: 'ffe4c4',black: '000000',blanchedalmond: 'ffebcd',blue: '0000ff',blueviolet: '8a2be2',brown: 'a52a2a',burlywood: 'deb887',cadetblue: '5f9ea0',chartreuse: '7fff00',chocolate: 'd2691e',coral: 'ff7f50',cornflowerblue: '6495ed',cornsilk: 'fff8dc',crimson: 'dc143c',cyan: '00ffff',darkblue: '00008b',darkcyan: '008b8b',darkgoldenrod: 'b8860b',darkgray: 'a9a9a9',darkgreen: '006400',darkkhaki: 'bdb76b',darkmagenta: '8b008b',darkolivegreen: '556b2f',darkorange: 'ff8c00',darkorchid: '9932cc',darkred: '8b0000',darksalmon: 'e9967a',darkseagreen: '8fbc8f',darkslateblue: '483d8b',darkslategray: '2f4f4f',darkturquoise: '00ced1',darkviolet: '9400d3',deeppink: 'ff1493',deepskyblue: '00bfff',dimgray: '696969',dodgerblue: '1e90ff',feldspar: 'd19275',firebrick: 'b22222',floralwhite: 'fffaf0',forestgreen: '228b22',fuchsia: 'ff00ff',gainsboro: 'dcdcdc',ghostwhite: 'f8f8ff',gold: 'ffd700',goldenrod: 'daa520',gray: '808080',green: '008000',greenyellow: 'adff2f',honeydew: 'f0fff0',hotpink: 'ff69b4',indianred : 'cd5c5c',indigo : '4b0082',ivory: 'fffff0',khaki: 'f0e68c',lavender: 'e6e6fa',lavenderblush: 'fff0f5',lawngreen: '7cfc00',lemonchiffon: 'fffacd',lightblue: 'add8e6',lightcoral: 'f08080',lightcyan: 'e0ffff',lightgoldenrodyellow: 'fafad2',lightgrey: 'd3d3d3',lightgreen: '90ee90',lightpink: 'ffb6c1',lightsalmon: 'ffa07a',lightseagreen: '20b2aa',lightskyblue: '87cefa',lightslateblue: '8470ff',lightslategray: '778899',lightsteelblue: 'b0c4de',lightyellow: 'ffffe0',lime: '00ff00',limegreen: '32cd32',linen: 'faf0e6',magenta: 'ff00ff',maroon: '800000',mediumaquamarine: '66cdaa',mediumblue: '0000cd',mediumorchid: 'ba55d3',mediumpurple: '9370d8',mediumseagreen: '3cb371',mediumslateblue: '7b68ee',mediumspringgreen: '00fa9a',mediumturquoise: '48d1cc',mediumvioletred: 'c71585',midnightblue: '191970',mintcream: 'f5fffa',mistyrose: 'ffe4e1',moccasin: 'ffe4b5',navajowhite: 'ffdead',navy: '000080',oldlace: 'fdf5e6',olive: '808000',olivedrab: '6b8e23',orange: 'ffa500',orangered: 'ff4500',orchid: 'da70d6',palegoldenrod: 'eee8aa',palegreen: '98fb98',paleturquoise: 'afeeee',palevioletred: 'd87093',papayawhip: 'ffefd5',peachpuff: 'ffdab9',peru: 'cd853f',pink: 'ffc0cb',plum: 'dda0dd',powderblue: 'b0e0e6',purple: '800080',red: 'ff0000',rosybrown: 'bc8f8f',royalblue: '4169e1',saddlebrown: '8b4513',salmon: 'fa8072',sandybrown: 'f4a460',seagreen: '2e8b57',seashell: 'fff5ee',sienna: 'a0522d',silver: 'c0c0c0',skyblue: '87ceeb',slateblue: '6a5acd',slategray: '708090',snow: 'fffafa',springgreen: '00ff7f',steelblue: '4682b4',tan: 'd2b48c',teal: '008080',thistle: 'd8bfd8',tomato: 'ff6347',turquoise: '40e0d0',violet: 'ee82ee',violetred: 'd02090',wheat: 'f5deb3',white: 'ffffff',whitesmoke: 'f5f5f5',yellow: 'ffff00',yellowgreen: '9acd32'
					// };
					// for (var key in namedColors) {
					// 	if (swatchColor === key) {
					// 		swatchElement.css('border-color', '#' + namedColors[key]);
					// 	}
					// 	else {
					// 		swatchElement.addClass('selected-swatch');
					// 	}
					// }
				}
			});
		}
		selectedSwatch();

		// ---- Update Display When Attribute Machine Fires ---- //
		MivaEvents.SubscribeToEvent('variant_changed', function () {
			gallery.length = 0;
			mainImageZoom.attr('data-index', 0);
			thumbnailIndex = 0;
			outOfStock();
			selectedSwatch();
			debouncedThumbnailSlider();
		});

		document.addEventListener('ImageMachine_Generate_Thumbnail', function(e) {
			debouncedThumbnailSlider();
		}, false);

		// ---- Update Display Price Based on Attribute Selections (If Attribute Machine Is Not Being Used) ---- //
		if (typeof attrMachCall === 'undefined' && document.getElementById('js-product-attribute-count').value > 0) {
			for(var baseProductPrice=Number(document.getElementById("js-price-value").getAttribute("data-base-price")),regularProductPrice=Number(),productAttributeCount=Number(document.getElementById("js-product-attribute-count").value+1),productAttributes=document.getElementById("js-purchase-product").elements,attributeType=[""],i=0;i<productAttributes.length;i++){var tagName=productAttributes[i].tagName.toLowerCase(),elementType=productAttributes[i].type,type=productAttributes[i].getAttribute("data-attribute-type"), name=productAttributes[i].name;"hidden"==elementType&&null!=type&&attributeType.push(type);productAttributes[i].onchange=function(){updateProductDisplayPrice()}} function updateProductDisplayPrice(){for(var b,a,c=baseProductPrice,f=regularProductPrice,d=1;d<productAttributeCount;d++)if(b=document.getElementsByName("Product_Attributes["+d+"]:value"),"select"==attributeType[d])for(var e=0;e<b.length;e++)a=b.item(e),a=a.options.item(a.selectedIndex),c+=Number(a.getAttribute("data-option-price")),f+=Number(a.getAttribute("data-regular-price"));else if("radio"==attributeType[d]||"checkbox"==attributeType[d])for(e=0;e<b.length;e++)a=b.item(e),a.checked&&(c+=Number(a.getAttribute("data-option-price")), f+=Number(a.getAttribute("data-regular-price")));else if("text"==attributeType[d]||"memo"==attributeType[d])a=b.item(0),a.value&&(c+=Number(a.getAttribute("data-option-price")),f+=Number(a.getAttribute("data-regular-price")));b=document.getElementsByName("Quantity");c*=Number(b.item(0).value);b.item(0);document.getElementById("js-price-value").innerHTML=formatCurrency(c);document.getElementById("js-mobile-price-value")&&(document.getElementById("js-mobile-price-value").innerHTML=formatCurrency(c))} function formatCurrency(b){var a=!1;0>b&&(a=!0,b=Math.abs(b));return(a?"-$":"$")+parseFloat(b,10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g,"$1,").toString()}updateProductDisplayPrice();
		}

		// ---- AJAX Add To Cart ---- //
		function addToCart () {
			$('#js-add-to-cart').on('click', function (e) {
				var purchaseForm = $('#js-purchase-product');
				// Check the form is not currently submitting
				if (purchaseForm.data('formstatus') !== 'submitting') {
					// Set up variables
					var form = purchaseForm,
						formData = form.serialize(),
						formUrl = form.attr('action').replace('^https?:', ''),
						formMethod = form.attr('method'),
						responseMessage = $('#js-purchase-message'),
						miniBasket = $('#js-mini-basket-container'),
						processingImage = $('#js-processing-purchase'),
						purchaseButton = $(this),
						purchaseButtonText = purchaseButton.val();

					// Add status data to form
					form.data('formstatus', 'submitting');

					// Show processing message
					processingImage.show();
					purchaseButton.toggleDisabled().val('Processing...');
					responseMessage.html('').hide();

					// Send data to server for validation
					$.ajax({
						url: formUrl,
						type: formMethod,
						cache: false,
						data: formData,
						success: function(data, textStatus, jqXHR) {
							if (data.search(/id="js-BASK"/i) != -1) {
								$('html, body').animate({scrollTop: '0px'}, 250);
								var responseMiniBasket = $(data).find('#js-mini-basket-container'),
									miniBasketCount = responseMiniBasket.contents()[1].getAttribute('data-itemcount'),
									miniBasketSubtotal = ' ' + responseMiniBasket.contents()[1].getAttribute('data-subtotal'),
									miniBasketLinkCount = $('#js-mini-basket-count, #js-mobile-basket-button .notification'),
									miniBasketLinkSubtotal = $('#js-mini-basket-subtotal');

								miniBasketLinkCount.text(miniBasketCount); // Update basket quantity (display only)
								miniBasketLinkSubtotal.text(miniBasketSubtotal); // Update basket subtotal (display only)

								miniBasket.html(responseMiniBasket.contents()).addClass('open');
								setTimeout(function () {
									miniBasket.removeClass('open');
								}, 5000);

								// Re-Initialize Attribute Machine (if it is active)
								if (typeof attrMachCall !== 'undefined') {
									attrMachCall.Initialize();
								}
							}
							else if(data.search(/id="js-PATR"/i) != -1) {
								var missingAttrs = [];
								form.find('.required').each(function () {
									missingAttrs.push(' ' + $(this).attr('title'));
								});
								responseMessage.html('All <em class="red">Required</em> options have not been selected.<br />Please review the following options: <span class="red">' + missingAttrs + '</span>.').fadeIn().delay(5000).fadeOut();
							}
							else if(data.search(/id="js-PLMT"/i) != -1) {
								responseMessage.html('We do not have enough of the Size/Color you have selected.<br />Please adjust your quantity.').fadeIn().delay(3000).fadeOut();
							}
							else if(data.search(/id="js-POUT"/i) != -1) {
								responseMessage.html('The Size/Color you have selected is out of stock.<br />Please review your options or check back later.').fadeIn().delay(3000).fadeOut();
							}
							else {
								responseMessage.html('Please review options.').fadeIn().delay(3000).fadeOut();
							}

							// Hide processing message and reset formstatus
							processingImage.hide();
							purchaseButton.toggleDisabled().val(purchaseButtonText);
							form.data('formstatus', 'idle');
						},
						error: function (jqXHR, textStatus, errorThrown) {
						}
					});
				}
				// Prevent form from submitting
				e.preventDefault();
			});
		}
		addToCart();

		// ---- Related Products Carousel ---- //
		$.getScript(theme_path + '/js/jquery.slick.min.js', function () {
			$('#js-related-products-carousel').slick({
				draggable: false,
				slidesToScroll: 2,
				slidesToShow: 2,
			});
		});

		// --- Mobile slider for Images --- //
		function mobileImageSlider() {
			var totalThumbs = parseFloat($('#js-thumbnails .thumbnail-img-wrap').length - 1 ),
				currentImg = parseFloat($('#js-main-image-zoom').attr('data-index'));

				if (totalThumbs === -1 ) {
					$('.main-image-nav').hide();
				} else {
					$('#js-main-dots').html('');
					$('#js-main-dots').html('<ul class="inline-list np"></ul>');
					for (var i = totalThumbs; i >= 0; i--) {
						if (i > 0){
							$('#js-main-dots ul').prepend('<li data-index="' + i + '"></li>');
						} else {
							$('#js-main-dots ul').prepend('<li class="active" data-index="' + i + '"></li>');
						}
					}
				}


			$('#js-main-dots ul li').on('click', function() {
				var clickedLI = parseFloat($(this).attr('data-index'));
				$('#js-thumbnails .thumbnail-img-wrap[data-index="' + clickedLI + '"]').click();
				$('#js-main-dots ul li.active').removeClass('active');
				$(this).addClass('active');
				currentImg = clickedLI;
			});

			function nextMobileImage() {
				var currIndex = parseFloat($('#js-main-image-zoom').attr('data-index')),
					nextImage = $('#js-main-dots li[data-index="' + (currIndex + 1) + '"]'),
					firstImage = $('#js-main-dots li[data-index="0"]');
				if ($(nextImage).length > 0) {
					$(nextImage).click();
				} else {
					$(firstImage).click();
				}
			}

			function prevMobileImage() {
				var currIndex = parseFloat($('#js-main-image-zoom').attr('data-index')),
					prevImage = $('#js-main-dots li[data-index="' + (currIndex - 1) + '"]'),
					lastImage = $('#js-main-dots li[data-index="' + totalThumbs + '"]');
				if ($(prevImage).length > 0) {
					$(prevImage).click();
				} else {
					$(lastImage).click();
				}

			}
			if (totalThumbs > 1 ) {
				$("#js-main-image-zoom").swipe( {
					swipeLeft:function(event, direction, distance, duration, fingerCount) {
						nextMobileImage();
					},
					swipeRight:function(event, direction, distance, duration, fingerCount) {
						prevMobileImage();
					},
					threshold:10
				});
			}
		}
		mobileImageSlider();

	},
<mvt:assign name="l.settings:clean:product:name" value="glosub(l.settings:product:name, asciichar(39), '&#39;')" />
<script>
	var gallery = [],
		thumbnailIndex = 0;
		generate_thumbnail_event = new Event('ImageMachine_Generate_Thumbnail');

	ImageMachine.prototype.ImageMachine_Generate_Thumbnail = function (thumbnail_image, main_image, closeup_image, type_code) {
		var thumbnail,
			img;

		thumbnail = document.createElement('div');
		thumbnail.className = 'thumbnail-img-wrap';
		thumbnail.setAttribute('data-index', thumbnailIndex++);

		if (typeof(thumbnail_image) == 'string' && thumbnail_image.length > 0) {
			img = document.createElement('img');
			img.src = thumbnail_image;
			thumbnail.appendChild(img);
		};

		var gallery_image = (typeof(closeup_image) == 'string' && closeup_image.length > 0) ? closeup_image : main_image;
		gallery.push({
			src: gallery_image,
			title: '&mvt:clean:product:name;'
		});

		document.dispatchEvent(generate_thumbnail_event);

		return thumbnail;
	};
</script>