(function($) {
    $.extend($.fn.DataTable.ext.classes, {
        sWrapper: "dataTables_wrapper form-inline dt-bootstrap",
        sFilterInput: "form-control input-sm",
        sLengthSelect: "form-control input-sm"
    });
    $.extend($.fn.dataTable.defaults, {
        dom: "<" +
            "<'row'<'col-sm-6 dtL'l><'col-sm-6 dtB text-right'B>>" +
            "<'row'<'col-sm-12'tr>>" +
            "<'row'<'col-sm-5'i><'col-sm-7'p>>" +
            ">",
        renderer: "bootstrap",
        displayLength: 10,
        lengthMenu: [
            [10, 25, 50],
            [10, 25, 50]
        ],
        pagingType: "simple_numbers",
        language: {
            "lengthMenu": "_MENU_",
            "search": "",
            "paginate": {
                "first": "&laquo;",
                "previous": "&lsaquo;",
                "next": "&rsaquo;",
                "last": "&raquo;"
            }
        },
        serverSide: true,
        ajax: {
            url: "",
            type: "GET"
        },
        colReorder: true,
        select: true,
        responsive: true,
        processing: true,
        autoWidth: false,
        stateSave: false,
        buttons: exportFileName('Data')
    });
}(window.jQuery));
(function($) {
    var defaults = {
        data: null,
        type: 'POST',
        beforeSend: function(jqXHR, settings) {},
        success: function(data, textStatus, jqXHR) {},
        error: function(jqXHR, textStatus, errorThrown) {},
        complete: function(jqXHR, textStatus) {}
    };
    var options = $.extend({}, defaults, options);
    var ajaxfn = function(options) {
        $.ajax({
            url: options.url,
            data: options.data,
            type: options.type,
            cache: false,
            dataType: 'json',
            processData: false,
            contentType: false,
            beforeSend: options.beforeSend,
            success: options.success,
            error: options.error,
            complete: options.complete
        });
    };
    $.fn.extend({
        ajaxFormData: function(options) {
            return this.each(function() {
                options.url = $(this)[0].action;
                if (options.data == null) {
                    options.data = new FormData($(this)[0]);
                }
                ajaxfn(options);
            });
        }
    });
})(jQuery);

function exportFileName(name) {
    return [{
        extend: 'excel',
        text: '<i class="fa fa-file-excel-o"></i>',
        title: name
    }, {
        extend: 'csv',
        text: '<i class="fa fa-file-o"></i>',
        title: name
    }, {
        extend: 'pdf',
        text: '<i class="fa fa-file-pdf-o"></i>',
        title: name
    }, {
        extend: 'print',
        text: '<i class="fa fa-print"></i>',
        title: name
    }];
}

function fnInner() {
    fnMenuActive();
    fnProfile();
    $("[data-submenu]").submenupicker();
}

