///<reference Path='utility.js' />
$.AdminBSB = {};
$.AdminBSB.options = {
    colors: {
        nightMode: '#000000',
        red: '#F44336',
        pink: '#E91E63',
        purple: '#9C27B0',
        deepPurple: '#673AB7',
        indigo: '#3F51B5',
        blue: '#2196F3',
        lightBlue: '#03A9F4',
        cyan: '#00BCD4',
        teal: '#009688',
        green: '#4CAF50',
        lightGreen: '#8BC34A',
        lime: '#CDDC39',
        yellow: '#ffe821',
        amber: '#FFC107',
        orange: '#FF9800',
        deepOrange: '#FF5722',
        brown: '#795548',
        grey: '#9E9E9E',
        blueGrey: '#607D8B',
        black: '#000000',
        white: '#ffffff'
    },
    leftSideBar: {
        scrollColor: 'rgba(0,0,0,0.5)',
        scrollWidth: '6px',
        scrollAlwaysVisible: true,
        scrollBorderRadius: '0',
        scrollRailBorderRadius: '0'
    },
    dropdownMenu: {
        effectIn: 'fadeIn',
        effectOut: 'fadeOut'
    }
}

/* Left Sidebar - Function =================================================================================================
*  You can manage the left sidebar menu options
*  
*/
$.AdminBSB.leftSideBar = {
    activate: function () {
        var _this = this;
        var $body = $('body');
        var $overlay = $('.overlay');

        //Close sidebar
        $(window).click(function (e) {
            var $target = $(e.target);
            if (e.target.nodeName.toLowerCase() === 'i') { $target = $(e.target).parent(); }

            if (!$target.hasClass('bars') && _this.isOpen() && $target.parents('#leftsidebar').length === 0) {
                if (!$target.hasClass('js-right-sidebar')) $overlay.fadeOut();
                $body.removeClass('overlay-open');
            }
        });

        $.each($('.menu-toggle.toggled'), function (i, val) {
            $(val).next().slideToggle(0);
        });

        //When page load
        $.each($('.menu .list li.active'), function (i, val) {
            var $activeAnchors = $(val).find('a:eq(0)');

            $activeAnchors.addClass('toggled');
            $activeAnchors.next().show();
        });

        //Collapse or Expand Menu
        $('.menu-toggle').on('click', function (e) {
            var $this = $(this);
            var $content = $this.next();

            if ($($this.parents('ul')[0]).hasClass('list')) {
                var $not = $(e.target).hasClass('menu-toggle') ? e.target : $(e.target).parents('.menu-toggle');

                $.each($('.menu-toggle.toggled').not($not).next(), function (i, val) {
                    if ($(val).is(':visible')) {
                        $(val).prev().toggleClass('toggled');
                        $(val).slideUp();
                    }
                });
            }

            $this.toggleClass('toggled');
            $content.slideToggle(60);
        });

        //Set menu height
        _this.setMenuHeight();
        _this.checkStatuForResize(true);
        $(window).resize(function () {
            _this.setMenuHeight();
            _this.checkStatuForResize(false);
        });

        //Set Waves
        Waves.attach('.menu .list a', ['waves-block']);
        Waves.init();
    },
    setMenuHeight: function () {
        if (typeof $.fn.slimScroll != 'undefined') {
            var configs = $.AdminBSB.options.leftSideBar;
            var height = ($(window).height() - ($('.legal').outerHeight() + $('.navbar').innerHeight()));
            var $el = $('.list');
            if ($el && $el.length > 0) {
                $el.slimScroll({ destroy: true }).height("auto");
                $el.parent().find('.slimScrollBar, .slimScrollRail').remove();

                $el.slimscroll({
                    height: height + "px",
                    color: configs.scrollColor,
                    size: configs.scrollWidth,
                    alwaysVisible: configs.scrollAlwaysVisible,
                    borderRadius: configs.scrollBorderRadius,
                    railBorderRadius: configs.scrollRailBorderRadius,
                    railVisible: true
                });
            }
        }
    },
    checkStatuForResize: function (firstTime) {
        var $body = $('body');
        var $openCloseBar = $('.navbar .navbar-header .bars');
        var width = $body.width();

        if (firstTime) {
            $body.find('.content, .sidebar').addClass('no-animate').delay(1000).queue(function () {
                $(this).removeClass('no-animate').dequeue();
            });
        }

        if (width < 1200) {
            $body.addClass('ls-closed');
            $openCloseBar.fadeIn();
        }
        else {
            var menu_visible = getCookie('menu_visible');
            if (menu_visible) {
                if (menu_visible == 'true') {
                    $body.removeClass('ls-closed');
                    $openCloseBar.fadeOut();
                    $('.menu-display a span').addClass('icon-menu-hide').removeClass('icon-menu-show');
                }
                else {
                    $body.addClass('ls-closed');
                    $openCloseBar.fadeIn();
                    $('.menu-display a span').addClass('icon-menu-show').removeClass('icon-menu-hide');
                }
            }
        }
    },
    isOpen: function () {
        return $('body').hasClass('overlay-open');
    }
};
//==========================================================================================================================

