· 8 years ago · Aug 17, 2018, 03:42 PM
1/*
2 * 2007-2015 PrestaShop
3 *
4 * NOTICE OF LICENSE
5 *
6 * This source file is subject to the Academic Free License (AFL 3.0)
7 * that is bundled with this package in the file LICENSE.txt.
8 * It is also available through the world-wide-web at this URL:
9 * http://opensource.org/licenses/afl-3.0.php
10 * If you did not receive a copy of the license and are unable to
11 * obtain it through the world-wide-web, please send an email
12 * to license@prestashop.com so we can send you a copy immediately.
13 *
14 * DISCLAIMER
15 *
16 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
17 * versions in the future. If you wish to customize PrestaShop for your
18 * needs please refer to http://www.prestashop.com for more information.
19 *
20 * @author PrestaShop SA <contact@prestashop.com>
21 * @copyright 2007-2015 PrestaShop SA
22 * @license http://opensource.org/licenses/afl-3.0.php Academic Free License (AFL 3.0)
23 * International Registered Trademark & Property of PrestaShop SA
24 */
25
26//global variables
27var serialScrollNbImagesDisplayed;
28var selectedCombination;
29var globalQuantity;
30var colors;
31var original_url;
32var first_url_check;
33var firstTime;
34
35function resetGlobalVariables() {
36 serialScrollNbImagesDisplayed = null;
37 selectedCombination = [];
38 globalQuantity = 0;
39 colors = [];
40 original_url = window.location + '';
41 first_url_check = true;
42 firstTime = true;
43}
44resetGlobalVariables();
45
46/* Retro compat from product.tpl */
47function iHaveNoIdeaWhatItDoes() {
48 if (typeof customizationFields !== 'undefined' && customizationFields) {
49 var customizationFieldsBk = customizationFields;
50 customizationFields = [];
51 var j = 0;
52 for (var i = 0; i < customizationFieldsBk.length; ++i) {
53 var key = 'pictures_' + parseInt(id_product) + '_' + parseInt(customizationFieldsBk[i]['id_customization_field']);
54 customizationFields[i] = [];
55 customizationFields[i][0] = (parseInt(customizationFieldsBk[i]['type']) == 0) ? 'img' + i : 'textField' + j++;
56 customizationFields[i][1] = (parseInt(customizationFieldsBk[i]['type']) == 0 && customizationFieldsBk[i][key]) ? 2 : parseInt(customizationFieldsBk[i]['required']);
57 }
58 }
59
60 if (typeof combinationImages !== 'undefined' && combinationImages) {
61 combinationImagesJS = [];
62 combinationImagesJS[0] = [];
63 var k = 0;
64 for (var i in combinationImages) {
65 combinationImagesJS[i] = [];
66 for (var j in combinationImages[i]) {
67 var id_image = parseInt(combinationImages[i][j]['id_image']);
68 if (id_image) {
69 combinationImagesJS[0][k++] = id_image;
70 combinationImagesJS[i][j] = [];
71 combinationImagesJS[i][j] = id_image;
72 }
73 }
74 }
75
76 if (typeof combinationImagesJS[0] !== 'undefined' && combinationImagesJS[0]) {
77 var array_values = [];
78 for (var key in arrayUnique(combinationImagesJS[0]))
79 array_values.push(combinationImagesJS[0][key]);
80 combinationImagesJS[0] = array_values;
81 }
82 combinationImages = combinationImagesJS;
83 }
84
85 if (typeof combinations !== 'undefined' && combinations) {
86 combinationsJS = [];
87 var k = 0;
88 for (var i in combinations) {
89 globalQuantity += combinations[i]['quantity'];
90 combinationsJS[k] = [];
91 combinationsJS[k]['idCombination'] = parseInt(i);
92 combinationsJS[k]['idsAttributes'] = combinations[i]['attributes'];
93 combinationsJS[k]['quantity'] = combinations[i]['quantity'];
94 combinationsJS[k]['price'] = combinations[i]['price'];
95 combinationsJS[k]['ecotax'] = combinations[i]['ecotax'];
96 combinationsJS[k]['image'] = parseInt(combinations[i]['id_image']);
97 combinationsJS[k]['reference'] = combinations[i]['reference'];
98 combinationsJS[k]['unit_price'] = combinations[i]['unit_impact'];
99 combinationsJS[k]['minimal_quantity'] = parseInt(combinations[i]['minimal_quantity']);
100
101 combinationsJS[k]['available_date'] = [];
102 combinationsJS[k]['available_date']['date'] = combinations[i]['available_date'];
103 combinationsJS[k]['available_date']['date_formatted'] = combinations[i]['date_formatted'];
104
105 combinationsJS[k]['specific_price'] = [];
106 combinationsJS[k]['specific_price']['reduction_percent'] = (combinations[i]['specific_price'] && combinations[i]['specific_price']['reduction'] && combinations[i]['specific_price']['reduction_type'] == 'percentage') ? combinations[i]['specific_price']['reduction'] * 100 : 0;
107 combinationsJS[k]['specific_price']['reduction_price'] = (combinations[i]['specific_price'] && combinations[i]['specific_price']['reduction'] && combinations[i]['specific_price']['reduction_type'] == 'amount') ? combinations[i]['specific_price']['reduction'] : 0;
108 combinationsJS[k]['price'] = (combinations[i]['specific_price'] && combinations[i]['specific_price']['price'] && parseInt(combinations[i]['specific_price']['price']) != -1) ? combinations[i]['specific_price']['price'] : combinations[i]['price'];
109
110 combinationsJS[k]['reduction_type'] = (combinations[i]['specific_price'] && combinations[i]['specific_price']['reduction_type']) ? combinations[i]['specific_price']['reduction_type'] : '';
111 combinationsJS[k]['id_product_attribute'] = (combinations[i]['specific_price'] && combinations[i]['specific_price']['id_product_attribute']) ? combinations[i]['specific_price']['id_product_attribute'] : 0;
112 k++;
113 }
114 combinations = combinationsJS;
115 }
116 /* */
117
118
119
120
121}
122iHaveNoIdeaWhatItDoes();
123
124function startup() {
125 $(document).ready(function() {
126 var url_found = checkUrl();
127 //init the price in relation of the selected attributes
128 if (!url_found) {
129 if (typeof productHasAttributes != 'undefined' && productHasAttributes)
130 findCombination();
131 else
132 refreshProductImages(0);
133 }
134
135 initLocationChange();
136 serialScrollSetNbImages();
137
138 //init the serialScroll for thumbs
139 if (!!$.prototype.serialScroll)
140 $('#thumbs_list').serialScroll({
141 items: 'li:visible',
142 prev: '#view_scroll_left',
143 next: '#view_scroll_right',
144 axis: 'x',
145 offset: 0,
146 start: 0,
147 stop: true,
148 onBefore: serialScrollFixLock,
149 duration: 700,
150 step: 2,
151 lazy: true,
152 lock: false,
153 force: false,
154 cycle: false
155 });
156
157 $('#thumbs_list').trigger('goto', 0);
158
159 //set jqZoom parameters if needed
160 if (typeof(jqZoomEnabled) != 'undefined' && jqZoomEnabled) {
161 if ($('#thumbs_list .shown img').length) {
162 var new_src = $('#thumbs_list .shown img').attr('src').replace('cart_', 'large_');
163 if ($('.jqzoom img').attr('src') != new_src)
164 $('.jqzoom img').attr('src', new_src).parent().attr('href', new_src);
165 }
166
167 $('.jqzoom').jqzoom({
168 zoomType: 'innerzoom', //innerzoom/standard/reverse/drag
169 zoomWidth: 458, //zooming div default width(default width value is 200)
170 zoomHeight: 458, //zooming div default width(default height value is 200)
171 xOffset: 21, //zooming div default offset(default offset value is 10)
172 yOffset: 0,
173 title: false
174 });
175
176 }
177 if (typeof(contentOnly) != 'undefined' && !contentOnly) {
178 if (!!$.prototype.fancybox)
179 $('li:visible .fancybox, .fancybox.shown').fancybox({
180 'hideOnContentClick': true,
181 'openEffect': 'elastic',
182 'closeEffect': 'elastic'
183 });
184 } else if (typeof ajax_allowed != 'undefined' && !ajax_allowed)
185 $('#buy_block').attr('target', '_top');
186
187 if ($('#bxslider li').length && !!$.prototype.bxSlider)
188 $('#bxslider').bxSlider({
189 minSlides: 1,
190 maxSlides: 6,
191 slideWidth: 178,
192 slideMargin: 20,
193 pager: false,
194 nextText: '',
195 prevText: '',
196 moveSlides: 1,
197 infiniteLoop: false,
198 hideControlOnEnd: true
199 });
200
201 if (!$('#bxslider li').length)
202 $('.accessories-block').parent().remove();
203
204 if (typeof product_fileDefaultHtml !== 'undefined')
205 $.uniform.defaults.fileDefaultHtml = product_fileDefaultHtml;
206 if (typeof product_fileButtonHtml !== 'undefined')
207 $.uniform.defaults.fileButtonHtml = product_fileButtonHtml;
208
209 if ($('#customizationForm').length) {
210 var url = window.location + '';
211 if (url.indexOf('#') != -1)
212 getProductAttribute();
213 }
214
215 activateGroupedProducts();
216 userFocusOnVariants();
217 });
218}
219startup();
220
221$(window).resize(function() {
222 serialScrollSetNbImages();
223 $('#thumbs_list').trigger('goto', 0);
224 serialScrollFixLock('', '', '', '', 0);
225});
226
227// The button to increment the product value
228$(document).on('click', '.product_quantity_up', function(e) {
229 e.preventDefault();
230 fieldName = $(this).data('field-qty');
231 var currentVal = parseInt($('input[name=' + fieldName + ']').val());
232 if (!allowBuyWhenOutOfStock && quantityAvailable > 0)
233 quantityAvailableT = quantityAvailable;
234 else
235 quantityAvailableT = 100000000;
236 if ($('#multiplication_limit').length) {
237 if (!isNaN(currentVal) && currentVal < quantityAvailableT) {
238 if (currentVal % parseInt($('#multiplication_limit').val()) == 0)
239 $('input[name=' + fieldName + ']').val(currentVal + parseInt($('#multiplication_limit').val())).trigger('keyup');
240 else
241 $('input[name=' + fieldName + ']').val(parseInt($('#multiplication_limit').val()));
242 } else {
243 $('input[name=' + fieldName + ']').val(quantityAvailableT);
244 }
245 } else {
246 if (!isNaN(currentVal) && currentVal < quantityAvailableT) {
247 $('input[name=' + fieldName + ']').val(currentVal + 1).trigger('keyup');
248 } else {
249 $('input[name=' + fieldName + ']').val(quantityAvailableT);
250 }
251 }
252});
253// The button to decrement the product value
254$(document).on('click', '.product_quantity_down', function(e) {
255 e.preventDefault();
256 fieldName = $(this).data('field-qty');
257 var currentVal = parseInt($('input[name=' + fieldName + ']').val());
258 if ($('#multiplication_limit').length) {
259 if (!isNaN(currentVal) && currentVal > parseInt($('#multiplication_limit').val())) {
260 if (currentVal % parseInt($('#multiplication_limit').val()) == 0)
261 $('input[name=' + fieldName + ']').val(currentVal - parseInt($('#multiplication_limit').val())).trigger('keyup');
262 else
263 $('input[name=' + fieldName + ']').val(parseInt($('#multiplication_limit').val()));
264 } else {
265 $('input[name=' + fieldName + ']').val(parseInt($('#multiplication_limit').val()));
266 }
267 } else {
268 if (!isNaN(currentVal) && currentVal > 1) {
269 $('input[name=' + fieldName + ']').val(currentVal - 1).trigger('keyup');
270 } else {
271 $('input[name=' + fieldName + ']').val(1);
272 }
273 }
274});
275
276//hover 'other views' images management
277$(document).on('mouseover', '#views_block li a', function() {
278 displayImage($(this));
279});
280//add a link on the span 'view full size' and on the big image
281$(document).on('click', '#view_full_size, #image-block', function(e) {
282 $('#views_block .shown').click();
283});
284//catch the click on the "more infos" button at the top of the page
285$(document).on('click', '#short_description_block .button', function(e) {
286 $('#more_info_tab_more_info').click();
287 $.scrollTo('#more_info_tabs', 1200);
288});
289// Hide the customization submit button and display some message
290$(document).on('click', '#customizedDatas input', function(e) {
291 $('#customizedDatas input').hide();
292 $('#ajax-loader').fadeIn();
293 $('#customizedDatas').append(uploading_in_progress);
294});
295
296$(document).on('click', 'a[data-id=resetImages]', function(e) {
297 e.preventDefault();
298 refreshProductImages(0);
299});
300
301$(document).on('click', '.color_pick', function(e) {
302 e.preventDefault();
303 colorPickerClick($(this));
304 getProductAttribute();
305});
306
307$(document).on('change', '.attribute_select', function(e) {
308 e.preventDefault();
309 findCombination();
310 getProductAttribute();
311});
312
313$(document).on('click', '.attribute_radio', function(e) {
314 e.preventDefault();
315 findCombination();
316 getProductAttribute();
317});
318
319$(document).on('click', 'button[name=saveCustomization]', function(e) {
320 saveCustomization();
321});
322
323$(document).on('click', '.grouped-product-square-images a', function(e) {
324 e.preventDefault();
325});
326
327$(document).on('click', '.color_pick', function(e) {
328 //console.log($(e.target).attr("value"));
329 if ($(e.target).attr("value") != id_product)
330 ajaxRequestNewProduct($(e.target).attr("value"));
331});
332
333if (typeof ad !== 'undefined' && ad && typeof adtoken !== 'undefined' && adtoken) {
334 $(document).on('click', 'input[name=publish_button]', function(e) {
335 e.preventDefault();
336 submitPublishProduct(ad, 0, adtoken);
337 });
338 $(document).on('click', 'input[name=lnk_view]', function(e) {
339 e.preventDefault();
340 submitPublishProduct(ad, 1, adtoken);
341 });
342}
343
344if (typeof(contentOnly) != 'undefined' && contentOnly) {
345 $(document).on('click', '.fancybox', function(e) {
346 e.preventDefault();
347 });
348
349 $(document).on('click', '#image-block', function(e) {
350 e.preventDefault();
351 var productUrl = window.document.location.href + '';
352 var data = productUrl.replace(/[\?|&]content_only=1/, '');
353
354 if (window.parent.page_name == 'search')
355 data += ((data.indexOf('?') < 0) ? '?' : '&') + 'HTTP_REFERER=' + encodeURIComponent(window.parent.document.location.href);
356
357 window.parent.document.location.href = data;
358 return;
359 });
360}
361
362
363
364if (typeof minimalQuantity != 'undefined' && minimalQuantity) {
365 checkMinimalQuantity();
366 $(document).on('keyup', 'input[name=qty]', function(e) {
367 checkMinimalQuantity(minimalQuantity);
368 });
369}
370
371
372function arrayUnique(a) {
373 return a.reduce(function(p, c) {
374 if (p.indexOf(c) < 0)
375 p.push(c);
376 return p;
377 }, []);
378};
379
380//check if a function exists
381function function_exists(function_name) {
382 if (typeof function_name === 'string')
383 function_name = this.window[function_name];
384 return typeof function_name === 'function';
385}
386
387//execute oosHook js code
388function oosHookJsCode() {
389 for (var i = 0; i < oosHookJsCodeFunctions.length; i++) {
390 if (function_exists(oosHookJsCodeFunctions[i]))
391 setTimeout(oosHookJsCodeFunctions[i] + '()', 0);
392 }
393}
394
395//add a combination of attributes in the global JS sytem
396function addCombination(idCombination, arrayOfIdAttributes, quantity, price, ecotax, id_image, reference, unit_price, minimal_quantity, available_date, combination_specific_price) {
397 globalQuantity += quantity;
398
399 var combination = [];
400 combination['idCombination'] = idCombination;
401 combination['quantity'] = quantity;
402 combination['idsAttributes'] = arrayOfIdAttributes;
403 combination['price'] = price;
404 combination['ecotax'] = ecotax;
405 combination['image'] = id_image;
406 combination['reference'] = reference;
407 combination['unit_price'] = unit_price;
408 combination['minimal_quantity'] = minimal_quantity;
409 combination['available_date'] = [];
410 combination['available_date'] = available_date;
411 combination['specific_price'] = [];
412 combination['specific_price'] = combination_specific_price;
413 combinations.push(combination);
414}
415
416// search the combinations' case of attributes and update displaying of availability, prices, ecotax, and image
417function findCombination() {
418 $('#minimal_quantity_wanted_p').fadeOut();
419 if (typeof $('#minimal_quantity_label').text() === 'undefined' || $('#minimal_quantity_label').html() > 1)
420 $('#quantity_wanted').val(1);
421
422 //create a temporary 'choice' array containing the choices of the customer
423 var choice = [];
424 var radio_inputs = parseInt($('#attributes .checked > input[type=radio]').length);
425 if (radio_inputs)
426 radio_inputs = '#attributes .checked > input[type=radio]';
427 else
428 radio_inputs = '#attributes input[type=radio]:checked';
429
430 $('#attributes select, #attributes input[type=hidden], ' + radio_inputs).each(function() {
431 choice.push(parseInt($(this).val()));
432 });
433
434 if (typeof combinations == 'undefined' || !combinations)
435 combinations = [];
436 //testing every combination to find the conbination's attributes' case of the user
437 for (var combination = 0; combination < combinations.length; ++combination) {
438 //verify if this combinaison is the same that the user's choice
439 var combinationMatchForm = true;
440 $.each(combinations[combination]['idsAttributes'], function(key, value) {
441 if (!in_array(parseInt(value), choice))
442 combinationMatchForm = false;
443 });
444
445 if (combinationMatchForm) {
446 if (combinations[combination]['minimal_quantity'] > 1) {
447 $('#minimal_quantity_label').html(combinations[combination]['minimal_quantity']);
448 $('#minimal_quantity_wanted_p').fadeIn();
449 $('#quantity_wanted').val(combinations[combination]['minimal_quantity']);
450 $('#quantity_wanted').bind('keyup', function() { checkMinimalQuantity(combinations[combination]['minimal_quantity']); });
451 }
452 //combination of the user has been found in our specifications of combinations (created in back office)
453 selectedCombination['unavailable'] = false;
454 selectedCombination['reference'] = combinations[combination]['reference'];
455 $('#idCombination').val(combinations[combination]['idCombination']);
456
457 //get the data of product with these attributes
458 quantityAvailable = combinations[combination]['quantity'];
459 selectedCombination['price'] = combinations[combination]['price'];
460 selectedCombination['unit_price'] = combinations[combination]['unit_price'];
461 selectedCombination['specific_price'] = combinations[combination]['specific_price'];
462 if (combinations[combination]['ecotax'])
463 selectedCombination['ecotax'] = combinations[combination]['ecotax'];
464 else
465 selectedCombination['ecotax'] = default_eco_tax;
466
467 //show the large image in relation to the selected combination
468 if (combinations[combination]['image'] && combinations[combination]['image'] != -1)
469 displayImage($('#thumb_' + combinations[combination]['image']).parent());
470
471 //show discounts values according to the selected combination
472 if (combinations[combination]['idCombination'] && combinations[combination]['idCombination'] > 0)
473 displayDiscounts(combinations[combination]['idCombination']);
474
475 //get available_date for combination product
476 selectedCombination['available_date'] = combinations[combination]['available_date'];
477
478 //update the display
479 updateDisplay();
480
481 if (firstTime) {
482 refreshProductImages(0);
483 firstTime = false;
484 } else
485 refreshProductImages(combinations[combination]['idCombination']);
486 //leave the function because combination has been found
487 return;
488 }
489 }
490
491 //this combination doesn't exist (not created in back office)
492 selectedCombination['unavailable'] = true;
493 if (typeof(selectedCombination['available_date']) != 'undefined')
494 delete selectedCombination['available_date'];
495
496 updateDisplay();
497}
498
499//update display of the availability of the product AND the prices of the product
500function updateDisplay() {
501 var productPriceDisplay = productPrice;
502 var productPriceWithoutReductionDisplay = productPriceWithoutReduction;
503
504 if (!selectedCombination['unavailable'] && quantityAvailable > 0 && productAvailableForOrder == 1) {
505 //show the choice of quantities
506 $('#quantity_wanted_p:hidden').show('slow');
507
508 //show the "add to cart" button ONLY if it was hidden
509 $('#add_to_cart:hidden').fadeIn(600);
510
511 //hide the hook out of stock
512 $('#oosHook').hide();
513
514 $('#availability_date').fadeOut();
515
516 //availability value management
517 if (stock_management && availableNowValue != '') {
518 $('#availability_value').removeClass('label-warning').addClass('label-success').text(availableNowValue).show();
519 $('#availability_statut:hidden').show()
520 } else
521 $('#availability_statut:visible').hide();
522
523 //'last quantities' message management
524 if (!allowBuyWhenOutOfStock) {
525 if (quantityAvailable <= maxQuantityToAllowDisplayOfLastQuantityMessage)
526 $('#last_quantities').show('slow');
527 else
528 $('#last_quantities').hide('slow');
529 }
530
531 if (quantitiesDisplayAllowed) {
532 $('#pQuantityAvailable:hidden').show('slow');
533 $('#quantityAvailable').text(quantityAvailable);
534
535 if (quantityAvailable < 2) // we have 1 or less product in stock and need to show "item" instead of "items"
536 {
537 $('#quantityAvailableTxt').show();
538 $('#quantityAvailableTxtMultiple').hide();
539 } else {
540 $('#quantityAvailableTxt').hide();
541 $('#quantityAvailableTxtMultiple').show();
542 }
543 }
544 } else {
545 //show the hook out of stock
546 if (productAvailableForOrder == 1) {
547 $('#oosHook').show();
548 if ($('#oosHook').length > 0 && function_exists('oosHookJsCode'))
549 oosHookJsCode();
550 }
551
552 //hide 'last quantities' message if it was previously visible
553 $('#last_quantities:visible').hide('slow');
554
555 //hide the quantity of pieces if it was previously visible
556 $('#pQuantityAvailable:visible').hide('slow');
557
558 //hide the choice of quantities
559 if (!allowBuyWhenOutOfStock)
560 $('#quantity_wanted_p:visible').hide('slow');
561
562 //display that the product is unavailable with theses attributes
563 if (!selectedCombination['unavailable']) {
564 $('#availability_value').text(doesntExistNoMore + (globalQuantity > 0 ? ' ' + doesntExistNoMoreBut : ''));
565 if (!allowBuyWhenOutOfStock)
566 $('#availability_value').removeClass('label-success').addClass('label-warning');
567 } else {
568 $('#availability_value').text(doesntExist).removeClass('label-success').addClass('label-warning');
569 $('#oosHook').hide();
570 }
571
572 if ((stock_management == 1 && !allowBuyWhenOutOfStock) || (!stock_management && selectedCombination['unavailable']))
573 $('#availability_statut:hidden').show();
574
575 if (typeof(selectedCombination['available_date']) != 'undefined' && selectedCombination['available_date']['date'].length != 0) {
576 var available_date = selectedCombination['available_date']['date'];
577 var tab_date = available_date.split('-');
578 var time_available = new Date(tab_date[0], tab_date[1], tab_date[2]);
579 time_available.setMonth(time_available.getMonth() - 1);
580 var now = new Date();
581 if (now.getTime() < time_available.getTime() && $('#availability_date_value').text() != selectedCombination['available_date']['date_formatted']) {
582 $('#availability_date').fadeOut('normal', function() {
583 $('#availability_date_value').text(selectedCombination['available_date']['date_formatted']);
584 $(this).fadeIn();
585 });
586 } else if (now.getTime() < time_available.getTime())
587 $('#availability_date').fadeIn();
588 } else
589 $('#availability_date').fadeOut();
590
591 //show the 'add to cart' button ONLY IF it's possible to buy when out of stock AND if it was previously invisible
592 if (allowBuyWhenOutOfStock && !selectedCombination['unavailable'] && productAvailableForOrder) {
593 $('#add_to_cart:hidden').fadeIn(600);
594
595 if (stock_management && availableLaterValue != '')
596 $('#availability_value').addClass('label-warning').text(availableLaterValue).show('slow');
597 else
598 $('#availability_statut:visible').hide('slow');
599 } else {
600 $('#add_to_cart:visible').fadeOut(600);
601 if (stock_management == 1 && productAvailableForOrder)
602 $('#availability_statut:hidden').show('slow');
603 }
604
605 if (productAvailableForOrder == 0)
606 $('#availability_statut:visible').hide();
607 }
608
609 if (selectedCombination['reference'] || productReference) {
610 if (selectedCombination['reference'])
611 $('#product_reference span').text(selectedCombination['reference']);
612 else if (productReference)
613 $('#product_reference span').text(productReference);
614 $('#product_reference:hidden').show('slow');
615 } else
616 $('#product_reference:visible').hide('slow');
617
618 // If we have combinations, update price section: amounts, currency, discount amounts,...
619 if (productHasAttributes)
620 updatePrice();
621}
622
623function updatePrice() {
624 // Get combination prices
625 var combID = $('#idCombination').val();
626 var combination = combinationsFromController[combID];
627 if (typeof combination == 'undefined')
628 return;
629
630 // Set product (not the combination) base price
631 var basePriceWithoutTax = productBasePriceTaxExcl;
632 var priceWithGroupReductionWithoutTax = 0;
633
634 // Apply combination price impact
635 // 0 by default, +x if price is inscreased, -x if price is decreased
636 basePriceWithoutTax = basePriceWithoutTax + +combination.price;
637
638 // If a specific price redefine the combination base price
639 if (combination.specific_price && combination.specific_price.price > 0) {
640 if (combination.specific_price.id_product_attribute === 0)
641 basePriceWithoutTax = +combination.specific_price.price;
642 else
643 basePriceWithoutTax = +combination.specific_price.price + +combination.price;
644 }
645
646 // Apply group reduction
647 priceWithGroupReductionWithoutTax = basePriceWithoutTax ;
648 var priceWithDiscountsWithoutTax = priceWithGroupReductionWithoutTax;
649
650 // Apply specific price (discount)
651 // We only apply percentage discount and discount amount given before tax
652 // Specific price give after tax will be handled after taxes are added
653 if (combination.specific_price && combination.specific_price.reduction > 0) {
654 if (combination.specific_price.reduction_type == 'amount') {
655 if (typeof combination.specific_price.reduction_tax !== 'undefined' && combination.specific_price.reduction_tax === "0") {
656 var reduction = +combination.specific_price.reduction / currencyRate;
657 priceWithDiscountsWithoutTax -= reduction;
658 }
659 } else if (combination.specific_price.reduction_type == 'percentage') {
660 priceWithDiscountsWithoutTax = priceWithDiscountsWithoutTax * (1 - +combination.specific_price.reduction);
661 }
662 }
663
664 // Apply Tax if necessary
665 if (noTaxForThisProduct || customerGroupWithoutTax) {
666 basePriceDisplay = basePriceWithoutTax;
667 priceWithDiscountsDisplay = priceWithDiscountsWithoutTax;
668 } else {
669 basePriceDisplay = basePriceWithoutTax * (taxRate / 100 + 1);
670 priceWithDiscountsDisplay = priceWithDiscountsWithoutTax * (taxRate / 100 + 1);
671
672 }
673
674 if (default_eco_tax) {
675 // combination.ecotax doesn't modify the price but only the display
676 basePriceDisplay = basePriceDisplay + default_eco_tax * (1 + ecotaxTax_rate / 100);
677 priceWithDiscountsDisplay = priceWithDiscountsDisplay + default_eco_tax * (1 + ecotaxTax_rate / 100);
678 }
679
680 // If the specific price was given after tax, we apply it now
681 if (combination.specific_price && combination.specific_price.reduction > 0) {
682 if (combination.specific_price.reduction_type == 'amount') {
683 if (typeof combination.specific_price.reduction_tax === 'undefined' ||
684 (typeof combination.specific_price.reduction_tax !== 'undefined' && combination.specific_price.reduction_tax === '1')) {
685 var reduction = +combination.specific_price.reduction / currencyRate;
686 priceWithDiscountsDisplay -= reduction;
687 // We recalculate the price without tax in order to keep the data consistency
688 priceWithDiscountsWithoutTax = priceWithDiscountsDisplay - reduction * (1 / (1 + taxRate / 100));
689 }
690 }
691 }
692
693 // Compute discount value and percentage
694 // Done just before display update so we have final prices
695 if (basePriceDisplay != priceWithDiscountsDisplay) {
696 var discountValue = basePriceDisplay - priceWithDiscountsDisplay;
697 var discountPercentage = (1 - (priceWithDiscountsDisplay / basePriceDisplay)) * 100;
698 }
699
700 var unit_impact = +combination.unit_impact;
701 if (productUnitPriceRatio > 0 || unit_impact) {
702 if (unit_impact) {
703 baseUnitPrice = productBasePriceTaxExcl / productUnitPriceRatio;
704 unit_price = baseUnitPrice + unit_impact;
705
706 if (!noTaxForThisProduct || !customerGroupWithoutTax)
707 unit_price = unit_price * (taxRate / 100 + 1);
708 } else
709 unit_price = priceWithDiscountsDisplay / productUnitPriceRatio;
710 }
711
712 /* Update the page content, no price calculation happens after */
713
714 // Hide everything then show what needs to be shown
715 $('#reduction_percent').hide();
716 $('#reduction_amount').hide();
717 $('#old_price,#old_price_display,#old_price_display_taxes').hide();
718 $('.price-ecotax').hide();
719 $('.unit-price').hide();
720
721 $('#our_price_display').text(formatCurrency(priceWithDiscountsDisplay * currencyRate, currencyFormat, currencySign, currencyBlank)).trigger('change');
722
723 // If the calculated price (after all discounts) is different than the base price
724 // we show the old price striked through
725 if (priceWithDiscountsDisplay.toFixed(2) != basePriceDisplay.toFixed(2)) {
726 $('#old_price_display').text(formatCurrency(basePriceDisplay * currencyRate, currencyFormat, currencySign, currencyBlank));
727 $('#old_price,#old_price_display,#old_price_display_taxes').show();
728
729 // Then if it's not only a group reduction we display the discount in red box
730 if (priceWithDiscountsWithoutTax != priceWithGroupReductionWithoutTax) {
731 if (combination.specific_price.reduction_type == 'amount') {
732 $('#reduction_amount_display').html('-' + formatCurrency(+discountValue * currencyRate, currencyFormat, currencySign, currencyBlank));
733 $('#reduction_amount').show();
734 } else {
735 var toFix = 2;
736 if ((parseFloat(discountPercentage).toFixed(2) - parseFloat(discountPercentage).toFixed(0)) == 0)
737 toFix = 0;
738 $('#reduction_percent_display').html('-' + parseFloat(discountPercentage).toFixed(toFix) + '%');
739 $('#reduction_percent').show();
740 }
741 }
742 }
743
744 // Green Tax (Eco tax)
745 // Update display of Green Tax
746 if (default_eco_tax) {
747 ecotax = default_eco_tax;
748
749 // If the default product ecotax is overridden by the combination
750 if (combination.ecotax)
751 ecotax = +combination.ecotax;
752
753 if (!noTaxForThisProduct)
754 ecotax = ecotax * (1 + ecotaxTax_rate / 100)
755
756 $('#ecotax_price_display').text(formatCurrency(ecotax * currencyRate, currencyFormat, currencySign, currencyBlank));
757 $('.price-ecotax').show();
758 }
759
760 // Unit price are the price per piece, per Kg, per m²
761 // It doesn't modify the price, it's only for display
762 if (productUnitPriceRatio > 0) {
763 $('#unit_price_display').text(formatCurrency(unit_price * currencyRate, currencyFormat, currencySign, currencyBlank));
764 $('.unit-price').show();
765 }
766
767 // If there is a quantity discount table,
768 // we update it according to the new price
769 updateDiscountTable(priceWithDiscountsDisplay);
770}
771
772//update display of the large image
773function displayImage(domAAroundImgThumb, no_animation) {
774 if (typeof(no_animation) == 'undefined')
775 no_animation = false;
776 if (domAAroundImgThumb.attr('href')) {
777 var new_src = domAAroundImgThumb.attr('href').replace('thickbox', 'large');
778 var new_title = domAAroundImgThumb.attr('title');
779 var new_href = domAAroundImgThumb.attr('href');
780 if ($('#bigpic').attr('src') != new_src) {
781 $('#bigpic').attr({
782 'src': new_src,
783 'alt': new_title,
784 'title': new_title
785 }).load(function() {
786 if (typeof(jqZoomEnabled) != 'undefined' && jqZoomEnabled)
787 $(this).attr('rel', new_href);
788 });
789 }
790 $('#views_block li a').removeClass('shown');
791 $(domAAroundImgThumb).addClass('shown');
792 }
793}
794
795//update display of the discounts table
796function displayDiscounts(combination) {
797 $('#quantityDiscount tbody tr').each(function() {
798 if (($(this).attr('id') != 'quantityDiscount_0') &&
799 ($(this).attr('id') != 'quantityDiscount_' + combination) &&
800 ($(this).attr('id') != 'noQuantityDiscount'))
801 $(this).fadeOut('slow');
802 });
803
804 if ($('#quantityDiscount_' + combination + ',.quantityDiscount_' + combination).length != 0 ||
805 $('#quantityDiscount_0,.quantityDiscount_0').length != 0) {
806 $('#quantityDiscount').parent().show();
807 $('#quantityDiscount_' + combination + ',.quantityDiscount_' + combination).show();
808 $('#noQuantityDiscount').hide();
809 } else {
810 $('#quantityDiscount').parent().hide();
811 $('#noQuantityDiscount').show();
812 }
813}
814
815function updateDiscountTable(newPrice) {
816 $('#quantityDiscount tbody tr').each(function() {
817 var type = $(this).data("discount-type");
818 var discount = $(this).data("discount");
819 var quantity = $(this).data("discount-quantity");
820
821 if (type == 'percentage') {
822 var discountedPrice = newPrice * (1 - discount / 100);
823 var discountUpTo = newPrice * (discount / 100) * quantity;
824 } else if (type == 'amount') {
825 var discountedPrice = newPrice - discount;
826 var discountUpTo = discount * quantity;
827 }
828
829 if (displayDiscountPrice != 0)
830 $(this).children('td').eq(1).text(formatCurrency(discountedPrice * currencyRate, currencyFormat, currencySign, currencyBlank));
831 $(this).children('td').eq(2).text(upToTxt + ' ' + formatCurrency(discountUpTo * currencyRate, currencyFormat, currencySign, currencyBlank));
832 });
833}
834
835function serialScrollFixLock(event, targeted, scrolled, items, position) {
836 var serialScrollNbImages = $('#thumbs_list li:visible').length;
837 var leftArrow = position == 0 ? true : false;
838 var rightArrow = position + serialScrollNbImagesDisplayed >= serialScrollNbImages ? true : false;
839
840 $('#view_scroll_left').css('cursor', leftArrow ? 'default' : 'pointer').css('display', leftArrow ? 'none' : 'block').fadeTo(0, leftArrow ? 0 : 1);
841 $('#view_scroll_right').css('cursor', rightArrow ? 'default' : 'pointer').fadeTo(0, rightArrow ? 0 : 1).css('display', rightArrow ? 'none' : 'block');
842 return true;
843}
844
845function serialScrollSetNbImages() {
846 serialScrollNbImagesDisplayed = 4;
847 if ($('#thumbs_list').outerWidth(true) < 294)
848 serialScrollNbImagesDisplayed = 2;
849 else if ($('#thumbs_list').outerWidth(true) < 392)
850 serialScrollNbImagesDisplayed = 3;
851}
852
853
854// Change the current product images regarding the combination selected
855function refreshProductImages(id_product_attribute) {
856 id_product_attribute = parseInt(id_product_attribute);
857
858 if (id_product_attribute > 0 && typeof(combinationImages) != 'undefined' && typeof(combinationImages[id_product_attribute]) != 'undefined') {
859 $('#thumbs_list li').hide();
860 for (var i = 0; i < combinationImages[id_product_attribute].length; i++)
861 if (typeof(jqZoomEnabled) != 'undefined' && jqZoomEnabled)
862 $('#thumbnail_' + parseInt(combinationImages[id_product_attribute][i])).show().children('a.shown').trigger('click');
863 else
864 $('#thumbnail_' + parseInt(combinationImages[id_product_attribute][i])).show();
865 } else
866 $('#thumbs_list li').show();
867
868 if (parseInt($('#thumbs_list_frame >li:visible').length) != parseInt($('#thumbs_list_frame >li').length))
869 $('#wrapResetImages').stop(true, true).show();
870 else
871 $('#wrapResetImages').stop(true, true).hide();
872
873 $('#thumbs_list_frame').width(parseInt($('#thumbs_list_frame >li').outerWidth(true) * $('#thumbs_list_frame >li').length) + 'px');
874 $('#thumbs_list').trigger('goto', 0);
875 serialScrollFixLock('', '', '', '', 0);
876}
877
878function saveCustomization() {
879 $('#quantityBackup').val($('#quantity_wanted').val());
880 $('#customizationForm').submit();
881}
882
883function submitPublishProduct(url, redirect, token) {
884 var id_product = $('#admin-action-product-id').val();
885
886 $.ajaxSetup({ async: false });
887 $.post(url + '/index.php', {
888 action: 'publishProduct',
889 id_product: id_product,
890 status: 1,
891 redirect: redirect,
892 ajax: 1,
893 tab: 'AdminProducts',
894 token: token
895 },
896 function(data) {
897 if (data.indexOf('error') === -1)
898 document.location.href = data;
899 }
900 );
901 return true;
902}
903
904function checkMinimalQuantity(minimal_quantity) {
905 if ($('#quantity_wanted').val() < minimal_quantity) {
906 $('#quantity_wanted').css('border', '1px solid red');
907 $('#minimal_quantity_wanted_p').css('color', 'red');
908 } else {
909 $('#quantity_wanted').css('border', '1px solid #BDC2C9');
910 $('#minimal_quantity_wanted_p').css('color', '#374853');
911 }
912}
913
914function colorPickerClick(elt) {
915 id_attribute = $(elt).attr('id').replace('color_', '');
916 $(elt).parent().parent().children().removeClass('selected');
917 $(elt).fadeTo('fast', 1, function() {
918 $(this).fadeTo('fast', 0, function() {
919 $(this).fadeTo('fast', 1, function() {
920 $(this).parent().addClass('selected');
921 });
922 });
923 });
924 $(elt).parent().parent().parent().children('.color_pick_hidden').val(id_attribute);
925 findCombination();
926}
927
928
929function getProductAttribute() {
930 // get every attributes values
931 request = '';
932 //create a temporary 'tab_attributes' array containing the choices of the customer
933 var tab_attributes = [];
934 var radio_inputs = parseInt($('#attributes .checked > input[type=radio]').length);
935 if (radio_inputs)
936 radio_inputs = '#attributes .checked > input[type=radio]';
937 else
938 radio_inputs = '#attributes input[type=radio]:checked';
939
940 $('#attributes select, #attributes input[type=hidden], ' + radio_inputs).each(function() {
941 tab_attributes.push($(this).val());
942 });
943
944 // build new request
945 for (var i in attributesCombinations)
946 for (var a in tab_attributes)
947 if (attributesCombinations[i]['id_attribute'] === tab_attributes[a])
948 request += '/' + attributesCombinations[i]['id_attribute'] + '-' + attributesCombinations[i]['group'] + attribute_anchor_separator + attributesCombinations[i]['attribute'];
949 request = request.replace(request.substring(0, 1), '#/');
950 var url = window.location + '';
951
952 // redirection
953 if (url.indexOf('#') != -1)
954 url = url.substring(0, url.indexOf('#'));
955
956 if ($('#customizationForm').length) {
957 // set ipa to the customization form
958 customAction = $('#customizationForm').attr('action');
959 if (customAction.indexOf('#') != -1)
960 customAction = customAction.substring(0, customAction.indexOf('#'));
961 $('#customizationForm').attr('action', customAction + request);
962 }
963
964 window.location = url + request;
965}
966
967function initLocationChange(time) {
968 if (!time) time = 500;
969 setInterval(checkUrl, time);
970}
971
972function checkUrl() {
973 if (original_url != window.location || first_url_check) {
974 first_url_check = false;
975 var url = window.location + '';
976 // if we need to load a specific combination
977 if (url.indexOf('#/') != -1) {
978 // get the params to fill from a "normal" url
979 params = url.substring(url.indexOf('#') + 1, url.length);
980 tabParams = params.split('/');
981 tabValues = [];
982 if (tabParams[0] == '')
983 tabParams.shift();
984 for (var i in tabParams)
985 tabValues.push(tabParams[i].split(attribute_anchor_separator));
986 // fill html with values
987 $('.color_pick').removeClass('selected').parent().parent().children().removeClass('selected');
988
989 count = 0;
990 for (var z in tabValues)
991 for (var a in attributesCombinations)
992 if (attributesCombinations[a]['group'] === decodeURIComponent(tabValues[z][1]) &&
993 attributesCombinations[a]['id_attribute'] === decodeURIComponent(tabValues[z][0])) {
994 count++;
995
996 // add class 'selected' to the selected color
997 $('#color_' + attributesCombinations[a]['id_attribute']).addClass('selected').parent().addClass('selected');
998 $('input:radio[value=' + attributesCombinations[a]['id_attribute'] + ']').attr('checked', true);
999 $('input[type=hidden][name=group_' + attributesCombinations[a]['id_attribute_group'] + ']').val(attributesCombinations[a]['id_attribute']);
1000 $('select[name=group_' + attributesCombinations[a]['id_attribute_group'] + ']').val(attributesCombinations[a]['id_attribute']);
1001 }
1002 // find combination and select corresponding thumbs
1003 if (count >= 0) {
1004 firstTime = false;
1005 findCombination();
1006 original_url = url;
1007 return true;
1008 }
1009 // no combination found = removing attributes from url
1010 else
1011 window.location = url.substring(0, url.indexOf('#'));
1012 }
1013 }
1014 return false;
1015}
1016
1017function hideCurrentProductProduct() {
1018 var height_to_hide = $("#center_column").outerHeight(true);
1019 $("#center_column").append("<div class='hide_product_panel' style='position: absolute; width: 100%; height: " + height_to_hide + "px; margin-top: -" + height_to_hide + "px; background-color: #ffffff; opacity: 0.5; z-index: 900'></div>");
1020 console.log(height_to_hide);
1021}
1022
1023function hideCurrentProductProductOld() {
1024 var height_to_hide = $("#center_column>div:nth-child(4)").outerHeight(true);
1025 $("#center_column>div:nth-child(4)").append("<div class='hide_product_panel' style='position: absolute; width: 100%; height: " + height_to_hide + "px; margin-top: -" + height_to_hide + "px; background-color: #f6f6f6; opacity: 0.5; z-index: 900'></div>");
1026}
1027
1028function displayNewProduct(view) {
1029 //console.log(view);
1030
1031 // Przechowanie starej listy polecanych produktów.
1032 var productscategory_list = $("<div></div>");
1033 $("#center_column #productscategory_list").appendTo(productscategory_list);
1034 productscategory_list = productscategory_list.first();
1035
1036 // Czyszczenie widoku produktu.
1037 $("#center_column").empty();
1038
1039 // Åadowanie nowego widoku.
1040 var new_content = $("<div></div>").html(view).find("#center_column").children();
1041
1042 // Przywracanie starej listy polecanych produktów.
1043 $("#center_column").append(new_content);
1044 $("#center_column #productscategory_list").empty();
1045 $(productscategory_list).appendTo("#center_column #productscategory_list");
1046
1047 // Uruchamianie skryptów od formatowania widoku produktu.
1048 resetGlobalVariables();
1049 iHaveNoIdeaWhatItDoes();
1050 startup();
1051
1052 // Nadpisanie ID produktu i naprawienie adresu obrazka.
1053 id_product = $("#id_product_ajax").text();
1054 fixImageAddress();
1055}
1056function displayNewProductOld(view) {
1057
1058 // Przechowanie starej listy polecanych produktów.
1059 var productscategory_list = $("<div></div>");
1060 $("#center_column>div:nth-child(4) #productscategory_list").appendTo(productscategory_list);
1061 productscategory_list = productscategory_list.first();
1062
1063 // Czyszczenie widoku produktu.
1064 $("#center_column>div:nth-child(4)").empty();
1065
1066 // Åadowanie nowego widoku.
1067 var new_content = $("<div></div>").html(view).find("#center_column>div:nth-child(4)").children();
1068
1069 // Przywracanie starej listy polecanych produktów.
1070 $("#center_column>div:nth-child(4)").append(new_content);
1071 $("#center_column>div:nth-child(4) #productscategory_list").empty();
1072 $(productscategory_list).appendTo("#center_column>div:nth-child(4) #productscategory_list");
1073
1074 // Uruchamianie skryptów od formatowania widoku produktu.
1075 resetGlobalVariables();
1076 iHaveNoIdeaWhatItDoes();
1077 startup();
1078
1079 // Nadpisanie ID produktu i naprawienie adresu obrazka.
1080 id_product = $("#id_product_ajax").text();
1081 fixImageAddress();
1082}
1083
1084function ajaxRequestNewProduct(productIdToShow) {
1085
1086 $.ajax({
1087 cache: false,
1088 method: "POST",
1089 url: "/index.php",
1090 data: {
1091 id_product: 9,
1092 controller: "product"
1093 },
1094 dataType: "html",
1095 contentType: "application/x-www-form-urlencoded; charset=UTF-8",
1096 beforeSend: function() {
1097 // Ukrycie widoku produktu. (Tylko nakładka wizualna.)
1098 hideCurrentProductProduct();
1099 },
1100 success: function(response) {
1101 // Podmiana wyswietlanego produktu.
1102
1103 displayNewProduct(response);
1104 },
1105 error: function(response) {
1106 console.log(response);
1107
1108 }
1109 });
1110}
1111
1112function fixImageAddress() {
1113 var currentUrl = $("#bigpic").attr("src");
1114 currentUrl = currentUrl.split("/");
1115 currentUrl[currentUrl.length - 1] = id_product + currentUrl[currentUrl.length - 1];
1116 currentUrl = currentUrl.join("/");
1117 $("#bigpic").attr("src", currentUrl);
1118}
1119
1120function activateGroupedProducts() {
1121
1122
1123 if ($('.grouped-product').length && $('#grouped-product-select').length) {
1124 $('#grouped-product-select').on('change', function() {
1125 var productIdToShow = parseInt($(this).val());
1126 //if (productIdToShow != this_product_id)
1127 // window.location.href = '/index.php?id_product=' + productIdToShow + '&controller=product';
1128 ajaxRequestNewProduct(productIdToShow);
1129 });
1130 }
1131}
1132
1133function userFocusOnVariants() {
1134 if ($('.grouped-product').length && $('#grouped-product-select').length) {
1135 $(window).load(function() {
1136 $('.grouped-product').highlight();
1137 })
1138 }
1139}
1140
1141jQuery.fn.highlight = function() {
1142 $(this).each(function() {
1143 var el = $(this);
1144 el.append("<div class='flash'></div>")
1145 el.children('.flash')
1146 .width(el.width())
1147 .height(el.height())
1148 .css({
1149 "position": "absolute",
1150 "background-color": "#6B4A1F",
1151 "opacity": ".9",
1152 "top": "0",
1153 "left": "0",
1154 "width": "100%",
1155 "height": "100%"
1156 })
1157 .fadeOut(2000);
1158 });
1159}