/**
 * @Author: Amirhosseinhpv
 * @Date:   2021/08/28 00:08:00
 * @Email:  its@hpv.im
 * @Last modified by:   Amirhosseinhpv
 * @Last modified time: 2021/09/15 13:41:00
 * @License: GPLv2
 * @Copyright: Copyright © Amirhosseinhpv (https://hpv.im), all rights reserved.
 */


/*!

 =========================================================
 * Material Dashboard Dark Edition - v2.1.0
 =========================================================

 * Product Page: https://www.creative-tim.com/product/material-dashboard-dark
 * Copyright 2019 Creative Tim (http://www.creative-tim.com)

 * Coded by www.creative-tim.com

 =========================================================

 * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

 */
 (function($) {

   var breakCards = true;

   var searchVisible = 0;
   var transparent = true;

   var transparentDemo = true;
   var fixedTop = false;

   var mobile_menu_visible = 0,
     mobile_menu_initialized = false,
     toggle_initialized = false,
     bootstrap_nav_initialized = false;

   var seq = 0,
     delays = 80,
     durations = 500;
   var seq2 = 0,
     delays2 = 80,
     durations2 = 500;

   $(document).ready(function() {

     $('body').bootstrapMaterialDesign();

     $sidebar = $('.sidebar');

     md.initSidebarsCheck();

     window_width = $(window).width();

     // check if there is an image set for the sidebar's background
     md.checkSidebarImage();

     //    Activate bootstrap-select
     if ($(".selectpicker").length != 0) {
       $(".selectpicker").selectpicker();
     }

     //  Activate the tooltips
     $('[rel="tooltip"]').tooltip();

     $('.form-control').on("focus", function() {
       $(this).parent('.input-group').addClass("input-group-focus");
     }).on("blur", function() {
       $(this).parent(".input-group").removeClass("input-group-focus");
     });

     // remove class has-error for checkbox validation
     $('input[type="checkbox"][required="true"], input[type="radio"][required="true"]').on('click', function() {
       if ($(this).hasClass('error')) {
         $(this).closest('div').removeClass('has-error');
       }
     });

   });

   $(document).on('click', '.navbar-toggler', function() {
     $toggle = $(this);

     if (mobile_menu_visible == 1) {
       $('html').removeClass('nav-open');

       $('.close-layer').remove();
       setTimeout(function() {
         $toggle.removeClass('toggled');
       }, 400);

       mobile_menu_visible = 0;
     } else {
       setTimeout(function() {
         $toggle.addClass('toggled');
       }, 430);

       var $layer = $('<div class="close-layer"></div>');

       if ($('body').find('.main-panel').length != 0) {
         $layer.appendTo(".main-panel");

       } else if (($('body').hasClass('off-canvas-sidebar'))) {
         $layer.appendTo(".wrapper-full-page");
       }

       setTimeout(function() {
         $layer.addClass('visible');
       }, 100);

       $layer.click(function() {
         $('html').removeClass('nav-open');
         mobile_menu_visible = 0;

         $layer.removeClass('visible');

         setTimeout(function() {
           $layer.remove();
           $toggle.removeClass('toggled');

         }, 400);
       });

       $('html').addClass('nav-open');
       mobile_menu_visible = 1;

     }

   });

   // activate collapse right menu when the windows is resized
   $(window).resize(function() {
     md.initSidebarsCheck();

     // reset the seq for charts drawing animations
     seq = seq2 = 0;

     setTimeout(function() {
       md.initDashboardPageCharts();
     }, 500);
   });



   md = {
     misc: {
       navbar_menu_visible: 0,
       active_collapse: true,
       disabled_collapse_init: 0
     },

     checkSidebarImage: function() {
       $sidebar = $('.sidebar');
       image_src = $sidebar.data('image');

       if (image_src !== undefined) {
         sidebar_container = '<div class="sidebar-background" style="background-image: url(' + image_src + ') "/>';
         $sidebar.append(sidebar_container);
       }
     },

     initSidebarsCheck: function() {
       if ($(window).width() <= 991) {
         if ($sidebar.length != 0) {
           md.initRightMenu();
         }
       }
     },

     initDashboardPageCharts: function() {

       if ($('#dailySalesChart').length != 0 || $('#completedTasksChart').length != 0 || $('#websiteViewsChart').length != 0) {
         /* ----------==========     Daily Sales Chart initialization    ==========---------- */

         dataDailySalesChart = {
           labels: ['M', 'T', 'W', 'T', 'F', 'S', 'S'],
           series: [
             [12, 17, 7, 17, 23, 18, 38]
           ]
         };

         optionsDailySalesChart = {
           lineSmooth: Chartist.Interpolation.cardinal({
             tension: 0
           }),
           low: 0,
           high: 50, // creative tim: we recommend you to set the high sa the biggest value + something for a better look
           chartPadding: {
             top: 0,
             right: 0,
             bottom: 0,
             left: 0
           },
         }

         var dailySalesChart = new Chartist.Line('#dailySalesChart', dataDailySalesChart, optionsDailySalesChart);

         md.startAnimationForLineChart(dailySalesChart);


         /* ----------==========     Completed Tasks Chart initialization    ==========---------- */

         dataCompletedTasksChart = {
           labels: ['12p', '3p', '6p', '9p', '12p', '3a', '6a', '9a'],
           series: [
             [230, 750, 450, 300, 280, 240, 200, 190]
           ]
         };

         optionsCompletedTasksChart = {
           lineSmooth: Chartist.Interpolation.cardinal({
             tension: 0
           }),
           low: 0,
           high: 1000, // creative tim: we recommend you to set the high sa the biggest value + something for a better look
           chartPadding: {
             top: 0,
             right: 0,
             bottom: 0,
             left: 0
           }
         }

         var completedTasksChart = new Chartist.Line('#completedTasksChart', dataCompletedTasksChart, optionsCompletedTasksChart);

         // start animation for the Completed Tasks Chart - Line Chart
         md.startAnimationForLineChart(completedTasksChart);


         /* ----------==========     Emails Subscription Chart initialization    ==========---------- */

         var dataWebsiteViewsChart = {
           labels: ['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
           series: [
             [542, 443, 320, 780, 553, 453, 326, 434, 568, 610, 756, 895]

           ]
         };
         var optionsWebsiteViewsChart = {
           axisX: {
             showGrid: false
           },
           low: 0,
           high: 1000,
           chartPadding: {
             top: 0,
             right: 5,
             bottom: 0,
             left: 0
           }
         };
         var responsiveOptions = [
           ['screen and (max-width: 640px)', {
             seriesBarDistance: 5,
             axisX: {
               labelInterpolationFnc: function(value) {
                 return value[0];
               }
             }
           }]
         ];
         var websiteViewsChart = Chartist.Bar('#websiteViewsChart', dataWebsiteViewsChart, optionsWebsiteViewsChart, responsiveOptions);

         //start animation for the Emails Subscription Chart
         md.startAnimationForBarChart(websiteViewsChart);
       }
     },

     showNotification: function(from, align) {
       type = ['', 'info', 'danger', 'success', 'warning', 'primary'];

       color = Math.floor((Math.random() * 5) + 1);

       $.notify({
         icon: "add_alert",
         message: "Welcome to <b>Material Dashboard</b> - a beautiful freebie for every web developer."

       }, {
         type: type[color],
         timer: 3000,
         placement: {
           from: from,
           align: align
         }
       });
     },

     checkScrollForTransparentNavbar: debounce(function() {
       if ($(document).scrollTop() > 260) {
         if (transparent) {
           transparent = false;
           $('.navbar-color-on-scroll').removeClass('navbar-transparent');
         }
       } else {
         if (!transparent) {
           transparent = true;
           $('.navbar-color-on-scroll').addClass('navbar-transparent');
         }
       }
     }, 17),

     initRightMenu: debounce(function() {

       $sidebar_wrapper = $('.sidebar-wrapper');

       if (!mobile_menu_initialized) {
         console.log('intra');
         $navbar = $('nav').find('.navbar-collapse').children('.navbar-nav');

         mobile_menu_content = '';

         nav_content = $navbar.html();

         nav_content = '<ul class="nav navbar-nav nav-mobile-menu">' + nav_content + '</ul>';

         navbar_form = $('nav').find('.navbar-form').length != 0 ? $('nav').find('.navbar-form')[0].outerHTML : null;

         $sidebar_nav = $sidebar_wrapper.find(' > .nav');

         // insert the navbar form before the sidebar list
         $nav_content = $(nav_content);
         $navbar_form = $(navbar_form);
         $nav_content.insertBefore($sidebar_nav);
         $navbar_form.insertBefore($nav_content);

         $(".sidebar-wrapper .dropdown .dropdown-menu > li > a").click(function(event) {
           event.stopPropagation();

         });

         // simulate resize so all the charts/maps will be redrawn
         window.dispatchEvent(new Event('resize'));

         mobile_menu_initialized = true;
       } else {
         if ($(window).width() > 991) {
           // reset all the additions that we made for the sidebar wrapper only if the screen is bigger than 991px
           $sidebar_wrapper.find('.navbar-form').remove();
           $sidebar_wrapper.find('.nav-mobile-menu').remove();

           mobile_menu_initialized = false;
         }
       }
     }, 200),

     startAnimationForLineChart: function(chart) {
       chart.on('draw', function(data) {
         if ((data.type === 'line' || data.type === 'area') && window.matchMedia("(min-width: 900px)").matches) {
           data.element.animate({
             d: {
               begin: 600,
               dur: 700,
               from: data.path.clone().scale(1, 0).translate(0, data.chartRect.height()).stringify(),
               to: data.path.clone().stringify(),
               easing: Chartist.Svg.Easing.easeOutQuint
             }
           });
         } else if (data.type === 'point') {
           seq++;
           data.element.animate({
             opacity: {
               begin: seq * delays,
               dur: durations,
               from: 0,
               to: 1,
               easing: 'ease'
             }
           });
         }

       });

       seq = 0;

     },
     startAnimationForBarChart: function(chart) {
       chart.on('draw', function(data) {
         if (data.type === 'bar' && window.matchMedia("(min-width: 900px)").matches) {
           seq2++;
           data.element.animate({
             opacity: {
               begin: seq2 * delays2,
               dur: durations2,
               from: 0,
               to: 1,
               easing: 'ease'
             }
           });
         }

       });

       seq2 = 0;

     }
   }

   // Returns a function, that, as long as it continues to be invoked, will not
   // be triggered. The function will be called after it stops being called for
   // N milliseconds. If `immediate` is passed, trigger the function on the
   // leading edge, instead of the trailing.

   function debounce(func, wait, immediate) {
     var timeout;
     return function() {
       var context = this,
         args = arguments;
       clearTimeout(timeout);
       timeout = setTimeout(function() {
         timeout = null;
         if (!immediate) func.apply(context, args);
       }, wait);
       if (immediate && !timeout) func.apply(context, args);
     };
   };
 })(jQuery);
