let LoadData, LoadData2, LoadScreen, SideBarItemClick, setButtonWavesEffect;
$(function () {

    $(document).ready(function () {

        let
            mainContent = $('section.content div.container-fluid'),
            LoadingSection = $('section.loading');
        SideBarItemClick = $('div.menu ul.list');

        LoadData = function (request, tag, json, callback) {

            if (tag !== null) LoadScreen(false, tag);
            try {
                $.ajax({
                    url: "ResourcesHolder/core/index.php",
                    async: true,
                    type: "POST",
                    data: request,
                    success: function (result) {
                        if (json !== null)
                            if (json)
                                result = JSON.parse(result);
                        if (tag !== null) {
                            LoadScreen(true, tag, function (e) {
                                tag.fadeIn('fast', function () {
                                    e.html(result);
                                    $('.content-animation').addClass('fadeIn');
                                    if (history.pushState && request.hasOwnProperty('action')) {
                                        var new_url = window.location.protocol + "//" + window.location.host + window.location.pathname + '?page=' + request.action;
                                        window.history.pushState({path: new_url}, '', new_url);
                                    }
                                });
                            });
                        }
                        if (callback !== null)
                            if (IsValidJSONString(result)) {
                                callback(result);
                            } else {
                                callback(JSON.parse("[{'error':'1','result':'" + result + "'}]"));
                            }
                    }, error: function (xhr, textStatus, errorThrown) {
                        if (tag !== null)
                            tag.html(errorThrown);
                        if (callback !== null)
                            callback(xhr);
                    }
                });
            } catch (err) {
                console.log(err.message);
            }

            /**
             * @return {boolean}
             */
            function IsValidJSONString(data) {
                return true;
                //(/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
            }
        };

        LoadData2 = function (request, tag, json, callback) {

            try {
                $.ajax({
                    url: "ResourcesHolder/core/index.php",
                    type: "POST",
                    cache: false,
                    contentType: false,
                    processData: false,
                    data: request,
                    success: function (result) {
                        if (json !== null)
                            if (json)
                                result = JSON.parse(result);
                        if (tag !== null) {
                            tag.html(result);
                            $('.content-animation').addClass('zoomInUp')
                        }
                        if (callback !== null)
                            if (IsValidJSONString(result)) {
                                callback(result);
                            } else {
                                callback(JSON.parse("[{'error':'1','result':'" + result + "'}]"));
                            }
                    }, error: function (xhr, textStatus, errorThrown) {
                        if (tag !== null)
                            tag.html(errorThrown);
                        if (callback !== null)
                            callback(xhr);
                    }
                });
            } catch (err) {
                console.log(err.message);
            }

            /**
             * @return {boolean}
             */
            function IsValidJSONString(data) {
                return true;
                //(/^[\],:{}\s]*$/.test(data.replace(/\\["\\\/bfnrtu]/g, '@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').replace(/(?:^|:|,)(?:\s*\[)+/g, '')));
            }
        };


        LoadScreen = function (mode, tag, callback) {
            //page-loader-wrapper
            let loading = '<div class="col-md-12" style="height:500px!important;top: 250px!important;">';//'<div style="z-index: 99999999;position: fixed;top: 0;left: 0;bottom: 0;right: 0;width: 100%;height: 100%;background: #eee;overflow: hidden;text-align: center" class="animated fade-in">';
            loading += '<div class="loader" style="text-align: center;">';
            loading += '<div class="preloader">';
            loading += '<div class="spinner-layer pl-red">';
            loading += '<div class="circle-clipper left">';
            loading += '<div class="circle"></div>';
            loading += '</div>';
            loading += '<div class="circle-clipper right">';
            loading += '<div class="circle">';
            loading += '</div>';
            loading += '</div>';
            loading += '</div>';
            loading += '</div>';
            loading += '<p>...منتظر بمانید</p>';
            loading += '</div>';
            loading += '</div>';
            if (mode) {
                if (tag !== null && typeof tag !== 'undefined') {
                    tag.append().fadeOut("fast", function () {
                        tag.append().empty();
                        if (typeof callback === 'function') callback(tag);
                    });
                } else {
                    LoadingSection.fadeOut("slow", function () {
                        LoadingSection.empty()
                    });
                }
            } else {
                if (tag !== null && typeof tag !== 'undefined') {
                    (tag.append()).fadeOut('fast', function () {
                        tag.append().empty();
                        tag.append().fadeIn('fast', function () {
                            tag.append(loading);
                        });
                    });
                } else {
                    LoadingSection.append().empty();
                    mainContent.append().empty();
                    LoadingSection.append(loading);
                }
            }
            return (mainContent);
        };

        setButtonWavesEffect = function (event) {
            $(event.currentTarget).find('[role="menu"] li a').removeClass('waves-effect');
            $(event.currentTarget).find('[role="menu"] li:not(.disabled) a').addClass('waves-effect');
        };


        $('a.sign-out').unbind().bind("click", function (e) {
            LoadData({
                request: 'proxy', action: 'SessionController',
                'header-type': 'logout'
            }, null, false, function (data) {
                if (data === "1") {
                    location.reload();
                } else {
                    console.log(data);
                }
            });
        });
    });
}(jQuery));