var BlankonDashboard = function () {
    return {
        init: function () {
            BlankonDashboard.counterOverview();
            BlankonDashboard.callModal1();
            BlankonDashboard.weatherIcons();
            BlankonDashboard.gritterNotification();
            BlankonDashboard.visitorChart();
            BlankonDashboard.realtimeStatusChart();
            BlankonDashboard.countNumber();
            BlankonDashboard.dropzone();
        },
        counterOverview: function () {
            if($('.counter').length){
                $('.counter').counterUp({
                    delay: 10,
                    time: 4000
                });
            }
        },
        callModal1: function () {
            $('#modal-bootstrap-tour').modal(
                {
                    show: true,
                    backdrop: 'static',
                    keyboard: false
                }
            );
        },
        callModal2: function () {
            $('#modal-bootstrap-tour-new-features').modal(
                {
                    show: true,
                    backdrop: 'static',
                    keyboard: false
                }
            );
        },
        handleTour: function () {
            var tour = new Tour({
                name: "tour",
                steps: [
                    {
                        element: "#tour-1",
                        title: "Логотип",
                        content: "Характеристика логотипа: Фон - прозрачный. Ширина - 175px. Высота - 50px",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-2",
                        title: "Боковая панель навигации",
                        content: "Нажмите для изменения на боковой панели, чтобы свести к минимуму панель навигации.",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-3",
                        title: "Поиск",
                        content: "Введите ваш запрос,и мы найдем все!",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-4",
                        title: "Сообщении",
                        content: "Все сообщения. Вывод последних сообщений.",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-5",
                        title: "Уведомления",
                        content: "Все уведомления. Вывод последних уведомлений.",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-6",
                        title: "Меню профиля",
                        content: "Необходимые ссылки для управление аккаунтом.",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-7",
                        title: "Боковая правая панель навигации",
                        content: "Нажмите для показа боковой панели прямо к содержимому.",
                        placement: "left"
                    },
                    {
                        element: "#tour-8",
                        title: "Приветствие",
                        content: "Приветствие пользователя, аватар,имя и фамилия.",
                        placement: "right"
                    },
                    {
                        element: "#tour-9",
                        title: "Боковая панель навигации",
                        content: "Основное меню сайта",
                        placement: "right"
                    },
                    {
                        element: "#tour-10",
                        title: "Настройки сайта",
                        content: "Дополнительные инструменты боковой панели.",
                        placement: "top"
                    },
                    {
                        element: "#tour-11",
                        title: "Содержание шапки",
                        content: "Заголовок, подзаголовок и местонахождение пользователя",
                        placement: "bottom"
                    },
                    {
                        element: "#tour-12",
                        title: "Содержание под шапкой",
                        content: "Create your overview system website on here",
                        placement: "top"
                    },
                    {
                        element: "#tour-13",
                        title: "Page Content",
                        content: "Handle all daily visitor on here",
                        placement: "top"
                    },
                    {
                        element: "#tour-14",
                        title: "Page Content",
                        content: "Widget weather with animation icons weather",
                        placement: "left"
                    },
                    {
                        element: "#tour-15",
                        title: "Page Content",
                        content: "Simple post your blog on here",
                        placement: "left"
                    },
                    {
                        element: "#tour-16",
                        title: "Page Content",
                        content: "Sample your list members",
                        placement: "top"
                    },
                    {
                        element: "#tour-17",
                        title: "Page Content",
                        content: "Mini additional overview social media on here",
                        placement: "left"
                    },
                    {
                        element: "#tour-18",
                        title: "Page Content",
                        content: "Just sample upload system your application",
                        placement: "top"
                    },
                    {
                        element: "#tour-19",
                        title: "Конец сайта",
                        content: "Информация о сайте.",
                        placement: "top"
                    },
                    {
                        element: "#tour-20",
                        title: "Footer Content",
                        content: "Additional style for handle storage system",
                        placement: "top"
                    }
                ],
                container: "body",
                next: 0,
                prev: 0,
                keyboard: true,
                storage: false,
                debug: false,
                backdrop: false,
                backdropContainer: 'body',
                backdropPadding: 0,
                redirect: true,
                orphan: false,
                duration: false,
                delay: false,
                basePath: "",
                template: "<div class='popover tour'>" +
                "<div class='arrow'></div>" +
                "<h3 class='popover-title'></h3>" +
                "<div class='popover-content'></div>" +
                "<div class='popover-navigation'>" +
                "<button class='btn btn-primary btn-sm' data-role='prev'>« Назад</button>" +
                "<span data-role='separator'></span>" +
                "<button class='btn btn-primary btn-sm' data-role='next'>Перед »</button>" +
                "<span data-role='separator'></span>" +
                "<button class='btn btn-danger btn-sm' data-role='end'>Завершить</button>" +
                "</div>" +
                "</div>" +
                "</div>",
                afterGetState: function (key, value) {},
                afterSetState: function (key, value) {},
                afterRemoveState: function (key, value) {},
                onStart: function (tour) {},
                onEnd: function (tour) {
                    $('#modal-bootstrap-tour-end').modal(
                        {
                            show: true
                        }
                    );
                    $('#modal-bootstrap-tour-end').on('hide.bs.modal', function () {
                        BlankonDashboard.sessionTimeout();
                    });
                },
                onShow: function (tour) {},
                onShown: function (tour) {},
                onHide: function (tour) {},
                onHidden: function (tour) {},
                onNext: function (tour) {},
                onPrev: function (tour) {},
                onPause: function (tour, duration) {},
                onResume: function (tour, duration) {},
                onRedirectError: function (tour) {}
            });
            tour.init();
            tour.start();
        },
        weatherIcons: function () {
            var icons = new Skycons({"color": "white"},{"resizeClear": true}),
                list  = [
                    "clear-day", "clear-night", "partly-cloudy-day",
                    "partly-cloudy-night", "cloudy", "rain", "sleet", "snow", "wind",
                    "fog"
                ],
                i;
            for(i = list.length; i--; )
                icons.set(list[i], list[i]);
            icons.play();
        },
        gritterNotification: function () {
            if($('#wrapper').css('opacity')) {
                if (!$.cookie('intro')) {
                    setTimeout(function () {
                        var unique_id = $.gritter.add({
                            title: 'Добро пожаловать!',
                            text: 'Бла бла..потом напишу',
                            image: BlankonApp.handleBaseURL()+'/assets/global/img/icon/64/contact.png',
                            sticky: false,
                            time: ''
                        });
                        setTimeout(function () {
                            $.gritter.remove(unique_id, {
                                fade: true,
                                speed: 'slow'
                            });
                        }, 12000);
                    }, 5000);
                    setTimeout(function () {
                        $.gritter.add({
                            title: 'Воспроизведение звуков',
                            text: 'Ваш браузер должен поддержать воспроизведение Javascript скриптов.',
                            image: BlankonApp.handleBaseURL()+'/assets/global/img/icon/64/sound.png',
                            sticky: true,
                            time: ''
                        });
                    }, 8000);
                    $.cookie('intro',1, {expires: 1});
                }
            }
        },
        visitorChart: function () {
            if($('#visitor-chart').length){
                $.plot("#visitor-chart", [{
                    label: "New Visitor",
                    color: "rgba(0, 177, 225, 0.35)",
                    data: [
                        ["Jan", 450],
                        ["Feb", 532],
                        ["Mar", 367],
                        ["Apr", 245],
                        ["May", 674],
                        ["Jun", 897],
                        ["Jul", 745]
                    ]
                }, {
                    label: "Old Visitor",
                    color: "rgba(233, 87, 63, 0.36)",
                    data: [
                        ["Jan", 362],
                        ["Feb", 452],
                        ["Mar", 653],
                        ["Apr", 756],
                        ["May", 670],
                        ["Jun", 352],
                        ["Jul", 243]
                    ]
                }], {
                    series: {
                        lines: { show: false },
                        splines: {
                            show: true,
                            tension: 0.4,
                            lineWidth: 2,
                            fill: 0.5
                        },
                        points: {
                            show: true,
                            radius: 4
                        }
                    },
                    grid: {
                        borderColor: "transparent",
                        borderWidth: 0,
                        hoverable: true,
                        backgroundColor: "transparent"
                    },
                    tooltip: true,
                    tooltipOpts: { content: "%x : %y" + " People" },
                    xaxis: {
                        tickColor: "transparent",
                        mode: "categories"
                    },
                    yaxis: { tickColor: "transparent" },
                    shadowSize: 0
                });
            }
        },
        realtimeStatusChart: function () {
            if($('#realtime-status-chart').length){
                var data = [], totalPoints = 50;
                function getRandomData() {
                    if (data.length > 0)
                        data = data.slice(1);
                    while (data.length < totalPoints) {
                        var prev = data.length > 0 ? data[data.length - 1] : 50,
                            y = prev + Math.random() * 10 - 5;
                        if (y < 0) {
                            y = 0;
                        } else if (y > 100) {
                            y = 100;
                        }
                        data.push(y);
                    }
                    var res = [];
                    for (var i = 0; i < data.length; ++i) {
                        res.push([i, data[i]])
                    }
                    return res;
                }
                var updateInterval = 1000;
                var plot4 = $.plot("#realtime-status-chart", [ getRandomData() ], {
                    colors: ["#F6BB42"],
                    series: {
                        lines: {
                            fill: true,
                            lineWidth: 0
                        },
                        shadowSize: 0	
                    },
                    grid: {
                        borderColor: '#ddd',
                        borderWidth: 1,
                        labelMargin: 10
                    },
                    xaxis: {
                        color: '#eee'
                    },
                    yaxis: {
                        min: 0,
                        max: 100,
                        color: '#eee'
                    }
                });
                function update() {
                    plot4.setData([getRandomData()]);
                    plot4.draw();
                    setTimeout(update, updateInterval);
                }
                update();
            }
        },
        countNumber: function () {
            $.fn.digits = function(){
                return this.each(function(){
                    $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
                })
            };
            function counter($selector){
                $({countNum: $('.counter-' + $selector).text()}).animate({countNum: $('.counter-' + $selector).data('counter')}, {
                    duration: 8000,
                    easing:'linear',
                    step: function() {
                        $('.counter-' + $selector).text(Math.floor(this.countNum)).digits();
                    },
                    complete: function() {
                        $('.counter-' + $selector).text(this.countNum).digits();
                    }
                });
            }
            if($('#wrapper').css('opacity')) {
                counter('visit');
                counter('unique');
                counter('page');
            }
        },
        sessionTimeout: function () {
            if($('.demo-dashboard-session').length){
                $.sessionTimeout({
                    title: 'JUST DEMO Your session is about to expire!',
                    logoutButton: 'Logout',
                    keepAliveButton: 'Stay Connected',
                    countdownMessage: 'Your session will be redirecting in {timer} seconds.',
                    countdownBar: true,
                    keepAliveUrl: '#',
                    logoutUrl: 'page-signin.html',
                    redirUrl: 'page-lock-screen.html',
                    ignoreUserActivity: true,
                    warnAfter: 50000,
                    redirAfter: 65000
                });
            }
        },
        dropzone: function () {
            Dropzone.options.myDropzone = {
                init: function() {
                    this.on("addedfile", function(file) {
                        var removeButton = Dropzone.createElement("<button class='btn btn-sm btn-block btn-danger'>Remove file</button>");
                        var _this = this;
                        removeButton.addEventListener("click", function(e) {
                            e.preventDefault();
                            e.stopPropagation();
                            _this.removeFile(file);
                         });
                        file.previewElement.appendChild(removeButton);
                    });
                }
            }
        }
    };
}();
BlankonDashboard.init();