Advertisement
kotvalera83

Untitled

Jan 11th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. require([
  2.     "modules/jquery-mozu",
  3.     "underscore",
  4.     "bxslider",
  5.     "elevatezoom",
  6.     'modules/block-ui',
  7.     "hyprlive",
  8.     "modules/backbone-mozu",
  9.     "modules/cart-monitor",
  10.     "modules/models-product",
  11.     "modules/views-productimages",
  12.     "hyprlivecontext",
  13.     "pages/family",
  14.     "modules/api",
  15.     "async"
  16. ], function($, _, bxslider, elevatezoom, blockUiLoader, Hypr, Backbone, CartMonitor, ProductModels, ProductImageViews, HyprLiveContext, FamilyItemView, api, async) {
  17.     var sitecontext = HyprLiveContext.locals.siteContext;
  18.     var cdn = sitecontext.cdnPrefix;
  19.     var siteID = cdn.substring(cdn.lastIndexOf('-') + 1);
  20.     var imagefilepath = cdn + '/cms/' + siteID + '/files';
  21.     var slider;
  22.     var slider_mobile;
  23.     var productInitialImages;
  24.     var priceModel;
  25.     var width_thumb = HyprLiveContext.locals.themeSettings.maxProductImageThumbnailSize;
  26.     var width_pdp = HyprLiveContext.locals.themeSettings.productImagePdpMaxWidth;
  27.     var width_zoom = HyprLiveContext.locals.themeSettings.productZoomImageMaxWidth;
  28.     var colorSwatchesChangeAlternate = HyprLiveContext.locals.themeSettings.colorSwatchesChangeAlternate;
  29.     var colorSwatchesChangeMain = HyprLiveContext.locals.themeSettings.colorSwatchesChangeMain;
  30.     var current_zoom_id_added;
  31.     var deviceType = navigator.userAgent.match(/Android|BlackBerry|iPhone|iPod|Opera Mini|IEMobile/i);
  32.  
  33.     function initSlider() {
  34.         slider = $('#productpager-Carousel').bxSlider({
  35.             slideWidth: 125,
  36.             minSlides: 3,
  37.             maxSlides: 3,
  38.             moveSlides: 1,
  39.             slideMargin: 15,
  40.             nextText: '<i class="fa fa-caret-right" aria-hidden="true"></i>',
  41.             prevText: '<i class="fa fa-caret-left" aria-hidden="true"></i>',
  42.             infiniteLoop: false,
  43.             hideControlOnEnd: true,
  44.             pager: false
  45.         });
  46.         window.slider = slider;
  47.     }
  48.  
  49.     function initslider_mobile() {
  50.         var id;
  51.         if (current_zoom_id_added)
  52.             id = $(current_zoom_id_added)[0].attributes.id.value.replace('zoom_', '') - 1;
  53.         slider_mobile = $('#productmobile-Carousel').bxSlider({
  54.             slideWidth: 300,
  55.             minSlides: 1,
  56.             maxSlides: 1,
  57.             moveSlides: 1,
  58.             preloadImages: 'all',
  59.             onSliderLoad: function(currentIndex) {
  60.                 $('ul#productmobile-Carousel li').eq(currentIndex).find('img').addClass("active");
  61.                 $("#productmobile-Carousel,#productCarousel-pager").css("visibility", "visible");
  62.             },
  63.             onSlideAfter: function($slideElement, oldIndex, newIndex) {
  64.                 var bkimg = $(current_zoom_id_added)[0].attributes['data-zoom-image'].value;
  65.                 $(".mz-productimages-pager div").removeClass("activepager").eq(newIndex).addClass("activepager");
  66.                 setTimeout(function() {
  67.                     $('div.zoomWindowContainer div').css({ 'background-image': 'url(' + bkimg + ')' });
  68.                 }, 500);
  69.  
  70.             },
  71.             onSlideBefore: function(currentSlide, totalSlides, currentSlideHtmlObject) {
  72.                 current_zoom_id_added = $('#productmobile-Carousel>li').eq(currentSlideHtmlObject).find('img');
  73.                 $('ul#productmobile-Carousel li img').removeClass('active');
  74.             },
  75.             startSlide: id ? id : 0,
  76.             nextText: '<i class="fa fa-caret-right" aria-hidden="true"></i>',
  77.             prevText: '<i class="fa fa-caret-left" aria-hidden="true"></i>',
  78.             infiniteLoop: false,
  79.             hideControlOnEnd: true,
  80.             pager: true,
  81.             pagerCustom: '#productCarousel-pager'
  82.         });
  83.     }
  84.  
  85.     //using GET request CheckImage function checks whether an image exist or not
  86.     var checkImage = function(imagepath, callback) {
  87.         $.get(imagepath).done(function() {
  88.             callback(true); //return true if image exist
  89.         }).error(function() {
  90.             callback(false);
  91.         });
  92.     };
  93.  
  94.     function updateImages(productInitialImages) {
  95.         var mainImage = productInitialImages.mainImage.src + '?maxWidth=' + width_pdp;
  96.         var zoomImage = productInitialImages.mainImage.src + '?maxWidth=' + width_zoom;
  97.         $('.mz-productimages-mainimage').attr('src', mainImage).data('zoom-image', zoomImage);
  98.         try {
  99.             slider.destroySlider();
  100.         } catch (e) {}
  101.         var slideCount = productInitialImages.thumbImages.length;
  102.         for (var i = 1; i <= productInitialImages.thumbImages.length; i++) {
  103.             $(".mz-productimages-thumbs li:eq(" + (i - 1) + ") .mz-productimages-thumb img")
  104.                 .attr({
  105.                     "src": productInitialImages.thumbImages[i - 1].src + '?maxWidth=' + width_thumb,
  106.                     "data-orig-src": productInitialImages.thumbImages[i - 1].src + '?maxWidth=' + width_pdp,
  107.                     "data-orig-zoom": productInitialImages.thumbImages[i - 1].src + '?maxWidth=' + width_zoom
  108.                 });
  109.         }
  110.         if (slideCount > 4) {
  111.             initSlider();
  112.         }
  113.         initslider_mobile();
  114.     }
  115.     window.family = [];
  116.     var ProductView = Backbone.MozuView.extend({
  117.         templateName: 'modules/product/product-detail',
  118.         autoUpdate: ['quantity'],
  119.         renderOnChange: [
  120.             'quantity',
  121.             'stockInfo'
  122.         ],
  123.         additionalEvents: {
  124.             "change [data-mz-product-option]": "onOptionChange",
  125.             "blur [data-mz-product-option]": "onOptionChange",
  126.             "click [data-mz-product-option-attribute]": "onOptionChangeAttribute",
  127.             "click [data-mz-qty-minus]": "quantityMinus",
  128.             "click [data-mz-qty-plus]": "quantityPlus",
  129.             'mouseenter .color-options': 'onMouseEnterChangeImage',
  130.             'mouseleave .color-options': 'onMouseLeaveResetImage'
  131.         },
  132.         render: function() {
  133.             var me = this;
  134.             var id = Hypr.getThemeSetting('oneSizeAttributeName'),
  135.                 oneSizeOption = this.model.get('options').get(id);
  136.             if (oneSizeOption) {
  137.                 var onlyEnabledOneSizeOption = _.find(oneSizeOption.get('values'), function(value) { return value.isEnabled; });
  138.                 oneSizeOption.set('value', onlyEnabledOneSizeOption.value);
  139.             }
  140.             Backbone.MozuView.prototype.render.apply(this);
  141.             this.$('[data-mz-is-datepicker]').each(function(ix, dp) {
  142.                 $(dp).dateinput().css('color', Hypr.getThemeSetting('textColor')).on('change  blur', _.bind(me.onOptionChangeAttribute, me));
  143.             });
  144.             $('#details-accordion').find('.panel-heading a').first().click();
  145.             $(".family-details [data-mz-action='addToCart']").addClass('hide');
  146.             $(".mz-productdetail-conversion-buttons").removeClass('hide');
  147.  
  148.             if (this.model.get('productType') === Hypr.getThemeSetting('familyProductType')) {
  149.                 try {
  150.                     blockUiLoader.globalLoader();
  151.                     $('.family-details .mz-productdetail-shortdesc, .family-details .stock-info, .family-details .mz-reset-padding-left, .family-details #SelectValidOption').remove();
  152.                     var familyData = me.model.get('family');
  153.                     $("#mz-family-container .family-members").empty();
  154.                     var familyItemModelOnready = function() {
  155.                         var product = familyData.models[this.index];
  156.                         if (typeof product.get('inventoryInfo').onlineStockAvailable !== 'undefined' && product.get('inventoryInfo').onlineStockAvailable === 0 && product.get('inventoryInfo').outOfStockBehavior === "HideProduct") {
  157.                             //if all family members are out of stock, disable add to cart button.
  158.                             if (window.outOfStockFamily) {
  159.                                 $(".family-details [data-mz-action='addToCart']").addClass('hide');
  160.                                 $("[data-mz-action='addToCart']").addClass('button_disabled').attr("disabled", "disabled");
  161.                             }
  162.                         } else {
  163.                             var productCode = product.get('productCode');
  164.                             var view = new FamilyItemView({
  165.                                 model: product,
  166.                                 messagesEl: $('#family-item-error-' + productCode + " [data-mz-message-bar]")
  167.                             });
  168.                             window.family.push(view);
  169.                             var renderedView = view.render().el;
  170.                             $("#mz-family-container").find("#" + productCode).append(renderedView);
  171.                             $(".family-details [data-mz-action='addToCart']").removeClass('hide');
  172.                             //if all family members are out of stock, disable add to cart button.
  173.                             if (window.outOfStockFamily) {
  174.                                 $("[data-mz-action='addToCart']").addClass('button_disabled').attr("disabled", "disabled");
  175.                             }
  176.                         }
  177.                     };
  178.                     if (familyData.models.length) {
  179.                         for (var i = 0; i < familyData.models.length; i++) {
  180.                             //var x = this.model.checkVariationCode(familyData.models[i]);
  181.                             var familyItemModel = familyData.models[i];
  182.                             if (familyItemModel.get("isReady")) {
  183.                                 familyItemModel.off('ready');
  184.                                 familyItemModelOnready.call({ index: i });
  185.                             } else {
  186.                                 familyItemModel.on('ready', familyItemModelOnready.bind({ index: i }));
  187.                                 if (i === (familyData.models.length - 1)) {
  188.                                     blockUiLoader.unblockUi();
  189.                                 }
  190.                             }
  191.                         }
  192.                     } else {
  193.                         $(".family-details [data-mz-action='addToCart']").addClass('hide');
  194.                         $("[data-mz-action='addToCart']").addClass('button_disabled').attr("disabled", "disabled");
  195.                         blockUiLoader.unblockUi();
  196.                     }
  197.                 } catch (e) {}
  198.             }
  199.         },
  200.         quantityMinus: function() {
  201.             this.model.messages.reset();
  202.             var qty = this.model.get('quantity');
  203.             if (qty === 1) {
  204.                 return;
  205.             }
  206.             this.model.set('quantity',--qty);
  207.             setTimeout(function(){
  208.                 if (typeof window.productView.model.attributes.inventoryInfo.onlineStockAvailable !== "undefined" && window.productView.model.attributes.inventoryInfo.outOfStockBehavior != "AllowBackOrder") {
  209.                     var onlineStock = window.productView.model.attributes.inventoryInfo.onlineStockAvailable;
  210.                     if (onlineStock >= window.productView.model.get('quantity')) {
  211.                         $("[data-mz-action='addToCart']").removeClass("button_disabled");
  212.                         $('#plus').removeClass('disabled btn-disable-color');
  213.                     }
  214.                     if (onlineStock !== 0 && onlineStock < window.productView.model.get('quantity')) {
  215.                         $('[data-mz-validationmessage-for="quantity"]').css('visibility', "visible").text("*Only " + onlineStock + " left in stock.");
  216.                         $("[data-mz-action='addToCart']").addClass("button_disabled");
  217.                         $('#plus').addClass('disabled btn-disable-color');
  218.                     }
  219.                 }
  220.             },500);
  221.         },
  222.         quantityPlus: function() {
  223.             if(!$("#plus").hasClass('disabled')){
  224.                 this.model.messages.reset();
  225.                 var qty = this.model.get('quantity');
  226.                 this.model.set('quantity',++qty);
  227.                 setTimeout(function(){
  228.                     if (typeof window.productView.model.attributes.inventoryInfo.onlineStockAvailable !== "undefined" && window.productView.model.attributes.inventoryInfo.outOfStockBehavior != "AllowBackOrder") {
  229.                         var onlineStock = window.productView.model.attributes.inventoryInfo.onlineStockAvailable;
  230.                         if (onlineStock < window.productView.model.get('quantity')) {
  231.                             $('[data-mz-validationmessage-for="quantity"]').css('visibility', "visible").text("*Only " + onlineStock + " left in stock.");
  232.                             $("[data-mz-action='addToCart']").addClass("button_disabled");
  233.                             $('#plus').addClass('disabled btn-disable-color');
  234.                         }
  235.                         if (onlineStock >= window.productView.model.get('quantity')) {
  236.                             $("[data-mz-action='addToCart']").removeClass("button_disabled");
  237.                         }
  238.                     }
  239.                 },500);
  240.             }
  241.         },
  242.         onOptionChangeAttribute: function(e) {
  243.             return this.configureAttribute($(e.currentTarget));
  244.         },
  245.         configureAttribute: function($optionEl) {
  246.             var $this = this;
  247.             if (!$optionEl.hasClass("active")) {
  248.                 if ($optionEl.attr('disabled') == 'disabled') {
  249.                     return false;
  250.                 } else {
  251.                     blockUiLoader.globalLoader();
  252.                     var newValue = $optionEl.data('value'),
  253.                         oldValue,
  254.                         id = $optionEl.data('mz-product-option-attribute'),
  255.                         optionEl = $optionEl[0],
  256.                         isPicked = (optionEl.type !== "checkbox" && optionEl.type !== "radio") || optionEl.checked,
  257.                         option = this.model.get('options').get(id);
  258.                     if (!option) {
  259.                         var byIDVal = JSON.parse(JSON.stringify(this.model.get('options')._byId));
  260.                         for (var key in byIDVal) {
  261.                             if (id === byIDVal[key].attributeFQN) {
  262.                                 option = this.model.get('options').get(key);
  263.                             }
  264.                         }
  265.                     }
  266.                     if (option) {
  267.                         if (option.get('attributeDetail').inputType === "YesNo") {
  268.                             option.set("value", isPicked);
  269.                         } else if (isPicked) {
  270.                             oldValue = option.get('value');
  271.                             if (oldValue !== newValue && !(oldValue === undefined && newValue === '')) {
  272.                                 option.set('value', newValue);
  273.                                 this.render();
  274.                             }
  275.                         }
  276.                     }
  277.                     this.model.whenReady(function() {
  278.                         setTimeout(function() {
  279.                             if (window.productView.model.get('variationProductCode') && typeof window.productView.model.get('variationProductCode') !== "undefined") {
  280.                                 $(".mz-productcodes-productcode").text(Hypr.getLabel('sku')+" # " + window.productView.model.get('variationProductCode'));
  281.                             }
  282.                             $('.mz-productdetail-price.prize-mobile-view').html($('.mz-l-stack-section.mz-productdetail-conversion .mz-productdetail-price').html());
  283.                             blockUiLoader.unblockUi();
  284.                             $this.isColorClicked = false;
  285.                         }, 1000);
  286.                     });
  287.                 }
  288.             }
  289.         },
  290.         onOptionChange: function(e) {
  291.             return this.configure($(e.currentTarget));
  292.         },
  293.         configure: function($optionEl) {
  294.             var newValue = $optionEl.val(),
  295.                 oldValue,
  296.                 id = $optionEl.data('mz-product-option'),
  297.                 optionEl = $optionEl[0],
  298.                 isPicked = (optionEl.type !== "checkbox" && optionEl.type !== "radio") || optionEl.checked,
  299.                 option = this.model.get('options').get(id);
  300.             if (option) {
  301.                 if (option.get('attributeDetail').inputType === "YesNo") {
  302.                     option.set("value", isPicked);
  303.                 } else if (isPicked) {
  304.                     oldValue = option.get('value');
  305.                     if (oldValue !== newValue && !(oldValue === undefined && newValue === '')) {
  306.                         option.set('value', newValue);
  307.                     }
  308.                 }
  309.             }
  310.         },
  311.         addToCart: _.debounce(function() {
  312.             var me = this;
  313.             me.model.messages.reset();
  314.             //If Family Products
  315.             if (this.model.get('productType') === Hypr.getThemeSetting('familyProductType')) {
  316.                 blockUiLoader.globalLoader();
  317.                 /* jshint ignore:start */
  318.                 var promises = [];
  319.                 var productsAdded = [];
  320.                 for (var i = 0; i < this.model.get('family').models.length; i++) {
  321.                     promises.push((function(callback) {
  322.                         var familyItem = me.model.get('family').models[this.index];
  323.                         var productCode = familyItem.get('productCode');
  324.                         familyItem.addToCart().then(function(e) {
  325.                             //Clear options and set Qty to 0
  326.                             for (var j = 0; j < window.family.length; j++) {
  327.                                 if (window.family[j].model.get('productCode') === productCode) {
  328.                                     var optionModels = window.family[j].model.get('options').models;
  329.                                     for (var k = 0; k < optionModels.length; k++) {
  330.                                         optionModels[k].unset('value');
  331.                                     }
  332.                                     window.family[j].model.set('quantity', 0);
  333.                                     window.family[j].model.unset('stockInfo');
  334.                                     window.family[j].model.set('addedtocart', true);
  335.                                 }
  336.                             }
  337.                             productsAdded.push(e);
  338.                             callback(null, e);
  339.                         }, function(e) {
  340.                             callback(null, e);
  341.                         });
  342.                     }).bind({ index: i }))
  343.                 }
  344.                 var errors = { "items": [] };
  345.                 async.series(promises, function(err, results) {
  346.                         var resp = results.reduce(
  347.                             function(flag, value) {
  348.                                 return flag && results[0] === value;
  349.                             },
  350.                             true
  351.                         );
  352.                         if (resp === true) {
  353.                             window.productView.model.trigger('error', { message: Hypr.getLabel('selectValidOption') });
  354.                             blockUiLoader.unblockUi();
  355.                             return;
  356.                         }
  357.                         if (results) {
  358.                             var failureNames = [];
  359.                             var successNames = [];
  360.                             for (var i = 0; i < results.length; i++) {
  361.                                 if (results[i].errorCode) {
  362.                                     var errorMessage = results[i].message.split(':');
  363.                                     failureNames.push(errorMessage[2]);
  364.                                 } else if (typeof results[i].attributes === 'undefined' && results[i].indexOf("Please enter quantity of ") !== -1) {
  365.                                     failureNames.push(results[i]);
  366.                                 } else if (typeof results[i].attributes === 'undefined' && results[i].indexOf("Select Valid Option(s) for ") !== -1) {
  367.                                     failureNames.push(results[i]);
  368.                                 } else if (typeof results[i].attributes !== 'undefined') {
  369.                                     successNames.push(results[i].get('content').get('productName'));
  370.                                 }
  371.                             }
  372.                             if (failureNames.length) {
  373.                                 errors.items.push({
  374.                                     "name": "error",
  375.                                     "message": Hypr.getLabel('productaddToCartError') + ": " + failureNames.join(', ')
  376.                                 });
  377.                             }
  378.                             if (successNames.length) {
  379.                                 errors.items.push({
  380.                                     "name": 'success',
  381.                                     "message": Hypr.getLabel('successfullyAddedItems') + ": " + successNames.join(', '),
  382.                                     "messageType": "success"
  383.                                 });
  384.                             }
  385.                             if (failureNames.length || successNames.length)
  386.                                 me.model.trigger("error", errors);
  387.                         }
  388.                         if (productsAdded.length)
  389.                             CartMonitor.update('showGlobalCart');
  390.                         if (!deviceType) {
  391.                             $('html,body').animate({
  392.                                 scrollTop: $('figure.mz-productimages-main').offset().top
  393.                             }, 1000);
  394.                         } else {
  395.                             $('html,body').animate({
  396.                                 scrollTop: $('.mz-product-top-content').offset().top
  397.                             }, 1000);
  398.                         }
  399.                         blockUiLoader.unblockUi();
  400.                     })
  401.                     /* jshint ignore:end */
  402.             }else if(me.model.get('inventoryInfo').manageStock === false){
  403.                 me.model.addToCart();
  404.             }else if(typeof me.model.get('inventoryInfo').onlineStockAvailable !== 'undefined' && me.model.get('inventoryInfo').outOfStockBehavior === "AllowBackOrder"){
  405.                 me.model.addToCart();
  406.             }else if (typeof me.model.get('inventoryInfo').onlineStockAvailable !== "undefined" && me.model.get('inventoryInfo').onlineStockAvailable === 0 && me.model.get('inventoryInfo').outOfStockBehavior === "DisplayMessage") {
  407.                 blockUiLoader.productValidationMessage();
  408.                 $('#SelectValidOption').children('span').html(Hypr.getLabel('productOutOfStock'));
  409.             }else if (typeof me.model.get('inventoryInfo').onlineStockAvailable === "undefined" || $(".mz-productoptions-optioncontainer").length != $(".mz-productoptions-optioncontainer .active").length) {
  410.                 blockUiLoader.productValidationMessage();
  411.             } else if (me.model.get('inventoryInfo').onlineStockAvailable) {
  412.                 if (me.model.get('inventoryInfo').onlineStockAvailable < me.model.get('quantity')) {
  413.                     $('[data-mz-validationmessage-for="quantity"]').css('visibility', "visible").text("*Only " + me.model.get('inventoryInfo').onlineStockAvailable + " left in stock.");
  414.                     return false;
  415.                 }
  416.                 this.model.addToCart();
  417.             }
  418.         }, 1500),
  419.         addToWishlist: function() {
  420.             this.model.addToWishlist();
  421.         },
  422.         addToWishlistPdp: function() {
  423.             console.log("Hi");
  424.         },
  425.         checkLocalStores: function(e) {
  426.             var me = this;
  427.             e.preventDefault();
  428.             this.model.whenReady(function() {
  429.                 var $localStoresForm = $(e.currentTarget).parents('[data-mz-localstoresform]'),
  430.                     $input = $localStoresForm.find('[data-mz-localstoresform-input]');
  431.                 if ($input.length > 0) {
  432.                     $input.val(JSON.stringify(me.model.toJSON()));
  433.                     $localStoresForm[0].submit();
  434.                 }
  435.             });
  436.  
  437.         },
  438.         onMouseEnterChangeImage: function(_e) {
  439.             if (!deviceType) {
  440.                 this.mainImage = $('.mz-productimages-mainimage').attr('src');
  441.                 var colorCode = $(_e.currentTarget).data('mz-swatch-color');
  442.                 this.changeImages(colorCode, 'N');
  443.             }
  444.         },
  445.         onMouseLeaveResetImage: function(_e) {
  446.             if (!this.isColorClicked && !deviceType) {
  447.                 var colorCode = $("ul.product-color-swatches").find('li.active').data('mz-swatch-color');
  448.                 if (typeof colorCode != 'undefined') {
  449.                     this.changeImages(colorCode, 'N');
  450.                 } else if (typeof this.mainImage != 'undefined') {
  451.                     $('.mz-productimages-mainimage').attr('src', this.mainImage);
  452.                 } else {
  453.                     $('.mz-productimages-main').html('<span class="mz-productlisting-imageplaceholder img-responsive"><span class="mz-productlisting-imageplaceholdertext">[no image]</span></span>');
  454.                 }
  455.             }
  456.         },
  457.         selectSwatch: function(e) {
  458.             this.isColorClicked = true;
  459.             var colorCode = $(e.currentTarget).data('mz-swatch-color');
  460.             if(colorSwatchesChangeAlternate)
  461.                 this.changeImages(colorCode, 'Y');
  462.             else
  463.                 this.changeImages(colorCode, 'N');
  464.         },
  465.         changeImages: function(colorCode, _updateThumbNails) {
  466.             var self = this;
  467.             var version = 1;
  468.             if (deviceType && $("figure.mz-productimages-thumbs ul.products_list_mobile li img.active").length > 0) {
  469.                 version = $("figure.mz-productimages-thumbs ul.products_list_mobile li img.active").data("mz-productimage-mobile");
  470.             } else if ($("figure.mz-productimages-thumbs ul.products_list li.active").length > 0) {
  471.                 version = $("figure.mz-productimages-thumbs ul.products_list li.active").data("mz-productimage-thumb");
  472.             }
  473.             var pdpMainImageNameSwatch = HyprLiveContext.locals.themeSettings.pdpMainImageNameSwatch;
  474.             if(pdpMainImageNameSwatch){
  475.                 if(pdpMainImageNameSwatch.indexOf("{0}") != -1){
  476.                     pdpMainImageNameSwatch = pdpMainImageNameSwatch.replace("{0}", this.model.attributes.productCode);
  477.                 }
  478.                 if(pdpMainImageNameSwatch.indexOf("{1}") != -1){
  479.                     pdpMainImageNameSwatch = pdpMainImageNameSwatch.replace("{1}", colorCode);
  480.                 }
  481.                 if(pdpMainImageNameSwatch.indexOf("{2}") != -1){
  482.                     pdpMainImageNameSwatch = pdpMainImageNameSwatch.replace("{2}", version);
  483.                 }
  484.             }
  485.             var imagepath = imagefilepath + '/' + pdpMainImageNameSwatch +'?maxWidth=';
  486.             var mainImage = imagepath + width_pdp;
  487.             var zoomimagepath = imagepath + width_zoom;
  488.             var _this = this;
  489.             //TODO: following function is checking if images exist on server or not
  490.             checkImage(imagepath, function(response) {
  491.                 if (response) {
  492.                     if (!$('#zoom').length) {
  493.                         $('.mz-productimages-main').html('<img class="mz-productimages-mainimage" data-mz-productimage-main="" id="zoom" itemprop="image">');
  494.                     }
  495.                     if (_updateThumbNails == 'Y') {
  496.                         $('body div.zoomContainer').remove();
  497.                         if (deviceType && $('ul.products_list_mobile').length) {
  498.                         } else {
  499.                             $('.mz-productimages-mainimage').attr('src', mainImage).data('zoom-image', zoomimagepath);
  500.                             $('.mz-productimages-mainimage').attr('src', mainImage);
  501.                         }
  502.                     } else {
  503.                         $('.mz-productimages-mainimage').attr('src', mainImage);
  504.                     }
  505.                 } else if (typeof self.mainImage === 'undefined') {
  506.                     $('.mz-productimages-main').html('<span class="mz-productlisting-imageplaceholder img-responsive"><span class="mz-productlisting-imageplaceholdertext">[no image]</span></span>');
  507.                 }
  508.                 if ($("figure.mz-productimages-thumbs").length && $("figure.mz-productimages-thumbs").data("length") && _updateThumbNails == 'Y') {
  509.                     _this.updateAltImages(colorCode);
  510.                 }
  511.             });
  512.         },
  513.         updateAltImages: function(colorCode) {
  514.             try {
  515.                 slider.destroySlider();
  516.             } catch (e) {}
  517.             try {
  518.                 slider_mobile.destroySlider();
  519.             } catch (e) {}
  520.             var slideCount = parseInt($("figure.mz-productimages-thumbs").data("length"), 10);
  521.             var productCode = this.model.attributes.productCode;
  522.             var pdpAltImageName = HyprLiveContext.locals.themeSettings.pdpAltImageName;
  523.             for (var i = 1; i <= slideCount; i++) {
  524.                 if(pdpAltImageName){
  525.                     if(pdpAltImageName.indexOf("{0}") != -1){
  526.                         pdpAltImageName = pdpAltImageName.replace("{0}", this.model.attributes.productCode);
  527.                     }
  528.                     if(pdpAltImageName.indexOf("{1}") != -1){
  529.                         pdpAltImageName = pdpAltImageName.replace("{1}", colorCode);
  530.                     }
  531.                     if(pdpAltImageName.indexOf("{2}") != -1){
  532.                         pdpAltImageName = pdpAltImageName.replace("{2}", i);
  533.                     }
  534.                 }
  535.                 $(".mz-productimages-thumbs .products_list li:eq(" + (i - 1) + ") .mz-productimages-thumb img")
  536.                     .attr({
  537.                         "src": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_thumb,
  538.                         "data-orig-src": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_pdp,
  539.                         "data-orig-zoom": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_zoom
  540.                     });
  541.                 $(".mz-productimages-thumbs .products_list_mobile li:eq(" + (i - 1) + ") img")
  542.                     .attr({
  543.                         "src": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_pdp,
  544.                         "data-orig-src": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_pdp,
  545.                         "data-orig-zoom": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_zoom,
  546.                         "data-zoom-image": imagefilepath + '/' + pdpAltImageName +'?maxWidth=' + width_zoom
  547.                     });
  548.             }
  549.             if (slideCount > 4) {
  550.                 initSlider();
  551.             }
  552.             initslider_mobile();
  553.         },
  554.         initialize: function() {
  555.             // handle preset selects, etc
  556.             var me = this;
  557.             //create div for family members
  558.             if(this.model.get('family').models.length){
  559.                 for(var i=0; i < this.model.get('family').models.length; i++){
  560.                     var html="";
  561.                     html+='<div id="'+this.model.get('family').models[i].get('productCode')+'" class="family-members"></div>';
  562.                     $("#mz-family-container").append(html);
  563.                 }
  564.             }
  565.             me.isColorClicked = false;
  566.             me.mainImage = '';
  567.             this.$('[data-mz-product-option]').each(function() {
  568.                 var $this = $(this),
  569.                     isChecked, wasChecked;
  570.                 if ($this.val()) {
  571.                     switch ($this.attr('type')) {
  572.                         case "checkbox":
  573.                         case "radio":
  574.                             isChecked = $this.prop('checked');
  575.                             wasChecked = !!$this.attr('checked');
  576.                             if ((isChecked && !wasChecked) || (wasChecked && !isChecked)) {
  577.                                 me.configure($this);
  578.                             }
  579.                             break;
  580.                         default:
  581.                             me.configure($this);
  582.                     }
  583.                 }
  584.             });
  585.         }
  586.     });
  587.  
  588.     $(document).ready(function() {
  589.         if ($('.mz-product-detail-tabs ul.tabs li').length === 0)
  590.             $('.mz-product-detail-tabs').remove();
  591.  
  592.         var product = ProductModels.Product.fromCurrent();
  593.  
  594.         product.on('addedtocart', function(cartitem) {
  595.             if (cartitem && cartitem.prop('id')) {
  596.                 //product.isLoading(true);
  597.                 CartMonitor.addToCount(product.get('quantity'));
  598.                 $('html,body').animate({
  599.                     scrollTop: $('header').offset().top
  600.                 }, 1000);
  601.                 product.set('quantity', 1);
  602.                 if(product.get('options')){
  603.                     var optionModels = product.get('options').models;
  604.                     for(var k = 0; k< product.get('options').models.length; k++){
  605.                         optionModels[k].set('value', null);
  606.                     }
  607.                 }
  608.                 product.unset('stockInfo');
  609.                 var priceDiscountTemplate = Hypr.getTemplate("modules/product/price-stack");
  610.                 $('.mz-productdetail-price').html(priceDiscountTemplate.render({
  611.                     model: priceModel
  612.                 }));
  613.                 if (product.get('options').length)
  614.                     $("[data-mz-action='addToCart']").addClass('button_disabled');
  615.                 $(".mz-productcodes-productcode").text(Hypr.getLabel('item')+" # " + product.get('productCode'));
  616.             } else {
  617.                 product.trigger("error", { message: Hypr.getLabel('unexpectedError') });
  618.             }
  619.         });
  620.  
  621.         product.on('addedtowishlist', function(cartitem) {
  622.             $('#add-to-wishlist').prop('disabled', 'disabled').text(Hypr.getLabel('addedToWishlist'));
  623.         });
  624.  
  625.         initSlider();
  626.         initslider_mobile();
  627.         //Custom Functions related to slider
  628.         function createPager(carousal) {
  629.             var totalSlides = carousal.getSlideCount();
  630.             var newPager = $(".mz-productimages-pager");
  631.             for (var i = 0; i < totalSlides; i++) {
  632.                 if (i === 0) {
  633.                     newPager.append("<div data-mz-productimage-thumb=" + (i + 1) + " class=\"activepager\"></div>");
  634.                 } else {
  635.                     newPager.append("<div data-mz-productimage-thumb=" + (i + 1) + " class=\"\"></div>");
  636.                 }
  637.             }
  638.             newPager.find('div').click(function() {
  639.                 var indx = $(".mz-productimages-pager div").index($(this));
  640.                 slider_mobile.goToSlide(indx);
  641.                 $(".mz-productimages-pager div").removeClass("activepager").eq(indx).addClass("activepager");
  642.             });
  643.         }
  644.         if ($('#productmobile-Carousel').length) {
  645.             createPager(slider_mobile);
  646.         }
  647.  
  648.         var productImagesView = new ProductImageViews.ProductPageImagesView({
  649.             el: $('[data-mz-productimages]'),
  650.             model: product
  651.         });
  652.  
  653.         var productView = new ProductView({
  654.             el: $('.product-detail'),
  655.             model: product,
  656.             messagesEl: $('[data-mz-message-bar]')
  657.         });
  658.  
  659.         window.productView = productView;
  660.         window.familyLength = window.productView.model.attributes.family.models.length;
  661.  
  662.         productView.render();
  663.  
  664.         //IF on page laod Variation code is available then Displays UPC messages
  665.         if (window.productView.model.get('variationProductCode')) {
  666.             var sp_price = "";
  667.             if (window.productView.model.get('inventoryInfo').onlineStockAvailable && typeof window.productView.model.get('inventoryInfo').onlineStockAvailable !== "undefined") {
  668.                 if (typeof window.productView.model.get('price').get('salePrice') != 'undefined')
  669.                     sp_price = window.productView.model.get('price').get('salePrice');
  670.                 else
  671.                     sp_price = window.productView.model.get('price').get('price');
  672.                 var price = Hypr.engine.render("{{price|currency}}", { locals: { price: sp_price } });
  673.                 $('.stock-info').show().html("In Stock <span class='stock-price'>" + price + "</span>");
  674.             }
  675.         }
  676.         productInitialImages = {
  677.             mainImage: product.attributes.mainImage,
  678.             thumbImages: product.attributes.content.attributes.productImages
  679.         };
  680.         if (product.attributes.hasPriceRange) {
  681.             priceModel = {
  682.                 hasPriceRange: product.attributes.hasPriceRange,
  683.                 priceRange: {
  684.                     lower: product.attributes.priceRange.attributes.lower.attributes,
  685.                     upper: product.attributes.priceRange.attributes.upper.attributes
  686.                 },
  687.                 price: product.attributes.price.attributes
  688.             };
  689.         } else {
  690.             priceModel = {
  691.                 hasPriceRange: product.attributes.hasPriceRange,
  692.                 price: product.attributes.price.attributes
  693.             };
  694.         }
  695.  
  696.         var productData = product.apiModel.data;
  697.         var recentProduct = {
  698.             code:productData.productCode
  699.         };
  700.         var existingProducts = $.cookie("recentProducts");
  701.         var recentProducts = existingProducts ? $.parseJSON(existingProducts) : [];
  702.         recentProducts = recentProd(recentProducts, recentProduct);
  703.         $.cookie("recentProducts", JSON.stringify(recentProducts), {path: '/', expires: 21 });
  704.         var user = require.mozuData('user');
  705.         if(user.accountId){
  706.             api.createSync('wishlist').getOrCreate(user.accountId).then(function(wishlist) {
  707.                 return wishlist.data;
  708.             }).then(function(wishlistItems) {          
  709.                 for (var i = 0; i < wishlistItems.items.length; i++) {
  710.                     $('[data-mz-product-code="'+wishlistItems.items[i].product.productCode+'"] span').removeClass("heart-outline").addClass("heart-filled");
  711.                 }
  712.             });
  713.         }
  714.     });
  715.  
  716.     function recentProd(json, product) {
  717.         var found = false;
  718.         var maxItems = HyprLiveContext.locals.themeSettings.maxRecentlyViewedItems;
  719.  
  720.         for (var i = 0 ; i < json.length; i++) {
  721.             if (json[i].code == product.code){
  722.                 found = true;
  723.                 json.splice(i, 1);
  724.                 break;
  725.             }
  726.         }
  727.         json.unshift(product);
  728.  
  729.         if(json.length == maxItems+2){
  730.             json.splice(maxItems+1, 1);
  731.         }
  732.         return json;
  733.     }
  734.     $('body').on('click', '#mz-close-button', function(e) {
  735.         e.preventDefault();
  736.         blockUiLoader.unblockUi();
  737.     });
  738. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement