function findGetParameter(parameter) {
    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] === parameter) {
            return decodeURIComponent(tmp[1]);
        }
    }
    return false;
}

(function($) {
    $.fn.submitForm = function(options) {
        var form = $(this).parents("form");
        var formid = $(form).attr("id");
        var text = $(this).html();
        var subBut = $(this);

        if ($('#' + formid).attr("action") != null) {
            var action = $('#' + formid).attr("action");
        } else var action = "app/includes/ajax.php";
        if ($(form).validateForm({
                password: 'password'
            })) {
            var submittingMsg = "Submitting";
            if ($("#" + formid).data("submittingmsg") != null) {
                submittingMsg = $("#" + formid).data("submittingmsg");
            }
            $(this).html("<em>" + submittingMsg + "</em>").attr("disabled", true);
            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";
            $(subBut).css({
                "position": "relative"
            }).append(loader);
            var formData = new FormData(form[0]);
            if ($('#item-img-output').data('updated')) {
                var image = $('#item-img-output').attr('src');
                var base64ImageContent = image.replace(/^data:image\/(png|jpg);base64,/, "");
                // var blob = base64ToBlob(base64ImageContent, 'image/png'); 
                var blob = $.base64ToBlob({ 'base64': base64ImageContent, 'mime': 'image/png' })
                formData.append('imagebase64', base64ImageContent);
            }
            $(form).trigger("koweb-submit", ["Custom", "Event"]);
            // Submit the form using AJAX.
            $.ajax({
                type: 'POST',
                url: action,
                data: formData,
                processData: false,
                contentType: false,
                success: function(data) {
                    try {
                        $(loader).remove();
                        data = JSON.parse(data);
                        if (data.error == 1) {
                            data.msg = (data.msg === undefined) ? "Failed" : data.msg;
                            $(subBut).notify(data.msg, {
                                className: "error",
                                autoHide: true,
                                position: "bottom",
                                autoHideDelay: 10000
                            });
                            $.notify(data.msg, {
                                className: "error",
                                autoHide: true,
                                autoHideDelay: 10000
                            });
                        } else if (data.error == 0) {
                            $('#' + formid + ' #item-img-output').data('updated', false);
                            data.msg = (data.msg === undefined) ? "Done" : data.msg;
                            $(subBut).notify(data.msg, {
                                className: "success",
                                autoHide: false,
                                position: "top"
                            });
                            $.notify(data.msg, {
                                className: "success",
                                autoHide: true,
                                autoHideDelay: 10000
                            });
                            if ($('#' + formid).data("clearform") != null) {
                                $('#' + formid).clearForm();
                            }
                            if ($('#' + formid).data("callback") != null && $('#' + formid).data("callbackid") != null) {
                                eval('$("' + $('#' + formid).data("callbackid") + '").' + $('#' + formid).data("callback") + "(data)");
                                return;
                            }
                            if ($('#' + formid).data("callback") != null && $('#' + formid).data("callbackid") == null) {
                                if ($('#' + formid).data("callback") === "redirectLogin") {
                                    var link = $('#' + formid).data("redirect");
                                    link = (data.urlParams !== undefined && data.urlParams !== null) ? link + data.urlParams : link;
                                    window.location = link;
                                    return;
                                }
                                try {
                                    eval('$.' + $('#' + formid).data("callback") + "(data)");
                                } catch (err) {
                                    try {
                                        eval('$(document).' + $('#' + formid).data("callback") + "(data)");
                                    } catch (err) {
                                        $(subBut).notify(err + "\nYou are seeing this error because you are possibly using an old outdated browser to access this site. Update your browser.", "warning");
                                        $.notify(err + "\nYou are seeing this error because you are possibly using an old outdated browser to access this site. Update your browser.", "warning");
                                        setTimeout(function() {
                                            window.location = "dashboard";
                                        }, 5000);
                                    } finally {
                                        $(subBut).html(text).attr("disabled", false);
                                    }
                                } finally {
                                    $(subBut).html(text).attr("disabled", false);
                                }

                                return;
                            }
                            if ($('#' + formid).data("closeonsuccess") != null || findGetParameter("ispopup")) {
                                setTimeout(function() { window.close(); }, 1000);
                            }
                            if ($('#' + formid + ' #addMore').data('activate')) {
                                window.location = $('#' + formid + ' #addMore').data('url');
                            }
                        }
                    } catch (err) {
                        console.log(err);
                        console.log(data);
                    } finally {
                        console.log(data);
                        $(subBut).html(text).attr("disabled", false);
                    }

                },
                error: function(e) {
                    $(subBut).notify("Please check your internet connection. Seems you are offline", "warning");
                    $.notify("Please check your internet connection. Seems you are offline", "warning");
                    $(subBut).html(text).attr("disabled", false);
                }
            });
        }
    }

    $.fn.getEntries = function() {
        var output = $(this);
        // try	{
        if ($(output).data("form") == undefined) {
            var form = $("form[data-callbackid = \"#" + $(output).attr("id") + "\"]")[0];
        } else {
            var form = $($(output).data("form"))[0];
        }
        var fields = $(form).find("input, select, textarea");
        var columns = { "sn": "SN" };
        var dynamicColumns = {};
        for (var i = 0; i < fields.length; i++) {
            if (fields[i].id != "" && fields[i].id != undefined && fields[i].id != null) {
                var label = $("label[for=" + fields[i].id + "]");
                if (label.length > 0) {
                    var text = label[0].innerText;
                    text = text.replace("*", "");
                    if ($("#" + fields[i].id).data("exclude") === undefined) {
                        columns[fields[i].name] = text;
                    }
                    if ($(fields[i]).data("dynamicColumn") !== undefined) {
                        dynamicColumns[fields[i].name] = $(fields[i]).data("dynamicColumn");
                    }
                }
            }
        }
        var settings = $(output).find(".settings").data();
        var data = { action: "get_entries", settings: settings, columns: columns, dynamicColumns: dynamicColumns };
        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);
                $(output).find(".display-result").html(data);
            } catch (err) {
                console.log(err);
                console.log(data);
            } finally {
                // console.log(data);
            }
        })

    }

})(jQuery);

