/* |-------------------------------------------------------------------------- | Common |-------------------------------------------------------------------------- */ core.common = { /** * Default settings for the website */ defaults: { user: { isLoggedIn: false }, global: { environment: 'development', } }, init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; this.onReady(); this.onScroll(); }, onReady: function() { var $this = this; $(document).ready(function() { _self.form.select2(); $this.bindHashScrolling(); $this.textToCopy(); }); }, onScroll: function() { $window.scroll(function() { if($('.page-slide').hasClass("open") && $window.scrollTop() > $('.mobile-menu--inner').outerHeight(true)) { $('.page-slide, .mobile-menu--btn').toggleClass("open"); } }); }, /** * Height match * * @param {object} params * -- @param {object} $matchElement * -- @param {bool} matchByRow (optional) * -- @param {object} $gridElement (optional) * -- @param {int} breakpoint (optional) */ heightMatch: function(params) { _self.util.heightMatch(params); }, setDefaults: function(options, defaults) { return (typeof options == 'object') ? $.extend(defaults, options) : options; }, selectBoxTrigger: function($elements, $parent, $label) { var $label = ($label) ? $label : 'label'; $elements.each(function() { var $element = $(this); $element.on("select2:open", function (e) { $parent.css({'border-color': '#019dc3'}).find($label).css({'color': '#019dc3'}); }); $element.on("select2:close", function (e) { $parent.css({'border-color': ""}).find($label).css({'color': ''}); }); }); }, bindHashScrolling: function() { var $this = this; if (location.hash) { setTimeout(function() { $('html, body').scrollTop(0).show(); $this.scrollToTarget(); }, 0); } else { $('html, body').show(); } $('a[href^=\\#][data-enable-hash-scrolling="true]').on("click", function(event) { $this.scrollToTarget($(this), event); }); }, scrollToTarget: function(element, event) { var target = (element) ? element.attr("href") : location.hash if(location.hash === "#upsells" && core.listing.data.overrideSparesScroll) { console.log(11111); $('.jump-menu--link[href="#range"]').click(); return; } $('html,body').animate({ scrollTop: $(target).offset().top },1200,function() { location.hash = target; }); if(event) { event.preventDefault(); } }, textToCopy: function() { var $this = this; $('.copy-line--link').on('click', function() { const toast = $(this).attr('data-toast-text'); const data = $(this).attr('data-to-copy'); let error = 2; let message = 'Sorry something went wrong copying ' + toast; let messageType = 'message-error'; if(data.length) { if (navigator.clipboard && window.isSecureContext) { navigator.clipboard.writeText(data) .then(function() { error = 1; }) .catch(function(err) { }); } else { var $temp = $(""); $("body").append($temp); $temp.val(data).select(); document.execCommand("copy"); $temp.remove(); error = 1; } if(error = 1) { message = toast + ' Copied to Clipboard'; messageType = 'message-success'; } $this.messageToast(message, messageType); } }); }, messageToast: function(message, messageType) { if ($('.toast-container').length === 0) { $('body').append('
'); } var $toast = $('
').text(message); $('.toast-container').prepend($toast); $toast.stop().slideDown(); setTimeout(function() { $(this).stop().slideUp(); $toast.fadeOut(1000, function() { $(this).fadeOut(500); if($('.toast-container').is(':empty')) { $('.toast-container').stop().slideUp(); } }); }, 2000); }, }; /* |-------------------------------------------------------------------------- | Utils |-------------------------------------------------------------------------- */ core.util = { /* Shows or hides an element depending on makeVisible being true/false * @param {string} selector * @param {bool} makeVisible */ showOrHideElementBoolean(selector, makeVisible) { if(makeVisible == true) { selector.show(); } else { selector.hide(); } }, /** * Custom console logging function */ log: function() { console.groupCollapsed('----- CONSOLE LOG -----'); console.log({'environment': _self.common.data.global.environment}); console.group('Arguments'); console.log(arguments); console.groupEnd(); console.groupCollapsed('Stack Trace'); console.trace(); console.groupEnd(); console.groupEnd(); }, /** * Height match * * @param {object} params * -- @param {object} $matchElement * -- @param {bool} matchByRow (optional) * -- @param {object} $gridElement (optional) * -- @param {int} breakpoint (optional) */ heightMatch: function(params) { var $matchElement = params.$matchElement.removeAttr("style"); var breakpoint = (params.breakpoint) ? params.breakpoint : 0; if(Modernizr.mq('(min-width: ' +breakpoint+ 'px)')) { var itemOffset, maxHeight = 0, rows = [], rowElements = []; if(params.$gridElement){ params.$gridElement.each(function(){ $this = $(this); $this.data('style-cache', $this.attr('style')); }); params.$gridElement.css('height', '250px'); params.$gridElement.each(function(i) { var $thisItem = $(this); // Set first offset as expected result if (i == 0) { itemOffset = $thisItem.offset().top; } // If this elements offset equals expected offset they are on the same line if ($thisItem.offset().top == itemOffset || !params.matchByRow) { // Push element to array to height match when row ends rowElements.push($thisItem); } else { // Set new offset & reset variables itemOffset = $thisItem.offset().top; rows.push(rowElements); rowElements = []; // Set element of the new row rowElements.push($thisItem); } }); if (rowElements) { // Last row has ended, finish height matching left overs. rows.push(rowElements); } params.$gridElement.each(function(){ $this = $(this); $this.attr('style', $this.data('style-cache') || ''); }); $.each(rows, function(k, row){ maxHeight = 0; $row = $(row); $row.each(function(){ var $matchElement = $(this).find(params.$matchElement); maxHeight = ($matchElement.outerHeight() > maxHeight) ? $matchElement.outerHeight() : maxHeight; }); $row.each(function() { $(this).find(params.$matchElement).css('height', maxHeight); }); }); } } }, /** * Price rounding * * @param {int} amount * @return {int} */ parsePrice: function(amount) { var amount = parseFloat(amount); if(parseFloat(amount.toFixed(4)) == parseFloat(amount.toFixed(3))) { if (parseFloat(amount.toFixed(3)) == parseFloat(amount.toFixed(2))) { return amount.toFixed(2); } else { return amount.toFixed(3); } } else { return amount.toFixed(4); } }, format: function(string) { //e.g format("a %1 and a %2", "cat", "dog"); => a cat and a dog var args = arguments; var pattern = RegExp("%([1-" + (arguments.length-1) + "])", "g"); return string.replace(pattern, function(match, index) { return args[index]; }); }, createCookie: function(name, value, days, domain) { var expires; if (days) { var date = new Date(); date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); expires = "; expires=" + date.toGMTString(); } else { expires = ""; } document.cookie = name + "=" + value + expires + "; domain=" + domain + "; path=/"; }, readCookie: function(name) { var nameEQ = encodeURIComponent(name) + "="; var ca = document.cookie.split(';'); for (var i = 0; i < ca.length; i++) { var c = ca[i]; while (c.charAt(0) === ' ') c = c.substring(1, c.length); if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length)); } return null; }, removeCookie: function (name) { this.createCookie(name, "", -1); }, scrollTo: function($element, settings) { var defaults = { speed: 1000, offset: -20 }; var settings = $.extend(true, defaults, settings); $('html, body').animate({ scrollTop: ($element.offset().top + settings.offset) }, settings.speed); }, debounce: function (func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }, trimCommas: function (str) { if (str) { str = str.replace(/(^[,\s]+)|([,\s]+$)/g, ''); } return str; }, strTruncate: function (str, len) { if (str) { // Replace duplicate spaces and trim str = str.replace(/\s+/g, ' ').trim(); // Truncate the string if (str && len) { str = str.substring(0, len).trim(); } } return str; }, inputIncrement: function() { $('.input-inc > div').off('click').on('click', function() { const $container = $(this).parent(); const $input = $container.find('input'); const input_min = parseInt($input.attr('min')); const input_max = parseInt($input.attr('max')); let currentValue = parseInt($input.val(), 10) || input_min; if ($(this).hasClass('input-inc--minus')) { $input.val(Math.max(currentValue - 1, input_min)); } else { if(currentValue + 1 <= input_max) { $input.val(currentValue + 1); } } $input.trigger('change'); }); } } // Reference shorthand variable to logging function core.log = core.util.log; core.form = { /** * Apply the select2 plugin to a target or * to all select elements if no element * is passed as a parameter * * @param {object} element (optional) */ select2: function(element, params) { function formatState (state) { let $state = ""; if(state.text.includes("#")) { const parts = state.text.split("#"); let firstPart = ""; let remainingParts = ""; parts.map((value, index) => { if(index == 0) { firstPart = value; } else { remainingParts += value; }; }); $state = $('
' + firstPart + ' - ' + remainingParts + '
'); } else { $state = state.text; } return $state; }; var options = { width: 'style', minimumResultsForSearch: 2000, templateResult: formatState } if(params) { $.extend(options, params); } var $element = (element) ? element : $("select"); $element.select2(options); $element.on("change", function (e) { if(this.multiple){ $(this).select2("close"); $(this).select2("open"); } }); }, /** * Handles the trigger of a checkbox element, sets the * relative hidden checkbox input accordingly and * passes the status through the callback * * @param {object} $element * @param {function} callback */ checkboxController: function(action, $element, callback) { var $this = this; var $checkbox = $element.find('input[type="checkbox"]'); var checkedBefore, checkedAfter; checkedBefore = $checkbox.prop('checked'); if(action == "toggle" || action == "") { $element.toggleClass("checked"); ($element.hasClass("checked")) ? $checkbox.prop('checked', true) : $checkbox.prop('checked', false); } else if(action == "on") { $this.checkboxOn($element); } else if(action == "off") { $this.checkboxOff($element); } checkedAfter = $checkbox.prop("checked"); if(checkedBefore != checkedAfter){ $checkbox.trigger('change'); } var callback_eval = eval(callback); if (typeof callback_eval == 'function') { callback_eval($checkbox.is(':checked')); } }, checkboxOn: function ($element) { $element.addClass("checked").find('input[type="checkbox"]').prop('checked', true); }, checkboxOff: function ($element) { $element.removeClass("checked").find('input[type="checkbox"]').prop('checked', false); }, /** * Validate children values of $element that have the * required attribute. If a callback is defined, * pass the failed elements to the callback. * * @param {object} element * @param {function} callback */ validateForm: function ($element, callback) { var failedInputs = new Array(); $element.find('[data-required="true"]:visible').removeClass("validate-border").each(function(index, element) { if(!element.value) { // Trigger reflow to allow animation to rerun. // element.offsetWidth = element.offsetWidth; failedInputs.push(element); } }); setTimeout(function() { $(failedInputs).addClass("validate-border"); }, 0); if(failedInputs.length > 0) { $('html, body').animate({scrollTop: $element.offset().top - 100}, 700); if($element.find('.message-error').length) { $element.find('.message-error').slideDown(); } else if($element.find('.error-msg').length) { $element.find(".error-msg").slideDown(); } setTimeout(function() { if($element.find('.message-error').length) { $element.find('.message-error').slideUp(); } else if($element.find('.error-msg').length) { $element.find('.error-msg').slideUp(); } }, 3000); } if(typeof callback == 'function') { callback(failedInputs); } }, fileUploadController: function($element) { var parent = $element.parent(); var fileUpload = parent.find('input[type="file"]'); $element.on('click', function() { fileUpload.click(); }); fileUpload.on('change', function() { if($(this).val() != "") { parent.find('.input-file-dummy').html($(this).val().split(/(\\|\/)/g).pop()); } else { parent.find('.input-file-dummy').html(" "); } }); }, validateNumberInputs: function() { // Validate any number inputs that have a min/max value $('input[type=number]').on('change', function(){ var $this = $(this); var inputValue = parseInt($this.val()); var inputMaxValue = parseInt($this.attr("max")); var inputMinValue = parseInt($this.attr("min")); if(inputValue > inputMaxValue){ $this.val(inputMaxValue); }else if(inputValue < inputMinValue){ $this.val(inputMinValue); } if($this.hasClass("voucher-amount-input")) { // We only need to update the price if it's a voucher input. var priceValue = parseInt(Math.max($this.val(), 0)); $('.listing-price .price').text(priceValue.toFixed(2)); } }); } } /* |-------------------------------------------------------------------------- | Header |-------------------------------------------------------------------------- */ core.header = { init: function() { var $this = this; this.dropdownHeightMatch(); this.bindEventListeners(); this.onLoad(); this.onReady(); core.loadModule('diagram'); //if(this.data.isTrade) { setInterval(function() { $this.initCountdown() }, 1000); //} }, bindEventListeners: function() { var $this = this; $('.mobile-menu--btn').on('click', function() { $('.mobile-menu--btn').toggleClass('open'); $('.page-slide').toggleClass('open'); }); $('.change_vat').on('click', function() { if($(this).hasClass('head_vat_inc')) { $(this).addClass('head_vat_ex'); $(this).removeClass('head_vat_inc'); } else { $(this).addClass('head_vat_inc'); $(this).removeClass('head_vat_ex'); } }); $('body').on('click', '.diagram--hotspot', function() { var link = $(this).find('a').first().attr('href'); if(link) { window.location = link; } }) $('.mobile-nav--toggle > a:not(.mobile-multi-view-all)').on('click', function(e) { e.preventDefault(); var par = $(this).parent('li'); var child = par.find('> ul'); $(child).slideToggle(); if($(par).hasClass('mobile-multi--dropdown')) { if($(par).hasClass('open')) { $(par).find('.open').each(function() { $(this).removeClass('open'); }); $(par).find('ul').each(function() { $(this).hide(); }); } else { var rem = $('.mobile-multi--dropdown.mobile-nav--toggle.open').not(par); $(rem).find('.open').each(function() { $(this).removeClass('open'); }); $(rem).find('ul').each(function() { $(this).hide(); }); $(rem).removeClass('open'); } $('ul.mobile-nav--multi > li').not(par).slideToggle(); } $(par).toggleClass('open'); }); $('.mobile-nav--toggle > a').on('click', function(e) { console.log(); e.stopPropagation(); }); window.addEventListener('resize', $this.debounce(function() { $this.dropdownHeightMatch(); }, 250)); }, onLoad: function() { var $this = this; $(window).on('load', function() { $this.dropdownHeightMatch(); $this.autocomplete(); $this.headerUspSlider(); if(!core.header.data.isTrade && !core.util.readCookie('nlsuvc')) { setTimeout(function(){core.header.newsletterShow();}, 10000); } else if(core.header.data.isTrade) { _self.util.createCookie('nlsuvc', '1', 365, ''); } }); }, onReady: function() { var $this = this; $(document).ready(function() { $this.dropdownHeightMatch(); }); }, headerUspSlider: function() { $(".header-usps").slick({ slidesToShow: 6, slidesToScroll: 1, infinite: true, autoplay: true, autoplaySpeed: 5000, arrows: false, responsive: [{ breakpoint: 1281, settings: { slidesToShow: 5, } }, { breakpoint: 1101, settings: { slidesToShow: 4, } }, { breakpoint: 800, settings: { slidesToShow: 3, } }, { breakpoint: 600, settings: { slidesToShow: 2, } }, { breakpoint: 450, settings: { slidesToShow: 1, } }] }); }, newsletterShow: function (hidden=false, submit=false, fields = {}) { var lurl = 'newsletter.php'; overlay_obj.abort(); overlay_obj.open('get', PATH + 'olay/' + lurl + '?nocache=' + nocache()); overlay_obj.params = {}; overlay_obj.params.hidden = hidden; overlay_obj.params.submit = submit; overlay_obj.params.fields = fields; overlay_obj.onreadystatechange = core.header.newsletter_show_response; overlay_obj.send(null); return false; }, newsletter_show_response: function () { var lurl = 'newsletter.php'; if(overlay_obj.readyState == 4){ if(overlay_obj.status == 200){ var hidden = overlay_obj.params.hidden; var submit = overlay_obj.params.submit; var fields = overlay_obj.params.fields; document.getElementById('olay_content').innerHTML = overlay_obj.responseText; document.getElementById('olay').style.display = 'block'; $('#selectbox').select2(); $('html, body').animate({ scrollTop: ($('#olay_box_container').offset().top - 20) }, 300); $("#olay").addClass("newsletter-olay"); if(hidden) { $("#olay").addClass("force-hidden"); } if(typeof fields.contact_name != 'undefined') { $('#olay.newsletter-olay input[name="contact_name"]').val(fields.contact_name); } if(typeof fields.email != 'undefined') { $('#olay.newsletter-olay input[name="email"]').val(fields.email); } $('#olay.newsletter-olay').off('click').on('click', '#submit-newsletter-signup', function(e){ e.preventDefault(); var $overlay = $('#olay.newsletter-olay'); var $overlay_form_container = $overlay.find('#newsletter-olay-form-container'); var $overlay_form_error = $overlay.find('#newsletter-olay-form-error'); var formData = $('#newsletter-olay-form').serialize(); formData = formData + '&is_trade=' + ($("#newsletter_trade").is(":checked") ? 1 : 0); _self.util.createCookie('nlsuvc', '1', 365, ''); $.ajax({ url: PATH + 'olay/' + lurl + '?nocache=' + nocache(), method: "POST", data: formData, success: function(data){ var result = $.parseJSON(data.trim()); console.log(result); if(result.status == 'success') { $overlay_form_error.hide(); $overlay_form_container.html('

' + result.message + '

' + result.code + '

'); } else if(result.status == 'error') { $overlay_form_error.html(result.message).slideDown(300); } else { $overlay_form_error.html('An unknown error has occurred').slideDown(300); } } }); return false; }); if(submit) { $("#olay").removeClass("force-hidden"); $('#olay.newsletter-olay #submit-newsletter-signup').trigger('click'); } } } return false; }, debounce: function (func, wait, immediate) { var timeout; return function() { var context = this, args = arguments; var later = function() { timeout = null; if (!immediate) func.apply(context, args); }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) func.apply(context, args); }; }, dropdownHeightMatch: function() { var dropdowns = document.getElementsByClassName("header-dropdown"); for (var i = 0; i < dropdowns.length; i++) { dropdowns[i].setAttribute("style","display:flex; opacity: 0; left: -9999px; top: -9999px"); } var list = document.getElementsByClassName("header-dropdown-column--height-match"); var heights = []; $('.header-dropdown-column-1, .header-dropdown-column-2, .header-dropdown-column-3, .header-dropdown-column--height-match').removeAttr('style').css('display', 'block'); for (var i = 0; i < list.length; i++) { // if(list[i].getBoundingClientRect().height == 0) { // console.log(0, $(list[i]), $(list[i]).css('display')); // } heights.push(list[i].getBoundingClientRect().height); } $('.header-dropdown-column-1, .header-dropdown-column-2, .header-dropdown-column-3, .header-dropdown-column--height-match').removeAttr('style'); var maxHeight = Math.max.apply(Math, heights); // Match height with homeTop to prevent bottom of banners showing. var homeTop = document.getElementById('homeTop'); if(homeTop) { var sliderHeight = homeTop.getBoundingClientRect().height; maxHeight = (sliderHeight > maxHeight) ? sliderHeight : maxHeight; } $('.header-bottom--cont').attr("style", "padding-bottom:"+(maxHeight+10)+"px"); for (var i = 0; i < list.length; i++) { list[i].setAttribute("style","height:"+maxHeight+"px"); } for (var i = 0; i < dropdowns.length; i++) { // console.log(dropdowns[i]); dropdowns[i].removeAttribute("style"); } }, /** * Auto complete search **/ autocomplete: function() { var $spinner = "Loading"; var typingTimer, search_val, focused_elem; var inputs = ".search-input, .mobile-search--input, .header-search--input"; var mobile_input = "mobile-search--input"; var desktop_input = "header-search--input"; search_val = Modernizr.mq('(min-width: 1000px)') ? $("."+desktop_input).val() : $("."+mobile_input).val(); $(inputs).on("input", function(){ focused_elem = $(this); clearTimeout(typingTimer); search_val = $(this).val(); if(search_val.length > 2){ typingTimer = setTimeout(doneTyping, 250); }else{ $('.search_dropdown').remove(); } }); function doneTyping(){ $this = focused_elem; $('.spinner').remove(); $this.parent().append($spinner); $.ajax({ url: "/search.php", method: "POST", data: {q: search_val, Go: "+", ajax_search: true} , success: function(data){ $('.spinner').remove(); if($(".search_dropdown").length > 0) { $('.search_dropdown').replaceWith(data); } else { $this.parent().append(data); } $('.search_dropdown').on("mouseleave", function() { $(this).removeClass("over"); }); $('.search_section_left').css({"height":$(".search_dropdown .sidebar-content").height()+"px"}); height_correct_class(".product-overlay"); } }); } $(inputs).on("click", function(){ var can_run = false; if(Modernizr.mq('(min-width: 1000px)')) { if($(this).hasClass(desktop_input)) { can_run = true; } } else { if($(this).hasClass(mobile_input)) { can_run = true; } } if(search_val.length > 2 && $('.search_dropdown').length == 0 && can_run) { focused_elem = $(this); doneTyping(); } }); $(inputs).focusin(function() { $(this).parent().addClass("focus"); }); $(inputs).focusout(function() { if($('.search_dropdown').hasClass("over")) { $(this).focus(); } else { $(this).parent().removeClass("focus"); } }); $(window).bind('beforeunload', function() { $("."+desktop_input).focusout(); }); }, initCountdown: function() { var hours = 0; var mins = 0; var current = this.data.serverTime; if (current > 60){ hours = Math.floor(current / 3600); current = current - (hours * 3600); mins = Math.floor(current / 60); document.getElementById('cd_hours').innerHTML = hours; document.getElementById('cd_mins').innerHTML = mins; if (hours == 0){ document.getElementById('cd_hours_txt').innerHTML = ''; document.getElementById('cd_hours').innerHTML = ''; }else if (hours == 1){ document.getElementById('cd_hours_txt').innerHTML = 'hour'; }else{ document.getElementById('cd_hours_txt').innerHTML = 'hours'; } if (mins == 1){ document.getElementById('cd_mins_txt').innerHTML = 'minute'; }else{ document.getElementById('cd_mins_txt').innerHTML = 'minutes'; } document.getElementById('cd_txt').innerHTML = ' remaining'; }else{ document.getElementById('order_countdown').innerHTML = ' '; } } } /* |-------------------------------------------------------------------------- | Header dropdown |-------------------------------------------------------------------------- */ core.headerDropdown = { activeCol: null, activeCol2: null, timeouts: [], timeouts2: [], timeouts3: [], init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; var $parentLinkElements = $('.header-nav--link-cont, .header-link'); $('body').on('click', function(e) { if($(e.target).parents('.header-bottom').length == 0) { $parentLinkElements.removeClass('hover'); $('.header-bottom--cont').removeClass('header-nav--padding'); } }); $parentLinkElements.on('click', function(e) { if($(e.target).hasClass('has-dropdown') || $(e.target).parents('.header-trade-link').length > 0 || $(e.target).parents('.header-centre-link').length > 0 || $(e.target).hasClass('header-trade-link') || $(e.target).hasClass('header-centre-link')) { if($(this).hasClass('header-help-link--cont--no-dropdown')) { return; } console.log(1); if($(this).hasClass('header-trade-link--account')) { return; } console.log(2); if(false === $(this).hasClass('header-trade-link-mobile') && false === $(this).hasClass('header-centre-link')) { console.log(22); e.preventDefault(); } console.log(32); if($(this).hasClass('hover')) { $('.header-bottom--cont').removeClass('header-nav--padding'); } else { $('.header-bottom--cont').addClass('header-nav--padding'); } $parentLinkElements.not($(this)).removeClass("hover"); $(this).toggleClass('hover'); // if($(this).hasClass('hover')) { // $('.header-nav--link-cont:not(.hover)').find('header-dropdown').hide(); // $(this).find('.header-dropdown').slideDown(300, function() { // $(this).css({ // display: 'flex' // }) // }); // } else { // $('.header-dropdown').slideUp(200); // } $('.header-dropdown-diagram').hide(); var imageMapCategoryId = $(this).data('image-map-category-id'); if(imageMapCategoryId) { $('.header-dropdown-diagram[data-image-map-category-id="'+imageMapCategoryId+'"]').show(); } } }); $parentLinkElements.on('mouseleave', function(e) { // $parentLinkElements.removeClass("hover") }); $('.header-dropdown-diagram').on('mouseover', function() { // console.log('header-dropdown-diagram:mouseover'); $this.clearTimeouts($this.timeouts); $this.clearTimeouts($this.timeouts2); $this.clearTimeouts($this.timeouts3); }) $('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont').mousemove(function() { if($this.activeCol && $this.activeCol[0] == $(this)[0]) { $this.clearTimeouts($this.timeouts); } if(!$this.activeCol) { $this.activeCol = $(this); $(this).addClass('hover') $this.heightMatchTitles(); } $this.removeOtherHoverStates(this); $this.showImageMapsForHoverTree(); if($('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont.hover').length > 1) { $this.clearTimeouts($this.timeouts); // console.log("removing from ", $('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont.hover').not(this)) $('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont.hover').not(this).removeClass('hover') } }); $('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont').mouseout(function() { var $that = $(this); if($that && $this.activeCol && $that[0] == $this.activeCol[0]) { $this.timeouts.push(setTimeout(function() { $this.activeCol = null; $that.removeClass('hover'); $this.clearTimeouts($this.timeouts); $('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont:hover').addClass('hover'); $this.heightMatchTitles(); $this.showImageMapsForHoverTree(); }, 300)); } }); $('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont').mousemove(function() { if($this.activeCol2 && $this.activeCol2[0] == $(this)[0]) { $this.clearTimeouts($this.timeouts2); } $this.clearTimeouts($this.timeouts3); var $that = this; // if(!$this.activeCol2) { $this.timeouts3.push(setTimeout(function() { $this.activeCol2 = $($that); $($that).addClass('hover'); $this.heightMatchTitles(); $this.showImageMapsForHoverTree(); }, 300)); // } if($('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont.hover').length > 1) { $this.clearTimeouts($this.timeouts3); // console.log("removing from ", $('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont.hover').not(this)) $('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont.hover').not(this).removeClass('hover') } }); $('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont').mouseout(function() { var $that = $(this); if($that && $this.activeCol2 && $that[0] == $this.activeCol2[0]) { $this.timeouts2.push(setTimeout(function() { $this.activeCol2 = null; $that.removeClass('hover'); $this.clearTimeouts($this.timeouts2); $('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont:hover').addClass('hover'); $this.heightMatchTitles(); $this.showImageMapsForHoverTree(); }, 300)); } }); }, clearTimeouts: function(timeouts) { for (var i=0; i maxHeight) { maxHeight = $(this).outerHeight() } }) $('.header-dropdown-column--title:visible').css({height: maxHeight}); }, showImageMapsForHoverTree: function() { // this.clearTimeouts(this.timeouts3); var imageMaps = []; var imageMapIds = []; $('.header-nav--link-cont.hover, .header-dropdown-subcat-link-cont.hover').each(function(){ imageMapIds.push($(this).data('image-map-category-id')); var diagram = $('.header-dropdown-diagram[data-image-map-category-id="'+$(this).data('image-map-category-id')+'"]'); if(diagram.length) { // console.log(diagram); imageMaps.push(diagram); } }); var lastDiagram = imageMaps[imageMaps.length - 1]; $('.header-dropdown-diagram').hide(); if(lastDiagram) { lastDiagram.show(); } // console.log("showImageMapsForHoverTree", imageMaps, lastDiagram); }, removeOtherHoverStates: function(ctx) { others = $('.header-dropdown-columns > .header-dropdown-column > .header-dropdown-subcats > .header-dropdown-subcat-link-cont').not(ctx); // console.log(others); others.find('.hover').removeClass('hover'); } } /* |-------------------------------------------------------------------------- | Footer |-------------------------------------------------------------------------- */ core.footer = { init: function() { var hideComparisonBar = (hideComparisonBar === undefined) ? false : hideComparisonBar; if(!hideComparisonBar) { _self.comparison.response = _self.comparison.request({}); } _self.loadModule('comparison'); _self.loadModule('wishlist'); this.bindEventListeners(); this.offerOverlay(); this.overlayClose(); }, bindEventListeners: function() { /* $("").on("change", function() { if($(this).is(":checked")) { $("#fieldddfkhjt").val($("#fieldddfkhjt").attr("original_channel_id")); } else { $("#fieldddfkhjt").val("24148410"); } }); */ $('#newsletter_trade').each(function(){ $(this).parent().parent().on('click', function () { _self.form.checkboxController('toggle', $(this)); }) }); $("#subForm").on("submit", function(event) { event.preventDefault(); $.post("/ajax/newsletter_signup.php", { email: $("#newsletter-email").val(), name: $("#newsletter-name").val(), is_trade: $("#newsletter_trade").is(":checked") ? 1 : 0 }, function() { core.message.create($('body'), { type: "success", message: "Subscription successful", closeable: false, }); }) }); $('#footer-menu-btn').on('click', function(event) { $(this).toggleClass("open"); $(this).parents('.footer-main').toggleClass('open'); event.preventDefault(); }); $('#footer-newsletter-btn').on('click', function(event) { $(this).toggleClass("open"); $('.footer-newsletter').toggleClass('open'); event.preventDefault(); }); $('.footer-nav--title').on('click', function(event) { event.preventDefault(); $('.footer-nav--title').not(this).removeClass('active'); $(this).toggleClass("active"); }); $('#nsltr').on('submit', function(e) { e.preventDefault(); if(!$('#fieldEmail').val()) { core.message.create($('#nsltr'), { type: 'error', message: 'Please enter your email', customClass: 'message-float' }); } else { $.getJSON( this.action + "?callback=?", $(this).serialize(), function (data) { if (data.Status === 400) { core.message.create($('#nsltr'), { type: 'error', message: data.Message, customClass: 'message-float' }); } else { $('.footer-newsletter--input').delay(0).fadeOut(1000, function() { core.message.create($('#nsltr'), { type: 'success', message: data.Message, closeable: false, }); }); } } ); } }); $('form.footer-newsletter-form .footer-newsletter-form--button').on('click', function(e) { var $form = $(this).closest('form'); e.preventDefault(); core.header.newsletterShow(true, true, {'contact_name' : $form.find('#newsletter-name').val(), 'email' : $form.find('#newsletter-email').val()}); return false; }); }, offerOverlay: function() { $('#offer').submit(function (e) { e.preventDefault(); $.getJSON(this.action + "?callback=?", $(this).serialize(), function(data) { var $error = $('.offer-overlay--upper .message-error'); var $success = $('.offer-overlay--upper .message-success'); if (data.Status === 400) { $error.html(data.Message); $error.fadeIn(); $error.delay(3000).fadeOut(1000); } else { $success.html(data.Message); $success.fadeIn(); $success.delay(3000).fadeOut(1000); var formData = { 'email': $('.overlay-offer--input').val(), }; $.ajax({ type: 'POST', url: '/ajax/ajax_offer_submit.php', data: formData, dataType: 'json', encode: true }); $('#offer').fadeOut(); } }); }); }, overlayClose: function() { $('.offer-overlay--action, .offer-overlay--bg').on('click', function() { $.ajax({ type: 'POST', url: '/ajax/ajax_offer_close.php' }); $('.offer-overlay').fadeOut(); }); } } /* |-------------------------------------------------------------------------- | CMS Pages > FAQ |-------------------------------------------------------------------------- */ core.faq = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $("#comment-form").submit(function(e) { _self.form.validateForm($(this), function(failedInputs) { if(failedInputs.length > 0) { e.preventDefault(); } }); }); $this.onLoad(); }, onLoad: function() { var $this = this; $window.on('load', function() { $this.faqController(); $('.dd-block').each(function() { var $this = $(this); $this.find('.dd-title').removeClass('dd-open'); $this.find('.dd-text').hide(); }); }); }, faqController: function() { $('.dd-title').unbind('click'); $('.dd-title').on('click', function() { var $this = $(this); $this.toggleClass('dd-open'); $this.next().stop().slideToggle(); }); }, } /* |-------------------------------------------------------------------------- | CMS Pages > Blog |-------------------------------------------------------------------------- */ core.blog = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $this.onLoad(); }, onLoad: function() { var $this = this; $window.on('load', function() { $this.commentOverflowController(); }); }, commentOverflowController: function() { var $overflow = $(".comment-overflow"); var $toggle = $(".comment-overflow-toggle"); var state = true; if($overflow.length) { $overflow.hide(); } $toggle.on('click', function() { if(state){ $overflow.slideUp(); $toggle.html($(this).data("original-text")).removeClass("open"); state = false; } else { $overflow.slideDown(); $toggle.html("HIDE").addClass("open"); state = true; } }); }, } /* |-------------------------------------------------------------------------- | CMS Pages > Contact |-------------------------------------------------------------------------- */ core.contact = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $('.button-file-upload').each(function() { _self.form.fileUploadController($(this)); }); $('#contact_us').on('submit', function(e) { _self.form.validateForm($(this), function(failedInputs) { if(failedInputs.length > 0) { e.preventDefault(); } }); }); this.onLoad(); }, onLoad: function() { var $this = this; console.log($this.data); $(window).on('load', function(e) { if($this.data.scrollToForm) { $('html, body').animate({ scrollTop: $('#contact_us').offset().top - 100 }, 1000); $('#contact_name').focus(); } }); }, } /* |-------------------------------------------------------------------------- | Feature Modules > Overlay |-------------------------------------------------------------------------- */ core.overlay = { init: function() { var $this = this; this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $this.bindOverlayClose(); }, /** * Handles the trigger of a onpage overlay * * @param {string} action * @param {object} element * @param {callback} function */ controller: function(action, element, callback) { var $this = this; var $overlay = $("#" + $(element).attr('data-overlay-id')); if(action == 'open') { $this.overlayOpen($overlay); } else if(action == 'close') { $this.overlayClose($overlay); } if (typeof callback == 'function') { callback(); } }, overlayOpen: function($element) { $element.addClass("open"); }, overlayClose: function($element) { $element.removeClass("open"); }, /** * Bind click event to the overlay--close element * and store in a function so it can be rebound * for future use. */ bindOverlayClose: function() { var $this = this; $(".overlay").off('click', '.overlay--close').on('click', '.overlay--close', function() { $this.controller('close', this); }); }, /** * Handles the trigger of a remote overlay * * @param {string} action * @param {object} params * @param {callback} function */ ajaxOverlay: function(params, callback) { return $.ajax({ url: params.url, type: (params.requestType) ? params.requestType : 'POST', data: params.data }); }, } /* |-------------------------------------------------------------------------- | Feature Modules > Overlay > Click and Collect |-------------------------------------------------------------------------- */ core.overlay.collect = { // Stores data that is set on the overlay include stores: {}, map: null, // MapOptions object for Google Maps Properties mapOptions: { zoom: 11, draggable: true, mapTypeControl: false, }, init: function() { this.googleMap(); this.bindEventListeners(); }, bindEventListeners: function() { var $this = this, $collectFormButton = $('.collect-form--button'); // Handle postcode submit $("#click-and-collect-overlay").on('click', '.collect-form--button', function(event, element) { $("#postcode-input-error").hide(); var postcode = $('#collect-postcode').val(); // Check input is a valid UK postcode if($this.validatePostcode(postcode)) { $collectFormButton.addClass('loading'); $storeRequest = $.ajax({ url: '/ajax/ajax_click_and_collect_overlay.php', type: 'POST', data: { postcode: postcode } }); $storeRequest.success(function(data) { setTimeout(function() { $collectFormButton.removeClass('loading'); $this.updateNearbyStores(JSON.parse(data)); }, 500); }); } else { $("#postcode-input-error").html('Please enter a valid UK Postcode').slideDown(); } event.preventDefault(); }); // User has clicked on a nearby store $('.collect-stores').on('click', '.collect-store', function() { if(!$(this).hasClass("sel")) { $('.collect-store').removeClass("sel"); $this.clickStore($(this)); } }); }, googleMap: function() { var $this = this; var googleMaps = google.maps; $this.map = new googleMaps.Map(document.getElementById("map"), $this.mapOptions); latlngbounds = new googleMaps.LatLngBounds(); directionsService = new googleMaps.DirectionsService; directionsDisplay = new googleMaps.DirectionsRenderer; $.each($this.stores, function(key, store) { markerPos = new googleMaps.LatLng(store.google.pin.lat, store.google.pin.long); marker = new googleMaps.Marker({ title: store.name, icon: '/images/style/hydro/icon-map-pin.png', position: markerPos, map: $this.map }); (function (marker, store, markerPos) { google.maps.event.addListener(marker, "click", function (e) { $this.map.setCenter(markerPos); $this.clickPin(store); }); })(marker, store, markerPos); latlngbounds.extend(marker.position); store.markerPosition = markerPos; }); directionsDisplay.setMap($this.map); $this.positionMap(); google.maps.event.addDomListener(window, 'resize', function() { $this.positionMap(location); }); }, clickPin: function(store) { var $this = this; $('.collect-store').removeClass("sel"); $(".collect-info--title, .collect-info--action").hide(); $this.updateCollectInfo(store); $this.resetDirections(); }, updateCollectInfo: function(store) { this.updateAddress(store.address); this.updateOpeningTimes(store.opening_times); }, updateAddress: function(address) { $("#collect-address--values span").remove(); $.each(address, function(index, value){ $("#collect-address--values").append('' + value + ''); }); }, updateOpeningTimes: function(times) { $("#opening_times .dblr").remove(); $.each(times, function(key, value) { $("#opening_times").append('
' + key + '
' + value + '
'); }); $(".collect-info").show(); }, clickStore: function($element, callback) { var $this = this; $element.toggleClass("sel"); var store = $this.stores[$element.attr('data-store-id')]; $(".collect-map .loading").fadeIn(); directionsService.route({ origin: document.getElementById('collect-postcode').value, destination: store.markerPosition, travelMode: google.maps.TravelMode.DRIVING }, function(response, status) { setTimeout(function() { $this.updateCollectInfo(store); $(".collect-map .loading").hide(); $(".collect-info--title, .collect-info--action").show(); $('.collect-info--title span').html(store.time_to_collect); if (status === google.maps.DirectionsStatus.OK) { $('#postcode-input-error').hide(); directionsDisplay.setDirections(response); } else { $('#postcode-input-error').html('We are afraid we could not retreive the directions for your request.').slideDown(); } if (typeof callback == 'function') { callback(); } }, 1000); }); }, updateNearbyStores: function(stores) { $(".collect-store").remove(); $(".collect--subtitle").find("span").html($('#collect-postcode').val()).parent().show(); $.each(stores, function(key, value) { $(".collect-stores").append('
' + value.name + 'IN STOCK' + value.distance + '
'); }); $(".collect-store").each(function(i, e){ setTimeout(function() {$(e).animate({top: 0,opacity: 1}, 500);}, i * 400) }); }, validatePostcode: function(postcode) { postcode = postcode.replace(/\s/g, ""); var regex = /^[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}$/i; return regex.test(postcode); }, resetDirections: function() { directionsDisplay.set('directions', null); }, positionMap: function(location) { var map = this.map; if(location) { map.setCenter(location); } else { map.setCenter(latlngbounds.getCenter()); map.fitBounds(latlngbounds); } } } /* |-------------------------------------------------------------------------- | Page Modules > Homepage |-------------------------------------------------------------------------- */ core.homepage = { init: function() { this.initialiseSliders(); this.bindEventListeners(); this.onResize(); this.handleHomeMapsResize(); }, bindEventListeners: function() { $('.home-map-side--link') .on('mouseover click', function() { var $diagram = $(this).parents('.home-map').find('.diagram'); var $hotspot = $diagram.find('.diagram--hotspot').eq($(this).parent().index()); $hotspot.trigger('mouseover'); // $diagram.addClass('is-hover') }) .on('mouseout', function() { var $diagram = $(this).parents('.home-map').find('.diagram'); var $hotspot = $diagram.find('.diagram--hotspot').eq($(this).parent().index()); $hotspot.trigger('mouseout'); }) }, onResize: function() { var $this = this; window.addEventListener('resize', core.util.debounce(function() { $this.handleHomeMapsResize(); }, 50)); }, handleHomeMapsResize: function() { var homeImageMapCount = $('.home-map').length; console.log({homeImageMapCount}); // if(homeImageMapCount > 2) { // $('.home-maps').slick({ // slidesToShow: 2, // adaptiveHeight: true, // nextArrow: '', // prevArrow: '', // }); // } else { // if(Modernizr.mq('(min-width: 650px)')) { // if($('.home-maps')[0] && $('.home-maps').hasClass('slick-initialized')) { // $('.home-maps').slick('unslick'); // } // } else { // if(false === $('.home-maps').hasClass('slick-initialized')) { // $('.home-maps').slick({ // slidesToShow: 1, // fade: true, // nextArrow: '', // prevArrow: '', // }); // } // } // } }, initialiseSliders: function() { $(".home-slider .slick-slider").slick({ slidesToShow: 1, slidesToScroll: 1, fade: true, autoplay: true, autoplaySpeed: 10000, nextArrow: '', prevArrow: '', responsive: [{ breakpoint: 767, settings: { adaptiveHeight: true, } }] }); $('.home-maps').slick({ slidesToShow: 2, nextArrow: '', prevArrow: '', responsive: [{ breakpoint: 1201, settings: { fade: true, slidesToShow: 1, } }] }); }, } /* |-------------------------------------------------------------------------- | Page Modules > Listing |-------------------------------------------------------------------------- */ core.listing = { init: function() { option_addevents('#listing_options_1', '1'); // Hide all tabs and auto select the first tab this.selectDefaultTab(1); if(this.data.preloadImages) { this.preloadImages(this.data.preloadImages); } if(this.data.isProd && (this.data.isOutOfStock)) { $('.header-countdown-link').remove(); } this.comments.init(); this.extrasWidth(); this.bindEventListeners(); this.magnificPopup(); this.initJumpMenuTracker($('#description')); this.initJumpMenuTracker($('#upsells')); this.initJumpMenuTracker($('#range')); this.initJumpMenuTracker($('#related')); this.initJumpMenuTracker($('#reviews')); this.removeEmptyTables(); // console.log('hi'); if($('#listing_options_1').find('*').is(':visible')) { $('#listing_options_1').show(); } else { $('#listing_options_1').hide(); } _self.form.validateNumberInputs(); _self.util.inputIncrement(); }, preloadImages: function(images) { for (var index = 0; index < images.length; index++) { image = new Image(); image.src = images[index]; } }, bindEventListeners: function() { var $this = this; this.initListingVideo(); $(".listing--same-choice").click(function() { _self.form.checkboxController('toggle', $(this)); }); // Handle listing tab click $(".listing-tabs-buttons").on('click', '.listing-tabs-button', function() { if($(this).hasClass("sel")) { $('.listing-tabs-buttons').toggleClass("show"); } var tabId = $(this).attr('data-tab'); $this.selectTab(tabId); }); $('#listingReviewStarRating .rating-star').on('click', function() { var selectedRating = $(this).data("rating"); $('#comments_rating').val(selectedRating); $('#listingReviewStarRating .rating-star').each(function() { var rating = $(this).data("rating"); if(rating <= selectedRating) { $(this).removeClass("rating-star--empty"); } else { $(this).addClass("rating-star--empty"); } }) }); $("#listingSubscribeButton, #sub-close").on('click', function() { $('#listingSubscribeButton').toggleClass('open'); $('.listing-subscribe').stop().slideToggle(); return false; }); $("#chooseOptions").on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $('#listing_options_1').offset().top - 100 }, 1000); }); $("#askQuestionBtn").on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $('#questions').offset().top - 100 }, 1000); }); $("#viewAlternatives, #viewAlternativesListingHeader").on('click', function(e) { e.preventDefault(); $('html, body').animate({ scrollTop: $('#range').offset().top - 100 }, 1000); }); $(".form-options").on("keypress", ":input:not(textarea):not([type=submit])", function(event) { if (event.keyCode == 13) { // console.log('enter'); event.preventDefault(); } }); $(".listing-overview").on('click', '.qty-discounts--btn', function() { $(this).toggleClass('active'); }); $('#listingHeaderAddToBasket').on('click', function(e) { e.preventDefault(); $('#ajax-options-buy-btn').click(); }) $('.listing-thumbnails').on('click', '.slick-arrow', function() { $('#listing360').hide(); }) $('#sparesAvailable').on('click', function(e) { e.preventDefault(); if($this.data.overrideSparesScroll) { $('.jump-menu--link[href="#range"]').click(); $('.listing-cat-upsells-nav--link[data-upsell-category-id="spare+parts"]').click(); return; } if($('#upsells').offset()) { $('html, body').animate({ scrollTop: $('#upsells').offset().top - 100 }, 1000); } }); $('.listing-360-btn').on('click', function() { $('#listing360').toggle(); }) $('[data-goto]').click(function() { const $target = $(`#${$(this).data('goto')}`); $('html, body').animate({ scrollTop: $target.offset().top - 100 }, 1000); if($target.hasClass('listingv2-tab')) { const $targetDdTitle = $target.find('.dd-title'); if(!$targetDdTitle.hasClass('dd-open')) { $targetDdTitle.click(); } } }); $(function() { $('.sharethis--container').on('click', '.sharethis--opener', function(e) { console.log('test'); e.preventDefault(); const $parent = $(this).parent(); $parent.stop().toggleClass('open'); if($parent.hasClass('open')) { $parent.find('.sharethis--list').stop().slideDown(); } else { $parent.find('.sharethis--list').stop().slideUp(); } }); }); // Close share menu when clicking outside $(document).on('mousedown', function(e) { var $openerParent = $('.sharethis--opener').parent(); // Only proceed if menu is open if ($openerParent.hasClass('open')) { // If click is outside the parent if (!$openerParent.is(e.target) && $openerParent.has(e.target).length === 0) { $openerParent.removeClass('open'); $openerParent.find('.sharethis--list').stop().slideUp(); } } }); this.bindFormValidationEventListeners(); this.syncMainSliderAndThumbs(); this.bindOverlayEventListeners(); this.responsiveLayout(); this.onResize(); this.onScroll(); this.onLoad(); this.ajaxOptions(); }, onResize: function() { var $this = this; window.addEventListener('resize', core.util.debounce(function() { $this.extrasWidth(); $this.responsiveLayout(); // $this.heightMatch(); }, 50)); }, onScroll: function() { var $this = this; $(window).on("scroll", function () { if($('.jump-menu--cont')[0]) { if ($(this).scrollTop() > $('.jump-menu--cont').offset().top) { $('.listing-header').removeClass('hide'); } else { $('.listing-header').addClass('hide'); } } }); }, onLoad: function() { var $this = this; $(window).on('load', function(e) { $this.initSubscription(); $this.heightMatch(); if($this.data.viewAlternatives) { $('html, body').animate({ scrollTop: $('#listings').offset().top - 100 }, 1000); } if($this.data.triggerStockNotifyOverlay) { if(!$('.message.message-success')[0]) { $('html, body').animate({ scrollTop: $('.listing-notify').offset().top - 100 }, 1000); $('.listing-notify .button').trigger('click'); } } $this.initialiseSliders(); $this.initialiseSecondarySliders(); }); }, bindOverlayEventListeners: function() { // Open Listing personalisation overlay $('.listing').on('click', '.listing-personalise', function() { var $element = $(this); if(!$element.hasClass("disabled")) { if($element.hasClass("checked")) { // If already checked, remove personalisation and reset fields _self.form.checkboxController('off', $('.listing-personalise'), function() { $("#custom_1").val(""); }); } else { _self.overlay.controller('open', $element); } } }); // Handle personalisation overlay submit event $("#personalise-submit").click(function(e) { var dd1 = document.getElementById('option_1_0'), dd2 = document.getElementById('option_2_0'), seloption = (dd2.options.length) ? dd2.options[dd2.selectedIndex].value : dd1.options[dd1.selectedIndex].value, value = (OPT_custom_mode[seloption] == 1) ? $("#custom-select").val() : $("#custom-text").val(); $("#custom_1").val($("#font-input").val() + " Text: " + value); _self.overlay.controller('close', $('#overlay-personalise .overlay--close')); _self.form.checkboxController('on', $('.listing-personalise')); return false; }); // Show 'Ask a Question' listing overlay $('.listing-extras').on('click', '#ask-a-question', function() { _self.overlay.controller('open', this, function () { $("#question-listing").val($(".listing--title").html()); }); }); // Show 'Bulk Quote' listing overlay $('#bulk').on('click', function() { _self.overlay.controller('open', this, function () { $("#bulk-listing").val($(".listing--title").html()); }); }); // Show 'Share with Friend' listing overlay $('.listing-share').on('click', '#overlay-share-btn', function() { _self.overlay.controller('open', this); return false; }); // Show 'Notify Me When Back In Stock' listing overlay $('.listing-notify').on('click', '.button', function() { _self.overlay.controller('open', this.closest('.listing-notify')); return false; }); }, /** * Binds that are used for validating * the forms on the page */ bindFormValidationEventListeners: function() { $("#overlay-question form, #overlay-share form, #overlay-stock-notify form").submit(function(e) { _self.form.validateForm($(this), function(failedInputs) { (failedInputs.length > 0) ? e.preventDefault() : true; }); }); $(".listing-comments-form").submit(function(e) { _self.form.validateForm($(this), function(failedInputs) { $('.input').removeClass('validate-border'); if(failedInputs.length > 0) { setTimeout(function() { $(failedInputs).removeClass("validate-border"); $(failedInputs).addClass("validate-border"); }, 0); e.preventDefault(); } }); }); $("#overlay-bulk form").submit(function(e) { _self.form.validateForm($(this), function(failedInputs) { if(failedInputs.length > 0) { $(".error-msg-js").html("Please fill in your email.").slideDown(); e.preventDefault(); } }); }); }, initialiseSliders: function() { if($(".listing-image .listing-thumbnails").hasClass("slick-initialized")) { $(".listing-thumbnails").slick('unslick'); return; } $(".listing-image .listing-thumbnails").slick({ speed: 300, slidesToShow: 1, infinite: false, nextArrow: '', prevArrow: '', responsive: [{ breakpoint: 1000, settings: { slidesToShow: 1, } },{ breakpoint: 700, settings: { slidesToShow: 1, } },{ breakpoint: 570, settings: { slidesToShow: 1, } }] }); if($(".listing-image .listing-thumbnail").length > 3) { $(".listing-image .listing-thumbnails").addClass("has-arrows"); } else { $(".listing-image .listing-thumbnails").removeClass("has-arrows"); } if($(".listing-main-images").hasClass("slick-initialized")) { $(".listing-main-images").slick('unslick'); } $(".listing-main-images").slick({ speed: 300, slidesToShow: 1, infinite: false, nextArrow: '', prevArrow: '', responsive: [{ breakpoint: 1000, settings: { slidesToShow: 1, } },{ breakpoint: 700, settings: { slidesToShow: 1, } },{ breakpoint: 570, settings: { slidesToShow: 1, } }] }); }, initialiseSecondarySliders: function() { $(".listing-related .product-grid, .listing-upsells .product-grid").slick({ slidesToShow: 6, slidesToScroll: 1, nextArrow: '', prevArrow: '', responsive: [ { breakpoint: 1600, settings: { slidesToShow: 5, }, }, { breakpoint: 1400, settings: { slidesToShow: 4, }, }, { breakpoint: 1200, settings: { slidesToShow: 3, }, }, { breakpoint: 650, settings: { slidesToShow: 2, }, } ] }); $(".listing-upsellsv2 .product-grid, .listingv2 .listing-upsell-products--inner").slick({ slidesToShow: 3, slidesToScroll: 1, responsive: [ { breakpoint: 650, settings: { slidesToShow: 2, }, } ] }); this.heightMatch(); }, heightMatch: function() { _self.common.heightMatch({ matchByRow: true, $gridElement: $('.listing-related .product-grid .product-grid-item'), $matchElement: $('.listing-related .product-grid .product-content'), }); }, selectTab: function(tabId) { $(".listing-tabs-button").removeClass("sel"); $(".listing-tabs-button[data-tab='" + tabId + "']").addClass("sel"); $('.listing-tab').hide(); $(".listing-tab[data-tab='" + tabId + "']").show(); return false; }, selectDefaultTab: function() { this.selectTab($('.listing-tabs-button').first().data('tab')); }, extrasWidth: function() { if(Modernizr.mq('(min-width: 1280px)')) { this.stretchChildrenByCount({ $parent: $('.listing-extras--grid'), $element: $('.listing-extra') }); }else{ $('.listing-extra').width(''); } if(Modernizr.mq('(min-width: 1022px)')) { $('.listing-header--bottom').append($('#listing-header--cta')); }else{ $('.listing-header--main').append($('#listing-header--cta')); } }, stretchChildrenByCount: function(params) { var $children = params.$parent.find(params.$element.filter(':visible')); var count = $children.length; var width = (100 / count) + "%"; $children.css({width: width}); }, magnificPopup: function () { $('.magnific').magnificPopup({ type:'image', gallery:{ enabled: true } }); }, initSubscription: function() { if($("#subscription_del_period").length > 0){ $("#listingSubscribeButton").show(); } else { $("#listingSubscribeButton").hide(); $(".listing-subscribe").hide(); } $("#subdays_1").val($("#subscription_del_preferred").val()); $("#subperiod_1").html($("#subscription_del_period").html()); try { $("#subscription_del_period").select2("destroy"); } catch(ex) { } $("#subscription_del_period").remove(); }, ajaxOptionsProperties: function(ids) { $('#listing_properties').replaceWith("
"); if(ids && ids.length > 0) { $ = jQuery; $.ajax({ type: "post", url: "/ajax/ajax_properties.php", data: {ids: ids}, error: function(jqXHR, textStatus, errorThrown){ console.log(jqXHR, textStatus, errorThrown); }, success: function(data){ $('#listing_properties').replaceWith(data); // var emptyTables = $('#listing_properties .listing_filters table:not(:has(tbody))') // emptyTables.parents('.listing_filters').hide(); } }); } }, ajaxOptions: function() { $(".listing--same-choice").unbind('click'); $(".listing--same-choice").click(function() { _self.form.checkboxController('toggle', $(this), function(state) { $(".listing--same-choice input[type='checkbox']").trigger('change'); }); }); $('.listingv2-price > .price').each(function() { var priceText = $(this).text().trim(); var parts = priceText.split('.'); if (parts.length === 2) { $(this).html(parts[0] + '' + parts[1] + ''); } }); }, initListingVideo: function() { $('.listing--video-btn, .listing-video-modal--click-trap, .listing-video-modal--close').on('click', function(e) { // So we can use the same button on Listing_2 if(!$(this).attr('href')) { e.preventDefault(); } $('#listingVideoModal').toggleClass('active'); }); }, initJumpMenuTracker: function($el) { var $this = this; if($el.length > 0) { var handler = $this.onVisibilityChange($el, function() { if($this.isElementInViewport($el)) { $('.listing-header a[href="#'+$el.attr('id')+'"]').addClass('active'); } else { $('.listing-header a[href="#'+$el.attr('id')+'"]').removeClass('active'); } }); $(window).on('DOMContentLoaded load resize scroll', handler); } }, isElementInViewport: function(el) { // Special bonus for those using jQuery if (typeof jQuery === "function" && el instanceof jQuery) { el = el[0]; } var rect = el.getBoundingClientRect(); var offset = 200; return ((rect.bottom - offset) >= 0 && rect.right >= 0 && (rect.top + offset) <= (window.innerHeight || document.documentElement.clientHeight) && rect.left <= (window.innerWidth || document.documentElement.clientWidth)); }, onVisibilityChange: function (el, callback) { var old_visible; var $this = this; return function () { var visible = $this.isElementInViewport(el); if (visible != old_visible) { old_visible = visible; if (typeof callback == 'function') { callback(); } } } }, removeEmptyTables: function() { $('table').each(function() { if($(this).find('td, th, thead, tbody, tr').length == 0) { // console.log($(this).parents('.listing_filters, .listing_dimensions')); // $(this).parents('.listing_filters, .listing_dimensions').remove(); } }) if($('#related .product-grid-item').length === 0) { // $('#related, .jump-menu--link[href="#related"], .listing-header--jump-link[href="#related"]').hide(); } if($('#upsells .product-grid-item').length === 0) { $('#upsells, .jump-menu--link[href="#upsells"], .listing-header--jump-link[href="#upsells"]').hide(); } if($('#range .upsell-listing').length === 0) { $('#range, .jump-menu--link[href="#range"], .listing-header--jump-link[href="#range"]').hide(); } }, syncMainSliderAndThumbs: function() { var $slider = $(".listing-main-images"); var $thumbs = $(".listingv2-gallery .listingv2-thumbnail"); function showThumbsAround(index) { var total = $thumbs.length; var start = index - 2; var end = index + 3; if(Modernizr.mq('(max-width: 1023px)')) { end = index + 3; } else if(Modernizr.mq('(max-width: 1200px)')) { end = index + 2; } // Adjust for start edge if (start < 0) { end += -start; start = 0; } // Adjust for end edge if (end > total) { start -= (end - total); end = total; if (start < 0) start = 0; } $thumbs.hide().removeClass('sel').removeClass('show'); for (var i = start; i < end; i++) { $thumbs.eq(i).addClass('show'); } $thumbs.eq(index).addClass('sel'); } // On slider init or after change, show the correct thumbs $slider.on('init reInit afterChange', function(event, slick, currentSlide){ var idx = typeof currentSlide === 'undefined' ? slick.currentSlide : currentSlide; showThumbsAround(idx); }); // On click of a thumbnail $thumbs.on('click', function(e){ e.preventDefault(); var idx = $thumbs.index(this); $slider.slick('slickGoTo', idx); // Do not call showThumbsAround here; let slider event handle it }); // If slider already initialized, trigger showing if ($slider.hasClass('slick-initialized')) { var idx = $slider.slick('slickCurrentSlide'); showThumbsAround(idx); } }, responsiveLayout: function() { var $this = this; if($('.responsive-element').length) { $('.responsive-element').each(function() { if( (Modernizr.mq('(max-width: 1200px)') && $(this).hasClass('element-pos-desksmall')) || (Modernizr.mq('(max-width: 1023px)') && $(this).hasClass('element-pos-tablet')) ) { let targetClass = $(this).data('grab-el'); let targetClasses = targetClass.split('|').map(c => c.trim()); let targetParentClass = false; if($(this).attr('data-grab-el-parent') !== undefined) { targetParentClass = $(this).data('grab-el-parent'); } targetClasses.forEach(function(cls, idx) { let fullTargetClass = targetParentClass ? '.' + targetParentClass + ' ' + '.' + cls : '.' + cls; if(!$(this).find('.' + cls).length) { $(this).append($(fullTargetClass).clone()); } }, this); } else { $(this).empty(); } }); } } }; /* |-------------------------------------------------------------------------- | Feature Modules > Listing Comments |-------------------------------------------------------------------------- */ core.listing.comments = { init: function() { $(".listing-comments-overflow").hide(); $('.listing-upsell--products').hide(); this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $(".listing-comments").on('click', '#listing-comments-button', function(e) { $this.controller($(e.delegateTarget), $(e.currentTarget)); }); $('.jump-menu--mbl').on('click', function(e) { $(this).toggleClass('active'); }); $('.jump-menu--link, .listing-header--jump-link').on('click', function(e) { e.preventDefault(); var $target = $($(this).attr('href')); if(!$target.length) { return; } var shouldOffset = true; var offset = (shouldOffset) ? $('.listing-header').outerHeight() + 30 : 0; $('html, body').animate({ scrollTop: $target.offset().top - offset }, 1000); }); $('.listing-cat-upsells-nav--link').on('click', function() { var catId = $(this).data('upsell-category-id'); $('.listing-upsell--products').hide(); $('.listing-upsell--products[data-upsell-category-id="'+catId+'"]').show(); $('.listing-cat-upsells-nav--link').removeClass('active'); $(this).addClass('active'); }); $('.listing-cat-upsells-nav--link').first().trigger('click'); }, settings: { cssProperties: { bottom: '-20px', opacity: 0 }, animation: { properties: { opacity: 1, bottom: 0, }, speed: 1000, }, iterationRevealSpeed: 200, }, controller: function(parent, button) { var state = parent.data('status'); if(state) { this.hide(parent); state = false; } else { this.show(parent); state = true; } parent.data('status', state); button.toggleClass("open").find("span").html(button.attr("data-toggle-" + state)); }, show: function(parent) { $this = this; parent.find('.listing-comments-overflow').slideDown().find(".listing-comment").css(this.settings.cssProperties).each(function(i, e){ setTimeout(function() { $(e).animate($this.settings.animation.properties, $this.settings.animation.speed); }, i * $this.settings.iterationRevealSpeed) }); return this; }, hide: function(parent) { parent.find('.listing-comments-overflow').slideUp(); return this; }, } /* |-------------------------------------------------------------------------- | Page Modules > Basket |-------------------------------------------------------------------------- */ core.basket = { init: function() { var $this = this; // if(!$('#voucher').val()){ // $(".cart-promo--form").hide(); // } this.bindEventListeners(); }, manageBasket: function(params, callback, callbackError) { $("#price-table").hide(); $("#price-spinner").show(); $("#checkout").addClass("button-loading"); $("#basket-errors").html(""); $.ajax({ type: "post", url: "/ajax/basket/manage.php", data: params, dataType: "json", error: function(error) { if(typeof callbackError == 'function') { callbackError(error); } $("#price-table").show(); $("#price-spinner").hide(); $("#checkout").removeClass("button-loading"); alert("Something went wrong updating your basket - please check your internet connection and try again"); console.error(error); }, success: function(response) { // Send data back to original caller (display a message etc) if(typeof callback == 'function') { callback(response); } $("#price-table").show(); $("#price-spinner").hide(); $("#checkout").removeClass("button-loading"); if(response.basket_totals != null) { // Upon successful response, update the basket totals displayed to user let basket_totals = response.basket_totals; // update the thing in navbar which shows how many items in basket & basket cost $("#navbar_basket_items").text(basket_totals.subtotal.items); $("#navbar_basket_cost").text(basket_totals.subtotal.amount); $("#overlayBasketTotal").text(basket_totals.subtotal.amount); $("#pricetable-subtotal-value").text(basket_totals.subtotal.amount); $("#pricetable-delivery-value").text(basket_totals.delivery.amount); core.util.showOrHideElementBoolean($("#pricetable-delivery"), basket_totals.delivery.amount > 0) $("#pricetable-discount-value").text(basket_totals.discount); core.util.showOrHideElementBoolean($("#pricetable-discount"), basket_totals.discount > 0) $("#pricetable-vat-value").text(basket_totals.vat.amount); core.util.showOrHideElementBoolean($("#pricetable-vat"), basket_totals.vat.show) core.util.showOrHideElementBoolean($("#pricetable-vat-inclusive"), basket_totals.vat.is_inclusive); $("#pricetable-total-value").text(basket_totals.total.amount); /* XVC Voucher */ if(basket_totals.xvc_voucher != null) { $("#pricetable-voucher-value").text(basket_totals.xvc_voucher.vouchers); $("#pricetable-totaltopay-value").text(basket_totals.xvc_voucher.total_to_pay); core.util.showOrHideElementBoolean($("#pricetable-voucher"), basket_totals.xvc_voucher.show); core.util.showOrHideElementBoolean($("#pricetable-totaltopay"), basket_totals.xvc_voucher.show); } else { $("#pricetable-voucher").hide(); $("#pricetable-totaltopay").hide(); } /* PayPal Pay Layer message */ $('.basket-pp-messaging').attr('data-pp-amount', basket_totals.total.amount.replace(',', '')); /* Deposit */ $("#pricetable-deposit-value").text(basket_totals.deposit); core.util.showOrHideElementBoolean($("#pricetable-deposit"), basket_totals.deposit > 0) $("#pricetable-totalpayable-value").text(basket_totals.total_payable_today.amount); core.util.showOrHideElementBoolean($("#pricetable-totalpayable"), basket_totals.total_payable_today.show) } if(response.basket != null) { // Basket contents: update multibuy promos and show/hide vat relief form if(response.basket.vat_relief != null) { core.util.showOrHideElementBoolean($("#vat-relief"), response.basket.vat_relief.show); } if(response.basket.multibuy_products != null) { let html = ""; for(let offer of response.basket.multibuy_products) { html += "
" html += "
Received with the "" + offer.label + "" offer
"; for(let product of offer.products) { html += "
"; html += "
"; html += "
"; html += "
"; html += "\"""; html += "
"; html += "
"; html += "
"; html += "
" + product.title + "
"; html += "
"; if(product.title_variant) { html += "
" + product.title_variant + "
"; } html += "
QTY: " + product.qty + "
"; html += "
"; html += "
"; html += "
"; html += "
"; html += "
£0.00
"; html += "
Normally £" + product.normal_price + "
"; html += "
"; html += "
"; } html += "
"; } $("#basket-multibuy-offers").html(html); } } if(response.status == "error" && response.message != "Please provide a valid postcode" && params.request != "voucher") { $("#basket-errors").html("
" + response.message + "
"); } } }); }, bindEventListeners: function() { var $this = this; $("#vat-relief--checkbox").click(function() { _self.form.checkboxController('toggle', $(this)); if ($('#vat-relief').is(':checked')) { $('#cart--vat-declaration-details').show(); } else { $('#cart--vat-declaration-details').hide(); } }); $('body').on('click', '.gift-option--action-button', function() { $("#gift-options-overlay").removeClass("open"); }); $(".cart-promo--button").click(function() { $(".cart-promo--form").stop().slideToggle(); }); // Show 'Send Quote To Email' basket overlay $('.cart-main').on('click', ".button[data-action='email-quote']", function() { if ($(this).attr('data-nocheckout') == 'true' && nopc() === false) { return false; } var $basketQuoteOverlay = core.overlay.ajaxOverlay({ url: '/olay/email_basket_quote.php' }); $basketQuoteOverlay.done(function(data) { $('body').append(data); var $olay = $("#basket-quote-olay"); $olay.addClass("open"); var $emptyBasketCheckbox = $olay.find('#quote-clear-basket'); var $emptyBasketCheckboxContainer = $emptyBasketCheckbox.closest('.overlay--input-group'); $emptyBasketCheckboxContainer.unbind('click'); $emptyBasketCheckboxContainer.click(function(e) { if($emptyBasketCheckboxContainer.hasClass('checked')) { _self.form.checkboxOff($emptyBasketCheckboxContainer); } else { _self.form.checkboxOn($emptyBasketCheckboxContainer); } return false; }); core.form.select2($olay.find('select')); $olay.on('click', function(e) { if($(e.target).is('#basket-quote-olay') || $(e.target).is('#basket-quote-olay .overlay--close') || $(e.target).parents('#basket-quote-olay .overlay--close').length == 1) { var refreshBasket = $olay.find('#quote-success').attr('data-refresh-cart'); $(this).closest('.overlay').fadeOut(200, function() { $(this).remove(); if(refreshBasket == '1') { window.location = window.location; } }); } }); let $form = $olay.find(".overlay--form"); $form.on('click', '#quote-submit', function(){$form.trigger('submit');}); $form.submit(function(e) { $form.find('.validate-border').removeClass('validate-border'); _self.form.validateForm($(this), function(failedInputs) { e.preventDefault(); if(failedInputs.length == 0) { let formData = $form.serializeArray().reduce(function(obj, item) { obj[item.name] = item.value; return obj; }, {}); $.ajax({ type: "post", url: "/ajax/ajax_basket_quote.php", data: formData, error: function(error) { if(typeof callbackError == "function") { callbackError(error); } console.error(error); }, success: function(response) { var data = JSON.parse(response); if(typeof(data.error) != 'undefined') { if(data.error == 'stock_check_failed') { window.location = window.location; } else if(data.error == 'age_error') { window.location = window.location; } else { let $errorCont = $form.find('#quote-error'); $('html, body').animate({scrollTop: $errorCont.offset().top - 100}, 700); $errorCont.text(data.error).stop().slideDown(); setTimeout(function() { $errorCont.slideUp(); }, 3000); } } if(typeof(data.input_errors) != 'undefined' && Object.keys(data.input_errors).length > 0) { $.each(data.input_errors, function(index, value) { if(value == true) { $form.find('input[name="' + index + '"]').addClass('validate-border'); } }); } if(typeof(data.success) != 'undefined') { let $successCont = $form.find('#quote-success'); $('html, body').animate({scrollTop: $successCont.offset().top - 100}, 700); $form.find('.overlay--input-group,.checkout-segment').hide(); $successCont.text(data.success).stop().show(); if(data.action == 'refresh-cart') { $successCont.attr('data-refresh-cart', 1); } } } }); } else { $form.find('#quote-error').text('Please fill out required fields'); } }); return false; }); }); }); this.onLoad(); _self.form.validateNumberInputs(); }, onLoad: function() { var $this = this; }, // Used for updating the basket totals updateTotals: function() { $.get('/ajax/basket_data_2.php', function(result) { var data = JSON.parse(result); if(typeof data.item_count != 'undefined' && typeof data.subtotal != 'undefined') { $('[data-updatable=basket-total]').text(data.subtotal); var itemCountText = (data.item_count == 1) ? data.item_count + ' Item' : data.item_count + ' Items' $('[data-updatable=basket-item-count]').text(itemCountText); if(data.item_count > 0) { $('.header-cart').addClass('header-cart--not-empty'); } else { $('.header-cart').removeClass('header-cart--not-empty'); } } }); }, } /* |-------------------------------------------------------------------------- | Feature Modules > Listing - Purchasable Vouchers |-------------------------------------------------------------------------- */ core.listing.vouchers = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $(".voucher-amount-input").on('keydown', function(e) { var $this = $(this); // Allow: backspace, delete, tab, escape, enter and . if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 || // Allow: Ctrl/cmd+A (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) || // Allow: Ctrl/cmd+C (e.keyCode == 67 && (e.ctrlKey === true || e.metaKey === true)) || // Allow: Ctrl/cmd+X (e.keyCode == 88 && (e.ctrlKey === true || e.metaKey === true)) || // Allow: home, end, left, right (e.keyCode >= 35 && e.keyCode <= 39)) { // let it happen, don't do anything return; } // Ensure that it is a number and stop the keypress if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) { e.preventDefault(); } if($this.val() > $this.attr('max') || $this.val() < $this.attr('min')){ if($this.val() > $this.attr('max')){ $this.val($this.attr('max')); } else { $this.val($this.attr('min')); } } }); }, } /* |-------------------------------------------------------------------------- | Page Modules > Checkout |-------------------------------------------------------------------------- */ core.checkout = { init: function() { var $this = this; this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; this.onLoad(); this.onScroll(); this.onResize(); }, onLoad: function() { var $this = this; $(window).on('load', function() { }); }, onScroll: function() { var $this = this; $window.on('scroll', function() { if(Modernizr.mq('(min-width: 1001px)')) { $this.positionCheckoutOverview(); } }); }, onResize: function() { var $this = this; $window.on('resize', function() { if(Modernizr.mq('(min-width: 1001px)')) { $this.positionCheckoutOverview(); } }); }, /** * Position the checkout overview side panel * */ positionCheckoutOverview: function() { var $cartOverview = $(".cart-overview"); var $checkoutHeader = $(".checkout-header"); var $checkoutLogin = $('.checkout-login'); var $checkoutSide = $('.checkout-side'); var windowHeight = $window.height(); var windowPosFromTop = $window.scrollTop(); var documentHeight = $(document).outerHeight(true); var elementHeight = $cartOverview.outerHeight(true); var headerHeight = $checkoutHeader.outerHeight(true); var loginHeight = $checkoutLogin.outerHeight(true); var footerHeight = $('footer').outerHeight(true); var elementWidth = $checkoutSide.width(); var sideHeight = $('.checkout-side').outerHeight(true); var mainHeight = $('.checkout-main').outerHeight(true); absoluteCSS = { 'position': 'absolute', 'bottom': 0, 'top': 'auto', 'width': elementWidth } fixedCSS = { 'position': 'fixed', 'top': 45, 'width': elementWidth } // if window height is larger than the element height so the fixed on scroll functionality is needed. if(windowHeight > elementHeight && Modernizr.mq('(min-width: 1001px)')) { // if the window has scrolled past the header if(windowPosFromTop > (headerHeight + loginHeight)) { $cartOverview.removeAttr('style'); if((windowPosFromTop + elementHeight) >= (documentHeight - footerHeight)) { $cartOverview.css(absoluteCSS); } else { $cartOverview.css(fixedCSS); } } else { $cartOverview.removeAttr('style'); } } else { $cartOverview.removeAttr('style'); } }, checkoutSideAdjust: function () { // var $cartElements = $('.checkout-main, .checkout-side').removeAttr("style"); // if(Modernizr.mq('(min-width: 1024px)')) { // var sideHeight = $('.checkout-side').outerHeight(true); // var mainHeight = $('.checkout-main').outerHeight(true); // var endHeight = (mainHeight > sideHeight) ? mainHeight : sideHeight; // $('.checkout-side').height(endHeight); // $('.checkout-main').height(endHeight); // } }, }; /* |-------------------------------------------------------------------------- | Page Modules > Checkout > Details |-------------------------------------------------------------------------- */ core.checkout.details = { init: function() { // Hide voucher form this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $(".cart-promo--button").click(function() { $(".cart-promo--form").stop().slideToggle(); }); $('.checkbox').each(function(){ $(this).parent().on('click', function() { _self.form.checkboxController('toggle', $(this), $(this).data('callback')); }) }); $(".delivery-address").click(function() { $this.selectDeliveryAddress($(this)); }); $("[data-postcode-button='true']").siblings('input').keydown(function(e) { if(e.which == 13) { $(this).siblings('span').click(); e.preventDefault(); } }); $("[data-postcode-button='true']").click(function(e) { var $btn = $(this); var $mode = $btn.data('lookup-mode'); var postcode = $btn.addClass("loading").siblings('input').val(); var address_dd = document.getElementById('postcode_results_' + $mode); var $error = $('#postcode_lookup_error_' + $mode); var $address_cont = $('#postcode_lookup_results_container_' + $mode); var new_opt, address, address_text, address_part, address_json, error; _self.checkout.details.postCodeRequest({postcode: postcode}, function(data) { setTimeout(function() { if(typeof data.Error == 'undefined'){ $address_cont.hide(); $error.children('.message').html('An error has occurred. Please enter your address manually or try again later'); $error.show(); } else { if(!data.Error){ while(address_dd.options.length > 0) { address_dd.remove(0); } if(data.Address.length > 0){ address_dd.appendChild(new Option('Select Address', '')); for(var i = 0; i < data.Address.length; i++){ address = data.Address[i]; address_text = ""; for(var j = 0; j <= Object.keys(address).length; j++){ address_part = (address[j] ? address[j].trim() : ''); if(address_part){ address_text += (address_text ? ", " : "") + address_part; } } address_json = encodeURIComponent(JSON.stringify(address)); new_opt = new Option(address_text, 'address'); new_opt.dataset.address = address_json; address_dd.appendChild(new_opt); } $address_cont.show(); $error.hide(); } else { $address_cont.hide(); $error.children('.message').html('No addresses can be found for your postcode'); $error.show(); } } else { $address_cont.hide(); $error.children('.message').html(data.Error); $error.show(); } } //_self.checkout.checkoutSideAdjust(); $btn.removeClass("loading"); }, 1000); }); }); $("[data-postcode-lookup-results='true']").change(function(e) { var $this = $(this); var $mode = $this.data('lookup-mode'); var $selected = $this.children(':selected'); var address_data; if($selected.val() == 'address'){ address_data = JSON.parse(decodeURIComponent($selected.data('address'))); $('#account_' + $mode + '_2').val(address_data[1]); $('#account_' + $mode + '_3').val(address_data[2]); $('#account_' + $mode + '_4').val(address_data[3]); $('#account_' + $mode + '_5').val(address_data[4]); $('#account_' + $mode + '_6').val(address_data[5]); } else { $('#account_' + $mode + '_2').val(); $('#account_' + $mode + '_3').val(); $('#account_' + $mode + '_4').val(); $('#account_' + $mode + '_5').val(); $('#account_' + $mode + '_6').val(); } }); $('#delivery_address_id').on('change', function () { var type = $('#del-as-bil-address').hasClass('checked') ? 'both' : 'del'; _self.checkout.details.updateAddress(this, type); }); $('#billing_address_id').on('change', function () { var type = $('#del-as-bil-address').hasClass('checked') ? 'both' : 'bill'; _self.checkout.details.updateAddress(this, type); }); }, /** * Send an AJAX request and return matched * postcodes as a callback parameter * * @param {type} name * @return {type} */ postCodeRequest: function(params, callback) { $ = jQuery; $.ajax({ type: "post", url: "/ajax/ajax_postcode.php", data: params, dataType: "json", error: function(jqXHR, textStatus, errorThrown){ }, success: function(data){ if (typeof callback == 'function') { callback(data); } } }); }, selectDeliveryAddress: function($element) { $(".delivery-address").removeClass("sel"); $element.addClass("sel"); }, showAddAddressOverlay: function() { $("#add-new-address-overlay").addClass("open").find(".message-error").hide(); }, toggleBillingAddressForm: function (status) { var $form = $('.billing-address-form'); if(!status){ $form.show(); } else { $form.hide(); _self.checkout.details.checkAddress(); } _self.checkout.positionCheckoutOverview(); //_self.checkout.checkoutSideAdjust(); }, checkAddress: function() { $('#account_bill_1').val($('#account_del_1').val()); $('#account_bill_2').val($('#account_del_2').val()); $('#account_bill_3').val($('#account_del_3').val()); // $('#account_bill_4').val($('#account_del_4').val()); $('#account_bill_5').val($('#account_del_5').val()); $('#account_bill_6').val($('#account_del_6').val()); $('#account_bill_7').val($('#account_del_7').val()); }, updateAddress: function(el, type) { var field; field = document.createElement('input'); field.type = 'hidden'; field.id = 'address_id'; field.name = 'address_id'; field.value = el.value; document.getElementById('form_checkout').appendChild(field); field = document.createElement('input'); field.type = 'hidden'; field.id = 'address_type'; field.name = 'address_type'; field.value = type; document.getElementById('form_checkout').appendChild(field); document.getElementById('form_checkout').submit(); }, }; /* |-------------------------------------------------------------------------- | Page Modules > Checkout > Confirm |-------------------------------------------------------------------------- */ core.checkout.confirm = { locked: true, init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $('.payment-method--button').click(function() { $this.openPaymentMethod($(this)); }); $('#terms-checkbox').click(function(e) { _self.form.checkboxController('toggle', $(this)); }); $('#extra-checkbox').click(function(e) { _self.form.checkboxController('toggle', $(this)); }); }, /** * Open the selected payment method tab and hide the others * * @param {object} $element */ openPaymentMethod: function($element) { $parent = $element.parent('.payment-method'); $('.payment-method').not($parent).removeClass('open').find('.payment-method--content').slideUp(); if(!$parent.hasClass("open")) { $parent.addClass("open").find('.payment-method--content').slideDown('normal', function(){ //core.checkout.checkoutSideAdjust(); }); } $('#payment').val($element.data('payment-method')); }, /** * Hide the selected payment method from the list of payment methods * * @param {int} id */ hidePaymentMethod: function(id) { var $this = this; if (id) { var container = document.querySelector('.payment-methods'); var method = container.querySelector('[data-payment-method="' + id + '"]'); if (method) { method.parentNode.style.display = 'none'; if (document.getElementById('payment').value == id) { // Select the first visible payment method, if the hidden method was selected var methods = container.querySelectorAll('.payment-method'); for (var i = 0; i < methods.length; i++) { if (methods[i].style.display != 'none') { var button = methods[i].querySelector('.payment-method--button'); return $this.openPaymentMethod($(button)); } } // If there are no other payment methods disable the checkout and display a message _self.checkout.confirm.showNoPaymentMethodsMsg(); } // This will be run in openPaymentMethod //_self.checkout.checkoutSideAdjust(); } } }, /** * Show the selected payment method in the list of payment methods * * @param {int} id */ showPaymentMethod: function(id) { var $this = this; if (id) { var container = document.querySelector('.payment-methods'); var method = container.querySelector('[data-payment-method="' + id + '"]'); if (method) { method.parentNode.style.display = ''; _self.checkout.confirm.hideNoPaymentMethodsMsg(); //_self.checkout.checkoutSideAdjust(); } } }, /** * Disable the form and voucher buttons to the prevent the form being submitted multiple times * or order details being changed when the payment is being authorised */ lockForm: function() { this.locked = true; $("#checkout-continue, .voucher_add, #voucher_add, #voucher-entry-linked, #voucher_container [data-voucher-remove]").prop('disabled', true); }, /** * Re-enable the form and voucher controls */ unlockForm: function () { if (this.locked) { this.locked = false; $("#checkout-continue, .voucher_add, #voucher_add, #voucher-entry-linked, #voucher_container [data-voucher-remove]").prop('disabled', false); } }, /** * Show no payment method message */ showNoPaymentMethodsMsg: function () { $('#payment-methods-no-options').show(); // document.getElementById('checkout-continue').disabled = true; _self.checkout.confirm.lockForm(); }, /** * Hide no payment method message */ hideNoPaymentMethodsMsg: function () { $('#payment-methods-no-options').hide(); // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); }, getCustomerDetails: function () { var $country = $('#account_bill_8'); var $country_option = $country.is('select') ? $country.find('option:selected') : $country; var country = $country_option.data('code'); return { firstname: $('#details_name').val(), surname: $('#details_surname').val(), email: $('#details_email').val(), phone: $('#details_telno').val(), address: { street: core.util.trimCommas($('#account_bill_2').val() + ', ' + $('#account_bill_3').val()), extended: $('#account_bill_4').val(), locality: $('#account_bill_5').val(), region: $('#account_bill_6').val(), postcode: $('#account_bill_7').val().replace(/-/g, ''), country: country } }; } }; /* |-------------------------------------------------------------------------- | Page Modules > Klarna |-------------------------------------------------------------------------- */ core.klarna = { initialized: false, height: 0, init: function() { var $this = this; $this.initialized = true; Klarna.Payments.on('heightChanged', function (newHeight) { if ($this.height != newHeight) { //_self.checkout.checkoutSideAdjust(); $this.height = newHeight; } }); }, /** * Setup Klarna * * @param {string} token */ setup: function (token) { Klarna.Payments.init({ client_token: token }); }, /** * Highlight invalid fields, display errors * * @param {object} error */ handleErrors: function (error) { if (error) { // Klarna displays the error to the customer so we don't need to do anthing // We could highlight the invalid fields but they are on the previous page // error: { // invalid_fields: [ // billing_address.street_address // billing_address.city // billing_address.given_name // billing_address.postal_code // billing_address.family_name // billing_address.email // ] // } // _self.checkout.checkoutSideAdjust(); } }, /** * Load Klarna payment methods * * @param {object} categories */ loadCategories: function(categories) { var $this = this; var processed = false; if (typeof Klarna !== 'undefined' && typeof categories === 'object') { for (var i in categories) { processed = true; if (categories[i].hidden == true) { _self.checkout.confirm.hidePaymentMethod(categories[i].id); } else { try { (function (category) { Klarna.Payments.load({ container: '#klarna-' + category.category, payment_method_category: category.category }, function (res) { if (res.show_form == true) { // Its ok to display the form, but there may be fixable errors $this.handleErrors(res.error); _self.checkout.confirm.showPaymentMethod(category.id); } else { // Pre-assessment failed - hide the method _self.checkout.confirm.hidePaymentMethod(category.id); } }); }(categories[i])); } catch (e) { _self.checkout.confirm.hidePaymentMethod(categories[i].id); console.error('Error loading methods: ', e); } } } } if (processed === false) { // Remove the Klarna methods if an empty or invalid array is provided var methods = document.querySelectorAll('.payment-method__klarna'); for (var i = 0; i < methods.length; i++) { var button = methods[i].querySelector('.payment-method--button'); if (button.dataset.paymentMethod) { _self.checkout.confirm.hidePaymentMethod(button.dataset.paymentMethod); } } } }, /** * Authorise Klarna payment * * @param {int} id * @param {string} category */ authorise: function(id, category) { var $this = this; // Disable button // document.getElementById('checkout-continue').disabled = true; _self.checkout.confirm.lockForm(); if (typeof Klarna !== 'undefined') { try { Klarna.Payments.authorize({ payment_method_category: category }, function(res) { if (res.approved == true) { // Approved - submit the token and complete the order document.getElementById('klarna-authorisation-token').value = res.authorization_token; document.getElementById('form_confirm').submit(); } else { if (res.show_form == true) { // Either there was a fixable error or the user has aborted a required action $this.handleErrors(res.error); } else { // Declined - hide the method _self.checkout.confirm.hidePaymentMethod(id); } // Re-enable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); } }); } catch (e) { console.error('Authorisation error: ', e); // Re-enable button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); } } } }; /* |-------------------------------------------------------------------------- | Page Modules > Braintree |-------------------------------------------------------------------------- */ core.braintree = { initialized: false, total: 0, paypalNonce: null, paypalReference: null, paypalCreditNonce: null, paypalCreditReference: null, hostedFields: null, threeDSecure: null, init: function() { var $this = this; $this.initialized = true; }, /** * Setup Braintree payments * * @param {string} token * @param {float} total * @param {string} environment * @param {bool} cardEnabled * @param {bool} paypalEnabled * @param {bool} paypalCreditEnabled */ setup: function (token, total, environment, cardEnabled, paypalEnabled, paypalCreditEnabled) { this.total = total; if (!environment) { environment = 'sandbox'; } braintree.client.create({ authorization: token }, function(clientErr, clientInstance) { if (clientErr) { core.braintree.unavailableError('both'); console.error('Error creating client:', clientErr); return; } if (paypalEnabled || paypalCreditEnabled) { core.braintree.createPaypal(clientInstance, environment, paypalEnabled, paypalCreditEnabled); } if (cardEnabled) { core.braintree.createThreeDSecure(clientInstance); core.braintree.createHostedFields(clientInstance); } }); }, /** * Display the PayPal logged in indication * * @param {string} type */ showLoggedIn: function (type, payload) { if (type == 'paypal-credit') { $('#braintree-paypal-credit-button').hide(); $('#braintree-paypal-credit-loggedin').find('.bt-pp-email').text(payload.details.email).end().fadeIn('slow'); this.paypalCreditNonce = payload.nonce; this.paypalCreditReference = payload.details.email; } else { $('#braintree-paypal-button').hide(); $('#braintree-paypal-loggedin').find('.bt-pp-email').text(payload.details.email).end().fadeIn('slow'); this.paypalNonce = payload.nonce; this.paypalReference = payload.details.email; } //_self.checkout.checkoutSideAdjust(); }, /** * Remove the PayPal logged in indication * * @param {string} type */ hideLoggedIn: function (type) { if (type == 'paypal-credit') { $('#braintree-paypal-credit-loggedin').fadeOut('fast', function() { $(this).find('.bt-pp-email').text(''); $('#braintree-paypal-credit-button').show(); }); this.paypalCreditNonce = null; this.paypalCreditReference = null; } else { $('#braintree-paypal-loggedin').fadeOut('fast', function() { $(this).find('.bt-pp-email').text(''); $('#braintree-paypal-button').show(); }); this.paypalNonce = null; this.paypalReference = null; } //_self.checkout.checkoutSideAdjust(); }, /** * Format the payment reference * * @param {object} payload */ formatReference: function (payload) { return '' + payload.details.cardType + ' ending in ' + payload.details.lastFour; }, /** * Display unavailable error for the specified types * * @param {string} type */ unavailableError: function (type) { var types = ['paypal', 'paypal-credit', 'card']; for (var i = 0; i < types.length; i++) { if (type == 'both' || types[i] == type) { _self.message.create($('#pay-' + types[i]), { type: 'error', message: 'This method is currently unavailable, please use another method or try again later.', closeable: false, scrollTo: false }); } } //_self.checkout.checkoutSideAdjust(); }, /** * Display transaction error for the specified types * * @param {string} type */ transactionError: function (type) { var types = ['paypal', 'paypal-credit', 'card']; for (var i = 0; i < types.length; i++) { if (type == 'both' || types[i] == type) { _self.message.create($('#pay-' + types[i]), { type: 'error', message: 'There was an error processing your request.', closeable: false, scrollTo: true }); } } //_self.checkout.checkoutSideAdjust(); }, /** * Display verification error * */ verificationError: function () { _self.message.create($('#pay-card'), { type: 'error', message: 'Card verification failed, please try another form of payment.', closeable: true }); //_self.checkout.checkoutSideAdjust(); }, /** * Create Braintree PayPal buttons * * @param {object} clientInstance * @param {string} environment * @param {bool} paypalEnabled * @param {bool} paypalCreditEnabled */ createPaypal: function (clientInstance, environment, paypalEnabled, paypalCreditEnabled) { var $this = this; braintree.paypalCheckout.create({ client: clientInstance }, function (paypalCheckoutErr, paypalCheckoutInstance) { if (paypalCheckoutErr) { if (paypalEnabled) { $this.unavailableError('paypal'); } if (paypalCreditEnabled) { $this.unavailableError('paypal-credit'); } console.error('Error creating PayPal Checkout:', paypalCheckoutErr); return; } // Set up PayPal with the checkout.js library if (paypalEnabled) { paypal.Button.render({ env: environment, payment: function () { return paypalCheckoutInstance.createPayment({ flow: 'vault' }); }, onAuthorize: function (data, actions) { return paypalCheckoutInstance.tokenizePayment(data, function (tokenizeErr, tokenizeRes) { if (tokenizeErr) { $this.transactionError('paypal'); console.error('Tokenisation error:', tokenizeErr); return; } // Remove errors as logging into paypal was successfull $('#pay-paypal .message').remove(); $this.showLoggedIn('paypal', tokenizeRes); }); }, onCancel: function (data) { console.log('checkout.js payment cancelled', data); }, onError: function (err) { $this.unavailableError('paypal'); console.error('checkout.js error:', err); } }, '#braintree-paypal-button').then(function () { $('#braintree-paypal-loggedin .bt-pp-cancel button').on('click', function () { $this.hideLoggedIn('paypal'); }); //_self.checkout.checkoutSideAdjust(); }); } // Setup PayPal Credit button with the checkout.js library if (paypalCreditEnabled) { paypal.Button.render({ env: environment, style: { label: 'credit' }, payment: function () { return paypalCheckoutInstance.createPayment({ flow: 'vault', offerCredit: true }); }, onAuthorize: function (data, actions) { return paypalCheckoutInstance.tokenizePayment(data, function (tokenizeErr, tokenizeRes) { if (tokenizeErr) { $this.transactionError('paypal-credit'); console.error('Tokenisation error:', tokenizeErr); return; } // Remove errors as logging into paypal was successfull $('#pay-paypal-credit .message').remove(); $this.showLoggedIn('paypal-credit', tokenizeRes); }); }, onCancel: function (data) { console.log('checkout.js payment cancelled', data); }, onError: function (err) { $this.unavailableError('paypal-credit'); console.error('checkout.js error:', err); } }, '#braintree-paypal-credit-button').then(function () { $('#braintree-paypal-credit-loggedin .bt-pp-cancel button').on('click', function () { $this.hideLoggedIn('paypal-credit'); }); //_self.checkout.checkoutSideAdjust(); }); } }); }, /** * Create Braintree 3D secure instance * * @param {object} clientInstance */ createThreeDSecure: function (clientInstance) { var $this = this; braintree.threeDSecure.create({ version: 2, client: clientInstance }, function (threeDSecureErr, threeDSecureInstance) { if (threeDSecureErr) { $this.unavailableError('card'); console.error('Error creating 3D secure:', threeDSecureErr); return; } $this.threeDSecure = threeDSecureInstance; }); }, /** * Create Braintree hosted fields instance * * @param {object} clientInstance */ createHostedFields: function (clientInstance) { var $this = this; braintree.hostedFields.create({ client: clientInstance, styles: { "input": { "color": "#222", "font-size": "14px", "line-height": "18px", "padding": "22px 8px 6px 8px" } }, fields: { number: { selector: "#card-number", placeholder: "0000 0000 0000 0000" }, cvv: { selector: "#cvv", placeholder: "000" }, expirationDate: { selector: "#expiration-date", placeholder: "MM/YY" }, } }, function (hostedFieldsErr, hostedFieldsInstance) { if (hostedFieldsErr) { $this.unavailableError('card'); console.error('Error creating hosted fields:', hostedFieldsErr); return; } hostedFieldsInstance.on('validityChange', function (event) { var field = event.fields[event.emittedBy]; if (field.isValid) { switch (event.emittedBy) { case "number": valid_number = true; break; case "cvv": valid_cvv = true; break; case "expirationDate": valid_expiry = true; break; } } else { switch (event.emittedBy) { case "number": valid_number = false; break; case "cvv": valid_cvv = false; break; case "expirationDate": valid_expiry = false; break; } } }); $this.hostedFields = hostedFieldsInstance; }); }, /** * Authorise Braintree payment * * @param {int} id * @param {string} type * @param {object} customerDetails */ authorise: function(id, type, customerDetails) { var $this = this; _self.checkout.confirm.lockForm(); if (type == 'paypal') { if (!this.paypalNonce) { this.transactionError('paypal'); console.error('PayPal nonce not found'); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); return; } // Submit the nonce retrieved earlier document.getElementById('braintree-nonce').value = this.paypalNonce; document.getElementById('braintree-reference').value = this.paypalReference; document.getElementById('form_confirm').submit(); } else if (type == 'paypal-credit') { if (!this.paypalCreditNonce) { this.transactionError('paypal-credit'); console.error('PayPal Credit nonce not found'); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); return; } // Submit the nonce retrieved earlier document.getElementById('braintree-nonce').value = this.paypalCreditNonce; document.getElementById('braintree-reference').value = this.paypalCreditReference; document.getElementById('form_confirm').submit(); } else { if (!this.hostedFields) { this.transactionError('card'); console.error('Hosted fields instance not found'); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); return; } // Tokenise the card details this.hostedFields.tokenize(function (tokenizeErr, tokenizeRes) { if (tokenizeErr) { $this.transactionError('card'); console.error('Tokenisation error:', tokenizeErr); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); return; } // Verify the card details using 3D secure 2.0 if (tokenizeRes.type == 'CreditCard') { if (!$this.threeDSecure) { $this.transactionError('card'); console.error('3D secure instance not found'); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); return; } $this.threeDSecure.verifyCard({ amount: $this.total, nonce: tokenizeRes.nonce, bin: tokenizeRes.details.bin, email: customerDetails.email, billingAddress: { givenName: customerDetails.firstname, surname: customerDetails.surname, phoneNumber: customerDetails.phone, streetAddress: customerDetails.shipping.street, extendedAddress: customerDetails.billing.extended, locality: customerDetails.billing.locality, region: customerDetails.billing.region, postalCode: customerDetails.billing.postcode, countryCodeAlpha2: customerDetails.billing.country }, additionalInformation: { shippingGivenName: customerDetails.firstname, shippingSurname: customerDetails.surname, shippingPhone: customerDetails.phone, shippingAddress: { streetAddress: customerDetails.shipping.street, extendedAddress: customerDetails.shipping.extended, locality: customerDetails.shipping.locality, region: customerDetails.shipping.region, postalCode: customerDetails.shipping.postcode, countryCodeAlpha2: customerDetails.shipping.country } }, onLookupComplete: function (data, next) { next(); } }, function (threeDSecureErr, threeDSecureRes) { if (threeDSecureErr) { $this.transactionError('card'); console.error('3D Secure error:', threeDSecureErr); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); return; } if (threeDSecureRes.liabilityShifted) { // Liablity has shifted document.getElementById('braintree-nonce').value = threeDSecureRes.nonce; document.getElementById('braintree-reference').value = $this.formatReference(threeDSecureRes); document.getElementById('form_confirm').submit(); } else if (threeDSecureRes.liabilityShiftPossible) { // Liablity may still be shifted $this.verificationError(); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); } else { // Liablity has not shifted and will not shift $this.verificationError(); // Renable the button as there was an error // document.getElementById('checkout-continue').disabled = false; _self.checkout.confirm.unlockForm(); } }); } else { document.getElementById('braintree-nonce').value = tokenizeRes.nonce; document.getElementById('braintree-reference').value = this.formatReference(tokenizeRes); document.getElementById('form_confirm').submit(); } }); } }, getCustomerDetails: function () { var details = core.checkout.confirm.getCustomerDetails(); return { firstname: core.util.strTruncate(details.firstname, 50), surname: core.util.strTruncate(details.surname, 50), email: details.email, phone: core.util.strTruncate(details.phone, 50), shipping: { street: core.util.strTruncate(details.address.street, 50), extended: core.util.strTruncate(details.address.extended, 50), locality: core.util.strTruncate(details.address.locality, 50), region: core.util.strTruncate(details.address.region, 50), postcode: core.util.strTruncate(details.address.postcode, 9), country: details.address.country }, billing: { street: core.util.strTruncate(details.address.street, 50), extended: core.util.strTruncate(details.address.extended, 50), locality: core.util.strTruncate(details.address.locality, 50), region: core.util.strTruncate(details.address.region, 50), postcode: core.util.strTruncate(details.address.postcode, 9), country: details.address.country } }; } }; /* |-------------------------------------------------------------------------- | Feature Modules > Comparison |-------------------------------------------------------------------------- */ core.comparison = { init: function() { this.cacheElements(); this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $(".product-grid, .listing-cat-upsells--cont").unbind("click").on('click', '.product-overlay-top--button__compare, .add-to-comparison-btn', function() { var listing_category_id = $(this).parents('.product-grid--item, .product-grid-item, .upsell-listing').attr('data-listing-category-id'); if(!$(this).parents('.product-grid--item, .product-grid-item, .upsell-listing').hasClass('product--has-options')) { // var opt_sel = $(this).parents('.product-grid--item').find(".opt_hidden").val(); var opt_sel = $(this).parents('.product-grid--item, .product-grid-item, .upsell-listing').find(".opt_hidden_encoded").val(); $this.request({ add: opt_sel, listing_category_id: listing_category_id }); } else { listing_category_id = $(this).parents('.product-grid--item, .product-grid-item, .upsell-listing').attr('data-listing-category-id'); $('#comp_site_listing_category_id').val(listing_category_id); $this.selectRequest({listing_category_id:listing_category_id}, function() { $("#overlay-comparison").addClass("open"); }); } return false; }); this.elements.$bar.unbind("click").on('click', '.comparison-bar--product-overlay', function() { var site_option_id = $(this).parent().attr("data-site-option-id"); $this.request({remove: site_option_id}); return false; }); $('#overlay-comparison--form').unbind("submit").submit(function(e) { var opt_id = $('#comp_site_option_id').val(); var listing_category_id = $('#comp_site_listing_category_id').val(); $this.request({ add: opt_id, listing_category_id: listing_category_id }, function() { $("#overlay-comparison").hide(); }); e.preventDefault(); }); $('#compare_1').unbind("click").on('click', function() { var listing_category_id = $('#listing_1').val(); // var opt_sel = $('#options_1').val(); console.log("Click"); $this.request({ add: JSON.stringify(opt_sel), listing_category_id: listing_category_id }); return false; }); }, response: {}, elements: {}, cacheElements: function() { this.elements = { $bar: $('.comparison-bar'), $grid: $(".comparison-bar--products .grid") } }, request: function(params, callback) { var $this = this; jQuery.ajax({ type: 'GET', url: '/ajax/ajax_comparison.php', data: params, dataType: 'html', error: function (e) { $this.elements.$bar.hide(); }, success: function (data) { $this.response = JSON.parse(data); $this.populateGrid(); if (typeof callback == 'function') { callback(); } } }); }, selectRequest: function(params, callback) { jQuery.ajax({ type: 'GET', url: '/ajax/ajax_comparison_select.php', data: params, dataType: 'html', error: function (e) { $comparisonBar.hide(); }, success: function (data) { $("body").append(data); if (typeof callback == 'function') { callback(); } } }); }, populateGrid: function() { var $this = this; if(this.response.count > 0) { this.elements.$bar.fadeIn(); $("body").addClass("comparison-visible"); } else { this.elements.$bar.hide(); $("body").removeClass("comparison-visible"); } $('.comparison-bar--product').remove(); (this.response.triggerAnimation) ? this.elements.$grid.addClass("animate") : this.elements.$grid.removeClass("animate"); // $('.product-overlay-top--button__compare').show(); $(this.response.listings).each(function(index, product) { var opt_labels = ''; $this.elements.$grid.append("
"); }); // $('.comparison-mobile').html(this.response.listings.length + ' listings selected'); } } /* |-------------------------------------------------------------------------- | Feature Modules > Wishlist |-------------------------------------------------------------------------- */ core.wishlist = { count: 0, init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $(".product-grid").on('click', '.product-overlay-top--button__wishlist', function() { var $parent = $(this).parents('.product-grid--item'); var listing_category_id = $parent.attr('data-listing-category-id'); if(!$parent.hasClass('product--has-options')) { var wishlists = $parent.attr('data-cart-count'); // Add a unique id for option_update_selected $this.count += 1; $parent.find('.product-grid--item-options').attr('id', 'wishlist_options_' + $this.count); option_update_selected('#wishlist_options_' + $this.count); $this.chooseWishlist(JSON.stringify(opt_sel), listing_category_id, wishlists, 1); } else { $this.selectRequest({ listing_category_id: listing_category_id }, function() { $("#overlay-wishlist").addClass("open"); }); } return false; }); $this.bindChooseOverlay(1); }, response: {}, request: function(params, callback) { var $this = this; jQuery.ajax({ type: 'GET', url: '/ajax/ajax_wishlist.php', data: params, dataType: 'html', success: function (data) { $this.response = JSON.parse(data); if (typeof callback == 'function') { callback(); } } }); }, selectRequest: function(params, callback) { jQuery.ajax({ type: 'GET', url: '/ajax/ajax_wishlist_select.php', data: params, dataType: 'html', success: function (data) { $("body").append(data); if (typeof callback == 'function') { callback(); } } }); }, chooseWishlist: function (opt_sel, listing_category_id, wishlists, submitcount) { var $this = this; if (wishlists > 1) { var $chooseWishlistOverlay = core.overlay.ajaxOverlay({ url: '/olay/account_basket_choose.php' }); $chooseWishlistOverlay.done(function (data) { if (submitcount == 2) { $("#overlay-wishlist").remove(); } $('body').append(data); var $olay = $("#account-cart-choose"); $olay.addClass("open"); $olay.find(".overlay--close").click(function() { $olay.remove(); }); $('.wishlist-choose').click(function () { var cart_secid = $(this).data('secid'); var cart_authid = $(this).data('authid'); $this.request({ add: opt_sel, listing_category_id: listing_category_id, cart_secid: cart_secid, cart_authid: cart_authid }, function () { $olay.remove(); if ($.inArray($this.response.status, ['success', 'error']) !== -1) { if($.inArray($this.response.status, ['success']) !== -1) { $('.button--listing-wishlist#wishlist_1').addClass('button--in-wishlist').find('span').html('Added to Wishlist'); } $this.flashMessage($this.response.status, $this.response.message); } }); }); }); } else { $this.request({ add: opt_sel, listing_category_id: listing_category_id, }, function () { if (submitcount == 2) { $("#overlay-wishlist").remove(); } if ($.inArray($this.response.status, ['success', 'error']) !== -1) { console.log(2); if($.inArray($this.response.status, ['success']) !== -1) { console.log(3); $('.button--listing-wishlist#wishlist_1').addClass('button--in-wishlist').find('span').html('Added to Wishlist'); } $this.flashMessage($this.response.status, $this.response.message); } }); } }, bindChooseOverlay: function (submitcount) { var $this = this; $('#wishlist_' + submitcount).on('click', function() { if($(this).hasClass('button--in-wishlist')) { window.location = $(this).data('wishlist-url'); return false; } var listing_category_id = $("#listing_" + submitcount).val(); var opt_sel = $("#options_" + submitcount).val(); var wishlists = $('input[name="cart_count"]').val(); $this.chooseWishlist(opt_sel, listing_category_id, wishlists, submitcount); return false; }); }, flashMessage: function (type, message) { $('.flash-message').remove(); var $msgContainer = $('
', { class: 'flash-message' }); var $msgBody = $('
', { class: 'message message-' + type, text: message }); $msgContainer.append($msgBody); $('body').append($msgContainer); $msgBody.slideDown(); setTimeout(function() { $msgBody.slideUp(300, function() { $msgContainer.remove(); }) }, 3000); }, redirect: function (secid, authid) { window.location = "/account_baskets.php?secid=" + secid + "&authid=" + authid; } } /* |-------------------------------------------------------------------------- | Feature Modules > Product List |-------------------------------------------------------------------------- */ core.products = { defaults: { slider: { min: 1, max: 100 } }, init: function() { this.bindEventListeners(); this.customHeightMatch(); if($('.sidebar').length) { _self.system.setData(_self.products.sidebar, this.data); } this.sidebar.init(); $('#warrantyOlay, .product-warranty--more, .shop-modal--click-trap, .shop-modal--close').on('click', function() { $('#warrantyModal').toggleClass('active'); }); $('.product--shortdesc ul li').not(':nth-child(1)').not(':nth-child(2)').not(':nth-child(3)').not(':nth-child(4)').hide(); }, bindEventListeners: function() { $('body').on('click', '.modal--backdrop, .modal--close', function() { $(".modal").remove(); }); // Quick view bind $(".button-listing-quickview").click(function() { var dataIncrement = $(this).parents('.product-grid--item').attr('data-increment'); var $listingRequest = _self.overlay.ajaxOverlay({ url: '/ajax/ajax_listing.php', data: { category_listing_id: $(this).parents('.product-grid--item').attr('data-listing-category-id'), j: $(this).parents('.product-grid--item').attr('data-increment') } }); $listingRequest.success(function(data) { $("body").append(data); option_addevents('#listing_options_' + dataIncrement, dataIncrement); _self.form.select2($('select')); $(".modal").fadeIn(); }); }); this.onLoad(); this.onResize(); }, heightMatch: function() { // _self.common.heightMatch({ // matchByRow: true, // $gridElement: $('.product-grid--item'), // $matchElement: $('.product-info') // }); // _self.common.heightMatch({ // matchByRow: true, // $gridElement: $('.product-grid--item'), // $matchElement: $('.product--titles') // }); // _self.common.heightMatch({ // matchByRow: true, // $gridElement: $('.product-grid--item'), // $matchElement: $('.product-grid--item-inner') // }); }, onLoad: function() { var $this = this; var $shop = $('.shop'); $(window).on('load', function() { $this.customHeightMatch(); $this.heightMatch(); }); }, onResize: function() { var $this = this; var windowWidth = $(window).width(); $(window).on('resize', function() { if(windowWidth != $(window).width()) { windowWidth = $(window).width(); $this.heightMatch(); } }); window.addEventListener('resize', core.util.debounce(function() { $this.customHeightMatch(); $this.heightMatch(); }, 50)); }, customHeightMatch: function() { $('.product-grid--item').each(function() { if($(this).hasClass('prod_list')) { var $prodViewBtn = $(this).find('.product-view-btn'); if(Modernizr.mq('(min-width: 768px)')) { $prodViewBtn.css({minHeight: $(this).find('.product-usps').outerHeight()}); } else { $prodViewBtn.removeAttr('style'); } } // var brandElement = $(this).find('.product--brand'); // if(Modernizr.mq('(min-width: 1200px)')) { // $(this).find('.product-main').append(brandElement) // } else { // console.log(1); // $(this).find('.mobile-spares-cont').append(brandElement) // } var quickFindelement = $(this).find('.product--quickfind'); if(Modernizr.mq('(min-width: 1281px)')) { $(this).find('.product-price').append(quickFindelement) } else { if(Modernizr.mq('(min-width: 767px)')) { quickFindelement.insertBefore($(this).find('.product-view-btn')); } else { if(Modernizr.mq('(min-width: 571px)')) { $(this).find('.product-price').append(quickFindelement) } else { quickFindelement.insertBefore($(this).find('.product-view-btn')); } } } }); } } /* |-------------------------------------------------------------------------- | Feature Modules > Product List Sidebar |-------------------------------------------------------------------------- */ core.products.sidebar = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; this.initRangeSlider(); this.onLoad(); }, onLoad: function() { var $this = this; $(window).on('load', function() { if($("#slider-range").length > 0) { $this.initRangeSlider(); $("#slider-range").slider("values", [$this.data.slider.rangePriceLow, $this.data.slider.rangePriceHigh]); } }); }, initRangeSlider: function() { var $this = this; var $rangeSlider = $("#slider-range"); if($rangeSlider.length > 0) { $rangeSlider.slider({ range: true, min: $this.data.slider.min, max: $this.data.slider.max, values: $this.data.slider.values, slide: function(event, ui) { $this.updateRangeValues(ui); if(!$this.data.slider.rangeSubmitState) { $this.data.slider.rangeSubmitState = true; $("#price_filter").addClass("show-submit"); } if(ui.values[0] == ui.values[1]) { return false; } }, change: function(event, ui) { $this.updateRangeValues(ui); }, create: function(event, ui) { $this.updateRangeValues({values:[$this.data.slider.rangePriceLow, $this.data.slider.rangePriceHigh]}); }, }); } }, updateRangeValues: function(ui) { var $rangeSlider = $("#slider-range"); $("#range-tooltip-1").html("£"+ui.values[ 0 ]); $("#range-tooltip-2").html("£"+ui.values[ 1 ]).css({'left':'auto', 'right':'0'}); $("#price_0").val(ui.values[0]); $("#price_1").val(ui.values[1]); } } /* |-------------------------------------------------------------------------- | Feature Modules > Tooltip |-------------------------------------------------------------------------- */ core.tooltip = { tooltips: [], init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $("[data-tooltip]").each(function() { var action = $(this).attr('data-tooltip-action'); var location = $(this).attr('data-tooltip-location'); // Count tooltips for UID var len = $.map($this.tooltips, function(n, i) { return i; }).length; var uid = len + 1; $(this).attr('data-tooltip-id', uid); if(action === "hover") { $(this).on('mouseover', function(){ $this.show(uid); }); $(this).on('mouseout', function(){ $this.hide(uid); }); } $this.tooltips.push({ origin: $(this), tooltip: '' }); }); }, show: function(uid) { var $element = $("[data-tooltip-id='"+uid+"']"); var pos = $element.offset(); var dimensions = { height: $element.outerHeight(true), width: $element.outerWidth(true) }; var tooltipClasses = $element.attr("data-tooltip-class"); if($("#tooltip-"+uid).length) { var $tooltip = $("#tooltip-"+uid); } else { var $tooltip = $("
", {"id": 'tooltip-'+uid, "class": "core-tooltip "+tooltipClasses}).html($element.attr('data-tooltip-text')); $("body").append($tooltip); } var tooltipHeight = $tooltip.outerHeight(true); $tooltip.css({top: pos.top - $tooltip.outerHeight(true) - 20, left: (pos.left + (dimensions.width / 2))}); }, hide: function(uid) { $("#tooltip-"+uid).remove(); }, } /* |-------------------------------------------------------------------------- | Plugin Modules > Countdown |-------------------------------------------------------------------------- */ core.countdown = { timers: [], bindEventListeners: function() { }, create: function(params) { var $this = this; var interval = setInterval(function() { params.onTick($this.counter(params.to)); }, 1000); this.timers.push({interval: interval}); }, counter: function(date) { var futureDate = (parseInt(date) * 1000); var currentDate = new Date().getTime(); var timeDifference = futureDate - currentDate; if(futureDate > currentDate) { var _second = 1000; var _minute = _second * 60; var _hour = _minute * 60; var _day = _hour * 24; var days = Math.floor(timeDifference / _day); var hours = Math.floor((timeDifference % _day) / _hour); var minutes = Math.floor((timeDifference % _hour) / _minute); var seconds = Math.floor((timeDifference % _minute) / _second); return { days: days, hours: hours, minutes: minutes, seconds: seconds, } } }, render: { asString: function(time) { var string = ''; } } }; core.countdown_timer = { init: function(){ var $this = this; this.tick(); this.clearTimers(); this.timer = setInterval(function(){ $this.tick(); }, 1000); this.validation = setInterval(function(){ $this.validate_time(); }, 60000); }, clearTimers: function(){ clearInterval(this.timer); clearInterval(this.validation); }, tick: function(){ $_self = this; $('.countdown-timer').each(function(){ var $daysLeft = 0, $hoursLeft = 0, $minutesLeft = 0, $secondsLeft = 0; var $this = $(this); var $remaining = parseInt($this.data("timestamp")) - 1; $this.data("timestamp", $remaining); var $day = 86400,$hour = 3600,$minute = 60,$second = 1; var days = $this.find(".countdown-days"); var hours = $this.find(".countdown-hours"); var minutes = $this.find(".countdown-minutes"); var seconds = $this.find(".countdown-seconds"); var day = days.text(); var hour = hours.text(); var minute = minutes.text(); var second = seconds.text(); if(days.length > 0) $daysLeft = Math.floor($remaining / $day); if(hours.length > 0) $hoursLeft = Math.floor(($remaining - ($daysLeft * $day)) / $hour); if(minutes.length > 0) $minutesLeft = Math.floor(($remaining - ($daysLeft * $day) - ($hoursLeft * $hour)) / $minute); if(seconds.length > 0) $secondsLeft = Math.floor(($remaining - ($daysLeft * $day) - ($hoursLeft * $hour)) - ($minutesLeft * $minute)); $this.find('.countdown-timer--doughnut').removeClass('pulse-animation'); if(day != $daysLeft) days.parents('.countdown-timer--doughnut').addClass('pulse-animation'); if(hour != $hoursLeft) hours.parents('.countdown-timer--doughnut').addClass('pulse-animation'); if(minute != $minutesLeft) minutes.parents('.countdown-timer--doughnut').addClass('pulse-animation'); if(second != $secondsLeft) seconds.parents('.countdown-timer--doughnut').addClass('pulse-animation'); if($remaining >= 0){ days.html($daysLeft); days.parents('.countdown-timer--doughnut').find("circle").css({ 'stroke-dasharray' : 100 - (($daysLeft / 365) * 100) + ', 100' }); hours.html($hoursLeft); if($hoursLeft > 24) $hoursLeft = 24; hours.parents('.countdown-timer--doughnut').find("circle").css({ 'stroke-dasharray' : 100 - (($hoursLeft / 24) * 100) + ', 100' }); minutes.html($minutesLeft); if($minutesLeft > 60) $minutesLeft = 60; minutes.parents('.countdown-timer--doughnut').find("circle").css({ 'stroke-dasharray' : (100 - (($minutesLeft / 60) * 100)) + ', 100' }); seconds.html($secondsLeft); seconds.parents('.countdown-timer--doughnut').find("circle").css({ 'stroke-dasharray' : (100 - (($secondsLeft / 60) * 100)) + ', 100' }); }else{ $countdown = $this.parents(".dispatch_countdown"); if($countdown.length > 0){ $_self.dispatch_countdown($countdown); } } }); }, validate_time: function(){ var $this = this; var el = document.querySelectorAll(".countdown-timer"); var arr = []; for(var i = 0; i < el.length; i ++){ var t = el[i].getAttribute("data-time"); if(t !== null && arr.indexOf(t) == -1){ arr.push(t); } } $this.clearTimers(); $.get("/ajax/ajax_server_time.php", function(res){ for(var i in arr){ var remaining = (arr[i] - res); var original = $(".countdown-timer[data-time='"+arr[i]+"']").data("timestamp"); if((original - remaining) > 2){ $(".countdown-timer[data-time='"+arr[i]+"']").data("timestamp", remaining); } } $this.init(); }); }, dispatch_countdown: function(parent){ var $this = this; if(typeof parent !== "undefined"){ var dispatch = parent.find(".dispatch_date"); var delivery = parent.find(".delivery_date"); var timer = parent.find(".countdown-timer"); $.get("/ajax/ajax_dispatch_countdown.php?dispatch_format="+dispatch.data("format")+"&delivery_format="+delivery.data("format"), function(res){ var result = JSON.parse(res); dispatch.text(result.dispatch_date); delivery.text(result.delivery_date); timer.data("timestamp", result.remaining); timer.data("time", result.dispatch_date); $this.init(); }); } } } /* Messages Module */ core.message = { /** * Current message count * * @value int */ i: 1, /** * Scaffold the base message object * that gets extended when * creating a new message * * @value object */ defaultParams: { targetMode: 'prepend', type: 'info', slideUp: false, scrollTo: true, customClass: false, unique: true, closeable: true, }, /** * Create the message * */ create: function($target, params) { // Copy defaults without reference... this.options = $.extend(true, {}, core.message.defaultParams); // Merge params into defaults... $.extend(this.options, params); // Remove previous messages if unique message is required... if(this.options.unique) { $target.find('.message[data-generated-message]').remove(); } // Increment and set id... this.id = core.message.i++; // Grab html template... var $messageHTML = $("
", {"class": "message", "data-generated-message": "true"}); // Construct message... $messageHTML.attr('id', 'message-' + this.id) .html(this.options.message); // Add style class if found if(jQuery.inArray(params.type, ['success', 'error', 'info', 'warn']) !== -1) { $messageHTML.addClass('message-' + params.type); } // If the user is allowed to close the message... if(this.options.closeable) { $messageHTML.append($("
").html('x')); // Bind event listener... $messageHTML.find('.message-close').on('click', function() { $(this).parent('.message').remove(); }); } // If present, add custom class... if(this.options.customClass) { $messageHTML.addClass(this.options.customClass); } // Add markup to dom... if(this.options.targetMode == "prepend") { $($target).prepend($messageHTML); } else if(this.options.targetMode == "append") { $($target).append($messageHTML); } // If required, scroll to the message... if(this.options.scrollTo) { $('html, body').animate({ scrollTop: $messageHTML.offset().top }, 1000); } // If required, slide the message after x milliseconds... if(this.options.slideUp) { // Account for time scrolling to the message... slideUpTimeoutLength = (this.options.scrollTo) ? this.options.slideUp + 1000 : this.options.slideUp; setTimeout(function() { $messageHTML.slideUp(300, function() { $messageHTML.remove(); }) }, this.options.slideUp); } } } core.returns = { init: function() { this.bindEventListeners(); this.onLoad(); }, onLoad: function() { }, bindEventListeners: function() { var $this = this; $this.submitEvents(); $this.handleData(); const $current_container = $('#returns_finder'); const $back_button = $('#returns_back_button'); $('#get_return_orders_form').on('submit', function(e) { //first form - always there so no need to recall like others e.preventDefault(); const $form = $(this); const $update_container = $('#choose_return_form'); const email = $form.find('input[name="return_email"]').val(); const postcode = $form.find('input[name="return_postcode"]').val(); if(email && postcode) { $.ajax({ type: 'GET', url: '/ajax/ajax_returns.php?get_return_orders=true', data: { email: email, postcode: postcode }, dataType: 'html', success: function (results) { if(results && results.trim() !== '') { if(!$('.account').length) { //if in account don't show back button on order list $back_button.show(); $back_button.attr('data-back-id', $current_container.attr('id')); } $current_container.hide(); $update_container.empty(); $update_container.show(); $update_container.html(results); $this.submitEvents(); } else { $this.showFormError($form, 'No orders matched your query, please check your email address and postcode'); } } }); } else { $this.showFormError($form, 'No orders matched your query, please check your email address and postcode'); } }); $back_button.on('click', function() { const $target_element = $('#'+$back_button.attr('data-back-id')); if($target_element.prev().length) { $target_element.show(); $target_element.prevAll().hide(); $target_element.prevAll().empty(); if($target_element.next().length) { $back_button.attr('data-back-id',$target_element.next().attr('id')); } else { $back_button.hide(); } } }); }, handleData: function() { if(this.data.request_return_id != 0 && this.data.request_token != 0) { this.getReturn(this.data.request_return_id, this.data.request_token); } if(this.data.request_order_id != 0 && this.data.request_token != 0 && this.data.default_email && this.data.default_postcode) { this.startReturnOptions(this.data.request_order_id, this.data.request_token, this.data.default_email, this.data.default_postcode); } }, submitEvents: function () { var $this = this; const $back_button = $('#returns_back_button'); $('.return-order-submit').unbind('click').on('click', function(e) { e.preventDefault(); const $current_container = $('#choose_return_form'); const order_id = $(this).val(); const order_token = $('input[name="return_order_token_'+order_id+'"]').val(); const email = $current_container.find('input[name="email"]').val(); const postcode = $current_container.find('input[name="postcode"]').val(); if(order_id && order_token && email) { $this.startReturnOptions(order_id, order_token, email, postcode); } else { $this.showFormError($form, 'Sorry something went wrong, please try again or contact us.'); } }); $('#start_return_form').unbind('submit').on('submit', function(e) { //gets final result and pdf e.preventDefault(); let errorMessage = ""; if($this.validateReturn() === "reason-required") { errorMessage = 'You must specify your reason for the return'; } if($this.validateReturn() === false) { errorMessage = 'You must specify some notes for your return'; } if(errorMessage.length === 0 && !$('input[name="tc_check"]').is(':checked')) { errorMessage = 'Please agree to the terms and conditions to continue'; } const $form = $(this); const form_data = $form.serializeArray(); if(errorMessage) { e.preventDefault(); $('#form_error_1').html(errorMessage); $('#form_error_1').stop().slideDown(); } else { $('#form_error_1').stop().slideUp(); $.ajax({ type: 'POST', url: '/ajax/ajax_returns.php?start_return=true', data: form_data, success: function (return_data) { var json_data = JSON.parse(return_data); if(json_data && json_data.return_id && json_data.token) { $this.getReturn(json_data.return_id, json_data.token); } else { $this.showFormError($form, 'Sorry something went wrong, please try again or contact us.' + (json_data.errors ? json_data.errors.join("\n") : [])); } } }); } }); $('.view-return').unbind('click').on('click', function() { //gets list of items to return within order const return_id = $(this).attr('data-return-id'); const token = $(this).attr('data-token'); if(return_id && return_id !== '' && token && token !== '') { $this.getReturn(return_id, token); } }); $("select[name*='return_reason_id']").on("change", function() { let description = $(this).children("option:selected").attr("description"); let order_line_id = $(this).attr("name").split("start_return_line[")[1].split("]")[0]; if(!description) { $("#return_inputs_" + order_line_id + "_reason_description").hide(); } else { $("#return_inputs_" + order_line_id + "_reason_description").html(atob(description)) $("#return_inputs_" + order_line_id + "_reason_description").show(); } $("[order-line-id='" + order_line_id + "'][return-reason-questions]").hide(); $("[order-line-id='" + order_line_id + "'][return-reason-questions='" + $(this).val() + "']").show(); }); // function getReturnResults(return_id, token) { // $.ajax({ // type: 'GET', // url: '/ajax/ajax_returns.php?get_return_results=true', // data: { // return_id: return_id, // token: token // }, // dataType: 'html', // success: function (results) { // if(!$($.parseHTML(results)).filter('.message-error-ajax').length) { // $('#start_return_container').hide(); // $back_button.show(); // $back_button.attr('data-back-id', 'choose_return_form'); // } // $('#return_results').empty(); // $('#return_results').show(); // $('#return_results').html(results); // } // }); // } }, startReturnOptions: function(order_id, order_token, email, postcode) { var $this = this; const $current_container = $('#choose_return_form'); const $update_container = $('#start_return_container'); $.ajax({ type: 'POST', url: '/ajax/ajax_returns.php?start_return_options=true', data: { order_id: order_id, token: order_token, email: email, postcode: postcode }, dataType: 'html', success: function (results) { if(results && results !== '') { if(!$($.parseHTML(results)).filter('.message-error-ajax').length) { $current_container.hide(); // $back_button.show(); // $back_button.attr('data-back-id', $current_container.attr('id')); } $update_container.empty(); $update_container.show(); $update_container.html(results); $('.return-inputs select').each(function() { $(this).select2(); }); $this.submitEvents(); $this.returnChecks(); } else { $this.showFormError($form, 'Sorry something went wrong, please try again or contact us.'); } } }); }, getReturn: function(return_id, token) { $.ajax({ type: 'GET', url: '/ajax/ajax_returns.php?get_return_results=true', data: { return_id: return_id, token: token }, dataType: 'html', success: function (results) { if(!$($.parseHTML(results)).filter('.message-error-ajax').length) { $('#start_return_container').hide(); // $back_button.show(); // $back_button.attr('data-back-id', 'choose_return_form'); } $('#return_results').empty(); $('#return_results').show(); $('#return_results').html(results); } }); }, validateReturn: function (event) { // Check if the return reason requires notes and that we have notes let ret = true; $("option[requires-notes]").each(function() { var input_group = $(this).parents('.return-inputs'); if(input_group.is(':visible') && $(this).parent().val() == $(this).val()) { if($("[name='" + $(this).parent().attr("name").replace("return_reason_id", "notes_customer") + "']").val().trim().length === 0) { ret = false; } } }); $("option[reason-required]").each(function() { var input_group = $(this).parents('.return-inputs'); if(input_group.is(':visible') && $(this).parent().val() == $(this).val()) { ret = "reason-required"; } }); return ret; }, returnChecks: function () { $('.return-check').unbind('click').on('click', function() { core.form.checkboxController('toggle', $(this)); var o_line_check = $(this).find('input'); var o_line = o_line_check.attr('name').replace('return_check_',''); if(o_line_check.is(":checked")) { $('#return_inputs_'+o_line).show(); } else { $('#return_inputs_'+o_line).hide(); $('#start_return_line_'+o_line).select2("val", "0"); } }); $('.tc-check').on('click', function() { core.form.checkboxController('toggle', $(this)); if($('input[name="tc_check"]').is(':checked')) { $('#form_error_1').stop().slideUp(); } }); }, updateBackButton: function() { }, showFormError: function ($form, error) { if($form && error) { if($form.find('.error-js').length) { $form.find('.error-js').html(error); } else { $form.prepend('
'+error+'
'); } $form.find('.msg-js').stop().slideDown(); } }, } core.account = { init: function() {} } core.account.login = { init: function() { this.bindEventListeners(); this.onLoad(); if (core.account.login.data.error != 1 && this.data.showTrade === false) { core.account.login.hideNewBlock(); } core.account.login.toggleTradeBlock(); }, onLoad: function() { var $this = this; $(window).on('load', function(e) { if($this.data.showTrade) { $('html,body').animate({ scrollTop:$('.account-login--block__new').offset().top - 50 }, 1200); } if($this.data.showNewAccount) { $('#submit_signup').trigger('click'); $('html,body').animate({ scrollTop:$('.account-login--block__new').offset().top - 50 }, 1200); } }); }, bindEventListeners: function() { $('#form1').on('submit', function (e) { if (!core.account.login.validateLoginForm()) { e.preventDefault(); } }); $('#newacc').on('submit', function (e) { if (!core.account.login.validateNewAccount()) { e.preventDefault(); } }); $('#button-password').on('click', function (e) { e.preventDefault(); var $this = $(this); var $input = $this.parent().find('input'); if ($input.attr('type') == 'password') { $input.attr('type', 'text'); $this.text('hide'); } else { $input.attr('type', 'password'); $this.text('show'); } }); $('.checkbox').each(function() { var $parent = $(this).parent(); $parent.on('click', function() { if ($parent.find('input').attr('name') === "trade_acc") { _self.form.checkboxController('toggle', $(this), function() { core.account.login.toggleTradeBlock(); }); } else { _self.form.checkboxController('toggle', $(this)); } }) }); }, hideNewBlock: function () { $('#account-box-new').hide(); }, toggleTradeBlock: function () { var checked = $('#trade_acc').is(':checked'); $('#account-box-trade').toggle(checked); }, validateLoginForm: function () { var email = $('#email').val(); var password = $('#password').val(); if (!email || !password) { core.message.create($('#form1'), { type: 'error', message: 'Please enter both your email address and password.', closeable: false, scrollToOffset: 160 }) return false; } return true; }, validateNewAccount: function () { // Show the form if it's not visible var $newAccount = $('#account-box-new'); if (!$newAccount.is(':visible')) { $newAccount.show(); return false; } // Validate var error = false; var emailError = false; var passwordError = false; var $section = $('.account-login--block__new'); var $contact_name = $('#contact_name'); var $last_name = $('#last_name'); var $email = $('#acc_email'); var $password = $('#login_password'); var $company_name = $('#company_name'); var $company_reg = $('#company_reg'); var $area_of_business = $('#area_of_business'); $section.find('.message').remove(); $section.find('.validate-border').removeClass('validate-border'); if (!$contact_name.val()) { $contact_name.addClass('validate-border'); error = true; } if (!$last_name.val()) { $last_name.addClass('validate-border'); error = true; } if (!$email.val()) { $email.addClass('validate-border'); error = true; } else if ($email.val().indexOf('@') == -1 || $email.val().indexOf('.') == -1) { $email.addClass('validate-border'); emailError = true; } if (!$password.val()) { $password.addClass('validate-border'); error = true; } else if ($password.val().length < 6) { $password.addClass('validate-border'); passwordError = true; } if ($('#trade_acc').is(':checked')) { if (!$company_name.val()) { $company_name.addClass('validate-border'); error = true; } if (!$company_reg.val()) { $company_reg.addClass('validate-border'); error = true; } if (!$area_of_business.val()) { $area_of_business.addClass('validate-border'); error = true; } } if (error || emailError || passwordError) { var messages = []; if (error) { messages.push('Please fill in all required fields (*).'); } if (emailError && passwordError) { messages.push('You must enter a valid email address and your password must contain at least 6 characters.'); } else if (emailError) { messages.push('Please enter a valid email address.'); } else if (passwordError) { messages.push('Your password must contain at least 6 characters.'); } core.message.create($('#newacc'), { type: 'error', message: messages.join(' '), closeable: false, scrollToOffset: 160 }); return false; } return true; } } core.account.orders = { init: function() { $("#fromDate").datepicker({ dateFormat: 'dd/mm/yy' }); $("#toDate").datepicker({ dateFormat: 'dd/mm/yy', minDate: new Date() }); this.bindEventListeners(); }, bindEventListeners: function() { $('.checkbox').each(function(){ $(this).parent().on('click', function () { _self.form.checkboxController('toggle', $(this)); }) }); var $this = this; var timeout = null; let $searchBox = $('.account-main-filter'); $searchBox.keyup(function(e) { if(timeout) { clearTimeout(timeout); } timeout = setTimeout(function() { timeout = null; $this.requestOrders(); }, 300); }); $(".order-history-filters #fromDate").on('change', function(){ $this.orderDates(); $this.requestOrders(); }); $(".order-history-filters #toDate").on('change', function(){ $this.orderDates(); $this.requestOrders(); }); $(".order-history-filters #accountID").on('change', function(){ $this.requestOrders(); }); }, orderDates: function() { let fromVal = $("#fromDate").val(); let fromParts = fromVal.split("/"); let date1 = new Date(parseInt(fromParts[2], 10), parseInt(fromParts[1], 10) - 1, parseInt(fromParts[0], 10)); let toVal = $("#toDate").val(); let toParts = toVal.split("/"); let date2 = new Date(parseInt(toParts[2], 10), parseInt(toParts[1], 10) - 1, parseInt(toParts[0], 10)); if(date1 > date2) { $("#toDate").val(fromVal); } $("#toDate").datepicker("destroy").datepicker({ dateFormat: 'dd/mm/yy', minDate: new Date(date1) }); }, requestOrders: function() { let account = $('#accountID').val(); let from = $('#fromDate').val(); let to = $('#toDate').val(); let search = $('.account-search-input input.order-history--search').val(); let params = 'cid=' + account + '&d1=' + from + '&d2=' + to + '&search=' + search; $.ajax({ type: "get", url: "/ajax/account_orders.php?" + params, error: function(error) { if(typeof callbackError == "function") { callbackError(error); } console.error(error); }, success: function(response) { if(typeof callback == "function") { callback(response); } $("#order-history-table-container").html(response); } }); } } core.account.order = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { this.onLoad(); this.onResize(); }, onLoad: function() { var $this = this; $(window).on('load', function(e) { $this.heightMatch(); }); }, onResize: function() { var $this = this; $(window).on('resize', function(e) { $this.heightMatch(); }); }, heightMatch: function() { _self.common.heightMatch({ matchByRow: true, $gridElement: $('.order-panel'), $matchElement: $('.order-panel--inner') }); } } core.account.invoices = { init: function() { $("#fromDate").datepicker({ dateFormat: 'dd/mm/yy' }); $("#toDate").datepicker({ dateFormat: 'dd/mm/yy', minDate: new Date() }); this.bindEventListeners(); this.togglePayInvoices(); }, bindEventListeners: function() { var $this = this; $('.account-table-invoices--outstanding [type="checkbox"]').on('change', $this.togglePayInvoices); $('.account-table-invoices--overdue [type="checkbox"]').on('change', $this.togglePayInvoices); }, togglePayInvoices: function () { var $this = $(this); var $invoices = $('.account-table-invoices--outstanding [type="checkbox"]').not('#invoice_all'); if ($this.attr('id') == 'invoice_all') { $invoices.prop('checked', $this.is(':checked')); } var total = $invoices.length; var checked = $invoices.filter(':checked').length; var value = 'Pay ' + (checked > 1 ? checked + ' ' : '') + 'Invoice' + (checked > 1 ? 's' : ''); $('.pay_invoices').val(value).prop('disabled', checked == 0); $('#invoice_all').prop('checked', checked == total); var $invoices_overdue = $('.account-table-invoices--overdue [type="checkbox"]').not('#invoice_all_overdue'); if ($this.attr('id') == 'invoice_all_overdue') { $invoices_overdue.prop('checked', $this.is(':checked')); } var total_overdue = $invoices_overdue.length; var checked_overdue = $invoices_overdue.filter(':checked').length; var value_overdue = 'Pay ' + (checked_overdue > 1 ? checked_overdue + ' ' : '') + 'Invoice' + (checked_overdue > 1 ? 's' : ''); $('.pay_invoices_overdue').val(value_overdue).prop('disabled', checked_overdue == 0); $('#invoice_all_overdue').prop('checked', checked_overdue == total_overdue); } } core.account.quotes = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.account-main-filter').on('keyup', function() { var term = $(this).val(); var terms = term.split(' '); $('.dblr:not(:first-child)').each(function() { $(this).show(); var match = false; $(this).find('.dblc').each(function() { for (var i = 0; i < terms.length; i++) { if($(this).html().indexOf(terms[i]) !== -1) { match = 1; } } }); if(!match) { $(this).hide(); } }) }); } } core.account.quote = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { this.onLoad(); this.onResize(); }, onLoad: function() { var $this = this; $(window).on('load', function(e) { $this.heightMatch(); }); }, onResize: function() { var $this = this; $(window).on('resize', function(e) { $this.heightMatch(); }); }, heightMatch: function() { _self.common.heightMatch({ matchByRow: true, $gridElement: $('.order-panel'), $matchElement: $('.order-panel--inner') }); } } core.account.details = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.checkbox').each(function(){ $(this).parent().on('click', function () { _self.form.checkboxController('toggle', $(this)); }) }); $('.button-update-logo, .account-table--image').on('click', function(e) { e.preventDefault(); $('.hidden-file-input').click(); }); $('.hidden-file-input').on('change', function() { $(this).parents('form').submit(); }); $('.account-details--right form').on('submit', function (e) { if (!core.account.details.validateDetailsForm()) { e.preventDefault(); } }); $('[data-modal]').on('click', function (e) { e.preventDefault(); var modal = $(this).data('modal'); if (modal && $.inArray(modal, ['contact_details', 'trade_details', 'change_password']) !== -1) { var $createOverlay = core.overlay.ajaxOverlay({ url: '/olay/account_' + modal + '.php', data: {} }); $createOverlay.done(function (data) { $('main').append(data); var $modal = $('.modal'); $modal.find('button').focus(); $modal.on('submit', 'form', function (e) { var valid = false; if (modal == 'trade_details') { valid = core.account.details.validateTradeDetailsForm(); } else if(modal == 'change_password') { valid = core.account.details.validatePasswordForm(); } else { valid = core.account.details.validateContactDetailsForm(); } if (!valid) { e.preventDefault(); } }); $modal.on('click', '.modal--backdrop, .modal--close', function () { $modal.remove(); }); }); } }); }, validateDetailsForm: function() { var error = []; var html = ''; var $section = $('.account-details--right'); var $errorCont = $section.find('.error-cont'); var $email = $('#eml'); var $password = $('#newpass'); $errorCont.html(''); $section.find('.validate-border').removeClass('validate-border'); if ($email.val().indexOf('@') == -1 || $email.val().indexOf('.') == -1) { $email.addClass('validate-border'); error.push('Please enter a valid email address'); } if ($password.val() && $password.val().length < 6) { $password.addClass('validate-border'); error.push('Your password must contain at least 6 characters'); } if (error.length == 0) { return true; } for (var i = 0, l = error.length; i < l; i++) { html += '
' + error[i] + '
'; } $errorCont.html(html); $errorCont.find('.message-error').hide().slideDown(); return false; }, validateContactDetailsForm: function() { var error = false; var $modal = $('.account-modal--contact'); var $errorCont = $modal.find('.error-cont'); var $firstName = $('#details_name'); var $lastName = $('#details_surname'); var $email = $('#details_email'); $errorCont.html(''); $modal.find('.validate-border').removeClass('validate-border'); if (!$firstName.val()) { $firstName.addClass('validate-border'); error = true; } if (!$lastName.val()) { $lastName.addClass('validate-border'); error = true; } if(!$email.val()) { $email.addClass('validate-border'); error = true; } if (!error) { return true; } var html = '
Please fill in all required fields (*).
'; $errorCont.html(html); $errorCont.find('.message-error').hide().slideDown(); return false; }, validateTradeDetailsForm: function() { var error = false; var $modal = $('.account-modal--trade'); var $errorCont = $modal.find('.error-cont'); var $companyName = $('#details_company'); $errorCont.html(''); $modal.find('.validate-border').removeClass('validate-border'); if (!$companyName.val()) { $companyName.addClass('validate-border'); error = true; } if (!error) { return true; } var html = '
Please fill in all required fields (*).
'; $errorCont.html(html); $errorCont.find('.message-error').hide().slideDown(); return false; }, validatePasswordForm: function() { var error = false; var $modal = $('.account-modal--password'); var $errorCont = $modal.find('.error-cont'); var pass_old = $('#password_old').val(); var pass = $('#password_new').val(); var pass1 = $('#password_new_confirm').val(); if(!pass || !pass1 || !pass_old) { error = "Please fill in all required fields (*)."; } else if(pass !== pass1) { error = "Passwords must match."; } else if(pass.length < 6) { error = "Password must be at least 6 characters."; } console.log(pass); console.log(pass1); console.log(pass_old); console.log(error); if(error) { var html = '
'+error+'
'; $errorCont.html(html); $errorCont.find('.message-error').hide().slideDown(); return false; } else { return true; } } } core.account.addressBook = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { this.onLoad(); this.onResize(); $('.address-block--add, [data-address]').on('click', function(e) { e.preventDefault(); var data = {}; var id = $(this).data('address'); if (id) { data.id = id; } var $createOverlay = core.overlay.ajaxOverlay({ url: '/olay/account_address_book.php', data: data }); $createOverlay.done(function(data) { $('main').append(data); var $modal = $('.modal'); core.form.select2($modal.find('select')); $modal.find('.checkbox').each(function(){ $(this).parent().on('click', function () { if (!$(this).hasClass('disabled')) { _self.form.checkboxController('toggle', $(this)); } }) }); $('#new_add_8').on('change', function () { var $county = $('#new_add_6').parent(); var $state = $('#new_add_6_state').parent(); var $postcodeLbl = $('#new_add_7').parent().find('label'); var $required = $('#new_add_state_required'); if ($(this).find('option:selected').data('group') == 2) { $required.val(1); $postcodeLbl.text('Zip Code*'); $county.hide(); $state.show(); } else { $required.val(0); $postcodeLbl.text('Postcode*'); $county.show(); $state.hide(); } }); $modal.find('button').focus(); $modal.on('submit', 'form', function (e) { if (!core.account.addressBook.validateAddressForm()) { e.preventDefault(); } }); $modal.on('click', '.modal--backdrop, .modal--close', function() { $modal.remove(); }); }); }); }, onLoad: function() { var $this = this; $(window).on('load', function(e) { $this.heightMatch(); }); }, onResize: function() { var $this = this; $(window).on('resize', function(e) { $this.heightMatch(); }); }, heightMatch: function() { _self.common.heightMatch({ matchByRow: true, $gridElement: $('.address-block'), $matchElement: $('.address-block--title') }); _self.common.heightMatch({ matchByRow: true, $gridElement: $('.address-block'), $matchElement: $('.address-block--address') }); _self.common.heightMatch({ matchByRow: true, $gridElement: $('.address-block'), $matchElement: $('.address-block--action') }); $('.address-block--add-inner').css('height', $('#savedAddresses .address-block--inner').outerHeight(true)); }, validateAddressForm: function() { var error = false; var $modal = $('.account-modal--address-book'); var $errorCont = $modal.find('.error-cont'); var $name = $('#new_add_1'); var $house = $('#new_add_2'); var $state = $('#new_add_6_state'); var $postcode = $('#new_add_7'); var required = $('#new_add_state_required'); $errorCont.html(''); $modal.find('.validate-border').removeClass('validate-border'); if (!$name.val()) { $name.addClass('validate-border'); error = true; } if (!$house.val()) { $house.addClass('validate-border'); error = true; } if (required.length && !$state.val()) { $state.parent().find('.select2-selection').addClass('validate-border'); error = true; } if (!$postcode.val()) { $postcode.addClass('validate-border'); error = true; } if (!error) { return true; } var html = '
Please fill in all required fields (*).
'; $errorCont.html(html); $errorCont.find('.message-error').hide().slideDown(); return false; } } core.account.wishlists = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('#create-new-wishlist-button').click(function(){ var $createWishlistOverlay = core.overlay.ajaxOverlay({ url: '/olay/account_basket_create.php' }); $createWishlistOverlay.done(function(data) { $('body').append(data); var $olay = $("#account-cart-create"); $olay.addClass("open"); $olay.find("form").submit(function(e) { core.form.validateForm($(this), function(failedInputs) { if(failedInputs.length > 0) { e.preventDefault(); } }); }); $olay.on('click', '.overlay--backdrop, .overlay--close', function () { $olay.remove(); }); }); }); $('.wishlist-del').click(function () { var basketId = $(this).closest('.wishlist').data('id'); var yesno = confirm('Are you sure you want to delete this wishlist?'); if(yesno){ $('#cart_del').val(basketId); $('#del_form').submit(); } }); } } core.account.wishlist = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.wishlist-edit span').click(function(){ var basketId = $('#basket_id').val(); var $editWishlistOverlay = core.overlay.ajaxOverlay({ url: '/olay/account_basket_edit.php', data: { cid: basketId } }); $editWishlistOverlay.done(function (data) { $('body').append(data); var $olay = $("#account-cart-edit"); $olay.addClass("open"); $olay.find("form").submit(function(e) { core.form.validateForm($(this), function(failedInputs) { if(failedInputs.length > 0) { e.preventDefault(); } }); }); $olay.on('click', '.overlay--backdrop, .overlay--close', function () { $olay.remove(); }); }); }); $('.wishlist-prod-move-button span').click(function () { var basketId = $('#basket_id').val(); var itemtId = $(this).closest('.wishlist-prod').data('id'); var $chooseWishlistOverlay = core.overlay.ajaxOverlay({ url: '/olay/account_basket_choose.php', data: { cid: basketId } }); $chooseWishlistOverlay.done(function (data) { $('body').append(data); var $olay = $("#account-cart-choose"); $olay.addClass("open"); $olay.find(".overlay--close").click(function() { $olay.remove(); }); $('.wishlist-choose').click(function () { var cart_secid = $(this).data('secid'); var cart_authid = $(this).data('authid');; core.wishlist.request({ move: itemtId, cart_secid: cart_secid, cart_authid: cart_authid }, function () { $olay.remove(); if (core.wishlist.response.status == 'error') { var error = core.wishlist.response.message || 'An error occured, please try again later'; core.wishlist.flashMessage('error', error); } else { core.wishlist.redirect(cart_secid, cart_authid); } }); }); }); }); $('.wishlist-prod-del-button span').click(function () { var itemtId = $(this).closest('.wishlist-prod').data('id'); $('#wl_del').val(itemtId); $('#form_wl').attr('action', ''); $('#form_wl').submit(); }); } } core.accountSidebar = { _: { $element: { list: $('.account-sidebar ul.list-reset') } }, init: function() { this.bindEventListeners(); }, bindEventListeners: function() { this.onResize(); $('.account-sidebar--mobile-title').on('click', function() { $(this).toggleClass('open'); }); }, onResize: function() { var $this = this; $(window).resize(function() { if(Modernizr.mq('(max-width: 900px)')) { $this._.$element.list.show(); } }); } } core.account.xvc = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $modal = $('.modal'); $('.account-voucher--remove').on('click', function(e) { $modal.show(); }); $('.modal--close, .modal--backdrop, .account-voucher--cancel').on("click", function() { $modal.hide(); }); } } core.xvc = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $('.voucher_add, #voucher_add').on('click', function(e) { e.preventDefault(); var btn = this; var input_default = $(btn).data('voucher-entry'); var input_override = $(btn).data('voucher-entry-override'); var entry; if($(input_override).is(':visible')){ entry = input_override; } else { entry = input_default; } var code = $(entry).val(); if(code && code != -1){ btn.disabled = true; $this.request('basket_add', code, function(data) { if(data.response.skipped) { // error $this.message(2, data.response.message); } else { // success $this.message(1, data.response.message); $this.vouchers.remove(); $(entry).val(''); var length = $this.vouchers.count(data.vouchers); if(length > 0){ $this.draw(data.vouchers); } $this.drawSidebarTotals(data.totals); } }, function(data){ }, function(){ btn.disabled = false; }); } }); $('#voucher_container').on('click', '[data-voucher-remove]', function(e){ e.preventDefault(); var btn = this; var code = $(this).data('voucher-remove'); btn.disabled = true; $this.request('basket_remove', code, function(data){ $this.vouchers.remove(); var length = $this.vouchers.count(data.vouchers); if(length > 0){ $this.draw(data.vouchers); } $this.drawSidebarTotals(data.totals); }, function(){ }, function(){ }); }); $('#voucher-entry-linked').on('change', function(){ var $this = $(this); var show_blank = $this.data('voucher-show-blank'); if($this.val() == 0){ $(show_blank).parent().show(); } else { $(show_blank).parent().hide(); } //core.checkout.checkoutSideAdjust(); }); }, draw: function(vouchers) { var $this = this; console.log(vouchers); var container = document.getElementById('voucher_container'); var vouchersCont = document.createElement('div'); vouchersCont.className = 'vouchers dbl account-table'; var temp = document.createElement('div'); temp.className = 'voucher dblr cf'; temp.innerHTML = '
Voucher
Balance
Payment
 
'; vouchersCont.appendChild(temp); for(var key in vouchers){ if(vouchers.hasOwnProperty(key)){ var voucher = document.createElement('div'); voucher.className = 'voucher dblr cf'; var voucher_display = document.createElement('div'); voucher_display.className = 'voucher_display dblc'; voucher_display.innerHTML = "Voucher: " + vouchers[key].response.display; var voucher_balance = document.createElement('div'); voucher_balance.className = 'voucher_balance dblc'; voucher_balance.innerHTML = "Balance: " + '£' + core.util.parsePrice(vouchers[key].response.balance_available); // voucher_balance.innerHTML = 'Balance: £' + core.util.parsePrice(vouchers[key].response.balance_available); var voucher_payment = document.createElement('div'); voucher_payment.className = 'voucher_payment dblc'; voucher_payment.innerHTML = "Payment: " + '£' + core.util.parsePrice(vouchers[key].response.payment_amount); // voucher_payment.innerHTML = 'Payment: £' + core.util.parsePrice(vouchers[key].response.payment_amount); voucher.appendChild(voucher_display); voucher.appendChild(voucher_balance); voucher.appendChild(voucher_payment); var dblc = $(voucher).append('
'); vouchersCont.appendChild(voucher); container.appendChild(vouchersCont); } } //core.checkout.checkoutSideAdjust(); }, drawSidebarTotals: function(totals){ var sel = $('.payment-method.open .payment-method--button'); if (core.braintree.initialized) { core.braintree.total = (totals.total_pay_today > 0) ? totals.total_pay_today : totals.total_pay; } if(totals.xvc > 0){ $('.voucher-total .cart-total--price').html('-£' + core.util.parsePrice(totals.xvc)); $('.voucher-total-pay .cart-total--price').html('£' + core.util.parsePrice(totals.total_pay)); $('.deposit-total-pay .cart-total--price').html('£' + core.util.parsePrice(totals.total_pay_today)); $('.voucher-sidebar').show(); if ($('.checkout-payment-methods')[0]) { if(totals.total_pay == 0){ $('#payment').val(8); $('.checkout-payment-methods').hide(); core.checkout.confirm.unlockForm(); }else{ if (sel.length > 0) { $('#payment').val(sel.data("payment-method")); } else { $('#payment').val(0); $('#checkout-continue').prop('disabled', true); } $('.checkout-payment-methods').show(); } } } else { $('.voucher-sidebar').hide(); $('.voucher-total .cart-total--price').html('-£' + core.util.parsePrice(totals.xvc)); $('.voucher-total-pay .cart-total--price').html('£' + core.util.parsePrice(totals.total_pay)); $('.deposit-total-pay .cart-total--price').html('£' + core.util.parsePrice(totals.total_pay_today)); if ($('.checkout-payment-methods')[0]) { if (sel.length > 0) { $('#payment').val(sel.data("payment-method")); } else { $('#payment').val(0); $('#checkout-continue').prop('disabled', true); } $('.checkout-payment-methods').show(); } } if (core.klarna.initialized) { core.klarna.loadCategories(totals.klarna); } if (totals.total_pay_today > 0) { $('.deposit-total-pay').show(); } else { $('.deposit-total-pay').hide(); } //core.checkout.checkoutSideAdjust(); }, request: function(request, code, onsuccess, onerror, oncomplete) { $.ajax({ data: { request: request, code: code, invoices: $("input[name='invoice[]']").toArray().map((input) => input.value) }, dataType: 'json', method: 'POST', url: '/ajax/ajax_voucher.php', success: onsuccess, error: onerror, complete: oncomplete }); }, updatePricing: function() { }, vouchers: { count: function(vouchers) { var length = 0; for(var key in vouchers) { if(vouchers.hasOwnProperty(key)){ length++; } } (length == 0) ? $('.vouchers-wrapper').hide() : $('.vouchers-wrapper').show(); return length; }, remove: function() { document.getElementById('voucher_container').innerHTML = ''; }, }, message: function(type, msg) { if(!msg) { return false; } var className = (type == 1) ? 'message-success' : 'message-error'; $('#xvc-message').remove(); $('#xvc-error-cont').append('
'+msg+'
'); //core.checkout.checkoutSideAdjust(); }, } core.importantBlock = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.important-block--title').click(function() { $(this).toggleClass('active'); }); } } core.downloads = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.download-section--title').click(function() { $(this).toggleClass('active'); }); } } core.gallery = { init: function() { this.onReady(); }, onReady: function() { var that = this; $(document).ready(function() { $('.gallery-page--images').magnificPopup({ delegate: 'a', // child items selector, by clicking on it popup will open type: 'image', gallery:{enabled:true}, image: { titleSrc: function(item) { return that.data.titles[item.el.attr('data-id')]; } // this tells the script which attribute has your caption } }); }); } } core.sendImage = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; var parent = $('#imageUpload').parent(); var fileUpload = parent.find('input[type="file"]'); $('#imageUpload').on('click', function() { fileUpload.click(); }); fileUpload.on('change', function() { if($(this).val() != "") { parent.find('.input-file-dummy').html($(this).val().split(/(\\|\/)/g).pop()); } else { parent.find('.input-file-dummy').html("(optional - must be JPG, PNG or GIF format)"); } }); $('.image-form').on('submit', function(e) { _self.form.validateForm($(this), function(failedInputs) { $('.input-file').removeClass('validate-border'); if($('#imageUploadInput').val() == "") { $('.input-file').addClass('validate-border'); e.preventDefault(); } if(failedInputs.length > 0) { e.preventDefault(); } }); }); }, } core.tradesmen = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { this.onLoad(); }, onLoad: function() { var $this = this; $(window).on('load', function() { $this.manageOverflows(); }); }, manageOverflows: function() { var $this = this; $('.tradesman').each(function() { $this.constrainElement($(this)); }); $('.tradesman--more-info--btn').click(function() { var closeText = 'More Information'; var openText = 'Less Information'; var $tradesman = $(this).parents('.tradesman'); var $tradesmanTextEl = $tradesman.find('.tradesman--text'); if($(this).html() == closeText) { $(this).html(openText); $tradesmanTextEl.removeAttr('style'); } else { $this.constrainElement($tradesman); } }); }, constrainElement: function($element) { var maxHeight = 60; var $tradesmanTextEl = $element.find('.tradesman--text'); var closeText = 'More Information'; var openText = 'Less Information'; if($tradesmanTextEl.outerHeight() > maxHeight) { $tradesmanTextEl.css({ height: 60, overflow: 'hidden' }); $element.find('.tradesman--more-info').removeClass('hidden'); $element.find('.tradesman--more-info--btn').html(closeText); } else { $element.find('.tradesman--more-info').addClass('hidden'); $element.find('.tradesman--more-info--btn').html(openText); } } } core.tradesmenMap = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $('.tradesman-input--form').on('submit', function(e) { var $that = $(this); e.preventDefault(); var postcode = $('.tradesman-input--input').val(); $(this).addClass('loading'); $this.data.geocoder.geocode({"address": postcode}, function(results, status) { $that.removeClass('loading'); if(status != google.maps.GeocoderStatus.OK) { alert("nope") } var lowestDistance = 999999; var lowestDistanceKey = null; for (var i = 0; i < $this.data.tradesmenLocations.length; i++) { // if this location is within 0.1KM of the user, add it to the list var distance = $this.calculateDistance( results[0].geometry.location.lat(), results[0].geometry.location.lng(), $this.data.tradesmenLocations[i].position.lat(), $this.data.tradesmenLocations[i].position.lng(), "K"); if(distance < lowestDistance ) { lowestDistance = distance; lowestDistanceKey = $this.data.tradesmenLocations[i].key } } $('.tradesman').removeClass('highlight'); $('.tradesman[data-key="'+lowestDistanceKey+'"]').addClass('highlight'); $('html,body').animate({ scrollTop:$('.tradesman[data-key="'+lowestDistanceKey+'"]').offset().top - 50 }, 1200); }); }); }, calculateDistance: function(lat1, lon1, lat2, lon2, unit) { var radlat1 = Math.PI * lat1/180 var radlat2 = Math.PI * lat2/180 var theta = lon1-lon2 var radtheta = Math.PI * theta/180 var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta); if (dist > 1) { dist = 1; } dist = Math.acos(dist) dist = dist * 180/Math.PI dist = dist * 60 * 1.1515 if (unit=="K") { dist = dist * 1.609344 } if (unit=="N") { dist = dist * 0.8684 } return dist; } } core.orderTracking = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.order-tracking-form').on('submit', function(e) { _self.form.validateForm($(this), function(failedInputs) { if(failedInputs.length > 0) { e.preventDefault(); } }); }) } } core.testimonials = { init: function() { this.onLoad(); }, onLoad: function() { var $this = this; $(window).on('load', function() { $('.testimonial-blocks').masonry({ // set itemSelector so .grid-sizer is not used in layout columnWidth: '.testimonial', itemSelector: '.testimonial', percentPosition: true }); }); }, } core.filters = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { var $this = this; $('.filter-overflow-button').unbind("click").click(function() { var $overflow = $(this).parent().find('.filter-overflow'); $overflow.toggleClass('active'); if($overflow.hasClass('active')) { $(this).html('SHOW LESS') } else { $(this).html('SHOW ALL') } }); }, } core.powerFilter = { _: { originalState: '' }, init: function() { this.onLoad(); }, onLoad: function() { var $this = this; }, } core.powerFilterTooltip = { init: function() { this.onLoad(); }, onLoad: function() { var $this = this; $(window).on('load', function() { $('.power-filter-tooltip').delay(1600).fadeOut(300, function() { $('.power-filter-tooltip--backdrop').fadeOut(300); }); }); }, } core.diagram = { init: function() { this.onLoad(); }, onLoad: function() { var $this = this; $(window).on('load', function() { $this.bindEventListeners(); // $this.generateHotspots(); }); }, bindEventListeners: function() { var $this = this; $(document).on('mouseover touchstart', '.diagram--hotspot', function() { $this.handleHotspotClickEvent($(this)); }); $(document).on('mouseleave', '.diagram--hotspot', function() { $('.home-map-side .home-map-side--link').removeClass('is-active'); var $diagram = $(this).parent('.diagram'); var $diagramImage = $diagram.find('img'); $('.header-dropdown-subcat-link.highlight').removeClass('highlight'); newImage = $diagram.attr('data-diagram-original'); $diagramImage.attr('src', newImage); $(this).removeClass('active'); $diagram.removeClass('is-hover'); }); $(document).on('mouseleave', '.diagram', function() { // console.log("OUT"); $('.header-dropdown-columns > .header-dropdown-column .header-dropdown-column > .header-dropdown-subcats .header-dropdown-subcat-link-cont').removeClass('hover'); $('.header-dropdown-subcat-link.highlight').removeClass('highlight'); $(this).removeClass('is-hover'); $(this).find('.diagram--hotspot.active').each(function() { $(this).removeClass('active'); $(this).parent('.diagram').find('img').attr('src', $(this).parent('.diagram').attr('data-diagram-original')); }) }); // $(document).bind('click', function(e) { // if(!$(e.target).is('.diagram--hotspot, .diagram-tooltip, .diagram-tooltip--text, .diagram-tooltip--link')) { // $('.diagram--hotspot.active').each(function() { // $(this).removeClass('active'); // $(this).parent('.diagram').find('img').attr('src', $(this).parent('.diagram').attr('data-diagram-original')); // }) // } else { // console.log("HOTSPOT", e.target) // } // }); }, generateHotspotsForDiagram: function(diagram, hotspots) { var $this = this; hotspots.forEach(function (hotspot, i) { $(diagram).delay(0).queue(function(next) { var tooltipHtml = (hotspot.link && hotspot.text) ? '
'+hotspot.text+'
' : ''; var diagramDot = (hotspot.link) ? '' : '
'; var transparentClass = (hotspot.transparent) ? ' diagram--hotspot--transparent' : ''; $(this).append('
'+diagramDot+''+tooltipHtml+'
'); next(); }); }); }, // generateHotspots: function() { // var $this = this; // $this.data.hotspots.forEach(function (hotspot, i) { // $($this.data.querySelector).delay(150).queue(function(next) { // $(this).append(''); // next(); // }); // }); // }, handleHotspotClickEvent: function($hotspot) { var $diagram = $hotspot.parent('.diagram'); var $diagramImage = $diagram.find('img'); var key = $hotspot.attr('data-hotspot-key'); var image = $hotspot.attr('data-hotspot-image'); var diagramHotSpotLink = $hotspot.find('.diagram-tooltip').attr('href'); var $headerDropdownLinks = $('.header-dropdown-subcat-link[href="'+diagramHotSpotLink+'"]'); $('.header-dropdown-subcat-link.highlight').removeClass('highlight'); if($headerDropdownLinks.length > 0) { $headerDropdownLinks.addClass('highlight'); } $diagram.find('.active').not($hotspot).toggleClass('active'); $hotspot.addClass('active'); $diagram.addClass('is-hover'); var newImage = null; if($hotspot.hasClass('active') && image) { newImage = image; } else { newImage = $diagram.attr('data-diagram-original'); } $diagramImage.attr('src', newImage); $('.home-map-side .home-map-side--link').removeClass('is-active'); if($diagram.parent().hasClass('home-map-main')) { $diagram.parent().siblings('.home-map-side').find('nav .home-map-side--item').eq($hotspot.index() - 1).find('.home-map-side--link').addClass('is-active') } }, } core.productSeriesCategory = { maxHeight: 166, init: function() { this.onLoad(); }, onLoad: function() { var $this = this; $(window).on('load', function() { $this.scaffoldClipper(); }); }, bindEventListeners: function() { var $this = this; var $element = $('.shop-category-heading--content .content'); $('.product-series--read-more').on('click', function() { $(this).toggleClass('active'); if($(this).hasClass('active')) { $element.removeAttr('style'); $(this).find('span').html('Read Less'); } else { $element.css({ height: $this.maxHeight(), overflow: 'hidden' }); $(this).find('span').html('Read More'); } }); }, scaffoldClipper: function() { var $element = $('.shop-category-heading--content .content'); var $this = this; if($element.outerHeight() > $this.maxHeight()) { $element.after('Read More'); // Constrain Height $element.css({ height: $this.maxHeight(), overflow: 'hidden' }); } else { $('.product-series--read-more').remove(); } this.bindEventListeners(); }, maxHeight: function() { return 158 + $('.shop-category-heading--title').outerHeight(true); } } core.homeTabs = { tabs: [], init: function() { var $this = this; this.bindEventListeners(); this.onLoad(); this.onResize(); $('.home-tabs--button').each(function(i) { $this.tabs.push({ key: i, text: $(this).html() }) }); $('.home-tabs--button[data-tab-key="0"]').click(); }, onLoad: function() { var $this = this; $(window).on('load', function(e) { $this.heightMatch($('.home-tab.active').attr('data-tab-key')); }); }, onResize: function() { var $this = this; window.addEventListener('resize', core.util.debounce(function() { $this.heightMatch($('.home-tab.active').attr('data-tab-key')); }, 80)); }, bindEventListeners: function() { var $this = this; $('.home-tabs--button').click(function() { var key = $(this).attr('data-tab-key'); var $tab = $('.home-tab[data-tab-key="'+key+'"]'); $('.home-tab, .home-tabs--button').removeClass('active'); $(this).addClass('active'); $tab.addClass('active'); $('.home-tabs--title').html($(this).html()); $('.home-tab .slick-initialized').slick('unslick'); $($tab).find(".product-grid").slick({ slidesToShow: 6, slidesToScroll: 1, adaptiveHeight: true, nextArrow: '', prevArrow: '', responsive: [ { breakpoint: 1600, settings: { slidesToShow: 5, }, }, { breakpoint: 1400, settings: { slidesToShow: 4, }, }, { breakpoint: 1200, settings: { slidesToShow: 3, }, }, { breakpoint: 767, settings: { slidesToShow: 2, }, } ] }); $($tab).find(".product-grid").on('beforeChange', function(event, slick, currentSlide, nextSlide) { var $track = $($tab).find('.slick-track').css({height: 'auto'}); var nextSlideId = (nextSlide > currentSlide) ? (nextSlide + 1) : nextSlide; var inActiveSlideId = (nextSlide > currentSlide) ? nextSlide - 1 : nextSlide + 2; _self.common.heightMatch({ matchByRow: false, $gridElement: $('.home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-active, .home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-slide[data-slick-index="'+(nextSlideId)+'"]').not(' .home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-slide[data-slick-index="'+inActiveSlideId+'"]'), $matchElement: $('.home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-active .product-content, .home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-slide[data-slick-index="'+(nextSlideId)+'"] .product-content').not(' .home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-slide[data-slick-index="'+inActiveSlideId+'"] .product-content'), }); $track.css({height: $('.home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-active, .home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-slide[data-slick-index="'+(nextSlideId)+'"]').not(' .home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-slide[data-slick-index="'+inActiveSlideId+'"]').outerHeight()}) setTimeout(function() { $this.heightMatch($('.home-tab.active').attr('data-tab-key')); }, 10); setTimeout(function() { $this.heightMatch($('.home-tab.active').attr('data-tab-key')); }, 20); setTimeout(function() { $this.heightMatch($('.home-tab.active').attr('data-tab-key')); }, 100); }); $this.heightMatch(key); }); }, heightMatch: function(key) { _self.common.heightMatch({ matchByRow: true, $gridElement: $('.home-tab[data-tab-key="'+key+'"] .slick-active'), $matchElement: $('.home-tab[data-tab-key="'+key+'"] .slick-active .product-content'), }); var $track = $('.home-tab[data-tab-key="'+key+'"]').find('.slick-track').css({height: 'auto'}); $track.css({height: $('.home-tab[data-tab-key="'+$('.home-tab.active').attr('data-tab-key')+'"] .slick-active').outerHeight()}) } } core.basicNav = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.cms-nav--mobile-btn').on('click', function() { $(this).toggleClass('active'); }); } } core.helpSidebar = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('body').on('click', '.help-sidebar--title', function() { $(this).toggleClass('active'); }); } } core.shopSidebar = { init: function() { this.handlePosition(); this.onLoad(); this.onReady(); this.bindEventListeners(); }, onLoad: function() { var $this = this; $(window).on('load', function() { $this.handlePosition(); core.products.sidebar.init(); }); }, onReady: function() { var $this = this; $(document).ready(function() { $this.handlePosition(); }); }, bindEventListeners: function() { var $this = this; $('body').on('click', '.sidebar--title', function() { $(this).toggleClass('active'); }); window.addEventListener('resize', core.util.debounce(function() { $this.handlePosition(); }, 80)); }, handlePosition: function() { var sidebarElement = document.getElementsByClassName('sidebar')[0]; if(Modernizr.mq('(min-width: 1000px)')) { $('.shop-category').prepend(sidebarElement) $('.sidebar').prepend($('.shop-sidebar-blue')) } else { if($('.shop-cats-cont')[0]) { $('.shop-cats-cont').prepend(sidebarElement) } else { $('.shop-products').prepend(sidebarElement) } $('#mobile-category-dropdown-cont').prepend($('.shop-sidebar-blue')) } } } // core.listingOverlay = { // init: function() { // this.bindEventListeners(); // }, // bindEventListeners: function() { // var $this = this; // $("#listing-overlay.overlay").on('click', '.overlay--backdrop', function() { // $('#listing-overlay').removeClass('open'); // if($('#listing-overlay .overlay-listing--main').children().length) { // $('#listing-overlay .overlay-listing--main').children().remove(); // } // }); // $("#listing-overlay.overlay").on('click keyup', '.overlay--close', function(event) { // if(event.keyCode === 13 || event.type === "click") { // $('#listing-overlay').removeClass('open'); // if($('#listing-overlay .overlay-listing--main').children().length) { // $('#listing-overlay .overlay-listing--main').children().remove(); // } // } // }); // $this.listOverlayController(); // }, // listOverlayController: function() { // var $this = this; // $(document).on("click", '.prodlist-buy', function(e) { // e.preventDefault(); // $this.listOverlayPopulate($(this).attr('data-list-id')); // }); // $(document).on("click", '.listing-buy-overlay', function(e) { // e.preventDefault(); // var formData = $(this).parents('form').serialize(); // $.ajax({ // url: "/ajax/ajax_basket_add.php", // data: formData + "&submit_999=true", // success: function(data) { // if($('#listing-overlay .overlay-listing--main').children().length) { // $('#listing-overlay .overlay-listing--main').children().remove(); // } // $('#listing-overlay .overlay-listing--main').append(data); // $('#listing-overlay').show(); // $('#listing-overlay').focus(); // } // }); // }); // }, // listOverlayPopulate: function(listId, options = true) { // // if($('#listing-overlay .overlay-listing--main').children().length) { // // $('#listing-overlay .overlay-listing--main').children().remove(); // // } // $.ajax({ // url: "/ajax/ajax_listing_overlay.php", // method: "POST", // data: {list_id: listId, show_options: options}, // success: function(data) { // window.scrollTo(0,0); // $('#listing-overlay .overlay-listing--main').html(data); // $('#listing-overlay').addClass('open'); // $('#listing-overlay').focus(); // } // }); // }, // // init: function() { // // this.bindEventListeners(); // // }, // // bindEventListeners: function() { // // var $this = this; // // $("#listing-overlay.overlay").on('click', '.overlay--backdrop', function() { // // $('#listing-overlay').hide(); // // if($('#listing-overlay .overlay-listing--main').children().length) { // // $('#listing-overlay .overlay-listing--main').children().remove(); // // } // // }); // // $("#listing-overlay.overlay").on('click', '.overlay--close', function() { // // $('#listing-overlay').hide(); // // if($('#listing-overlay .overlay-listing--main').children().length) { // // $('#listing-overlay .overlay-listing--main').children().remove(); // // } // // }); // // $this.listOverlayController(); // // }, // // listOverlayController: function() { // // var $this = this; // // $(document).on("click", '.prodlist-buy', function(e) { // // e.preventDefault(); // // $this.listOverlayPopulate($(this).attr('data-list-id')); // // }); // // $('.listing-buy-overlay').unbind("click").on('click', function(e) { // // e.preventDefault(); // // var formData = $(this).parents('form').serialize(); // // $.ajax({ // // url: "/ajax/ajax_basket_add.php", // // data: formData, // // success: function(data) { // // if($('#listing-overlay .overlay-listing--main').children().length) { // // $('#listing-overlay .overlay-listing--main').children().remove(); // // } // // $('#listing-overlay .overlay-listing--main').append(data); // // $('#listing-overlay').show(); // // $('#listing-overlay').focus(); // // } // // }); // // }); // // }, // // listOverlayPopulate: function(listId, options = true) { // // if($('#listing-overlay .overlay-listing--main').children().length) { // // $('#listing-overlay .overlay-listing--main').children().remove(); // // } // // $.ajax({ // // url: "/ajax/ajax_listing_overlay.php", // // method: "POST", // // data: {list_id: listId, show_options: options}, // // success: function(data) { // // $('#listing-overlay .overlay-listing--main').append(data); // // $('#listing-overlay').show(); // // } // // }); // // }, // } core.purchaseOverlayConfirm = { button: null, init: function() { this.bindEventListeners(); $(document).on("click", ".add-to-basket-button-requires-confirm", function(e) { e.preventDefault(); core.purchaseOverlayConfirm.button = $(this); $("#listing-confirm-overlay-message").html($(this).attr("confirm-message")); $("#listing-confirm-overlay-title").text($(this).attr("confirm-title")); $(this).removeClass("add-to-basket-button-requires-confirm").addClass("add-to-basket-button"); $("#listing-confirm-overlay").show(); }); $("#listing-confirm-overlay-button").on("click", function() { $("#listing-confirm-overlay").hide(); core.purchaseOverlayConfirm.button.click(); core.purchaseOverlayConfirm.button.addClass("add-to-basket-button-requires-confirm").removeClass("add-to-basket-button"); }) }, bindEventListeners: function() { $(window).on('load', function() { $("#listing-confirm-overlay .overlay--backdrop").on('click', function() { $('#listing-confirm-overlay').hide(); }); $("#listing-confirm-overlay.overlay").on('click', '.overlay--close', function() { $('#listing-confirm-overlay').hide(); }); $("#listing-confirm-overlay.overlay").on('click', '.button[data-close-overlay="true"]', function() { $('#listing-confirm-overlay').hide(); }); }); } } core.purchaseOverlay = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { this.onLoad(); $(document).on("click", ".add-to-basket-button", function(e) { e.preventDefault(); let $form = $(this).closest("form"); let extra_form = "&" + $(this).attr("name") + "=true"; let subscription = $(this).attr("data-sub"); let increment = $(this).attr('data-increment'); if(typeof increment !== 'undefined' && increment !== false && increment > 0 && !option_validate(increment)) { return false; } $.ajax({ url: "/ajax/ajax_basket_add.php", type: "POST", data: $form.serialize() + extra_form + "&sub=" + subscription, success: function(data) { $("#listing-options-overlay").hide(); if($('#listing-overlay .overlay-listing--main').children().length) { $('#listing-overlay .overlay-listing--main').children().remove(); } $('#listing-overlay .overlay-listing--main').append(data); $('#listing-overlay').show(); $('#listing-overlay').focus(); } }); }) }, onLoad: function() { var $this = this; $(window).on('load', function() { $("#listing-overlay .overlay--backdrop").on('click', function() { $('#listing-overlay').hide(); if($('#listing-overlay .overlay-listing--main').children().length) { $('#listing-overlay .overlay-listing--main').children().remove(); } }); $("#listing-overlay.overlay").on('click', '.overlay--close', function() { $('#listing-overlay').hide(); if($('#listing-overlay .overlay-listing--main').children().length) { $('#listing-overlay .overlay-listing--main').children().remove(); } }); $("#listing-overlay.overlay").on('click', '.button[data-close-overlay="true"]', function() { $('#listing-overlay').hide(); if($('#listing-overlay .overlay-listing--main').children().length) { $('#listing-overlay .overlay-listing--main').children().remove(); } }); }); } } core.listingOptionsOverlay = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $("#listing-options-overlay > .overlay--backdrop, #listing-options-overlay > .overlay--inner > .overlay--close").unbind("click").bind("click", function() { $("#listing-options-overlay").hide(); }); $(".view-options-overlay-button").unbind("click").on("click", function(event) { event.preventDefault(); // $('html, body').animate({ // scrollTop: ($('header').offset().top) // }, 500); $.get("/ajax/view_options_overlay.php?category_listing_id=" + $(this).data("list-id"), function(data) { $('#listing-options-overlay').find(".overlay-listing--main").html(data); option_addevents('#listing_options_300', '300'); core.form.select2($('#listing_options_300 .select_input')); core.form.select2($('#qty_300')); core.listing.magnificPopup(); $('#listing-options-overlay').show(); core.listing.initialiseSliders(); $('#listing-options-overlay').focus(); }); }); } } core.backToTop = { init: function() { this.onScroll(); this.bindEventListeners(); }, bindEventListeners: function() { $('.back-to-top-mobile').on('click', function() { $('html, body').animate({ scrollTop: ($('header').offset().top) }, 1200); }); }, onScroll: function() { var $this = this; $(window).on("scroll", function () { if ($(this).scrollTop() > 1000) { $('.back-to-top-mobile').slideDown(); } else { $('.back-to-top-mobile').slideUp(); } }); }, } core.listingNoOptions = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { if($('.listing-no-opt--desc .content').outerHeight() > 246) { $('.listing-no-opt--desc .content').addClass('clipped') } else { $('.listing-no-opt--desc .button--orange').hide() } $('.listing-no-opt--desc .button--orange').on('click', function(e) { e.preventDefault(); $('.listing-no-opt--desc .content').toggleClass('expanded'); if($('.listing-no-opt--desc .content').hasClass('expanded')) { $(this).find('span').html('Read Less').addClass('expanded') } else { $(this).find('span').html('Read More').removeClass('expanded') } }) $('.listing-ask-q-btn').on('click', function(e) { $('html, body').animate({ scrollTop: ($('#questions').offset().top) }, 1200); }) } } core.partFinder = { init: function() { this.bindEventListeners(); }, bindEventListeners: function() { $('.home-map-side--link') .on('mouseover click', function() { var $diagram = $(this).parents('.home-map').find('.diagram'); var $hotspot = $diagram.find('.diagram--hotspot').eq($(this).parent().index()); $hotspot.trigger('mouseover'); // $diagram.addClass('is-hover') }) .on('mouseout', function() { var $diagram = $(this).parents('.home-map').find('.diagram'); var $hotspot = $diagram.find('.diagram--hotspot').eq($(this).parent().index()); $hotspot.trigger('mouseout'); }) }, } /* Google address stuff */ core.google_address = { init: function() { var $this = this; this.bindEventListeners(); $(".google-address-lookup").each(function() { $(this).attr("token", uuidv4()); }) }, performPostcodeLookup: function(postcode, containers) { containers.css("cursor", "wait"); containers.each(function() { $(this).find(".button-loading").attr("style", "right:25px") }); $.post("/ajax/google_address_autocomplete.php", {type: "POSTCODE_LOOKUP", query: postcode, token: uuidv4()}, function(data) { let html = ""; let hasShowMore = false; for(let i = 0; i < data.addresses.length; i++) { let address = data.addresses[i]; html += "
"; html += "

"; html += "" + address.text.main + "
"; html += address.text.secondary html += "

"; html += "
"; if(i == 4 && data.addresses.length > 5) { hasShowMore = true; //html += "
"; html += "
"; } } if(hasShowMore) { html += "
"; // close up .google-address-lookup-showmore //html += ""; } containers.css("cursor", ""); containers.each(function() { let container = $(this); container.find(".button-loading").attr("style", "display:none;") container.find(".google-address-lookup-results").html(html); //core.checkout.checkoutSideAdjust(); container.find(".google-address-lookup-address").unbind("click").on("click", function() { let address = data.addresses[$(this).attr("index")].address; for(let k in address) { $("#account_" + container.find("input").attr("mode") + "_" + k).val(address[k]); } container.find(".google-address-lookup-results").html(""); container.find("input").val(""); }); container.find(".google-address-lookup-showmore-action").unbind("click").on("click", function() { container.find(".google-address-lookup-showmore").show(); $(this).hide(); }) }); }) }, bindEventListeners: function() { $(".google-address-lookup").each(function() { let lastTimeout = null; let container = $(this); let input = $(this).find("input"); let results = $(this).find(".google-address-lookup-results"); let mode = input.attr("mode"); container.on("click", ".button-locate", function() { if(input.val().toUpperCase().match(/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/)) { core.google_address.performPostcodeLookup(input.val().toUpperCase(), container); } }); input.on("keyup", function() { if(input.attr("disable-lookup-autocomplete")) return; if(lastTimeout) { clearTimeout(lastTimeout); lastTimeout = null; } container.find(".button-loading").attr("style", "right:25px"); lastTimeout = setTimeout(() => { // If it's a postcode then use postcode lookup if(input.val().toUpperCase().match(/^[A-Z]{1,2}\d[A-Z\d]? ?\d[A-Z]{2}$/)) return core.google_address.performPostcodeLookup(input.val().toUpperCase(), container); if(!input.val().trim()) { return results.html(""); } container.css("cursor", "wait"); $.post("/ajax/google_address_autocomplete.php", {token: container.attr("token"), type: "AUTOCOMPLETE", query: input.val(), country_id: $("[name='account_" + mode + "_country']").val()}, function(data) { container.find(".button-loading").attr("style", "display:none"); container.css("cursor", ""); if(data.softblock) { console.error("Softblocked from using autocomplete"); $(".google-address-lookup > input").attr("placeholder", "Enter your postcode"); $(".google-address-lookup > input").attr("disable-lookup-autocomplete", true); $(".google-address-lookup").append(""); return; } let html = ""; for(let i = 0; i < data.predictions.length; i++) { let address = data.predictions[i]; html += "
" html += "

" + address.text.main + "
" + address.text.secondary + "

"; html += "
"; } html += data.attribution; results.html(html); //core.checkout.checkoutSideAdjust(); container.find(".google-address-lookup-address").unbind("click").on("click", function() { $(this).css("cursor", "wait"); input.val(""); $.post("/ajax/google_address_autocomplete.php", {query: $(this).attr("place-id"), token: container.attr("token"), type: "PLACE_DETAILS", country_id: $("[name='account_" + mode + "_country']").val()}, function(data) { for(let i = 2; i <= 7; i++) $("#account_" + mode + "_" + i).val(""); results.html(""); if(data.house_number == null) data.house_number = ""; if(data.road_name == null) data.road_name = ""; if(data.house_name) { $("#account_" + mode + "_2").val(data.house_name); $("#account_" + mode + "_3").val((data.house_number + " " + data.road_name).trim()); $("#account_" + mode + "_4").val(data.locality); } else { $("#account_" + mode + "_2").val((data.house_number + " " + data.road_name).trim()); $("#account_" + mode + "_3").val(data.locality); } $("#account_" + mode + "_5").val(data.town); $("#account_" + mode + "_6").val(data.county); $("#account_" + mode + "_7").val(data.postcode); //core.checkout.checkoutSideAdjust(); container.attr("token", uuidv4()); }) }) }); }, 350); }) }) }, } /* |-------------------------------------------------------------------------- | Page Modules > Account Home |-------------------------------------------------------------------------- */ core.acchome = { init: function() { this.initialiseSliders(); }, initialiseSliders: function() { $(".account-main-slider .slick-slider").slick({ slidesToShow: 1, slidesToScroll: 1, autoplay: true, autoplaySpeed: 5000, arrows: false, /*nextArrow: '', prevArrow: '',*/ }); }, }