// 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();
        }
    });
    // 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
Successfully added to favourites - Go To Favourites ';
        } else {
            html = 'Add to Favourites Go To Favourites ',
                timeout: 3000,
                progressBar: true
            }).show();
            //$('#tooltipcontainer').html('').fadeIn(500);
            $(selectedButton).html('Successfully removed from favourites
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 + "   ' +
                            ' ' + title + ' ' +
                            '' +
                            ' ');
                            iCnt++;
                        }); //  end for each
                        $("" + items.join("") + '" ).append( "" + item.label + " " ).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
        /**********************************************************
     * 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 ( false === 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('