jQuery(document).ready(function($) {
    $.extend({
        base64ToBlob: function(options) {
            mime = options.mime || '';
            var sliceSize = 1024;
            var byteChars = window.atob(options.base64);
            var byteArrays = [];

            for (var offset = 0, len = byteChars.length; offset < len; offset += sliceSize) {
                var slice = byteChars.slice(offset, offset + sliceSize);

                var byteNumbers = new Array(slice.length);
                for (var i = 0; i < slice.length; i++) {
                    byteNumbers[i] = slice.charCodeAt(i);
                }

                var byteArray = new Uint8Array(byteNumbers);

                byteArrays.push(byteArray);
            }

            return new Blob(byteArrays, { type: mime });
        }
    });
    // var form = $("#form");
    $('.alert').css('display', 'none');
    // $('#preloader').css('display', 'none');


    $("#submit").addClass("submit");
    $(".submit").attr("disabled", false);

    $.each($("form"), function(i, e) {
        if ($(e).data("callback") != null && $(e).data("callbackid") != null) {
            if ($(e).data("dontcallbackonload") == 1) {
                //silence is golden
            } else {
                eval('$("' + $(e).data("callbackid") + '").' + $(e).data("callback") + "()");
            }
        }
    })

    $(document).on('click', '.submit', function(event) {
        $('#alert').css('display', 'none');
        event.preventDefault();
        var btn = $(this);
        if ($(btn).hasClass("confirmThis")) {
            $.confirm({
                content: $(btn).data('content'),
                buttons: {
                    continue: {
                        text: $(btn).data('continueBtn'),
                        btnClass: 'btn-blue',
                        action: function() {
                            $(btn).submitForm();
                        }
                    },
                    cancel: {
                        text: $(btn).data('cancelBtn'),
                        action: function() {

                        }
                    }
                }
            });
        } else {
            $(btn).submitForm();
        }
    });

    $(document).on("click", ".submit-controller", function(event) {
        event.preventDefault();
        var btnId = $(this).data("btnId");
        $("#" + btnId).click();
    })

    $(window).on('keydown', function(e) {
        if (e.which == 115 && e.ctrlKey) {
            e.preventDefault();
            $("form").each(function() {
                $(this).find(".submit").click();
                return false;
            })
        }
    });

    $('#addMore').click(function() {
        $('#addMore').data('activate', true);
        $('#submit').click();
    })
})