", {"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 = '