// 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: '/quotes/ajax/add', 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 Order Request Form',
timeout: 3000,
progressBar: true,
}).show();
//$('#tooltipcontainer').html('
Successfully added ' + obj.totalitems + ' ' + sItems + ' - Go To Quote Form
').fadeIn(500);
}
else {
new Noty({
id: 'tooltip-notifications',
type: 'error',
text: 'You have not added any items to the order request 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 */
/* Add Item to Edited Display Quotes Page*/
$(".quotesubmitinput-quoteedited").on("click", function(e){
e.preventDefault();
console.log('quote edited');
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-quoteedited").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();
}
console.log(sForm);
$.ajax({
type: 'POST',
//format: 'json',
url: '/ajaxQuoteEdited.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 Order Request Form',
timeout: 3000,
progressBar: true,
}).show();
//$('#tooltipcontainer').html('
Successfully added ' + obj.totalitems + ' ' + sItems + ' - Go To Quote Form
').fadeIn(500);
}
else {
new Noty({
id: 'tooltip-notifications',
type: 'error',
text: 'You have not added any items to the order request form',
timeout: 3000,
progressBar: true
}).show();
//$('#tooltipcontainer').html('
`);
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, categoryId, callback ) {
$.ajax({
url: "/ajaxFavourites.php",
type: 'POST',
data: {action: 'removeFavourite', stockCode: stockCode, categoryId: categoryId},
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 {
if ($("body").attr("class") !== 'favourite-products') {
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);
if ($("body").attr("class") === 'favourite-products') {
$parent = $(selectedButton).closest(".favourite");
$panel = $parent.closest(".panel-body");
$parent.remove();
if ($panel.html().trim() === '') {
$panelheading = $panel.parent().prev(".panel-heading").children();
if ($panelheading.html().indexOf("Not in Categories") !== -1) {
$panel.parent().parent().remove();
} else {
$panel.html("
No favourites in this category
");
}
}
location.reload();
} else {
$(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() {
if (typeof categoryId === 'undefined') {
categoryId = null;
}
$.ajax({
url: "/ajaxFavourites.php",
type: 'POST',
data: {action: 'checkStatus', stockCode: stockCode, categoryId: categoryId},
dataType: 'json',
success: function (data) {
if (data.status === 'isNotFavourite') {
$("#favourites-modal").modal({
show: true
});
} else {
removeFavourite(stockCode, categoryId, 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 () {
$('#stocklevels-modal').on('show.bs.modal', function () {
$("#stocklevels-modal .modal-body").empty();
$.ajax({
url: '/ajaxStockLevels.php',
type: 'POST',
data: {stockCode: stocklevelsCode},
success: function (data) {
$("#stocklevels-modal .modal-body").append(data);
}
});
});
// on modal open
$('#favourites-modal').on('show.bs.modal', function () {
catIds = [];
if (typeof categories !== "undefined") {
var catIds = categories.split("-");
}
var $select = $("#favourite-select-multi");
$select.empty();
var $noCatCB = $("");
if (catIds.indexOf("0") !== -1) {
$noCatCB.prop('selected', true);
}
$select.append($noCatCB);
// fetch categories from server and update drop-down
$.ajax({
url: '/ajaxFavourites.php',
type: 'POST',
data: {action: 'getCategories', stockCode: stockCode},
dataType: 'json',
success: function (data) {
$.each(data.categories, function (i, v) {
$select.append("");
})
$("#favourite-select-multi").select2({
closeOnSelect: false, // Prevents dropdown from closing when an option is clicked
templateSelection: formatSelection // Custom function to format selected items
});
function formatSelection(selection) {
return selection.text;
}
}
});
});
// whenever a key is pressed, update category drop-down
$("#new-category-name").on('keyup', updateCategorySelect);
// when save is clicked
$("#save-favourite").on('click', function () {
//onSaveCallback = function() {
// location.reload();
//};
var ids = '';
var data = $('#favourite-select-multi').select2('data');
if (data.length) {
for (var i = 0; i < data.length; i++) {
ids += data[i].id + "-";
}
ids = ids.substring(0, ids.length - 1);
}
var newCategory = $("#new-category-name").val().trim();
if (ids.length || newCategory.length) {
$.ajax({
url: "/ajaxFavourites.php",
type: "POST",
data: {action: "saveFavouriteMulti", stockCode: stockCode, ids: ids, title: newCategory},
dataType: 'json',
success: function (data) {
$("#favourites-modal").modal('hide');
onSaveCallback(data);
//if (onSaveCallback !== null && typeof onSaveCallback === "function") {
// onSaveCallback(data);
//}
}
});
}
/*
// 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-------------------------------------------------------------------------------------------------*/
$("#quoteitems").on("click", ".stocklevels-modal-span", function(e){
e.preventDefault();
stocklevelsCode = $(this).attr("data-stcode");
$("#stocklevels-modal").modal({
show: true
});
});
$(".stocklevels-modal-span").on('click', function (e) {
e.preventDefault();
e.stopPropagation();
stocklevelsCode = $(this).attr("data-stcode");
$("#stocklevels-modal").modal({
show: true
});
});
/*---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();
categories = $(this).siblings('[name=wishlistCategories]').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();
categoryId = $(this).parent().siblings('[name=category_id]').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('
' +
'' +
'
£
' +
'
Current Spend £' + periodspend.toFixed(2) + '
' +
'
').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('
' +
'' +
'
£
' +
'
Current Spend £' + periodspend.toFixed(2) + '
' +
'
').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('
' +
'' +
'
£
' +
'
Rollover £' + value.rollovervalue + '
' +
'
Current Spend £' + periodspend.toFixed(2) + '
' +
'
').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('
' +
'' +
'
£
' +
'
Current Spend £' + yearspend.toFixed(2) + '
' +
'
').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 += '