/* Right Sidebar - Function ================================================================================================
*  You can manage the right sidebar menu options
*  
*/
$.AdminBSB.rightSideBar = {
    activate: function () {
        var _this = this;
        var $sidebar = $('#rightsidebar');
        var $overlay = $('.overlay');

        //Close sidebar
        $(window).click(function (e) {
            var $target = $(e.target);
            if (e.target.nodeName.toLowerCase() === 'i') { $target = $(e.target).parent(); }

            if (!$target.hasClass('js-right-sidebar') && _this.isOpen() && $target.parents('#rightsidebar').length === 0) {
                if (!$target.hasClass('bars')) $overlay.fadeOut();
                $sidebar.removeClass('open');
            }
        });

        $('.js-right-sidebar').on('click', function () {
            $sidebar.toggleClass('open');
            if (_this.isOpen()) { $overlay.fadeIn(); } else { $overlay.fadeOut(); }
        });
    },
    isOpen: function () {
        return $('.right-sidebar').hasClass('open');
    }
}
//==========================================================================================================================

/* Searchbar - Function ================================================================================================
*  You can manage the search bar
*  
*/
var $searchBar = $('.search-bar');
$.AdminBSB.search = {
    activate: function () {
        var _this = this;

        //Search button click event
        $('.js-search').on('click', function () {
            _this.showSearchBar();
        });

        //Close search click event
        $searchBar.find('.close-search').on('click', function () {
            _this.hideSearchBar();
        });

        //ESC key on pressed
        $searchBar.find('input[type="text"]').on('keyup', function (e) {
            if (e.keyCode == 27) {
                _this.hideSearchBar();
            }
        });
    },
    showSearchBar: function () {
        $searchBar.addClass('open');
        $searchBar.find('input[type="text"]').focus();
    },
    hideSearchBar: function () {
        $searchBar.removeClass('open');
        $searchBar.find('input[type="text"]').val('');
    }
}
//==========================================================================================================================

/* Navbar - Function =======================================================================================================
*  You can manage the navbar
*  
*/
$.AdminBSB.navbar = {
    activate: function () {
        var $body = $('body');
        var $overlay = $('.overlay');

        //Open left sidebar panel
        $('.bars').on('click', function () {
            $body.toggleClass('overlay-open');
            if ($body.hasClass('overlay-open')) { $overlay.fadeIn(); } else { $overlay.fadeOut(); }
        });

        //Close collapse bar on click event
        $('.nav [data-close="true"]').on('click', function () {
            var isVisible = $('.navbar-toggle').is(':visible');
            var $navbarCollapse = $('.navbar-collapse');

            if (isVisible) {
                $navbarCollapse.slideUp(function () {
                    $navbarCollapse.removeClass('in').removeAttr('style');
                });
            }
        });
    }
}
//==========================================================================================================================

