var falseConditions = {};

function validateEmail(email) {
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return re.test(String(email).toLowerCase());
}

function validatePhone(phone) {
    var re = /^[\+]?[(]?[0-9]{3}[)]?[-\s\.]?[0-9]{3}[-\s\.]?[0-9]{4,7}$/im;
    return re.test(phone);
}

//Short code
function matchRuleShort(str, rule) {
    var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
    return new RegExp("^" + rule.split("*").map(escapeRegex).join(".*") + "$").test(str);
}

function instantPrint(divName) {
    var printContents = document.getElementById(divName).innerHTML;
    var originalContents = document.body.innerHTML;

    document.body.innerHTML = printContents;
    window.print();
    document.body.innerHTML = originalContents;
}

function format_date_for_input(date) {
    const months = ["01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"];
    let date_obj = new Date(date);
    let formatted_date = date_obj.getFullYear() + "-" + months[date_obj.getMonth()] + "-" + date_obj.getDate();
    return formatted_date;
}

function hexToRgb(hex) {
    var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
    return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
    } : null;
}

function colorShade(hex, perc = 10) {
    perc = 1 - (perc / 100);
    var r = hexToRgb(hex).r * perc;
    var g = hexToRgb(hex).g * perc;
    var b = hexToRgb(hex).b * perc;
    return [Math.floor(r), Math.floor(g), Math.floor(b)].join();
}

function numberWithCommas(x) {
    var parts = x.toString().split(".");
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    return parts.join(".");
}

function toMoney(amount, currency = false) {
    if (!currency) {
        currency = getOption("default_currency");
    }
    return currency + " " + numberWithCommas(amount);
}

function getMeta(id, metaType = "post", selCol = "id") {
    var result;
    $.ajax({
        url: "app/includes/ajax.php",
        type: "post",
        data: { action: "get_meta", id: id, meta_type: metaType, sel_col: selCol },
        async: false
    }).done(function(data) {
        try {
            result = JSON.parse(data);
        } catch (err) {
            console.log(err);
            console.log(result);
        } finally {}
    })
    return result;
}

function getMetaByData(metaData, metaType = "post") {
    var result;
    $.ajax({
        url: "app/includes/ajax.php",
        type: "post",
        data: { action: "get_meta_by_data", meta_data: metaData, meta_type: metaType },
        async: false
    }).done(function(data) {
        try {
            result = JSON.parse(data);
        } catch (err) {
            console.log(err);
            console.log(result);
        } finally {}
    })
    return result;
}

// function loadPage(url) {
//  $.get(url, function(data) {
//          $("body").replaceWith(data);
//  });
// }

function getOption(option, cache = true, expiry = 300) {
    if (!Date.now) {
        Date.now = function() { return new Date().getTime(); }
    }
    var now = Math.floor(Date.now() / 1000);
    if (cache && (sessionStorage.getItem(option) !== undefined)) {
        var testexpiry = parseInt(sessionStorage.getItem("optionTS_" + option)) + expiry;
        if (testexpiry > now) {
            return JSON.parse(sessionStorage.getItem(option));
        }
    }
    var theOption;
    jQuery.ajax({
        url: "app/includes/ajax.php",
        type: "post",
        data: { action: "get_option", option: option },
        async: false
    }).done(function(data) {
        try {
            theOption = JSON.parse(data);
            if (cache) {
                sessionStorage.setItem(option, data);
                sessionStorage.setItem("optionTS_" + option, now);
            }
        } catch (err) {
            console.log(err);
            console.log(data);
        } finally {}
    })
    return theOption;
}

function getRecord(record, cache = true, expiry = 300) {
    if (!Date.now) {
        Date.now = function() { return new Date().getTime(); }
    }
    var now = Math.floor(Date.now() / 1000);
    if (cache && (sessionStorage.getItem(record) !== undefined)) {
        var testexpiry = parseInt(sessionStorage.getItem("recordTS_" + record)) + expiry;
        if (testexpiry > now) {
            return JSON.parse(sessionStorage.getItem(record));
        }
    }
    var theRecord;
    jQuery.ajax({
        url: "app/includes/ajax.php",
        type: "post",
        data: { action: "get_record", record: record },
        async: false
    }).done(function(data) {
        try {
            theRecord = JSON.parse(data);
            if (cache) {
                sessionStorage.setItem(record, data);
                sessionStorage.setItem("recordTS_" + record, now);
            }
        } catch (err) {
            console.log(err);
            console.log(data);
        } finally {}
    })
    return theRecord;
}

function returnOption(option) {
    return option;
}
// console.log(getOption("user_roles", true, 60));

/**
 * Navigate is a function designed for creating a link and automatically redirects
 * @param  {string} href     Link
 * @param  {boolean} newTab   Weather to open in a new tab or not
 * @param  {boolean} download Weather to add download attribute or not
 * @return {Null}          No return
 */
