// Used in multiple functions to check page url
var loc = location.href;
var minibasket = 0;
var altunits = 0;
var incvat = 0;
var currentSearchRequest = null;
var currentQuickRequest = null;
var currentMobileRequest = null;
/**
* Main on document load function
**/
$(function () {
/**
* Alternate unit calculation on select change
*/
if($('select.altunitselect').length > 0 && altunits === 1){
// Alt unit select change
$('select.altunitselect').change(function () {
var price = $('.pdetails .price:eq(0)');
var opt = $(this).find('option:selected');
var prc = opt.data('price');
var prcinc = opt.data('priceinc');
var prcex = opt.data('priceex');
var prctext = "";
// Price per label update
var priceper = "Price per " + $(opt).text();
$(".price-per").html(priceper);
if(incvat === 0){
if(prcex !== "0"){
prctext += prcex + EXCVAT_TEXT;
}
} else {
if(prcex !== "0"){
prctext += prcex + INCVAT_TEXT;
}
}
price.html("" + prctext + " ");
// Quantity break quantities and prices
for(var i = 1; i <= 6; i++){
// Skip bad qty breaks (can't buy in certain qty breaks (e.g 1-0)
if(opt.data('break-' + i + '-skip') === ""){
if(incvat == 0) {
$('.qtybreak' + i + '-qtys').html(opt.data('break-' + i + '-qtys'));
$('.qtybreak' + i + '-price').html(opt.data('break-' + i + '-priceex'));
if(i === 1){
price.html("" + opt.data('break-' + i + '-priceex') + " ");
}
} else {
$('.qtybreak' + i + '-qtys').html(opt.data('break-' + i + '-qtys'));
$('.qtybreak' + i + '-price').html(opt.data('break-' + i + '-priceinc'));
if(i === 1) {
price.html("" + opt.data('break-' + i + '-priceinc') + " ");
}
}
} else {
// not available, empty it
$('.qtybreak' + i + '-qtys').html("");
$('.qtybreak' + i + '-price').html("");
}
}
//changes a hidden form element inside the actual form.
$(this).parent().parent().find('input#unit').val(opt.val());
});
$("#basketsubmit").bind("click", function(e){
// Stop customer changing alt unit
$('select.altunitselect').find('option').not(":selected").each(function (i) {
$(this).attr("disabled", true);
});
});
// preselect first one on load
$( "select.altunitselect" ).trigger( "change" );
}
// Alternate products on basket page (uses related products)
$(".alternative-product").on("click", function(e){
e.preventDefault();
// Change chevron to up else down
if($(this).children("i").hasClass("fa-chevron-down")){
$(this).children("i").removeClass("fa-chevron-down");
$(this).children("i").addClass("fa-chevron-up");
} else {
$(this).children("i").removeClass("fa-chevron-up");
$(this).children("i").addClass("fa-chevron-down");
}
// slide related box up else down
var suggestedBox = $(this).parent().find(".suggestedbox");
if(suggestedBox.is(":visible")){
suggestedBox.slideUp();
} else {
suggestedBox.slideDown();
}
});
/* Begin mega menu hover delay logic */
var menu = $('.level1');
var menu_items = menu.children('li');
var overlay = $('#menu-overlay');
var setDiv;
menu.bind('mouseenter', function (e) {
e.preventDefault();
$('.navtop').addClass('hovered');
overlay.stop(true, true).delay( (8 * 100) ).fadeTo(0, 0.6);
var scope_this = $(this);
scope_this.children("ul").eq(0).attr("style", "display:none");
$(function () {
setDiv = setTimeout(function () {
scope_this.children("ul").eq(0).attr("style", "display:block");
}, (8 * 100) )
});
});
menu.bind('mouseleave', function () {
menu_items.children('div').hide();
$('.dropdown-menu').removeAttr("style");
clearTimeout(setDiv);
});
$('.navtop').bind('mouseleave', function () {
$('.navtop').removeClass('hovered');
overlay.stop(true, true).delay(100).fadeTo(100, 0);
overlay.css("display", "none");
});
/* End mega menu hover delay logic */
// Account switch table
$('#account-switch-table').dataTable({
/** Good defaults to have for eShop */
/*responsive: true,*/
stateSave: true,
"sPaginationType": "full_numbers",
paging: true,
ordering: true,
info: true,
});
// Points log table - sorting disabled as it doesn't work well with the dates
$('#reward-points-table').dataTable({
stateSave: true,
"pagingType": "full_numbers",
paging: true,
"aaSorting": [],
"bSort" : false,
info: true,
});
// When changing from business to personal change vat calc by triggering basket update
$('input[name^="personal_business"]').change(function() {
$('#editbasketform input[value="Update Basket"]').click();
});
// Global popover
$('[data-toggle="popover"]').popover();
// Product video js
$('.btnVideo').on('click', function () {
$('.main-image').hide();
$('#video').show();
});
$('.zoom-thumbs a').click(function () {
$('.main-image').show();
$('#video').hide();
});
window.onload = function () {
$('#video').show();
};
// Product/group lightbox on clicks
// Already included in productgroup.php
//$(".lightbox").colorbox({photo: true, width: "80%", height: "80%"});
// Main drilldown menu
$('.drilldown').drilldown();
// Quick order search suggest
if($('#quick-order-form').length > 0 )
{
// if on fast order form lets hijack the links
$("#QuickSearchResults").on('click', 'a',function(e) {
e.preventDefault();
copyStockcode('mouseclick', this);
$('#QuickSearchResults').hide();
return false;
});
//focus on field on page load
$( "#stockcode").focus();
$( "#stockcode" ).keyup(function(e){
// lookup
var term = $(this).val();
if (term.length >= 3 && (e.keyCode!==38 && e.keyCode!==40 && e.keyCode!==13)){
doQuickSearch($(this).val(), "quickorder");
}
else if(term.length === 0){
$( "#QuickSearchResults").hide();
}
});
// Fast/Quick order add to basket function
fastOrderAjaxBasket = new AjaxBasket();
$('#quick-order-form').bind('submit', function (e) {
var sBasketAddString = $(this).serialize();
var term = $('#stockcode').val();
var action=checkCancelCopySubmit(term);
if (action==='copy'){
copyStockcode('enter');
e.preventDefault();
$('#QuickSearchResults').hide();
}
else if (action==='cancel'){
e.preventDefault();
}
else if (action==='submit'){
e.preventDefault();
fastOrderAjaxBasket.add(sBasketAddString);
$('#stockcode').val('').focus();
$('#qty').val('1');
}
return false;
});
var liSelected;
var li;
$(window).keydown(function (e) {
if ($('#stockcode').is(":focus")) {
if (e.which === 40 || e.which === 38) {
e.preventDefault();
li = $('#QuickSearchResults ul#prodList').children('li');
}
else {
liSelected = '';
}
if (e.which === 40) {
if (liSelected) {
liSelected.removeClass('selected');
next = liSelected.next();
if (next.length > 0) {
liSelected = next.addClass('selected');
} else {
liSelected = li.eq(0).addClass('selected');
}
} else {
liSelected = li.eq(0).addClass('selected');
}
} else if (e.which === 38) {
if (liSelected) {
liSelected.removeClass('selected');
next = liSelected.prev();
if (next.length > 0) {
liSelected = next.addClass('selected');
} else {
liSelected = li.last().addClass('selected');
}
} else {
liSelected = li.last().addClass('selected');
}
}
}
});
$(window).resize(function() {
$("#QuickSearchResults").css("width", $("#stockcode").css("width"));
});
}
function checkCancelCopySubmit(term){
if(term.length >= 3 && $(".selected").length){
return 'copy';
}
else if(term.length >= 3 && !$(".selected").length){
return 'submit';
}
else if(term.length < 3){
return 'cancel';
}
}
function copyStockcode(method, cntrl){
console.log(cntrl);
if(method==='mouseclick'){
var stcd = $(cntrl).attr('data-stcode'); // stockcode
}
else if (method==='enter'){
var stcd = $('#QuickSearchResults').children().children(".selected").children().attr('data-stcode'); // stockcode
}
console.log("Quick order selecting stock code: " + stcd);
$("#stockcode").val(stcd);
$("#QuickSearchResults").html('');
$('#stockcode').focus();
}
function hide_message(){
// Remove notification message
$('#tooltipcontainer').delay(4500).fadeOut(1000);
}
/*
======================================================================================================
============================== Ajax Add Multiple to Quote ============================================
======================================================================================================
*/
$("#quotesubmitinput, .quotesubmitinput-prodlist").on("click", function(e){
e.preventDefault();
var sItems;
var sForm;
var searchFor='quoterequest';
var currentUrl=$(location).attr('href');
if(currentUrl.indexOf(searchFor)!==-1){
// If we're in the console
sForm = $("form[data-attr='ajaxquoteform']").serialize();
}
else if($(".quotesubmitinput-prodlist").length>0){
// If we're on the product list page
sForm = $(this).parents('form:first').serialize();
}
else{
// If we're on the product page
sForm = $("form.addtobasket").serialize();
}
$.ajax({
type: 'POST',
//format: 'json',
url: '/ajaxQuote.php', data: sForm,
beforeSend:function(){
// this is where we append a loading image
$('#tooltipcontainer').html('
').fadeIn(500);
},
success:function(data){
// successful request; do something with the data
$('#tooltipcontainer').empty();
var obj = jQuery.parseJSON( data );
if(obj.totalitems===1){
sItems='item';
}
else if(obj.totalitems > 1){
sItems='items';
}
if (obj.totalitems > 0) {
new Noty({
id: 'tooltip-notifications',
type: 'success',
text: 'Successfully added ' + obj.totalitems + ' ' + sItems + ' - Go To Quote Form ',
timeout: 3000,
progressBar: true
}).show();
//$('#tooltipcontainer').html('').fadeIn(500);
}
else {
new Noty({
id: 'tooltip-notifications',
type: 'error',
text: 'You have not added any items to the quote form',
timeout: 3000,
progressBar: true
}).show();
//$('#tooltipcontainer').html('You have not added any items to the quote form
').fadeIn(500);
}
if (currentUrl.indexOf(searchFor) !== -1) {
setTimeout(location.reload(), 600);
}
hide_message();
}
});
});
/* End Ajax Add Multiple to Quote */
/* ---Begin Add to favourites------------------------------------------------------------------------------------ */
var stockCode; // stock code of favourite currently being processed
var selectedButton; // the element that instigated the update
var onSaveCallback; // callback to call after saving
/**
* Adds/deletes a favourite based on current existence
*
* @param stockCode - stock code of the favourite
* @param categoryId - category the favourite should belong to
* @param callback - optional function to call when operation is successful
*/
function saveFavourite(stockCode, categoryId, callback ) {
$.ajax({
url: "/ajaxFavourites.php",
type: 'POST',
data: {action: 'addFavourite', stockCode: stockCode, category: categoryId},
dataType: 'json',
success: function (data) {
$("#favourites-modal").modal('hide');
if (callback !== null && typeof callback === "function") {
callback(data);
}
}
});
}
function removeFavourite(stockCode, callback ) {
$.ajax({
url: "/ajaxFavourites.php",
type: 'POST',
data: {action: 'removeFavourite', stockCode: stockCode},
dataType: 'json',
success: function (data) {
if (callback !== null && typeof callback === "function") {
callback(data);
}
}
});
}
/**
* Updates form for product page when a favourite is saved, used as a callback
*
* @param data
*/
function onProductPageFavouriteSave(data) {
var html;
var toolTip;
if (data.status === "favAdded") {
html = 'Remove from Favourites ';
toolTip = 'Successfully added to favourites - Go To Favourites ';
} else {
html = 'Add to Favourites ';
toolTip = 'Successfully removed from favourites';
}
selectedButton.html(html);
new Noty({
id: 'tooltip-notifications',
type: 'success',
text: toolTip,
timeout: 3000,
progressBar: true
}).show();
//$('#tooltipcontainer').html(toolTip).fadeIn(500);
hide_message();
}
/**
* Updates form for a product list page when a favourite is saved, used as a callback
*
* @param data
*/
function onListPageFavouriteSave(data) {
if (data.status === "favAdded") {
new Noty({
id: 'tooltip-notifications',
type: 'success',
text: 'Successfully added to favourites - Go To Favourites ',
timeout: 3000,
progressBar: true
}).show();
//$('#tooltipcontainer').html('').fadeIn(500);
$(selectedButton).html(' ');
}
else {
new Noty({
id: 'tooltip-notifications',
type: 'success',
text: 'Successfully removed from favourites',
timeout: 3000,
progressBar: true
}).show();
//$('#tooltipcontainer').html('Successfully removed from favourites
').fadeIn(500);
$(selectedButton).html(' ');
}
hide_message();
}
/**
* Checks if a favourite exists and displays a modal if it doesn't, delete the favourite if it does
*
*/
function checkIfFavouriteExists() {
$.ajax({
url: "/ajaxFavourites.php",
type: 'POST',
data: {action: 'checkStatus', stockCode: stockCode},
dataType: 'json',
success: function (data) {
if (data.status === 'isNotFavourite') {
$("#favourites-modal").modal({
show: true
});
} else {
removeFavourite(stockCode, onSaveCallback);
}
}
});
}
/*--- Category selection modal -----------------------------------------------------------------------------------*/
/**
* Updates the category selection drop-down based on contents of category name input
*/
function updateCategorySelect() {
var categoryName = $("#new-category-name");
var select = $("#favourite-categories");
if (categoryName.val() === "") {
select.removeAttr('disabled');
} else {
select.attr('disabled', '');
}
}
$(function () {
// on modal open
$('#favourites-modal').on('show.bs.modal', function () {
// clear existing categories
var select = $("#favourite-categories");
select.empty();
select.append("No category ");
// fetch categories from server and update drop-down
$.ajax({
url: '/ajaxFavourites.php',
type: 'POST',
data: {action: 'getCategories'},
dataType: 'json',
success: function (data) {
$.each(data.categories, function (i, v) {
var option = $("");
option.html(v.title);
option.val(v.id);
select.append(option);
})
}
});
});
// whenever a key is pressed, update category drop-down
$("#new-category-name").on('keyup', updateCategorySelect);
// when save is clicked
$("#save-favourite").on('click', function () {
var newCategory = $("#new-category-name");
// if a new category is entered create one, then save the favourite
if (newCategory.val() !== "") {
$.ajax({
url: "/ajaxFavourites.php",
type: "POST",
data: {action: "createCategory", title: newCategory.val()},
dataType: 'json',
success: function (data) {
saveFavourite(stockCode, data.id, onSaveCallback);
}
});
// clear the name field and update drop-down
newCategory.val("");
updateCategorySelect();
} else {
var selectedCategory = $("#favourite-categories").find(":selected");
saveFavourite(stockCode, selectedCategory.val(), onSaveCallback);
}
});
});
/*---End of modal-------------------------------------------------------------------------------------------------*/
/*---Favourite toggle event listeners-----------------------------------------------------------------------------*/
$(".addFavourite").on('click', function (e) {
e.preventDefault();
onSaveCallback = onProductPageFavouriteSave;
selectedButton = $(this);
stockCode = $(this).parent().siblings('[name=addstockcode]').val();
checkIfFavouriteExists();
});
$(".moveFavourite").on("click", function (e) {
e.preventDefault();
onSaveCallback = function() {
location.reload();
};
selectedButton = $(this);
stockCode = $(this).siblings('[name=addstockcode]').val();
$("#favourites-modal").modal({
show: true
});
});
$(".wishlistsubmitinput").on("click", function(e){
e.preventDefault();
onSaveCallback = onListPageFavouriteSave;
selectedButton = $(this);
if (loc.indexOf("favourites") > 0 || loc.indexOf("wishlistbulk") > 0){
// If we're on the /myaccount/favourites page or wishlistbulk
stockCode = $(this).parent().siblings('[name=addstockcode]').val();
}
else{
// If we're on any other page...
stockCode = $('[name=addstockcode]').val();
}
checkIfFavouriteExists();
});
$(".wishlistsubmitinput-prodlist").on("click", function(e){
e.preventDefault();
onSaveCallback = onListPageFavouriteSave;
selectedButton = $(this);
stockCode = $(this).parent().siblings('[name=addstockcode]').val();
checkIfFavouriteExists();
});
$(".wishlistsubmitinput-prodgroup").on("click", function(e){
e.preventDefault();
onSaveCallback = onListPageFavouriteSave;
selectedButton = $(this);
stockCode = $(this).parent().siblings('[name=addstockcode]').val();
checkIfFavouriteExists();
});
/* ---End of favourite toggle event listeners---------------------------------------------------------------------*/
/* ---End Add to favourites-------------------------------------------------------------------------------------- */
/* -------------------------------------- Begin Budget logic ---------------------------------------------------- */
/* Global fade speeds */
var globFadeInSpeed = "fast";
var globFadeOutSpeed = "slow";
/* Months for monthly budget conifg (Matches PHp array when submitted */
var Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// Set to MYSQL date format for easy updating
var dateoptions = {
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd"
};
var yeardateoptions = {
changeMonth: true,
changeYear: true,
dateFormat: "yy-mm-dd"
};
/* Budget start date - Chrome also uses built in calendar which can cause conflicts */
$("#budgetstartdate").datepicker(dateoptions);
/* Year start date - Chrome also uses built in calendar which can cause conflicts */
//$("#yearstartdate").datepicker(yeardateoptions);
/* Enable selection of budget rollover period / approval rule if enabled */
$("input[name='enablerollover']").on("change", function () {
var ival = $(this).val();
if ($("input[name='enablerollover']").eq(0).attr("checked") === "checked") { // enable radio button checked status
switch ($("#budgetperiod").val()) {
case "daily5":
$("#budgetrolloverperiod [value='daily5']").attr("selected", true);
break;
case "daily7":
$("#budgetrolloverperiod [value='daily7']").attr("selected", true);
break;
case "weekly":
$("#budgetrolloverperiod [value='weekly']").attr("selected", true);
break;
case "monthly":
$("#budgetrolloverperiod [value='monthly']").attr("selected", true);
break;
case "yearly":
$("#budgetrolloverperiod [value='yearstart']").attr("selected", true);
break;
}
$("#periodstorollover").attr("disabled", false);
} else {
$("#budgetrolloverperiod [value='']").attr("selected", true);
$("#periodstorollover").attr("disabled", true);
}
});
/*
If enabling approval for orders over budget - what should it do if over budget? enable: warn, approve, stop dropdown
*/
$("#approvalrule").on("change", function () {
var ival = $(this).val();
if (ival === "overbudget") {
$("#overbudgetrule").attr("disabled", false);
} else {
$("#overbudgetrule").attr("disabled", true);
}
});
/* Set all budget period values to this value */
$("#setall").on("keypress", function (e) {
$("input[id*='-budget']").fadeIn(globFadeInSpeed).val($(this).val() + String.fromCharCode(e.which));
});
/* Enable/Disable all permissions checkbox */
$("#ckbCheckAll").on('click', function () {
$(".loading-overlay").fadeIn(globFadeInSpeed);
$("input:checkbox").prop('checked', $(this).prop('checked'));
$(".loading-overlay").fadeOut(globFadeOutSpeed);
});
/*
On changing the period, load differnt period text boxes, to populate with values
*/
$("#budgetperiod").on("change", function (e) {
$(".loading-overlay").fadeIn(globFadeInSpeed);
if ($("input[name='enablerollover']").eq(0).attr("checked") === "checked") { // enable radio button checked status
switch ($(this).val()) {
case "daily5":
$("#budgetrolloverperiod [value='daily5']").attr("selected", true);
$(".weekendoptions").show();
break;
case "daily7":
$("#budgetrolloverperiod [value='daily7']").attr("selected", true);
$(".weekendoptions").show();
break;
case "weekly":
$("#budgetrolloverperiod [value='weekly']").attr("selected", true);
$(".weekendoptions").hide();
break;
case "monthly":
$("#budgetrolloverperiod [value='monthly']").attr("selected", true);
$(".weekendoptions").hide();
break;
case "yearly":
$("#budgetrolloverperiod [value='yearstart']").attr("selected", true);
$(".weekendoptions").hide();
break;
}
}
var action = $("#useraction").val();
// Warn that this re start periods fresh - Doesnt set this val back to old val...
if (action === "updatebudget") {
if (!confirm('This will reset the currently configured budget period values AND current spend values \n\n Are you sure?')) {
e.preventDefault();
$(".loading-overlay").fadeOut(globFadeInSpeed);
return false;
}
}
var container = $("#budget-period-options");
container.html("");
var option = $(this).val();
container.addClass("budget-period-options-periods"); // label:after class
$("#setall-container").show();
// Initial value if swapping between months/weeks with 'set all' set
var iInitval = $("#setall").val();
var i;
if (iInitval === "") {
iInitval = 0;
}
switch (option) {
// Working week
case "daily5":
case "daily7":
// 365 days of the Year
for (i = 1; i <= 365; i++) {
container.append('').find('div#day' + i + '-container').fadeIn(globFadeInSpeed);
}
break;
case "weekly":
// 52 Weeks of the Year
for (i = 1; i <= 52; i++) {
container.append('').find('div#week' + i + '-container').fadeIn(globFadeInSpeed);
}
break;
case "monthly":
// Twelve months of the year
for (i = 1; i <= 12; i++) {
var curMonth = Months[(i - 1)];
var id = curMonth.toLowerCase();
container.append('').find('div#' + id + '-container').fadeIn(globFadeInSpeed);
}
break;
case "yearly":
// This year
container.append('').find('div#year-container').fadeIn(globFadeInSpeed);
break;
default:
break;
}
$(".loading-overlay").fadeOut(globFadeOutSpeed);
});
/*
Remove budget (based on budget year loaded
*/
$("#remove-user-budget").on("click", function (e) {
var cref = $("#cref").val();
var year = $("#yearstartdate").val();
$.ajax({
type: "POST",
url: "/myaccount/budgetmanagement",
async: true,
dataType: "json",
data: {"useraction": "removebudget", "cref": cref, date: year}
})
.done(function (msg) {
if (msg === true) {
$("#succes-box").html("Success! removed budget").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
$(".budgetcontrol-form-container").hide();
// Reset form
$('#budget-form').trigger("reset");
//Empty html
$("#budget-period-options")
.html('Select options above to load period options. ')
.removeClass("budget-period-options-periods");
// Re-hide option to set all
$("#setall-container").hide();
} else {
$("#failed-box").html("Fail! Whoops, Something went wrong, refresh and try again.").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
}
$(".loading-overlay").fadeOut(globFadeOutSpeed);
});
});
/*
Save user budget based on update or insert.
*/
$("#save-user-budget").on("click", function (e) {
e.preventDefault();
/* If period weekly or monthly then scroll up due to page length */
var period = $("#budgetperiod").val();
if (period === "weekly" || period === "monthly" || period === "daily5" || period === "daily7" ) {
$('body,html').animate({
scrollTop: 0
}, 1600);
}
$(".loading-overlay").fadeIn(globFadeInSpeed);
var sForm = $("#budget-form").serialize();
$.ajax({
type: "POST",
url: "/myaccount/budgetmanagement",
async: true,
dataType: "json",
data: sForm
})
.done(function (msg) {
if (msg === true) {
var action = $("#useraction").val();
if (action === "updatebudget") {
$("#succes-box").html("Success! Updated Budget Information").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
} else {
//Assume inserting
$("#succes-box").html("Success! Inserted Budget Information").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
}
$(".budgetcontrol-form-container").hide();
// Reset form
$('#budget-form').trigger("reset");
//Empty html
$("#budget-period-options")
.html('Select options above to load period options. ')
.removeClass("budget-period-options-periods");
// re hide option to set all
$("#setall-container").hide();
$("#remove-user-budget").hide();
} else {
$("#failed-box").html("Fail! Whoops, Something went wrong, refresh and try again.").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
}
$(".loading-overlay").fadeOut(globFadeOutSpeed);
});
});
/*
Modify budget. Checks if budget exists if not INSERTS else UPDATES
*/
$("#modifybudget").on("click", function (e) {
$(".loading-overlay").fadeIn(globFadeInSpeed);
$('#budget-form').trigger("reset");
$('#budget-form input').attr("disabled", false);
$('#budget-form select').attr("disabled", false);
$('#periodstorollover').attr("disabled", true);
$('#budgetrolloverperiod').attr("disabled", true);
$('#overbudgetrule').attr("disabled", true);
$("#save-user-budget").show();
var sCref = $('#userlist option:selected').val();
var dDate = $('#budgetyear option:selected').val();
e.preventDefault();
$.ajax({
type: "POST",
url: "/myaccount/budgetmanagement",
async: true,
dataType: "json",
data: {"useraction": "loadbudget", cref: sCref, budgetyear: dDate}
})
.done(function (msg) {
var sCref = msg.cref;
var bNewBudget = msg.newbudget;
$("#setall-container").show();
$('#budget-form').trigger("reset");
if (sCref !== "") {
var bNewOrUpdate = "";
$(".budgetcontrol-form-container").show();
$("#cref").val(sCref);
if (bNewBudget === "true") {
$("#yearstartdate").val($('#budgetyear option:selected').val() + "-01-01");
$("#remove-user-budget").hide();
$("#useraction").val("insertbudget");
bNewOrUpdate = "new";
// No form data to load
$("#budget-period-options").html('Select options above to load period options. ').removeClass("budget-period-options-periods");
} else {
bNewOrUpdate = "update"
$("#useraction").val("updatebudget");
$("#remove-user-budget").show(); // show remove button as it exists
// Populate form with data
$("#cref").val(msg.cref);
$("#yearstartdate").val(msg.yearstartdate);
$("#budgetstartdate").val(msg.budgetstartdate);
$("#budgetperiod [value='" + msg.budgetperiod + "']").attr("selected", true);
$("#periodstorollover").val(msg.rolloverperiods); // Number of periods to rollover
var rollover = msg.rollover === 1 ? 0 : 1; // element slector 0 = 1(enabled), 1 = 2(disabled)
$("input[name='enablerollover']").eq(rollover).attr("checked", true);
if (rollover === 0) { // enabled
//$("#budgetrolloverperiod").attr("disabled",false); // undisable elem
$("#budgetrolloverperiod [value='" + msg.rolloverrule + "']").attr("selected", true); // select configigured elem
$('#periodstorollover').attr("disabled", false);
}
var budgetperiod = msg.budgetperiod;
$("#approvalrule [value='" + msg.approvalrule + "']").attr("selected", true); // select configigured elem
if (msg.approvalrule === "overbudget") {
$("#overbudgetrule").attr("disabled", false); // undisable elem
} else {
$("#overbudgetrule").attr("disabled", true); // undisable elem
}
$("#overbudgetrule [value='" + msg.overbudgetrule + "']").attr("selected", true); // select configigured elem
var container = $("#budget-period-options");
// Return current period to highlight in table if updating
var currentperiod = msg.currentperiod;
var highlight = false;
if (bNewOrUpdate === "update") {
highlight = true; // highlight
}
container.html("");
switch (budgetperiod) {
case "daily5":
case "daily7":
// Weekly boxes populated with data from DB
$.each(msg.periods, function (key, value) {
$("#periodstorollover").val(value.rolloverperiods); // Number of periods to rollover
var period = key;
if (currentperiod === period && highlight) {
var css = "box-shadow: 2px 2px 11px 1px rgb(0, 0, 0); ";
} else {
var css = ""
}
var periodlabel = period.replace("day", "Day ");
var periodvalue = parseFloat(value.budgetvalue);
var periodcurrentspend = parseFloat(value.currentspend);
var periodoverspend = parseFloat(value.overspend);
var periodspend = 0;
periodspend = parseFloat(periodcurrentspend + periodoverspend);
container.append('').find('div#' + period + '-container').fadeIn(globFadeInSpeed);
});
break;
case "weekly":
// Weekly boxes populated with data from DB
$.each(msg.periods, function (key, value) {
$("#periodstorollover").val(value.rolloverperiods); // Number of periods to rollover
var period = key;
if (currentperiod === period && highlight) {
var css = "box-shadow: 2px 2px 11px 1px rgb(0, 0, 0); ";
} else {
var css = ""
}
var periodlabel = period.replace("week", "Week ");
var periodvalue = parseFloat(value.budgetvalue);
var periodcurrentspend = parseFloat(value.currentspend);
var periodoverspend = parseFloat(value.overspend);
var periodspend = 0;
periodspend = periodcurrentspend + periodoverspend;
container.append('').find('div#' + period + '-container').fadeIn(globFadeInSpeed);
});
break;
case "monthly":
//Monthly text fields populated with data from DB
$.each(msg.periods, function (key, value) {
$("#periodstorollover").val(value.rolloverperiods); // Number of periods to rollover
var periodspend = (parseFloat(value.currentspend) + parseFloat(value.overspend));
if (currentperiod === key && highlight) {
var css = "box-shadow: 2px 2px 11px 1px rgb(0, 0, 0); ";
} else {
var css = ""
}
container.append('').find('div#' + key + '-container').fadeIn(globFadeInSpeed);
});
break;
case "yearly":
// This year
$("#periodstorollover").val(msg.periods["year"].rolloverperiods); // Number of periods to rollover (same for each year
if (currentperiod === "year" && highlight) {
var css = "box-shadow: 2px 2px 11px 1px rgb(0, 0, 0); ";
} else {
var css = ""
}
var yearspend = (parseFloat(msg.periods["year"].currentspend) + parseFloat(msg.periods["year"].overspend));
container.append('').find('div#year-container').fadeIn(globFadeInSpeed);
break;
default:
break;
}
}
if (bNewOrUpdate === "update") {
$("#succes-box").html("Success, Loaded customer budget data.").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
} else {
$("#succes-box").html("Success, Ready to create new budget for customer.").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
}
} else {
$("#failed-box").html("Whoops, Something went wrong.").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
}
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$('.budget-spend-edit').tooltip();
});
});
/*
View budget. Just shows budget form with no modification available (removed buttons and disables form
*/
$("#viewbudgets").on("click", function (e) {
// Load list of budgets current periods
$.ajax({
type: "POST",
url: "/myaccount/budgetmanagement",
async: true,
dataType: "json",
data: {"useraction": "listbudgets"}
})
.done(function (msg) {
var oContainer = $("#listbudgets");
var sReturn = '';
sReturn += '';
sReturn += 'Customer Reference ';
sReturn += 'Period ';
sReturn += 'Rollover Periods ';
sReturn += 'Approval Rule ';
sReturn += 'Overbudget Rule ';
sReturn += 'Budget Value ';
sReturn += 'Current Spend ';
sReturn += 'Overspend ';
sReturn += 'Budget Inc Rollover ';
sReturn += 'Total Spend ';
sReturn += ' ';
$.each(msg, function (key, value) {
console.log("Listing info for cref = '" + key + "', period='" + value.budgetperiod + "'");
sReturn += '';
sReturn += '' + key + ' ';
sReturn += '' + value.year + ' - ' + value.budgetperiod + ' (' + value.currentperiod + ') ';
sReturn += '' + value.rolloverperiods + ' ';
sReturn += '' + value.approvalrule + ' ';
sReturn += '' + value.overbudgetrule + ' ';
sReturn += '£' + value.budgetvalue + ' ';
sReturn += '£' + value.currentspend + ' ';
sReturn += '£' + value.overspend + ' ';
var budget = parseFloat(value.budgetvalue) + parseFloat(value.rollovervalue);
budget = budget.toFixed(2);
sReturn += '£' + budget + ' ';
var tot = parseFloat(value.currentspend) + parseFloat(value.overspend);
tot = tot.toFixed(2);
sReturn += '£' + tot + ' ';
sReturn += ' ';
});
sReturn += '
';
oContainer.show();
oContainer.html(sReturn);
//cref
//budgetperiod
//budgetvalue
//approvalrule
//overbudgetrule
//overspend
//rolloverperiods
});
});
/**
* On spend click enable adjust modal
* 'on click' needs to be attached to parent that always exists as .budget-spend-edit is dynamically loaded
*/
$("#budget-period-options").on("click", ".budget-spend-edit", function(e){
// Record ID to update
var budgetid = $(this).data("budgetid");
console.info("Budget record: " + budgetid);
// Adjust modal
var adjustModal = $("#adjustbudgetmodal")
// Load modal form with:
// - cref of current budget loaded (select input)
var cref = $('#userlist option:selected').val();
console.info("Customer Ref: " + cref);
$(".adjust-cref").text(cref);
var budgetyear = $('#budgetyear option:selected').val();
console.info("Period Year: " + budgetyear);
$(".adjust-period-year").text(budgetyear);
// - period being edited (parent label)
var period = $(this).parent().parent().children("label").text();
console.info("Period: " + period);
$(".adjust-period").text(period);
// - Current spend (move to span tag to access value without £)
var currentspend = $(this).children(".current-spend-value").text();
//console.info("Current period spend: " + currentspend);
$(".adjust-current-spend").text(currentspend);
// Update hidden fields used to make ajax call
$("#adjust-cref").val(cref);
$("#adjust-budgetid").val(budgetid);
adjustModal.modal('show');
});
$("#send-adjustment").on("click", function(e){
e.preventDefault();
// Send updated current spend to ajax end point
// - create endpoint
// - on success update current spend value span
var budgetid = $("#adjust-budgetid").val();
var adjustment = $("#adjust-spend").val();
var comment = $("#adjust-reason").val();
$.ajax({
type: "POST",
url: "/myaccount/budgetmanagement",
async: true,
dataType: "json",
data: {
"useraction": "adjustbudget",
"budgetid": budgetid,
"adjustment": adjustment,
"comment": comment,
}
})
.done(function (msg) {
if(msg === false || msg === "false"){
// fail
$("#adjust-error").show();
} else {
// success
// Add new spend to UI
$("[data-budgetid='" + budgetid + "'] span").text(msg);
// Hide Adjust modal
var adjustModal = $("#adjustbudgetmodal");
adjustModal.modal('hide');
// reset adjust modal values
$("#adjust-spend").val(0);
$("#adjust-reason").val("");
}
});
});
var tableCreated = false;
/**
* Show budget log: Only create datatable object if it hasnt already been created (causes error)
*/
$("#viewlog").on("click", function(e){
e.preventDefault();
if(tableCreated === false){
$('#budget-log-table').dataTable({
"bJQueryUI": false,
"bAutoWidth": false,
"bStateSave": true,
"sPaginationType": "full_numbers",
"aaSorting": [[ 8, "desc" ]]
});
tableCreated = true;
}
// Show modal
var logModal = $("#logmodal");
logModal.modal('show');
})
/* -------------------------------------- End Budget logic ---------------------------------------------------- */
/* =====================================================================================================
============================= End Budget Managment =================================================
=====================================================================================================
*/
/* =====================================================================================================
============================= Begin MultiUser Managment =============================================
=====================================================================================================
*/
/*
//Generate a password using plugin
$('#genpass').bind('click', function(e){
e.preventDefault();
var pw = GPW.pronounceable(10);
$("#password").val(pw);
});
*/
// Only set if modifing
$("#modifypassmsg").html("");
// Begin create user form handling
$('#createuser-button').on('click', function (e) {
e.preventDefault();
$(".loading-overlay").fadeIn(globFadeInSpeed);
// validate email
if (!ValidateEmail($("#email").val())) {
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#failed-box").html("Please enter a valid email address.").fadeIn(globFadeInSpeed);
return false;
} else {
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#failed-box").fadeOut(globFadeOutSpeed).html("");
}
// Validate password seperatly if modifying it can be blank else if creating needs to be 6> chars
var sUpdateModify = $("#createuser-button").html();
if (sUpdateModify === "Create New Account") {
var pass = $("#password");
if (pass.val().length < 6) {
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#failed-box").html("Please ensure your password is longer than 6 characters.").fadeIn(globFadeInSpeed);
return false;
} else {
$("#failed-box").html("").fadeOut(globFadeOutSpeed);
}
} else {
// Ensure user id is loaded into form before modifying
var id = $("#userid").val();
if (id === "") {
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#failed-box").html("Whoops, Please refresh the page.").fadeIn(globFadeInSpeed);
return false;
}
// Can be blank... handled by php if different it updates it
$("#failed-box").html("").fadeOut(globFadeOutSpeed);
// Security check for webopts admin
var weboptsvalue = $("#webopts").attr("value");
var weboptsval = $("#webopts").val();
if(weboptsvalue.indexOf("level:admin") >= 0){
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#failed-box").html("Whoops, you can't make yourself admin.").fadeIn(globFadeInSpeed);
return false;
}
}
// Send data
var sUsername = $('#userlist option:selected').val();
var sFormData = $("#newuser-form").serialize();
$.ajax({
type: "POST",
url: "/myaccount/usermanagement",
async: true,
data: sFormData
})
.done(function (msg) {
switch (msg) {
case "true":
$("#succes-box").html("Success! Updated user account!").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
$('#removeuser-button').fadeOut(globFadeOutSpeed);
$("label[generated='true']").hide()
$("#failed-box").hide();
$("#newuser-form input").val("");
$("input:checkbox").val("1"); // set all vals to 1 for next update
$("#action").val("update");
$("input:checked").prop("checked", false);
$("#createuser-button").html("Create New Account");
$("legend").html("Create New Account");
setTimeout(function () {
getUserList();
}, 1000);
$(".loading-overlay").fadeOut(globFadeOutSpeed);
break;
case "false":
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#failed-box").html("Whoops, Please refesh the page.").fadeIn(globFadeInSpeed);
break;
default:
break;
}
});
});
/*
Removes user from MultiAuth table
*/
$('#removeuser-button').on('click', function (e) {
$(".loading-overlay").fadeIn(globFadeInSpeed);
$('#removeuser-button').attr("disabled", true);
var iRemoveID = $("#userid").val();
$.ajax({
type: "POST",
dataType: "json",
url: "/myaccount/usermanagement",
async: true,
data: {useraction: "removeuser", userid: iRemoveID}
})
.done(function (msg) {
switch (msg) {
case true:
$("#modifypassmsg").html("");
$("label[generated='true']").hide();
$("#failed-box").hide();
$("#newuser-form input").val("");
$("#action").val("update");
$("input:checked").prop("checked", false);
$("#createuser-button").html("Create New Account");
$("legend").html("Create New Account");
$('#removeuser-button').attr("disabled", false);
$('#removeuser-button').fadeOut(globFadeOutSpeed);
setTimeout(function () {
getUserList();
}, 1000);
$(".loading-overlay").fadeOut(globFadeOutSpeed);
$("#succes-box").html("Success! User account removed").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
break;
case false:
$(".loading-overlay").fadeOut();
$("#failed-box").html("Fail! User account not removed").fadeIn(globFadeInSpeed);
break;
}
});
});
//Modify user
$('#modifyuser').on('click', function (e) {
e.preventDefault();
$(".loading-overlay").fadeIn(globFadeInSpeed);
$("#createuser-button").attr("disabled", true);
$("label[generated='true']").hide();
$("#failed-box").hide();
$("#modifypassmsg").html("(Leave blank to not update)");
$('#removeuser-button').fadeIn(globFadeInSpeed);
var iUserID = $('#userlist option:selected').val();
$.ajax({
type: "POST",
dataType: "json",
url: "/myaccount/usermanagement",
async: true,
data: {useraction: "userinfo", userid: iUserID}
})
.done(function (msg) {
//Populate text fields
$("#userid").val(msg.userid);
$("#companyname").val(msg.name);
$("#email").val(msg.username);
$("#passwordcheck").val(msg.password);
$("#cref").val(msg.cref);
$("#webopts").val(msg.webopts);
//$("#usertype option[value='"+msg.webopts+"']").attr("selected",true);
$("#updatecref option[value='" + msg.cref + "']").attr("selected", true);
var perm1 = msg.permission1 === 1;
var perm2 = msg.permission2 === 1;
var perm3 = msg.permission3 === 1;
var perm4 = msg.permission4 === 1;
var perm5 = msg.permission5 === 1;
var perm6 = msg.permission6 === 1;
var perm7 = msg.permission7 === 1;
var perm8 = msg.permission8 === 1;
var perm9 = msg.permission9 === 1;
var perm10 = msg.permission10 === 1;
var perm11 = msg.permission11 === 1;
$("#permission-1").attr("checked", perm1);
$("#permission-2").attr("checked", perm2);
$("#permission-3").attr("checked", perm3);
$("#permission-4").attr("checked", perm4);
$("#permission-5").attr("checked", perm5);
$("#permission-6").attr("checked", perm6);
$("#permission-7").attr("checked", perm7);
$("#permission-8").attr("checked", perm8);
$("#permission-9").attr("checked", perm9)
$("#permission-10").attr("checked", perm10)
$("#permission-11").attr("checked", perm11)
$("#succes-box").html("Loaded user information.").fadeIn(globFadeInSpeed).delay(3000).fadeOut(globFadeOutSpeed);
$("#createuser-button").html("Update Account");
$("legend").html("Update Account - " + msg.username);
$("#createuser-button").attr("disabled", false);
$(".loading-overlay").fadeOut(globFadeOutSpeed);
});
//Populate create for with info and change post action to modify user!
});
/* -------------------------------------- Begin Multi Auth ---------------------------------------------------- */
/* Begin nasty IE 8 fix */
//if ($.browser.msie) {
// $("body").hide();
//
// $.getScript('/themes/default/js/plugins/bootstrap.respond.js', function () {
// // got script wait 3 seconds
// setTimeout(function () {
// $("body").fadeIn(globFadeInSpeed);
// }, 1000);
// //$("body").fadeIn();
// });
//}
/* End nasty IE 8 fix */
/* Delivery cost estimator */
$('.postcode-estimator-result').on('click', '.postcode-estimator-update-btn', function (e) {
e.preventDefault();
console.log("wait 2 seconds and refresh");
$("body").css("cursor", "progress");
$(".postcode-estimator-update-btn").css("cursor", "progress");
// Wait two seconds for session to be set (for some reason)
setTimeout(function () {
$("body").css("cursor", "");
$(".postcode-estimator-update-btn").css("cursor", "");
location.reload();
}, 1000);
});
/*
List postcodes out of possible account addresses
*/
$(".postcode-estimator-txt").bind('focus', function (e) {
// On focus load possible postcodes to insert
var results = $("#deliveryprice-postcodes");
$.ajax({
type: "POST",
dataType: "json",
url: "/ajaxShippingOptions.php",
async: true,
data: {list: true}
})
.done(function (msg) {
var items = [];
$.each(msg, function (key, val) {
items.push("" + val + " ");
});
results.html(items.join(""));
/* Bind postcode links */
$(".postcode-estimate-load").bind('click', function (e) {
e.preventDefault();
var loadpstcd = $(this).attr("href");
$(".postcode-estimator-txt").val(loadpstcd.toUpperCase());
$("#deliveryprice-postcodes").hide();
});
results.show();
});
});
/*
Load delivery options box
*/
$('.postcode-estimator-btn').bind('click', function (e) {
e.preventDefault();
$(".postcode-estimator-result").html("");
var sPostCode = $(".postcode-estimator-txt").val();
if (isValidPostcode(sPostCode)) { // check if valid
$(".postcode-estimator-txt").val(formatPostcode(sPostCode)); // If valid - Format it + submit
$.ajax({
type: "POST",
dataType: "json",
url: "/ajaxShippingOptions.php",
async: true,
data: {postcode: encodeURI(formatPostcode(sPostCode))}
})
.done(function (msg) {
var items = [];
var iCnt = 1;
if($.type(msg) === 'object') {
$.each(msg, function (key, val) {
var DelCode = key;
var info = val;
var title = info.Title;
var desc = info.Description;
var cost = info.Cost;
var costtxt = info.CostString;
if (($.type(info.Selected) === 'undefined' || info.Selected === "") && iCnt === 1) {
var checked = ' checked="checked" ';
} else {
var checked = info.Selected;
}
items.push('' +
' ' + title + ' ' +
'' +
' ');
iCnt++;
}); // end for each
$("" + items.join("") + ' ').appendTo(".postcode-estimator-result");
$(".postcode-estimator-result").fadeIn(globFadeInSpeed);
var preselected = $('[name="choosedelmethcode-estimate"]:checked').val();
if (preselected !== undefined) {
$.ajax({
type: "POST",
url: "/ajaxShippingOptions.php",
async: false,
data: {setmeth: encodeURI(preselected)}
})
}
$('[name="choosedelmethcode-estimate"]').bind('click', function (e) {
// Set del method for checkout
$.ajax({
type: "POST",
url: "/ajaxShippingOptions.php",
async: false,
data: {setmeth: encodeURI($(this).val())}
})
.done(function (msg) {
});
});
} else {
$(".postcode-estimator-result").fadeIn(globFadeInSpeed);
$(msg).appendTo(".postcode-estimator-result");
}
});
}
});
/*
Loads user dropdown list built with PHP
*/
function getUserList() {
param = "userlist";
$.ajax({
type: "POST",
url: "/myaccount/usermanagement",
cache: false,
async: true,
data: {useraction: param}
})
.done(function (msg) {
if (msg !== "") {
$(".dropdown-container").fadeOut(globFadeOutSpeed).html(msg).fadeIn(globFadeInSpeed);
$(".dropdown-container form").addClass("col-md-11");
$(".dropdown-container form").addClass("col-md-offset-1");
} else {
$("#failed-box").html("Error loading user list, try refreshing the page.").fadeIn(globFadeInSpeed);
}
});
}
function ValidateEmail(mail) {
return /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,10})+$/.test(mail);
}
/* Tests to see if string is in correct UK style postcode: AL1 1AB, BM1 5YZ etc. */
function isValidPostcode(p) {
var postcodeRegEx = /[A-Z]{1,2}[0-9]{1,2} ?[0-9][A-Z]{2}/i;
return postcodeRegEx.test(p);
}
/* Formats a VALID postcode nicely: AB120XY -> AB1 0XY */
function formatPostcode(p) {
if (isValidPostcode(p)) {
var postcodeRegEx = /(^[A-Z]{1,2}[0-9]{1,2})([0-9][A-Z]{2}$)/i;
return p.replace(postcodeRegEx, "$1 $2").toUpperCase();
} else {
return p;
}
}
// Begin Tooltip handler
if ($('#tooltipcontainer').length !== 0) {
var topcss = $('#tooltipcontainer').css('top').split('p');
var top = topcss[0];
$(window).scroll(function (event) {
// what the y position of the scroll is
var y = $(this).scrollTop();
// whether that's below the box
if (y >= top) {
// if so, add the fixed class
$('#tooltipcontainer').addClass('fixed');
} else {
// otherwise remove it
$('#tooltipcontainer').removeClass('fixed');
}
});
}
/*
Begin ajaxbasket instance. Binds the submit event to the add to basket button on form load (except for product tables) - see below.
*/
if ((loc.indexOf("Products") > 0 || loc.indexOf("ProductGrp") > 0 || loc.indexOf("product.php") > 0 || loc.indexOf("favourites") > 0) && $(".grptable").length == 0){
myAjaxBasket = new AjaxBasket();
$('.addtobasket').bind('submit', function () {
var BasketAddString = $(this).serialize();
var successadd = myAjaxBasket.add(BasketAddString);
return false;
});
}
/*
Begin ajaxbasket instance for product tables. As we've had issues with product tables, it's been seperated from the above for easier debugging
*/
if ($(".grptable").length > 0){
myAjaxBasket = new AjaxBasket();
$('.addtobasket').bind('submit', function () {
var BasketAddString = $(this).serialize();
var successadd = myAjaxBasket.add(BasketAddString);
console.log("Success in adding:" + successadd);
return false;
});
}
/* Load bootstrap switch */
//$('#chkPfToggle').bootstrapSwitch('size', 'small');
//$('.bootstrap-switch-id-chkPfToggle').on('click', function (el) {
// if ($('#chkPfToggle').is(':checked')) {
// $('#txtHAtts').val('pfToggleOn');
// //console.log("chkPfToggle is checked");
// } else {
// $('#txtHAtts').val('pfToggleOff');
// //console.log("chkPfToggle not checked");
// }
// //$('#frmFilters').submit();
//});
function submitForm(frmName) {
$('#' + frmName).submit();
}
$('#btnPrice').on('click', function () {
var min = $('#pricemin').val();
var max = $('#pricemax').val();
$('#txtHAtts').val('price~' + min + '~' + max);
$('#frmFilters').submit();
});
$('#btnPriceMob').on('click', function () {
var min = $('#priceminMob').val();
var max = $('#pricemaxMob').val();
$('#txtHAtts').val('price~' + min + '~' + max);
$('#frmFiltersMob').submit();
});
$('#pricemin').keypress(function (e) {
if (e.which == 13) {
$('#pricemax').focus();
}
});
$('#pricemax').keypress(function (e) {
$('#btnPrice').trigger('click');
});
$('.checkbox.option').on('click', function () {
var filter = $(this).find('input[type=checkbox]').val();
$('#txtHAtts').val(filter);
submitForm('frmFilters');
});
$('.checkbox.optionMob').on('click', function () {
var filter = $(this).find('input[type=checkbox]').val();
$('#txtHAtts').val(filter);
submitForm('frmFiltersMob');
});
$('.colour-blocks-filters input:checked').parent().css({'border': '2px solid #fff', 'outline': '2px solid #009'});
$('.colour-blocks-filters').on('click', function () {
var filter = $(this).find('input[type=checkbox]').val();
$('#txtHAtts').val(filter);
$('#frmFilters').submit();
});
$('.rmselected .delete').on('click', function () {
var attid = $(this).parent('div').attr('data-tag');
$('#txtHAtts').val(attid);
$('#frmFilters').submit();
});
$('#pfclearall').on('click', function () {
$('#txtHAtts').val('clearall');
$('#frmFilters').submit();
});
$('.colour-blocks-filters').tooltip({
items: '.colour-blocks-filters',
content: function () {
var colour = $(this).find('.colour-name').html();
var attvalcount = $(this).find('.attvalcount').html();
return colour + ' ' + attvalcount;
}
});
/*
//Fetch all the set colours from productGroup-blocks plugin.
var colorTable = $.fn.blocks.defaults.colourcodes;
//For each colour block.
$( '.colour-blocks-filters' ).each( function(){
//Replace any spaces wita a '-' as you cannot assign a class name with spaces in.
var spanColor = $( this ).find( '.colour-name' ).html().replace( ' ', '-' );
//Check if colour matches in table
if( colorTable[spanColor.toLowerCase()] != undefined ){
//Set the css bg color
$( this ).css( {
'background-color' : colorTable[spanColor.toLowerCase()]
});
} else {
//If no colour is found in array then add a class of that colour.
$( this ).addClass( spanColor );
}
});
*/
/* begin predictive search suggest */
//Hide SearchResults when clicking on body
$("body").on('click', function () {
$("#SearchResults").hide();
$("#SearchResultsMobile").hide();
$("#SearchResults").css('border-color', 'transparent');
$("#SearchResultsMobile").css('border-color', 'transparent');
});
$("#mainsearch").keyup(function (e) {
//doSearch($(this).val() + String.fromCharCode(e.which));
doSearch($(this).val());
});
$("#secondsearch").keyup(function (e) {
//doSearchMobile($(this).val() + String.fromCharCode(e.which));
doSearchMobile($(this).val());
});
// $("#mainsearch").keydown(function (e) {
// if (e.which == 8) {
// doSearch($(this).val().substring(0, $(this).val().length - 1));
// }
// });
//
// $("#secondsearch").keydown(function (e) {
// if (e.which == 8) {
// doSearchMobile($(this).val().substring(0, $(this).val().length - 1));
// }
// });
function doSearch(text) {
SearchCat = 'all';
showSearchResults(text, SearchCat);
$("#SearchResults").css('border-color', '#0060AA');
if (!$("#SearchResults").html()) {
$("#SearchResults").css('border-color', 'transparent');
}
$("#SearchResults").slideDown();
}
function doSearchMobile(text) {
SearchCat = 'all';
showSearchResultsMobile(text, SearchCat);
$("#SearchResultsMobile").css('border-color', '#0060AA');
if (!$("#SearchResultsMobile").html()) {
$("#SearchResultsMobile").css('border-color', 'transparent');
}
$("#SearchResultsMobile").slideDown();
}
function doQuickSearch(text, quickorder) {
SearchCat = 'all';
SearchCat = 'all';
showQuickSearchResults(text, SearchCat, quickorder);
$("#QuickSearchResults").css('border-color', '#0060AA');
if (!$("#QuickSearchResults").html()) {
$("#QuickSearchResults").css('border-color', 'transparent');
}
}
var ajax;
function showSearchResults(str, SearchCat) {
var minSearchLength = 3;
if (str.length < minSearchLength) {
$("#SearchResults").html("");
return;
} // If no search term
if (currentSearchRequest != null) {
currentSearchRequest.abort();
}
currentSearchRequest = $.ajax({
type: "GET",
url: "/searchajax.php",
async: true,
data: {
searchterm: encodeURI(str),
searchcat: SearchCat
},
success: function(msg) {
$("#SearchResults").html(msg);
}
});
}
function showSearchResultsMobile(str, SearchCat) {
if (str.length === 0) {
$("#SearchResultsMobile").html("");
} // If no search term
currentQuickRequest = $.ajax({
type: "GET",
url: "/searchajax.php",
async: true,
beforeSend: function() {
if (currentQuickRequest != null) {
currentQuickRequest.abort();
}
},
data: {
searchterm: encodeURI(str),
searchcat: SearchCat
}
})
.done(function (msg) {
$("#SearchResultsMobile").html(msg);
});
}
function showQuickSearchResults(str, SearchCat, quickorder) {
if (str.length === 0) {
$("#SearchResults").html("");
} // If no search term
currentMobileRequest = $.ajax({
type: "GET",
url: "/searchajax.php",
async: true,
beforeSend: function() {
if (currentMobileRequest != null) {
currentMobileRequest.abort();
}
},
data: {
searchterm: encodeURI(str),
searchcat: SearchCat,
quickorder: quickorder,
addList: 1
}
})
.done(function (msg) {
$("#QuickSearchResults").css("width", $("#stockcode").css("width"));
if(msg.length>0) {
$("#QuickSearchResults").html(msg);
$("#QuickSearchResults").slideDown();
}
});
}
$("#secondsearch").keydown(function (e) {
if (e.which === 8) {
doSearchMobile($(this).val().substring(0, $(this).val().length - 1));
}
});
$('#optDeliver').on('click', function(e) {
var mapShowCount;
e.preventDefault();
$('#optDeliver').addClass('btnActive');
$('#optDeliver').removeClass('btnDeactive');
$('#optCollect').addClass('btnDeactive');
$('#optCollect').removeClass('btnActive');
$('#optDeliver').children('p.tick').html(' ');
$('#optCollect').children('p.tick').html('');
$('#delmethod').val('DEL');
$('#deliverycharges').slideDown(100);
$('#map').slideUp(100);
$('#distanceMatrix').slideUp(100);
$('.mapErrors').slideUp(100);
$('#scopeSelector').slideUp(100);
$('.collect-panel').slideUp(100);
$('.delivery-panel').slideDown(100);
$('#delcol').prop("checked", false);
$('#delcol').removeAttr('checked');
$('input[name="checkoutmethod"]').val('deliver');
});
$('#optCollect').on('click', function(e) {
e.preventDefault();
$('#cancelMapAutoLoad').val('');
$('#optDeliver').addClass('btnDeactive');
$('#optDeliver').removeClass('btnActive');
$('#optCollect').addClass('btnActive');
$('#optCollect').removeClass('btnDeactive');
$('#optDeliver').children('p.tick').html('');
$('#optCollect').children('p.tick').html(' ');
$('#delmethod').val('COL');
$('#deliverycharges').slideUp(100);
// $('#map').slideDown(100);
// $('#scopeSelector').slideDown(100);
$('.collect-panel').slideDown(100);
$('.delivery-panel').slideUp(100);
$('input[name="checkoutmethod"]').val('collect');
// if initMap called, they must have selected collection option
$('.npbuttons .next').attr('disabled', true);
// setTimeout(function() {
// initMap(5);
// }, 400);
// $('#distanceMatrix').slideDown(400);
// $('.mapErrors').slideDown(400);
// $('#delcol').prop("checked", true);
});
function valid_postcode(postcode) {
postcode = postcode.replace(/\s/g, "");
var regex = /^(([gG][iI][rR] *0[aA]{2})|((([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y]?[0-9][0-9]?)|(([a-pr-uwyzA-PR-UWYZ][0-9][a-hjkstuwA-HJKSTUW])|([a-pr-uwyzA-PR-UWYZ][a-hk-yA-HK-Y][0-9][abehmnprv-yABEHMNPRV-Y]))) *[0-9][abd-hjlnp-uw-zABD-HJLNP-UW-Z]{2}))$/i;
return regex.test(postcode);
}
$('#collectPostCodeSubmit').on('click', function(e) {
e.preventDefault();
var pcode = getCollectPostcode();
if ( !valid_postcode(getCollectPostcode()) ) {
$('#collectPostCodeError').html("Please enter a valid postcode");
// alert("PLEASE ENTER A VALID POST CODE");
return;
}
$('#collectPostCodeError').html("");
$('#map').slideDown(100);
setTimeout(function() {
if ($('input:radio[name=scope]:checked').val() === "nearest5") {
initMap(5);
} else {
initMap("all");
}
}, 100);
setTimeout(function() {
$('#distanceMatrix').slideDown(200);
$('.mapErrors').slideDown(100);
$('#delcol').prop("checked", true);
}, 300);
});
//$("#scopeSelector input[name='scope']").click(function(){
// if($('input:radio[name=scope]:checked').val() === "nearest5"){
// initMap(5);
// }
// else{
// initMap("all");
// }
//});
$('body').on('click', 'table#storeMatrix tr', function() {
var mainElement = $(this);
if(mainElement.children("td").children(".selRadio").is(':enabled')) {
//mainElement.children("td").children(".selRadio").prop("checked", true);
$('#coldepot').val(mainElement.children("td").children(".selRadio").val());
$('#coldepotloc').val(mainElement.children("td").children(".depotloc").val());
$('#del_code_overide').val(mainElement.children("td").children(".del_meth_code").val());
$('#delcol').prop("checked", true);
$('#col_depot_label').val(mainElement.children("td").children(".col_depot_code").val());
// They have selected a collect depot, allow them to continue
if($('input[name="checkoutmethod"]').val() === 'collect'){
$('.npbuttons .next').attr('disabled',false);
}
}
});
$('#delandbillingsame').on('click', function(e){
if($(this).is(":checked")){
$('#choosedeladdfullnamelabel, #choosedeladdfullname, #choosedeladdadd1label, #choosedeladdadd1, ' +
'#choosedeladdadd2label, #choosedeladdadd2, #choosedeladdadd3label, #choosedeladdadd3, ' +
'#choosedeladdadd4label, #choosedeladdadd4, #choosedeladdpostcdlabel, #choosedeladdpostcd').slideUp(150).removeAttr('required');
$('#delandbillingsame').val('1');
}
else{
$('#choosedeladdfullnamelabel, #choosedeladdfullname, #choosedeladdadd1label, #choosedeladdadd1, ' +
'#choosedeladdadd2label, #choosedeladdadd2, #choosedeladdadd3label, #choosedeladdadd3, ' +
'#choosedeladdadd4label, #choosedeladdadd4, #choosedeladdpostcdlabel, #choosedeladdpostcd').slideDown(150).val('');
$('#delandbillingsame').val('0');
$('#choosedeladdfullname, #choosedeladdadd1, #choosedeladdadd3, #choosedeladdpostcd').attr('required','true');
}
});
// Pagination buttons
$( ".pgntionPage" ).on('click', function(e){
e.preventDefault();
//Get the page number inside the span.
var page = $( this ).find( "span" ).text();
$( this ).closest('form').find( "input.pageNo" ).val( page );
$( this ).closest('form').submit( );//Submit the Page
});
//If next button is clicked
$(".pgntionNext").on('click', function(e){
e.preventDefault();
//Set current page var
var page = $(".frmPageNav").find(".pageOn").html();
//Set last page var
var lastnum = $(".frmPageNav").find(".lastnum").html();
//If current page is not equal to lastpage
if(parseInt(page) !== parseInt(lastnum)){
//Set value of #idpage to current page plus 1 as we need to go to the next page.
$(".pageNo").val(parseInt(page)+1);
$(".frmPageNav").submit();//Submit the Page
}
});
//If Previous button is clicked
$(".pgntionPrevious").on('click', function(e){
e.preventDefault();
//Set current page var
var page=$(".frmPageNav").find(".pageOn").html();
if(parseInt(page) === 1){
// Check if we're already on the first page
return false;
}
//Set value of #idpage to current page minus 1 as we need to go back to the previous page.
$(".pageNo").val( parseInt(page)-1);
$(".frmPageNav").submit();//Submit the Page
});
//If First button is clicked
$(".pgntionFirst").on('click', function(e){
e.preventDefault();
if($('.pageOn').html()!=='1'){
//Set value of .pageNo to first page.
$(".pageNo").val(1);
$(".frmPageNav").submit();//Submit the Page
}
});
//If Last button is clicked
$(".pgntionLast").on('click', function(e){
e.preventDefault();
//Set current page var to the value of .lastnum class
var page = $(".frmPageNav").find(".lastnum").html();
if($('.pageOn').html()!==page) {
//Set value of #idpage to last page.
$(".pageNo").val(page);
$(".frmPageNav").submit();//Submit the Page
}
});
//Search suggest - Uses jquery UI outputs JSON file to load results faster
//loads results on page load so they are ready.
/*
$( "#mainsearch" ).autocomplete({
minLength: 0,
source: products,
max: 10,
focus: function( event, ui) {
//console.log(ui.label);
//$( "#mainsearch" ).val( ui.label );
return false;
},
select: function( event, ui ) {
//$( "#mainsearch" ).val( this.label );
//$( '#frmFilters' ).submit();
//$( "#project" ).val( ui.item.label );
//$( "#project-id" ).val( ui.item.value );
//$( "#project-description" ).html( ui.item.desc );
//$( "#project-icon" ).attr( "src", "images/" + ui.item.icon );
return false;
}
})
.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
return $( "" ).append( "" + item.label + " " + item.desc + " " ).appendTo( ul );
};
*/
// And finally calculate DOM load time
/******************************************************************
* Stock level less than what customer is trying to add to basket
* Modal trigger when clicked on add to basket button
******************************************************************/
// modal trigger when quantity submitted is greater than whats in stock
// works for product pages, product-list-product pages, grouped category-dropdown pages, from favourites page,
// does not work for grouped category - table layout and Quick order
if($(".table.group").length){
check_stock_backorder_message("table", '#btnAddToOrder[type="submit"]');
} else {
check_stock_backorder_message("standard", '.addtobasket[type="submit"], #addtobasket[type="submit"]');
}
/**********************************************************
* END Stock level less than what customer is trying to add to basket
**********************************************************/
}); // End Doc Ready
function calcaulateQtyVal ($click_button, $minimumorder, $soincr) {
//plus and minus buttons functionality
var newVal;
var $button = $click_button;
var oldValue = $button.parent().find("input[class*='qty']").val();
var $minOrderVal = parseFloat($minimumorder);
var $soincrVal = parseFloat($soincr);
var mod;
mod = parseFloat(oldValue) % $soincrVal;
var modMinordSoincr;
modMinordSoincr = $minOrderVal % $soincrVal;
if ( true === false ){
// when its disabled set minorderval and orderinc val to 0.
$minOrderVal = 0;
$soincrVal = 0;
}
// Default incrementing if no minimum order val and no sales order increment.
if ($minOrderVal === 0 && $soincrVal === 0) {
if ($button.text() === "+") {
newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below zero
if (oldValue > 1) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
}
// If minimum order value is in use and soincrement value is not in use.
if (($minOrderVal > 0) && ($soincrVal === 0)) {
if ($button.text() === "+") {
if (oldValue >= $minOrderVal) {
newVal = parseFloat(oldValue) + 1;
} else {
newVal = $minOrderVal;
}
} else {
// Don't allow decrementing below zero
if (oldValue > $minOrderVal) {
newVal = parseFloat(oldValue) - 1;
} else {
newVal = 0;
}
}
}
// If soincr value is in use and minimum order value is not in use.
if (($soincrVal > 0) && ($minOrderVal === 0)) {
if ($button.text() === "+") {
if (oldValue >= $soincrVal) {
newVal = parseFloat(oldValue) + (mod === 0 || !isNaN(mod) ? $soincrVal : ($soincrVal - mod) );
} else {
newVal = $soincrVal;
}
} else {
// Don't allow decrementing below zero
if (oldValue > $soincrVal) {
newVal = parseFloat(oldValue) - (mod === 0 || !isNaN(mod) ? $soincrVal : mod );
} else {
newVal = 0;
}
}
}
// If soincr value and minimum order value is in use and soincr is greater than minimum order value.
if (($soincrVal > 0) && ($minOrderVal > 0) && ($soincrVal > $minOrderVal) ){
if ($button.text() === "+") {
if (oldValue >= $soincrVal) {
newVal = parseFloat(oldValue) + (mod === 0 || !isNaN(mod) ? $soincrVal : ($soincrVal - mod) );
} else {
newVal = $soincrVal;
}
} else {
// Don't allow decrementing below zero
if (oldValue > $soincrVal) {
newVal = parseFloat(oldValue) - (mod === 0 || !isNaN(mod) ? $soincrVal : mod );
} else {
newVal = 0;
}
}
}
// If minimum order value and soincrement value both in use and minumum order val is greater than soincrement value and mod is equal to 0.
if (($soincrVal > 0) && ($minOrderVal > 0) && ($minOrderVal >= $soincrVal)) {
if ($button.text() === "+") {
if (modMinordSoincr === 0) {
// When diff between minorder and soincr is Zero.
if (oldValue >= $minOrderVal) {
newVal = parseFloat(oldValue) + (mod === 0 || !isNaN(mod) ? $soincrVal : ($soincrVal - mod));
} else {
newVal = $minOrderVal;
}
} else {
// When diff between minorder and soincr NOT Zero.
// reset minOrderVal due to minordeval not a modulus of soincr
$minOrderVal = $minOrderVal + (modMinordSoincr === 0 || !isNaN(modMinordSoincr) ? $soincrVal : ($soincrVal - modMinordSoincr));
if (oldValue >= $minOrderVal) {
newVal = parseFloat(oldValue) + (mod === 0 || !isNaN(mod) ? $soincrVal : ($soincrVal - mod));
} else {
newVal = $minOrderVal;
}
}
} else {
// Don't allow decrementing below zero
if (modMinordSoincr === 0) {
// When diff between minorder and soincr is Zero.
if (oldValue > $minOrderVal) {
newVal = parseFloat(oldValue) - (mod === 0 || !isNaN(mod) ? $soincrVal : mod );
} else {
newVal = 0;
}
} else {
// When diff between minorder and soincr NOT Zero.
// reset minOrderVal due to minordeval not a modulus of soincr
$minOrderVal = $minOrderVal + (modMinordSoincr === 0 || !isNaN(modMinordSoincr) ? $soincrVal : ($soincrVal - modMinordSoincr) );
if (oldValue > $minOrderVal) {
newVal = parseFloat(oldValue) - (mod === 0 || !isNaN(mod) ? $soincrVal : mod) ;
} else {
newVal = 0;
}
}
}
}
return Number(newVal);
}
function check_stock_backorder_message($layout, $btnSelector){
//For Standard pages like - product, productlist view, prodgroup dropdown
if ($layout === 'table'){
$($btnSelector).unbind();
$($btnSelector).bind("click", function(e) {
var $this = $(this);
var $form = $this.closest('form');
var stcode;
var qtySubmit;
var input = $('input[name*="addstockcode"].add-basket-stcode');
var numItems = input.length;
var qtyField = $('.table.group tbody tr .qty.basketqty input.add-basket-stcode');
var checkarray = [];
$.each(input, function(i,e){
stcode = $(e).val();
qtySubmit = $(e).parent().find('.buy-qty').val();
checkarray[i] = [];
checkarray[i][0] = stcode;
checkarray[i][1] = qtySubmit;
});
var data;
//console.log ("Stock code = '" + stcode + "' qtysubmitted='" + qtySubmit + "'");
e.preventDefault();
$.ajax({
type: "POST",
//dataType: "json",
url: "/ajaxAvailableStock.php",
data: {postdata: checkarray, noprods: numItems},
beforeSend: function(){},
success: function(data){
if(data === 'true'){
// enough stock available ..
$form.trigger('submit');
} else{
// not enough stock ..load modal data
$this.after(data);
// trigger modal
$('#buyOverStockModal').modal('show').on('click', '.btn-ok', function() {
$form.trigger('submit'); // submit the form
});
// reset qty button click - reset qty to available qty
$('#buyOverStockModal').on('click', '.btn-reset-qty', function() {
instockQty = $(this).attr('data-resetqty');
$this.closest('form').find('input[name="quantity"]').val(instockQty);
$form.trigger('submit'); // submit the form
});
//remove modal from dom
$('#buyOverStockModal').on('hidden.bs.modal', function (e) {
$(this).remove();
});
}
}
});
});
} else if ($layout === 'standard'){
//For Standard pages like - product, productlist view, prodgroup dropdown
$($btnSelector).unbind();
$($btnSelector).bind("click", function(e) {
var $this = $(this);
var $form = $this.closest('form');
var stcode = $this.closest('form').find('input[name="addstockcode"]').val();
var qtySubmit = $this.closest('form').find('input[name="quantity"]').val();
var data;
//console.log ("Stock code = '" + stcode + "' qtysubmitted='" + qtySubmit + "'");
e.preventDefault();
$.ajax({
type: "POST",
//dataType: "json",
url: "/ajaxAvailableStock.php",
data: {stockcode: stcode, quantitySubmitted: qtySubmit},
beforeSend: function(){},
success: function(data){
if(data === 'true'){
// enough stock available ..
$form.trigger('submit');
} else{
// not enough stock ..load modal data
$this.after(data);
// trigger modal
$('#buyOverStockModal').modal('show').on('click', '.btn-ok', function() {
$form.trigger('submit'); // submit the form
});
// reset qty button click - reset qty to available qty
$('#buyOverStockModal').on('click', '.btn-reset-qty', function() {
instockQty = $(this).attr('data-resetqty');
$this.closest('form').find('input[name="quantity"]').val(instockQty);
$form.trigger('submit'); // submit the form
});
//remove modal from dom
$('#buyOverStockModal').on('hidden.bs.modal', function (e) {
$(this).remove();
});
}
}
});
});
}
}
// adds record to table
function addToBackInStockNotificationTable (product, email, url) {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
product: product,
email: email
},
success: function (data) {
const $button = $('.prod-enquire-' + data);
$button.text('');
$button.html('
');
$button.css('background-color', 'grey');
$button.css('border-color', 'grey');
setTimeout(function () {
$button.html(' ');
$button.css('background-color', 'green');
$button.css('border-color', 'green');
}, 1000);
}
});
}
function checkIfCanAddToBackInStockNotificationTable (product, url) {
$.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
product: product
},
success: function (data) {
const $button = $('.prod-enquire-' + data[1]);
if (data[0] === true) {
$button.attr('disabled', 'disabled');
$button.text('You have already requested to be updated');
} else {
$button.text('Email when available');
$button.removeAttr('disabled');
}
}
});
}