/* Input - Function ========================================================================================================
*  You can manage the inputs(also textareas) with name of class 'form-control'
*  
*/
$.AdminBSB.input = {
    activate: function () {
        //On focus event
        $('.form-control').focus(function () {
            $(this).parent().addClass('focused');
        });

        //On focusout event
        $('.form-control').focusout(function () {
            var $this = $(this);
            if ($this.parents('.form-group').hasClass('form-float')) {
                if ($this.val() == '') { $this.parents('.form-line').removeClass('focused'); }
            }
            else {
                $this.parents('.form-line').removeClass('focused');
            }
        });

        //On label click
        $('body').on('click', '.form-float .form-line .form-label', function () {
            $(this).parent().find('input').focus();
        });
    }
}
//==========================================================================================================================

/* Form - Select - Function ================================================================================================
*  You can manage the 'select' of form elements
*  
*/
//$.AdminBSB.select = {
//    activate: function () {
//        if ($.fn.selectpicker) {
//            $('select:not(.ms)').selectpicker();
//        }
//    }
//}
//==========================================================================================================================

/* DropdownMenu - Function =================================================================================================
*  You can manage the dropdown menu
*  
*/

$.AdminBSB.dropdownMenu = {
    activate: function () {
        var _this = this;

        $('.dropdown, .dropup, .btn-group').on({
            "show.bs.dropdown": function () {
                var dropdown = _this.dropdownEffect(this);
                _this.dropdownEffectStart(dropdown, dropdown.effectIn);
            },
            "shown.bs.dropdown": function () {
                var dropdown = _this.dropdownEffect(this);
                if (dropdown.effectIn && dropdown.effectOut) {
                    _this.dropdownEffectEnd(dropdown, function () { });
                }
            },
            "hide.bs.dropdown": function (e) {
                var dropdown = _this.dropdownEffect(this);
                if (dropdown.effectOut) {
                    e.preventDefault();
                    _this.dropdownEffectStart(dropdown, dropdown.effectOut);
                    _this.dropdownEffectEnd(dropdown, function () {
                        dropdown.dropdown.removeClass('open');
                    });
                }
            }
        });

        //Set Waves
        Waves.attach('.dropdown-menu li a', ['waves-block']);
        Waves.init();
    },
    dropdownEffect: function (target) {
        var effectIn = $.AdminBSB.options.dropdownMenu.effectIn, effectOut = $.AdminBSB.options.dropdownMenu.effectOut;
        var dropdown = $(target), dropdownMenu = $('.dropdown-menu', target);

        if (dropdown.length > 0) {
            var udEffectIn = dropdown.data('effect-in');
            var udEffectOut = dropdown.data('effect-out');
            if (udEffectIn !== undefined) { effectIn = udEffectIn; }
            if (udEffectOut !== undefined) { effectOut = udEffectOut; }
        }

        return {
            target: target,
            dropdown: dropdown,
            dropdownMenu: dropdownMenu,
            effectIn: effectIn,
            effectOut: effectOut
        };
    },
    dropdownEffectStart: function (data, effectToStart) {
        if (effectToStart) {
            data.dropdown.addClass('dropdown-animating');
            data.dropdownMenu.addClass('animated dropdown-animated');
            data.dropdownMenu.addClass(effectToStart);
        }
    },
    dropdownEffectEnd: function (data, callback) {
        var animationEnd = 'webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend';
        data.dropdown.one(animationEnd, function () {
            data.dropdown.removeClass('dropdown-animating');
            data.dropdownMenu.removeClass('animated dropdown-animated');
            data.dropdownMenu.removeClass(data.effectIn);
            data.dropdownMenu.removeClass(data.effectOut);

            if (typeof callback == 'function') {
                callback();
            }
        });
    }
}
//==========================================================================================================================

/* Browser - Function ======================================================================================================
*  You can manage browser
*  
*/
var edge = 'Microsoft Edge';
var ie10 = 'Internet Explorer 10';
var ie11 = 'Internet Explorer 11';
var opera = 'Opera';
var firefox = 'Mozilla Firefox';
var chrome = 'Google Chrome';
var safari = 'Safari';