function navigate(href, newTab, download) {
    var a = document.createElement('a');
    a.href = href;
    if (newTab) {
        a.setAttribute('target', '_blank');
    }
    if (download) {
        a.setAttribute('download', '');
    }
    a.style.display = 'none';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

/**
 * sends a request to the specified url from a form. this will change the window location.
 * @param {string} path the path to send the post request to
 * @param {object} params the parameters to add to the url
 * @param {string} [method=post] the method to use on the form
 */

function post(path, params, method = 'post') {

    // The rest of this code assumes you are not using a library.
    // It can be made less verbose if you use one.
    const form = document.createElement('form');
    form.method = method;
    form.action = path;

    for (const key in params) {
        if (params.hasOwnProperty(key)) {
            const hiddenField = document.createElement('input');
            hiddenField.type = 'hidden';
            hiddenField.name = key;
            hiddenField.value = params[key];

            form.appendChild(hiddenField);
        }
    }

    document.body.appendChild(form);
    form.submit();
}

Object.size = function(obj) {
    var size = 0,
        key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

jQuery(document).ready(function($) {
    function editActionBtnState() {
        for (let key in falseConditions) {
            if (falseConditions[key] > 0) {
                $("#btn-" + key).css("display", "none");
            } else {
                $("#btn-" + key).css("display", "inline-block");
            }
        }
    }

    function inAppPopupShow(location) {
        $('#inAppPopup').modal('show');
        $('#inAppPopup').find('.modal-body iframe').attr("src", location);
    }

    // $("li.dropdown a").click(function(e){
    //     $(this).next('ul.dropdown-menu').css("display", "block");
    //     e.stopPropagation();
    // });

    (function($) {
        $.fn.refreshSectionList = function(options) {

            var defaultContentField = $(this).find("tbody");
            var defaultContent = $(defaultContentField).html();

            $.ajax({
                type: 'POST',
                url: 'app/includes/ajax.php',
                data: { action: 'get_db_sections' },
                success: function(data) {
                    data = JSON.parse(data);
                    if (data.error == 1) {
                        $(defaultContentField).html(defaultContent);
                    } else if (data.error == 0) {
                        var html = "";
                        var i = 1;
                        for (var key in data.sections) {
                            html += '<tr>';
                            html += '<td class="pt-0 pb-0">' + i + '</td>';
                            html += '<td class="pt-0 pb-0">' + data.sections[key].id + '</td>';
                            html += '<td class="pt-0 pb-0">' + data.sections[key].section_name + '</td>';
                            html += '<td class="pt-0 pb-0"' + data.sections[key].description + '</td>';
                            if (data.sections[key].status == 'active') {
                                html += '<td class="pt-0 pb-0"><a class="ajax-action red" href="javascript:void(0)" data-callback="refreshSectionList" data-callbackid=".db_section_table" data-action-callback="deactivate_post" data-id="' + data.sections[key].id + '">deactivate</a> | <a href="edit-db-section?id=' + data.sections[key].id + '">Edit</a></td>';
                            } else html += '<td class="pt-0 pb-0"><a class="ajax-action green" href="javascript:void(0)" data-callback="refreshSectionList" data-callbackid=".db_section_table" data-action-callback="activate_post" data-id="' + data.sections[key].id + '">activate</a> | <a href="edit-db-section?id=' + data.sections[key].id + '">Edit</a></td>';

                            html += '</tr>';
                            i++;
                        }
                        $(defaultContentField).html(html);
                    }
                },
                error: function(e) {
                    $(defaultContentField).html(defaultContent);
                }
            });
        };

    })(jQuery);

    (function($) {
        $.fn.findGetParameter = function(options) {

            var result = null,
                tmp = [];
            var items = location.search.substr(1).split("&");
            for (var index = 0; index < items.length; index++) {
                tmp = items[index].split("=");
                if (tmp[0] === options.param) result = decodeURIComponent(tmp[1]);
            }
            $(this).val(result);
            return result;
        };
    })(jQuery);

    (function($) {
        $.fn.removePostItem = function(options) {
            if (options.id == null) {
                return;
            }
            $.ajax({
                type: 'POST',
                url: 'app/includes/ajax.php',
                data: { action: 'remove_post_item', id: options.id },
                success: function(data) {
                    data = JSON.parse(data);
                    if (data.error == 1) {

                    } else if (data.error == 0) {
                        if (options.callback != null && options.callback != "") {
                            if (options.callbackid != null && options.callbackid != "") {
                                eval('$("' + options.callbackid + '").' + options.callback + "()");
                            } else eval('$.' + options.callback + "()");

                        }
                    }
                },
                error: function(e) {

                }
            });
        };

        $.fn.disable = function() {
            $(this).attr("disabled", true);
        };

        /**
         * Api used to download file from upload library
         * @param  {Object} options [must have ref which is image library ref]
         * @return {null}         [Does not return any parameter but automatically downloads the files]
         */
        $.fn.libraryFileGrabberApi = function(options) {
            $.ajax({
                type: "post",
                url: 'app/includes/ajax.php',
                data: { action: 'library_file_grabber_api', ref: options.ref },
            }).done(function(data) {
                try {
                    data = JSON.parse(data);
                    if (data) {
                        var x = 0;
                        $.each(data.files, function(i, file) {
                            setTimeout(function() {
                                navigate(i, false, true);
                                // window.location.href = i;
                            }, 3000 * x)
                            x++;
                        })
                    }
                } catch (err) {
                    console.log(err);
                    console.log(data);
                } finally {

                }
            })
        }

        $.fn.getStandaloneEntries = function() {
            var output = $(this);
            var loader = document.createElement("img");
            loader.src = "app/images/ajax-loader.gif";
            loader.width = 100;
            loader.style.display = "block";
            loader.style.margin = "auto";

            $(output).find(".display-result").append(loader);
            var columns = {};
            if ($(this).find(".columns").length > 0) {
                columns = $($(this).find(".columns")[0]).data();
            }
            var compare = {};
            if ($(this).find(".compare").length > 0) {
                compare = $($(this).find(".compare")[0]).data();
            }
            var dynamicColumns = {};
            if ($(this).find(".dynamiccolumns").length > 0) {
                dynamicColumns = $($(this).find(".dynamiccolumns")[0]).data();
            }
            var properties = {};
            if ($(this).find(".properties").length > 0) {
                properties = $($(this).find(".properties")[0]).data();
            }
            var settings = $(output).find(".settings").data();
            var data = { action: "get_entries", settings: settings, columns: columns, dynamicColumns: dynamicColumns, compare: compare, properties: properties };
            if ($(output).find(".actions").length > 0) {
                var actions = $($(output).find(".actions")[0]).data();
                var actionLinks = new Object();
                var actionArgs = new Object();
                var actionAccess = new Object();
                var actionCallback = new Object();
                var actionCondition = new Object();
                var actionConditioner = new Object();
                var actionPrompt = new Object();
                var actionPopup = new Object();
                for (var key in actions) {
                    var args = {}
                    args[$($(output).find(".action-args")[0]).data(key)] = $($(output).find(".action-args")[0]).data(key);
                    args['callbackid'] = "#" + $(output).attr("id");
                    args['callback'] = "getEntries";
                    actionLinks[actions[key]] = $($(output).find(".action-links")[0]).data(key);
                    actionArgs[actions[key]] = args;
                    actionAccess[actions[key]] = $($(output).find(".action-access")[0]).data(key);
                    actionCallback[actions[key]] = $($(output).find(".action-callback")[0]).data(key);
                    actionCondition[actions[key]] = $($(output).find(".action-condition")[0]).data(key);
                    actionConditioner[actions[key]] = $($(output).find(".action-conditioner")[0]).data(key);
                    actionPrompt[actions[key]] = $($(output).find(".action-prompt")[0]).data(key);
                    actionPopup[actions[key]] = $($(output).find(".action-popup")[0]).data(key);
                }
                data.actionLinks = actionLinks;
                data.actionArgs = actionArgs;
                data.actionAccess = actionAccess;
                data.actionCallback = actionCallback;
                data.actionCondition = actionCondition;
                data.actionConditioner = actionConditioner;
                data.actionPrompt = actionPrompt;
                data.actionPopup = actionPopup;
            }
            $.ajax({
                type: "post",
                url: "app/includes/ajax.php",
                data: data
            }).done(function(data) {
                try {
                    data = JSON.parse(data);
                    $(loader).remove();
                    $(output).find(".display-result").html(data);
                    $(".numberInput").numberInputInit();
                } catch (err) {
                    console.log(err);
                    console.log(data);
                } finally {
                    console.log(data);
                }
            })
        }

    })(jQuery);

    jQuery(document).on('click', '.library_file_grabber', function() {
        var ref = $(this).data("ref");
        $(this).libraryFileGrabberApi({ "ref": ref });
    })

    jQuery(document).on('change', '.table-multi-select-all', function(e) {
        e.preventDefault();
        if ($(this).is(":checked")) {
            $("." + $(this).data("groupClass")).prop('checked', true);
            $("." + $(this).data("groupClass")).each(function(i, v) {
                var conditions = $(this).data("actionCondition");
                if (conditions !== undefined) {
                    conditions = conditions.split(",");
                    $(conditions).each(function(index, value) {
                        if (falseConditions.hasOwnProperty(value)) {
                            falseConditions[value] = falseConditions[value] + 1;
                        } else {
                            falseConditions[value] = 1;
                        }
                    });
                }
            });
        } else {
            $("." + $(this).data("groupClass")).prop('checked', false);
            for (let key in falseConditions) {
                falseConditions[key] = 0;
            }
        }
        editActionBtnState();
    })

    jQuery(document).on('change', '.selectrowbtn', function(e) {
        e.preventDefault();
        if ($(this).is(":checked")) {
            var conditions = $(this).data("actionCondition");
            if (conditions !== undefined) {
                conditions = conditions.split(",");
                $(conditions).each(function(index, value) {
                    if (falseConditions.hasOwnProperty(value)) {
                        falseConditions[value] = falseConditions[value] + 1;
                    } else {
                        falseConditions[value] = 1;
                    }
                });
            }
        } else {
            var conditions = $(this).data("actionCondition");
            if (conditions !== undefined) {
                conditions = conditions.split(",");
                $(conditions).each(function(index, value) {
                    if (falseConditions.hasOwnProperty(value)) {
                        falseConditions[value] = falseConditions[value] - 1;
                    } else {
                        falseConditions[value] = 0;
                    }
                });
            }
        }
        editActionBtnState();
    })

    jQuery(document).on('click', '.popmeup', function(e) {
        e.preventDefault();
        var href = $(this).attr("href");
        href += (href.indexOf("?") === -1) ? "?" : "&";
        href += "ispopup=true";
        var isPrint = (href.indexOf("media=print") == -1) ? false : true;
        // inAppPopupShow(href);
        // return;
        var args = $(this).data();
        var e = $(this);
        var title = ($(this).data('title') !== undefined) ? $(this).data('title') : "";
        var continuebtn = ($(this).data("continueBtn") === undefined) ? "Continue" : $(this).data("continueBtn");
        if ($(this).hasClass("confirmThis")) {
            $.confirm({
                title: title,
                content: $(this).data('content'),
                buttons: {
                    continue: {
                        text: continuebtn,
                        btnClass: 'btn-blue',
                        action: function() {
                            if (($(e).data("window") !== undefined) && isPrint) {
                                var w = $(e).data("window");
                                w.window.close();
                            }
                            var settings = "";
                            for (var k in args) {
                                settings += k + "=" + args[k] + ",";
                            }
                            setTimeout(function() {
                                if (isPrint) {
                                    $(e).data("window", w);
                                } else {
                                    inAppPopupShow(href);
                                }
                            }, 500);
                        }
                    },
                    cancel: function() {

                    }
                }
            });
        } else {
            if ($(this).data("prompt") !== undefined && $(this).data("prompt") !== "") {
                delete args.prompt;
                var prompt = $(this).data("prompt");
                var promptform = '' +
                    '<form action="" class="formName">';
                for (var tag in prompt) {
                    promptform += '<div class="form-group">' +
                        '<label>' + prompt[tag] + '</label>' +
                        '<textarea type="text" id="prompttag-' + tag + '" class="name form-control" required /></textarea>' +
                        '</div>';
                }
                promptform += '</form>';
                $.confirm({
                    title: title,
                    content: promptform,
                    buttons: {
                        formSubmit: {
                            text: continuebtn,
                            btnClass: 'btn-blue',
                            action: function() {
                                var link = (href.indexOf("?") === -1) ? href + "?" : href + "&";
                                for (var tag in prompt) {
                                    var entry = this.$content.find('#prompttag-' + tag).val();
                                    if (!entry) {
                                        $.alert('Please enter ' + prompt[tag]);
                                        return false;
                                    }
                                    link += tag + "=" + entry + "&";
                                }
                                link = link.slice(0, -1);
                                if (($(e).data("window") !== undefined) && isPrint) {
                                    var w = $(e).data("window");
                                    w.window.close();
                                }
                                var settings = "";
                                for (var k in args) {
                                    settings += k + "=" + args[k] + ",";
                                }
                                if (isPrint) {
                                    setTimeout(function() {
                                        var w = window.open(link, '', settings);
                                        $(e).data("window", w);
                                    }, 500);
                                    return false;
                                } else {
                                    inAppPopupShow(link);
                                }


                            }
                        },
                        cancel: function() {
                            //close
                        },
                    },
                    onContentReady: function() {
                        // bind to events
                        var jc = this;
                        this.$content.find('form').on('submit', function(e) {
                            // if the user submits the form by pressing enter in the field.
                            e.preventDefault();
                            jc.$$formSubmit.trigger('click'); // reference the button and click it
                        });
                    }
                });
            } else {
                if (($(e).data("window") !== undefined) && isPrint) {
                    var w = $(e).data("window");
                    w.window.close();
                }
                var settings = "";
                for (var k in args) {
                    settings += k + "=" + args[k] + ",";
                }
                if (isPrint) {
                    setTimeout(function() {
                        var w = window.open(href, '', settings);
                        $(e).data("window", w);
                    }, 500);
                    return false;
                } else {
                    inAppPopupShow(href);
                }

            }
        }
        // var onreturncb = ($(e).data('onreturncb') === undefined) ? "refreshPage" : $(e).data('onreturncb');
        var onreturncb = $(e).data('onreturncb');
        $("#inAppPopup").on('hidden.bs.modal', function(e) {
            if (onreturncb != null && $(e).data("onreturncbid") != null) {
                eval('$("' + $(e).data("onreturncbid") + '").' + onreturncb + "(dataset)");
                return false;
            }
            if (onreturncb != null && $(e).data("onreturncbid") == null) {
                try {
                    eval('$.' + onreturncb + "(dataset)");
                } catch (err) {
                    try {
                        eval('$(document).' + onreturncb + "(dataset)");
                    } catch (err) {
                        $.notify(err + "\nYou are seeing this error because you are possibly using an old outdated browser to access this site. Update your browser.", "warning");
                    } finally {}
                } finally {}
                return false;
            }
        })
        return false;
    })

    jQuery(document).on('click', '.remove_post_item', function() {
        var btn = $(this);
        $.confirm({
            title: "",
            content: "Are you sure you want to delete this item?",
            buttons: {
                continue: {
                    text: 'Delete',
                    btnClass: 'btn-blue',
                    action: function() {
                        $(this).removePostItem({
                            id: $(btn).data("id"),
                            callback: $(btn).data("callback"),
                            callbackid: $(btn).data("callbackid"),
                        })
                    }
                },
                cancel: function() {

                }
            }
        });
    })

    jQuery(document).on('change', '.toggle-checkbox', function() {
        var input_el = $($(this).data("target")).find("input");
        $($(this).data("target")).toggle("fast", function() {
            if ($(input_el).attr("disabled") == "disabled") {
                $(input_el).attr({ "disabled": false, "required": "required" });
            } else $(input_el).attr({ "disabled": "disabled", "required": false });
        });
    })

    jQuery(document).on('click', '.ajax-action', function() {
        var btn = $(this);
        var btnText = $(btn).html();
        $(btn).data("action", "action").html('<em>Processing</em>').removeClass("ajax-action").css("cursor", "wait");
        var content = $(btn).data('content');
        var title = "";
        var continueBtn = $(btn).data("continueBtn");
        if ($(btn).data("url") != null) {
            var url = $(btn).data("url");
        } else var url = 'app/includes/ajax.php';
        var loader = document.createElement("img");
        loader.src = "app/images/ajax-loader.gif";
        loader.width = 100;
        loader.style.display = "block";
        loader.style.position = "absolute";
        loader.style.margin = "auto";
        loader.style.top = "-32px";
        loader.style.right = "-70px";
        $(btn).css({
            "position": "relative"
        }).append(loader);
        var dataset = $(btn).data();
        var withPrompt = false;
        delete dataset.content;

        if (dataset.actionCallback === "edit_post") {
            $.ajax({
                type: 'POST',
                url: 'app/includes/ajax.php',
                data: { id: dataset.id, action: 'edit_post_action' },
            }).done(function(data) {
                try {
                    data = JSON.parse(data);
                    var display = $(btn).closest(".display");
                    if (display.length > 0) {
                        var formid = $(display).data("form");
                        if (formid !== undefined && formid !== null) {
                            form = $(formid);
                            if (data.meta) {
                                for (key in data.meta) {
                                    var el = form.find($("[name=\"" + key + "\"]"));
                                    if (el !== undefined && el !== null) {
                                        console.log(el);
                                        if ($(el).hasClass("wyswyg-editor")) {
                                            $(el).trumbowyg('html', data.meta[key]);
                                        } else if ($(el).hasClass("croppie-file")) {
                                            ctrlId = $(el).data("controlId");
                                            $("#croppie-output-" + ctrlId).attr("src", data.meta[key]);
                                        } else {
                                            $(el).val(data.meta[key]);
                                        }
                                        if ($(el).hasClass("standardSelect")) {
                                            $(el).trigger("chosen:updated");
                                        }
                                    }
                                }
                                var idEl = document.createElement("input");
                                $(idEl).attr({ "name": "id", "type": "hidden" }).val(data.meta["id"]);
                                $(form).find($("[name=\"id\"]")).remove();
                                $(form).append(idEl);
                                var action = $(form).find($("[name=\"action\"]"));
                                var actionVal = $(action).val();
                                var newVal = actionVal + "__edit";
                                newVal = newVal.replace("__edit__edit", "__edit");
                                $(action).val(newVal);
                                var submitBtnText = $(form).find(".submit").html();
                                $(form).find(".submit").html("Save Edit");
                                $(form).one("koweb-submit", function(e) {
                                    $(form).find(".submit").html(submitBtnText);
                                    $(action).val(actionVal);
                                    $(idEl).remove();
                                    $(form).clearForm();
                                })
                                $([document.documentElement, document.body]).animate({
                                    scrollTop: $(formid).offset().top
                                }, 1000);
                            }
                        }
                    }
                } catch (err) {
                    console.log(err);
                    console.log(data);
                } finally {
                    $(loader).remove();
                    $(btn).html(btnText)
                        .addClass("ajax-action")
                        .css("cursor", "pointer");
                }
            })
            return;
        }

        if ($(this).data("prompt") !== undefined && $(this).data("prompt") !== "") {
            delete dataset.prompt;
            var prompt = $(this).data("prompt");
            '<form action="" class="formName">';
            for (var tag in prompt) {
                content += '<div class="form-group">' +
                    '<label>' + prompt[tag] + '</label>' +
                    '<input type="text" id="prompttag-' + tag + '" class="name form-control numbers-only" required />' +
                    '</div>';
            }
            withPrompt = true;
        }

        $.confirm({
            content: content,
            title: title,
            buttons: {
                continue: {
                    text: continueBtn,
                    btnClass: 'btn-blue',
                    action: function() {
                        if (withPrompt) {
                            for (var tag in prompt) {
                                var entry = this.$content.find('#prompttag-' + tag).val();
                                if (!entry) {
                                    $.alert('Please enter ' + prompt[tag]);
                                    return false;
                                }
                                dataset[tag] = entry;
                            }
                        }

                        $.ajax({
                            type: 'POST',
                            url: url,
                            data: dataset,
                            success: function(data) {
                                try {
                                    $(loader).remove();
                                    data = JSON.parse(data);
                                    if (data.error == 0) {
                                        $.notify(data.msg, "success");
                                        if ($(btn).data("rowid") != null) {
                                            data.rowid = $(btn).data("rowid");
                                        }
                                        if ($(btn).data("callback") != null && $(btn).data("callbackid") != null) {
                                            eval('$("' + $(btn).data("callbackid") + '").' + $(btn).data("callback") + "()");
                                        }
                                        if ($(btn).data("callback") != null && $(btn).data("callbackid") == null) {
                                            try {
                                                eval('$.' + $(btn).data("callback") + "(data)");
                                            } catch (err) {
                                                try {
                                                    eval('$(document).' + $(btn).data("callback") + "(data)");
                                                } catch (err) {
                                                    console.log(err);
                                                } finally {
                                                    $(btn).html(btnText)
                                                        .addClass("ajax-action")
                                                        .css("cursor", "pointer");
                                                }
                                            } finally {
                                                $(btn).html(btnText)
                                                    .addClass("ajax-action")
                                                    .css("cursor", "pointer");
                                            }
                                        }
                                        if ($(btn).data("closeonsuccess") != null) {
                                            setTimeout(function() { window.close(); }, 1000);
                                        }
                                    } else $.notify(data.msg, "error");
                                } catch (err) {
                                    $.notify('Action failed. Error message: <strong class="red">' + err.message + '</strong>. Please contact the software developers.', "error");
                                    console.error(err, err.stack);
                                    console.log(data);
                                } finally {
                                    $(btn).html(btnText)
                                        .addClass("ajax-action")
                                        .css("cursor", "pointer");
                                }
                            },
                            error: function(e) {
                                $.notify("Action failed due to network connection", "error");
                                $(btn).html(btnText)
                                    .addClass("ajax-action")
                                    .css("cursor", "pointer");
                            }
                        });
                    }
                },
                cancel: function() {
                    $(btn).html(btnText)
                        .addClass("ajax-action")
                        .css("cursor", "pointer");
                }
            },
            onContentReady: function() {
                // bind to events
                var jc = this;
                this.$content.find('form').on('submit', function(e) {
                    // if the user submits the form by pressing enter in the field.
                    e.preventDefault();
                    jc.$$continue.trigger('click'); // reference the button and click it
                });
            }
        });
    });

    jQuery(document).on('click', '.ajax-group-action', function() {
        var btn = $(this);
        var btnText = $(btn).html();
        $(btn).data("action", "action").html('<em>Processing</em>').removeClass("ajax-group-action").css("cursor", "wait");
        var content = $(btn).data('content');
        var title = "";
        var continueBtn = $(btn).data("continueBtn");
        if ($(btn).data("url") != null) {
            var url = $(btn).data("url");
        } else var url = 'app/includes/ajax.php';
        var loader = document.createElement("img");
        loader.src = "app/images/ajax-loader.gif";
        loader.width = 100;
        loader.style.display = "block";
        loader.style.position = "absolute";
        loader.style.margin = "auto";
        loader.style.top = "-32px";
        loader.style.right = "-70px";
        $(btn).css({
            "position": "relative"
        }).append(loader);
        var dataset = $(btn).data();
        var withPrompt = false;
        delete dataset.content;
        dataset.selectedItems = [];
        var groupClass = "." + dataset.tableId + "-selectrow";
        var elements = $(groupClass);
        var countele = 0;

        if ($(elements).length < 1) {
            $.notify("You have not made any selection");
            $(btn).html(btnText)
                .addClass("ajax-group-action")
                .css("cursor", "pointer");
            return;
        }

        if (dataset.actionCallback === "edit_post") {
            return;
        }

        if ($(this).data("prompt") !== undefined && $(this).data("prompt") !== "") {
            delete dataset.prompt;
            var prompt = $(this).data("prompt");
            '<form action="" class="formName">';
            for (var tag in prompt) {
                content += '<div class="form-group">' +
                    '<label>' + prompt[tag] + '</label>' +
                    '<input type="text" id="prompttag-' + tag + '" class="name form-control" required />' +
                    '</div>';
            }
            withPrompt = true;
        }

        $.confirm({
            content: content,
            title: title,
            buttons: {
                continue: {
                    text: continueBtn,
                    btnClass: 'btn-blue',
                    action: function() {
                        if (withPrompt) {
                            for (var tag in prompt) {
                                var entry = this.$content.find('#prompttag-' + tag).val();
                                if (!entry) {
                                    $.alert('Please enter ' + prompt[tag]);
                                    return false;
                                }
                                dataset[tag] = entry;
                            }
                        }

                        $(elements).each(function(index, e) {
                            if ($(this).is(":checked")) {
                                countele++;
                                var tempDataset = dataset;
                                $.extend(tempDataset, $(e).data());
                                $.ajax({
                                    type: 'POST',
                                    url: url,
                                    data: tempDataset,
                                    success: function(data) {
                                        try {
                                            $(loader).remove();
                                            data = JSON.parse(data);
                                            if (data.error == 0) {
                                                $.notify(data.msg, "success");
                                                data.rowid = $(e).data("rowid");
                                                if (tempDataset.callback != null && tempDataset.callbackid != null) {
                                                    eval('$("' + tempDataset.callbackid + '").' + tempDataset.callback + "()");
                                                }
                                                if (tempDataset.callback != null && tempDataset.callbackid == null) {
                                                    try {
                                                        eval('$.' + tempDataset.callback + "(data)");
                                                    } catch (err) {
                                                        try {
                                                            eval('$(document).' + tempDataset.callback + "(data)");
                                                        } catch (err) {
                                                            console.log(err);
                                                        } finally {}
                                                    } finally {}
                                                }
                                            } else $.notify(data.msg, "error");
                                        } catch (err) {
                                            $.notify('Action failed. Error message: <strong class="red">' + err.message + '</strong>. Please contact the software developers.', "error");
                                            console.error(err, err.stack);
                                            console.log(data);
                                        } finally {
                                            $(btn).html(btnText)
                                                .addClass("ajax-group-action")
                                                .css("cursor", "pointer");
                                        }
                                    },
                                    error: function(e) {
                                        $.notify("Action failed due to network connection", "error");
                                        $(btn).html(btnText)
                                            .addClass("ajax-group-action")
                                            .css("cursor", "pointer");
                                    }
                                });
                            }
                        });
                        if (countele < 1) {
                            $.notify("You have not made any selection");
                            $(btn).html(btnText)
                                .addClass("ajax-group-action")
                                .css("cursor", "pointer");
                            return;
                        }
                    }
                },
                cancel: function() {
                    $(btn).html(btnText)
                        .addClass("ajax-group-action")
                        .css("cursor", "pointer");
                }
            },
            onContentReady: function() {
                // bind to events
                var jc = this;
                this.$content.find('form').on('submit', function(e) {
                    // if the user submits the form by pressing enter in the field.
                    e.preventDefault();
                    jc.$$continue.trigger('click'); // reference the button and click it
                });
            }
        });

    });

    (function($) {
        $.fn.refreshFileList = function() {
            var e = $(this);
            var userId = $(this).data("userId");
            var ref = $(this).data("ref");
            $.ajax({
                type: 'POST',
                url: 'app/includes/ajax.php',
                data: { action: 'get_library_files', user_id: userId, ref: ref },
                success: function(data) {
                    try {
                        data = JSON.parse(data);
                        $(e).html("");
                        for (var url in data.files) {
                            var li = $("<li></li>");
                            var btn = $("<span class=\"btn-group\"></span>");
                            $(btn).addElement({ 'element': 'button', 'content': '<i class="fas fa-times"></i>', 'class': 'dz_fallback_file_remove btn btn-default', 'data-callback': 'refreshFileList', 'data-callbackid': "#" + $(e).attr("id"), 'data-libId': data.library_id, 'data-url': url })
                                .addElement({ 'element': 'a', 'content': '<i class="fas fa-download"></i>', 'class': 'dz_fallback_file_download btn btn-default', 'href': url, 'download': 'download' });
                            var testRegex = /image/;
                            if (testRegex.test(data.files[url].file_type)) {
                                $(btn).addElement({ 'element': 'a', 'content': '<i class="fas fa-eye"></i>', 'class': 'dz_fallback_file_view btn btn-default', 'href': url, 'data-title': data.files[url].title, 'data-magnify': 'gallery' });
                            }
                            $(li).addElement({ 'element': 'span', 'content': data.files[url].title, 'class': 'dz_fallback_file_title' })
                                .append(btn);
                            $(e).append(li);
                        }
                    } catch (err) {
                        console.log(err);
                        console.log(data);
                    } finally {

                    }
                },
                error: function(e) {

                }
            });
        }

        $.fn.redirectLogin = function() {
            window.location = "dashboard";
        }

        $.fn.refreshPage = function() {
            setTimeout(function() {
                document.location.reload();
            }, 3000);
        }

        $.fn.alertSuccess = function() {
            alert("<i class=\"fas fa-check\" style=\"color: green;\"></i>&nbsp;Success");
        }

    })(jQuery);

    $(document).on("click", ".dz_fallback_file_remove", function(e) {
        e.preventDefault();
        var library_id = $(this).data("libid");
        var serverfilename = $(this).data("url");
        var callbackid = $(this).data("callbackid");
        var callback = $(this).data("callback");
        $.ajax({
            type: 'POST',
            url: 'app/includes/ajax.php',
            data: { action: 'remove_library_file', library_id: library_id, serverfilename: serverfilename },
            success: function(data) {
                eval('$("' + callbackid + '").' + callback + "()");
            },
            error: function(e) {

            }
        });
    })

    $(document).on("click", ".ctc-btn", function() {
        var btnid = $(this).attr("id");
        var btn = document.getElementById(btnid);
        var list = document.getElementById(btn.dataset.textField).innerHTML;
        var input = document.createElement("INPUT");
        input.setAttribute("type", "text");
        input.setAttribute('id', 'ctc_temp_input');
        input.value = list;
        if (btn.dataset.id == null) {
            var cont = document.getElementById("ctc-cont");
        } else var cont = document.getElementById("ctc-cont-" + btn.dataset.id);
        var x = cont.appendChild(input);
        x.select();
        document.execCommand("Copy");
        input.remove();
        cont.innerHTML = 'COPIED <i class="fas fa-check"></i>';
    })


    /**
     * Get HTML asynchronously
     * @param  {String}   url      The URL to get HTML from
     * @param  {Function} callback A callback funtion. Pass in "response" variable to use returned HTML.
     */
    var getHTML = function(url, callback, external = false) {

        // Feature detection
        if (!window.XMLHttpRequest) return;

        // Create new request
        var xhr = new XMLHttpRequest();

        // Setup callback
        xhr.onload = function() {
            if (callback && typeof(callback) === 'function') {
                callback(this.responseXML);
            }
        }

        // Get the HTML
        if (external) {
            xhr.open('GET', "https://cors-anywhere.herokuapp.com/" + url);
        } else {
            xhr.open('GET', url);
        }

        xhr.responseType = 'document';
        xhr.send();

    };


    $(document).on("click", ".print-btn", function(e) {
        e.preventDefault();
        var div = $(this).data("div");
        $(div).printThis({
            base: window.location.href
        });
    })
    $.extend({
        refreshPage: function() {
            setTimeout(function() {
                document.location.reload();
            }, 3000);
        },

        alertSuccess: function() {
            $.alert("<i class=\"fas fa-check\" style=\"color: green;\"></i>&nbsp;Success");
        },

        redirectLogin: function() {
            window.location = "dashboard";
        },

        close_this_window: function() {
            window.close();
        },

        removeTableRow: function(data) {
            $("#" + data.rowid).remove();
        }
    });

    $(".findGetParameter").each(function() {
        var fieldName = $(this).attr("name");
        $(this).findGetParameter({ param: fieldName });
    })

    $(".getEntries").each(function() {
        $(this).getStandaloneEntries();
    })

    window.onbeforeunload = function(event) {
        $(".popmeup").each(function() {
            var w = $(this).data("window");
            if (w !== undefined) {
                w.window.close();
            }
        })
    };
})