function fnMenuActive() {
    $("#menu .panel-group a").each(function() {
        var pathname = location.pathname.split(/\//);
        if ($(this).data("href") == dfAdminC + pathname[pathname.length - 1]) {
            $(this).addClass("active").parent().addClass("in");
        }
    });
}

function fnProfile() {
    $("#profile").on("click", function() {
        $.post(dfAdminC + "profile", token, function(rs) {
            token = rs.token;
            if (typeof rs.msg != 'undefined') {
                fnNotify(rs.msg);
                return;
            }
            bootbox.dialog({
                    title: "Profile",
                    message: rs.html,
                    backdrop: false,
                    closeButton: false,
                    size: "small",
                    className: "formbootbox",
                    buttons: {
                        close: {
                            label: "Close"
                        },
                        submit: {
                            label: "Save",
                            className: "btn-primary",
                            callback: function(e) {
                                $(".formbootbox #form").submit();
                                return false;
                            }
                        }
                    }
                })
                .on("shown.bs.modal", function() {
                    $(".formbootbox #form").formValidation({
                        framework: "bootstrap",
                        excluded: [':disabled', ':hidden', ':not(:visible)'],
                        icon: {
                            valid: "glyphicon glyphicon-ok",
                            invalid: "glyphicon glyphicon-remove",
                            validating: "glyphicon glyphicon-refresh"
                        },
                        live: "enabled",
                        message: "This value is not valid",
                        fields: {
                            account: {
                                validators: {
                                    notEmpty: true,
                                    stringLength: {
                                        max: 32,
                                        min: 1
                                    }
                                }
                            },
                            name: {
                                validators: {
                                    notEmpty: true,
                                    stringLength: {
                                        max: 32,
                                        min: 1
                                    }
                                }
                            },
                            password: {
                                validators: {
                                    notEmpty: true,
                                    stringLength: {
                                        max: 32,
                                        min: 1
                                    }
                                }
                            }
                        }
                    }).on("success.form.fv", function(e) {
                        e.stopPropagation();
                        e.preventDefault();
                        var fv = $(e.target).data("formValidation");
                        var fd = new FormData($(this)[0]);
                        $.each(token, function(key, value) {
                            fd.append(key, value);
                        });
                        $(this).ajaxFormData({
                            data: fd,
                            beforeSend: function() {
                                fnLoadingOn();
                            },
                            success: function(data, textStatus, jqXHR) {
                                token = data.token;
                                fnNotify(data.msg);
                            },
                            error: function(jqXHR, textStatus, errorThrown) {
                                fnNotify('Error! Please reload page');
                            },
                            complete: function(jqXHR, textStatus) {
                                bootbox.hideAll();
                                fnLoadingOff();
                                fnDTDraw();
                            }
                        });
                    });
                });
        }, "json");
    });
}

function fnToolbar() {
    $(".breadcrumb").on("click", function() {
        if ($("#toolbar").is(":hidden")) {
            $("#toolbar").slideDown();
        } else {
            $("#toolbar").slideUp();
        }
    });
    $("#SelectAll").on("click", function() {
        $("#jqdatatable").DataTable().rows().select();
    });
    $("#SelectNone").on("click", function() {
        $("#jqdatatable").DataTable().rows().deselect();
    });
    $("#Filter").on("click", function() {
        $("#modal_filter").modal({
            backdrop: false,
            keyboard: false
        });
    });
    $("#modal_filter #Search").on("click", function() {
        $("#jqdatatable").DataTable().search($("#global_text").val());
        var col = null;
        $.each($(".colfilter"), function() {
            col = $(this).data("col");
            $("#jqdatatable").DataTable().column(col + ":name").search($("#col_" + col + "_text").val(), $("#col_" + col + "_regex").prop("checked"));
        });
        $("#jqdatatable").DataTable().draw();
    });
    $("#modal_filter #Clear").on("click", function() {
        $("#modal_filter input:text").val("");
        $("#modal_filter input:checkbox").prop("checked", false);
    });
}

function fnLoadingOn() {
    $("#modal_loading .modal-content").load(dfAdminC + "inner/loading");
    $("#modal_loading").modal({
        backdrop: "static",
        keyboard: false
    });
}

function fnLoadingOff() {
    setTimeout(function() {
        $("#modal_loading").modal("hide");
    }, 200);
}

function fnNotify(data) {
    $.notify(data, {
        placement: {
            from: "top",
            align: "center"
        },
        z_index: 10000
    });
}

function fnDTDraw() {
    var table = $("#jqdatatable").DataTable();
    table.page(table.page()).draw(false);
}

function fnBoxTable(options) {
    $(options.btn).on("click", function() {
        var dt = $("#jqdatatable").DataTable().rows({
            selected: true
        }).data();
        if (dt.length != 1) {
            fnNotify("Please Select 1 Item");
            return;
        }
        $.post(options.url, $.extend(dt[0], token), function(rs) {
            token = rs.token;
            if (typeof rs.msg != 'undefined') {
                fnNotify(rs.msg);
                return;
            }
            bootbox.dialog({
                title: options.title,
                message: rs.html,
                backdrop: false,
                closeButton: false,
                size: options.size,
                className: "formbootbox",
                buttons: {
                    close: {
                        label: "Close"
                    }
                }
            });
        }, "json");
    });
}

function fnBoxForm(options, callback) {
    $(options.btn).on("click", function() {
        var fd = {};
        if (options.selected == 1) {
            var dt = $("#jqdatatable").DataTable().rows({
                selected: true
            }).data();
            if (dt.length != options.selected) {
                fnNotify("Please Select Item");
                return;
            }
            $.extend(fd, dt[0]);
        }
        $.post(options.url, $.extend(fd, token), function(rs) {
            token = rs.token;
            if (typeof rs.msg != 'undefined') {
                fnNotify(rs.msg);
                return;
            }
            bootbox.dialog({
                    title: options.title,
                    message: rs.html,
                    backdrop: false,
                    closeButton: false,
                    size: options.size,
                    className: "formbootbox",
                    buttons: {
                        close: {
                            label: "Close"
                        },
                        submit: {
                            label: "Save",
                            className: "btn-primary",
                            callback: function(e) {
                                $(".formbootbox #form").submit();
                                return false;
                            }
                        }
                    }
                })
                .on("shown.bs.modal", function() {
                    $(".formbootbox #form").formValidation({
                        framework: "bootstrap",
                        excluded: [':disabled', ':hidden', ':not(:visible)'],
                        icon: {
                            valid: "glyphicon glyphicon-ok",
                            invalid: "glyphicon glyphicon-remove",
                            validating: "glyphicon glyphicon-refresh"
                        },
                        live: "enabled",
                        message: "This value is not valid",
                        fields: options.fields
                    }).on("success.form.fv", function(e) {
                        e.stopPropagation();
                        e.preventDefault();
                        var fv = $(e.target).data("formValidation");
                        var fd = new FormData($(this)[0]);
                        $.each(token, function(key, value) {
                            fd.append(key, value);
                        });
                        $(this).ajaxFormData({
                            data: fd,
                            beforeSend: function() {
                                fnLoadingOn();
                            },
                            success: function(data, textStatus, jqXHR) {
                                token = data.token;
                                fnNotify(data.msg);
                                if (data.msg == 'success') {
                                    bootbox.hideAll();
                                }
                            },
                            error: function(jqXHR, textStatus, errorThrown) {
                                fnNotify('Error! Please reload page');
                            },
                            complete: function(jqXHR, textStatus) {
                                fnLoadingOff();
                                fnDTDraw();
                            }
                        });
                    });
                    if (typeof callback != 'undefined') {
                        callback();
                    }
                });
        }, "json");
    });
}

function getSelectData() {
    var d = [];
    $("#jqdatatable").DataTable().rows({
        selected: true
    }).data().each(function(value, index) {
        d[index] = value;
    });
    return d;
}

function fnBoxConfirm(options) {
    $(options.btn).on("click", function() {
        var dt = getSelectData();
        if (dt.length == 0) {
            fnNotify("Please Select Item");
            return;
        }
        if (options.multi == false && dt.length != 1) {
            fnNotify("Please Select Item");
            return;
        }
        bootbox.confirm({
            message: options.msg,
            size: options.size,
            backdrop: false,
            callback: function(result) {
                if (result == false) return;
                fnLoadingOn();
                $.post(options.url, $.extend({
                    data: dt
                }, token), function(rs) {
                    token = rs.token;
                    fnLoadingOff();
                    fnNotify(rs.msg);
                    fnDTDraw();
                }, "json");
            }
        });
    });
}

function pluginSelectMultiple() {
    $("select[multiple]").multiselect({
        buttonWidth: "100%",
        includeSelectAllOption: true,
        enableFiltering: true,
        onChange: function(option, checked, select) {
            $(this).parent("#form").formValidation("revalidateField", $(option).parent("select").prop("name"));
        }
    });
}

function pluginCkedit(id, toolbar) {
    CKEDITOR.replace(id, {
        height: 100,
        toolbarCanCollapse: true,
        toolbar: toolbar,
        toolbar_basic: [{
            name: 'basicstyles',
            items: ['Bold', 'Italic']
        }, {
            name: 'paragraph',
            items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent']
        }, {
            name: 'links',
            items: ['Link', 'Unlink']
        }, {
            name: 'about',
            items: ['About']
        }],
        toolbar_standard: [{
                name: 'clipboard',
                items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PasteFromWord', '-', 'Undo', 'Redo']
            }, {
                name: 'editing',
                items: ['Scayt']
            }, {
                name: 'links',
                items: ['Link', 'Unlink', 'Anchor']
            }, {
                name: 'insert',
                items: ['Image', 'Table', 'HorizontalRule', 'SpecialChar']
            }, {
                name: 'tools',
                items: ['Maximize']
            }, {
                name: 'document',
                items: ['Source']
            },
            '/', {
                name: 'basicstyles',
                items: ['Bold', 'Italic', 'Underline', 'Strike', 'Subscript', 'Superscript', '-', 'RemoveFormat']
            }, {
                name: 'paragraph',
                items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'Blockquote']
            }, {
                name: 'styles',
                items: ['Styles', 'Format']
            }, {
                name: 'about',
                items: ['About']
            }
        ],
        //ckfinder
        filebrowserBrowseUrl: '/api/ckfinder/ckfinder.html',
        filebrowserUploadUrl: '/api/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files'
    });
    //CKFinder.setupCKEditor(editor); //or used
}

function pluginCkeditUpdateElement() {
    $.each(CKEDITOR.instances, function() {
        this.on('change', function() {
            this.updateElement();
        });
    });
}