$.AdminBSB.browser = {
    activate: function () {
        var _this = this;
        var className = _this.getClassName();

        if (className !== '') $('html').addClass(_this.getClassName());
    },
    getBrowser: function () {
        var userAgent = navigator.userAgent.toLowerCase();

        if (/edge/i.test(userAgent)) {
            return edge;
        } else if (/rv:11/i.test(userAgent)) {
            return ie11;
        } else if (/msie 10/i.test(userAgent)) {
            return ie10;
        } else if (/opr/i.test(userAgent)) {
            return opera;
        } else if (/chrome/i.test(userAgent)) {
            return chrome;
        } else if (/firefox/i.test(userAgent)) {
            return firefox;
        } else if (!!navigator.userAgent.match(/Version\/[\d\.]+.*Safari/)) {
            return safari;
        }

        return undefined;
    },
    getClassName: function () {
        var browser = this.getBrowser();

        if (browser === edge) {
            return 'edge';
        } else if (browser === ie11) {
            return 'ie11';
        } else if (browser === ie10) {
            return 'ie10';
        } else if (browser === opera) {
            return 'opera';
        } else if (browser === chrome) {
            return 'chrome';
        } else if (browser === firefox) {
            return 'firefox';
        } else if (browser === safari) {
            return 'safari';
        } else {
            return '';
        }
    }
}
//==========================================================================================================================

$(function () {
    $.AdminBSB.browser.activate();

    skinChanger();

    $.AdminBSB.leftSideBar.activate();
    $.AdminBSB.rightSideBar.activate();
    $.AdminBSB.navbar.activate();
    $.AdminBSB.dropdownMenu.activate();
    $.AdminBSB.input.activate();
    //$.AdminBSB.select.activate();
    $.AdminBSB.search.activate();

    setTimeout(function () { $('.page-loader-wrapper').fadeOut(); }, 10);

    $('.menu-display a').click(function () {

        if ($('.menu-display a span').hasClass('icon-menu-show')) {
            setCookie('menu_visible', 'true', 365);
        }
        else {
            setCookie('menu_visible', 'false', 365);
        }

        $.AdminBSB.leftSideBar.activate();

    });

    activateNotificationAndTasksScroll();

    setSkinListHeightAndScroll(true);

    setSettingListHeightAndScroll(true);

    wrapGrids();

    $(window).resize(function () {
        setSkinListHeightAndScroll(false);
        setSettingListHeightAndScroll(false);
        wrapGrids();
    });
});


function wrapGrids() {

    $('.table.table-bordered.table-striped').each(function () {
        $this = $(this);
        if (!$this.parent().parent().is('div.double-scroll-wrapper2')) {
            if ($(window).width() && $(window).width() < 900 && !$this.parent().is('div.sm-grid-wrapper')) {

                $this.wrap($('<div></div>').css('overflow-x', 'scroll').addClass('sm-grid-wrapper'));

                $pagerrow = $this.find(".pager-row").clone();

                if ($pagerrow) {

                    $this.find(".pager-row").parent().each(function () { $(this).remove(); });

                    $this.parent().parent().append($pagerrow);
                }


                if ($('div.sm-grid-wrapper').width() > $('section.content div.container-fluid').width()) {

                    setTimeout(function () { $('div.sm-grid-wrapper').width($('section.content div.container-fluid').width()) }, 200);

                }
            }
            else if ($(window).width() && $(window).width() > 900 && $this.parent().is('div.sm-grid-wrapper'))
                $this.unwrap('div.sm-grid-wrapper');
        }

        
        if (!$this.parent().parent().is('div.double-scroll-wrapper4')) {
            if ($(window).width() && $(window).width() < 900 && !$this.parent().is('div.sm-grid-wrapper')) {

                $this.wrap($('<div></div>').css('overflow-x', 'scroll').addClass('sm-grid-wrapper'));

                $pagerrow = $this.find(".pager-row").clone();

                if ($pagerrow) {

                    $this.find(".pager-row").parent().each(function () { $(this).remove(); });

                    $this.parent().parent().append($pagerrow);
                }


                if ($('div.sm-grid-wrapper').width() > $('section.content div.container-fluid').width()) {

                    setTimeout(function () { $('div.sm-grid-wrapper').width($('section.content div.container-fluid').width()) }, 200);

                }
            }
            else if ($(window).width() && $(window).width() > 900 && $this.parent().is('div.sm-grid-wrapper'))
                $this.unwrap('div.sm-grid-wrapper');
        }
    });

}



//Skin changer
function skinChanger() {
    var body_color = getCookie('body_color');


    //read theme name uing ajax

    var params = "{body_color_in_cookie: '" + body_color + "'}";

    $.ajax({
        type: "POST",
        url: "/WebServices/VPS.asmx/GetAsyncDefaultTheme",
        async: false,
        data: params,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {

            var defualtThemeInDb = msg.d;

            if (defualtThemeInDb == null || defualtThemeInDb == "") {
                setCookie('body_color', 'indigo', 365);
                body_color = 'indigo';
            }
            else {
                setCookie('body_color', defualtThemeInDb, 365);
                body_color = defualtThemeInDb;
            }
        }
    });

    $('body').attr('class', 'theme-' + body_color);
    $('.right-sidebar .demo-choose-skin li').removeClass('active');
    $('.right-sidebar .demo-choose-skin li[data-theme="' + body_color + '"]').addClass('active');

    $('.right-sidebar .demo-choose-skin li').on('click', function () {
        var $body = $('body');
        var $this = $(this);

        var existTheme = $('.right-sidebar .demo-choose-skin li.active').data('theme');
        $('.right-sidebar .demo-choose-skin li').removeClass('active');

        $body.removeClass('theme-' + existTheme);
        $this.addClass('active');
        var hasLsClosedClass = $body.hasClass('ls-closed');

        $body.attr('class', 'theme-' + $this.data('theme'));
        if (hasLsClosedClass)
            $body.addClass('ls-closed');
        setCookie('body_color', $this.data('theme'), 365);
        $('.right-sidebar').removeClass('open');
        $('.overlay').hide();
    });
}


//Skin tab content set height and show scroll
function setSkinListHeightAndScroll(isFirstTime) {
    var height = $(window).height() - ($('.navbar').innerHeight() + $('.right-sidebar .nav-tabs').outerHeight());
    var $el = $('.demo-choose-skin');

    if ($el && $el.length > 0) {
        if (!isFirstTime) {
            $el.slimScroll({ destroy: true }).height('auto');
            $el.parent().find('.slimScrollBar, .slimScrollRail').remove();
        }

        $el.slimscroll({
            height: height + 'px',
            color: 'rgba(0,0,0,0.5)',
            size: '6px',
            alwaysVisible: false,
            borderRadius: '0',
            railBorderRadius: '0'
        });
    }
}



//Setting tab content set height and show scroll
function setSettingListHeightAndScroll(isFirstTime) {
    var height = $(window).height() - ($('.navbar').innerHeight() + $('.right-sidebar .nav-tabs').outerHeight());
    var $el = $('.right-sidebar .demo-settings');
    if ($el && $el.length > 0) {
        if (!isFirstTime) {
            $el.slimScroll({ destroy: true }).height('auto');
            $el.parent().find('.slimScrollBar, .slimScrollRail').remove();
        }

        $el.slimscroll({
            height: height + 'px',
            color: 'rgba(0,0,0,0.5)',
            size: '6px',
            alwaysVisible: false,
            borderRadius: '0',
            railBorderRadius: '0'
        });
    }
}

//Activate notification and task dropdown on top right menu
function activateNotificationAndTasksScroll() {
    if ($('.navbar-right .dropdown-menu .body .menu').length > 0) {
        $('.navbar-right .dropdown-menu .body .menu').slimscroll({
            height: '254px',
            color: 'rgba(0,0,0,0.5)',
            size: '4px',
            alwaysVisible: false,
            borderRadius: '0',
            railBorderRadius: '0'
        });
    }
}
