/*

* Detact Mobile Browser
*/

if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

$('html').addClass('ismobile');

}

// create a new instance of `MutationObserver` named `observer`, // passing it a callback function const observer = new MutationObserver(function() {

update_html_elements();

});

$(document).ready(function(){

/*
 * Waves Animation
 */
(function(){
  Waves.attach('.btn:not(.btn-icon):not(.btn-float)');
  Waves.attach('.btn-icon, .btn-float', ['waves-circle', 'waves-float']);
  Waves.init();
})();
update_html_elements();

});

function update_html_elements() {

$("form.async").unbind("submit").submit(function(e){
  e.preventDefault();
  var datastring = $(this).serialize();
  var url = $(this).attr('action');
  $(this).closest('.modal').modal('hide');
  $('body').append('<div aria-labelledby="loading" class="modal bounceIn animated" id="loading-modal" role="dialog" tabindex="-1" data-backdrop="static" data-keyboard="false"><div class="modal-dialog modal-sm" style="width:150px !Important;"><div class="modal-content"><div class="modal-body p-20 text-center"><div class="preloader pl-lg"><svg class="pl-circular" viewBox="25 25 50 50"><circle class="plc-path" cx="50" cy="50" r="20"></circle></svg></div></div><div class="modal-footer" style="text-align: center !Important;"><div class="btn btn-link waves-effect c-gray">Espere...</div></div></div></div></div>');
  $('#loading-modal').modal('show');
  $.ajax({

    type: "POST",
    url: url,
    data: datastring,
    success: function(data) {
      $('#loading-modal').modal('hide');
      $('#loading-modal').remove();
      $('body').append('<div aria-labelledby="ok" class="modal bounceIn animated" id="ok-modal" role="dialog" tabindex="-1"><div class="modal-dialog modal-sm" style="width:150px !Important;"><div class="modal-content"><div class="modal-body p-20 text-center"><i class="zmdi zmdi-hc-3x zmdi-check-circle c-green"></i></div><div class="modal-footer" style="text-align: center !Important;"><div class="btn btn-link waves-effect c-gray">¡Listo!</div></div></div></div></div>');
      $('#ok-modal').modal('show');
      setTimeout(function () {
        location.reload();
      }, 1000)
    },
    error: function(data) {
      $('#loading-modal').modal('hide');
      $('#loading-modal').remove();
      $('body').append('<div aria-labelledby="error" class="modal bounceIn animated" id="error-modal" role="dialog" tabindex="-1"><div class="modal-dialog modal-sm" style="width:150px !Important;"><div class="modal-content"><div class="modal-body p-20 text-center"><i class="zmdi zmdi-hc-3x zmdi-alert-polygon c-red"></i></div><div class="modal-footer" style="text-align: center !Important;"><div class="btn btn-link waves-effect c-gray">Oops...</div></div></div></div></div>');
      $('#error-modal').modal('show');
    }
  });
});

// Fix modal inside other components
$('.modal').appendTo("body");

$( ".paginator" ).clone().appendTo( "#content" );

$('form').on('submit', function(e) {
  $(this).find(':input[required]').each(function() {
    if ($(this).val() == "" || $(this).val() == null) {
      $(this).parent().removeClass("success");
      $(this).parent().addClass("error");
    } else {
      $(this).parent().removeClass("error");
      $(this).parent().addClass("success");
    }
  });
  if ($(this).find('.error').length == 0 ) {
    $(this).find(':submit').attr('disabled','disabled');
  }
});

$('.chosen[required]').on('change', function(change, deselected) { //selected OR deselected
  if ($(this).val() == "" || $(this).val() == null) {
    $(this).parent().removeClass("success");
    $(this).parent().addClass("error");
  } else {
    $(this).parent().removeClass("error");
    $(this).parent().addClass("success");
  }
});

//Hack for modal to work on dropdown menu
$('header .lv-item').click(function(e) {
    e.stopPropagation();
    if ($(e.target).is('[data-toggle=modal]')) {
        $($(e.target).data('target')).modal()
    }
});

// Expand and reduce profile view
$(".detail_view").on('click',function() {
  $('.toggled_view').addClass('detail_view');
})
$(".regular_view").on('click',function() {
  $('.toggled_view').removeClass('detail_view');
})

/* --------------------------------------------------------
    Scrollbar
-----------------------------------------------------------*/
function scrollBar(selector, theme, mousewheelaxis) {
    $(selector).mCustomScrollbar({
        theme: theme,
        scrollInertia: 100,
        axis:'yx',
        mouseWheel: {
            enable: true,
            axis: mousewheelaxis,
            preventDefault: true
        }
    });
}

if (!$('html').hasClass('ismobile')) {
    //On Custom Class
    if ($('.c-overflow')[0]) {
        scrollBar('.c-overflow', 'minimal-dark', 'y');
    }
}

/*
 * Sidebar
 */
(function(){
    //Toggle
    $('body').on('click', '#menu-trigger', function(e){
        e.preventDefault();
        var x = $(this).data('trigger');

        $(x).toggleClass('toggled');
        $(this).toggleClass('open');

      //Close opened sub-menus
      $('.sub-menu.toggled').not('.active').each(function(){
        $(this).removeClass('toggled');
        $(this).find('ul').hide();
      });

      $('.profile-menu .main-menu').hide();

      if (x == '#sidebar') {

          $elem = '#sidebar';
          $elem2 = '#menu-trigger';

          $('#chat-trigger').removeClass('open');

          if (!$('#chat').hasClass('toggled')) {
              $('#header').toggleClass('sidebar-toggled');
          }
          else {
              $('#chat').removeClass('toggled');
          }
      }

      //When clicking outside
      if ($('#header').hasClass('sidebar-toggled')) {
          $(document).on('click', function (e) {
              if (($(e.target).closest($elem).length === 0) && ($(e.target).closest($elem2).length === 0)) {
                  setTimeout(function(){
                      $($elem).removeClass('toggled');
                      $('#header').removeClass('sidebar-toggled');
                      $($elem2).removeClass('open');
                  });
              }
          });
      }
    })

    //Submenu
    $('body').on('click', '.sub-menu > a', function(e){
      e.preventDefault();
      $(this).next().slideToggle(200);
      $(this).parent().toggleClass('toggled');
    });
})();

/*
 * Clear Notification
 */
$('body').on('click', '[data-clear="notification"]', function(e){
  e.preventDefault();

  var x = $(this).closest('.listview');
  var y = x.find('.lv-item');
  var z = y.size();

  $(this).parent().fadeOut();

  x.find('.list-group').prepend('<i class="grid-loading hide-it"></i>');
  x.find('.grid-loading').fadeIn(1500);

  var w = 0;
  y.each(function(){
      var z = $(this);
      setTimeout(function(){
      z.addClass('animated fadeOutRightBig').delay(1000).queue(function(){
          z.remove();
      });
      }, w+=150);
  })

  //Popup empty message
  setTimeout(function(){
     $('#notifications').addClass('empty');
  }, (z*150)+200);
});

/*
 * Dropdown Menu
 */
if($('.dropdown')[0]) {
  //Propagate
  $('body').on('click', '.dropdown.open .dropdown-menu', function(e){
      e.stopPropagation();
  });

  $('.dropdown').on('shown.bs.dropdown', function (e) {
      if($(this).attr('data-animation')) {
    $animArray = [];
    $animation = $(this).data('animation');
    $animArray = $animation.split(',');
    $animationIn = 'animated '+$animArray[0];
    $animationOut = 'animated '+ $animArray[1];
    $animationDuration = ''
    if(!$animArray[2]) {
        $animationDuration = 500; //if duration is not defined, default is set to 500ms
    }
    else {
        $animationDuration = $animArray[2];
    }

    $(this).find('.dropdown-menu').removeClass($animationOut)
    $(this).find('.dropdown-menu').addClass($animationIn);
      }
  });

  $('.dropdown').on('hide.bs.dropdown', function (e) {
  if($(this).attr('data-animation')) {
    e.preventDefault();
    $this = $(this);
    $dropdownMenu = $this.find('.dropdown-menu');

    $dropdownMenu.addClass($animationOut);
    setTimeout(function(){
        $this.removeClass('open')

    }, $animationDuration);
      }
  });
}

/*
* Profile Menu
*/
$('body').on('click', '.profile-menu > a', function(e){
    e.preventDefault();
    $(this).parent().toggleClass('toggled');
  $(this).next().slideToggle(200);
});

/*
 * Text Feild
 */

//Add blue animated border and remove with condition when focus and blur
if($('.fg-line')[0]) {
    $('body').on('focus', '.fg-line .form-control', function(){
        $(this).closest('.fg-line').addClass('fg-toggled');
    })

    $('body').on('blur', '.form-control', function(){
        var p = $(this).closest('.form-group, .input-group');
        var i = p.find('.form-control').val();

        if (p.hasClass('fg-float')) {
            if (i.length == 0) {
                $(this).closest('.fg-line').removeClass('fg-toggled');
            }
        }
        else {
            $(this).closest('.fg-line').removeClass('fg-toggled');
        }
    });
}

//Add blue border for pre-valued fg-flot text feilds
if($('.fg-float')[0]) {
    $('.fg-float .form-control').each(function(){
        var i = $(this).val();

        if (!i.length == 0) {
            $(this).closest('.fg-line').addClass('fg-toggled');
        }

    });
}

/*
 * Tag Select
 */
if($('.chosen')[0]) {
    $('.chosen').chosen({
        allow_single_deselect: true,
        width: '100%'
    });
}

// Chosen touch support.
if ($('.chosen-container').length > 0) {
  $('.chosen-container').on('touchstart', function(e){
    e.stopPropagation(); e.preventDefault();
    // Trigger the mousedown event.
    $(this).trigger('mousedown');
  });
}

/*
 * Date Time Picker
 */

//Date Time Picker
if ($('.date-time-picker')[0]) {
 $('.date-time-picker').datetimepicker({
     locale: 'es' 
  });
}

//Time
if ($('.time-picker')[0]) {
  $('.time-picker').datetimepicker({
      format: 'LT'
  });
}

//Date
if ($('.date-picker')[0]) {
  $('.date-picker').datetimepicker({
      format: 'DD/MM/YYYY',
      locale: 'en'
  });
}

//Date
if ($('.month-picker')[0]) {
  $('.month-picker').datetimepicker({
    viewMode: 'years',
    format: 'MM/YYYY'
  });
}

//Date
if ($('.year-picker')[0]) {
  $('.year-picker').datetimepicker({
    viewMode: 'years',
    format: 'YYYY'
  });
}

if ($('.date-range')[0]) {
  // to_data_source method is compliant with the calendar library used in holidays
  $('.date-range').daterangepicker({
      "parentEl" : $(this).id,
      "autoApply": true,
      "locale": {
        "format": "D MMMM, YYYY",
        "separator": " - ",
        "applyLabel": "Aplicar",
        "cancelLabel": "Cancelar",
        "fromLabel": "Desde",
        "toLabel": "Hasta",
        "customRangeLabel": "Custom",
        "weekLabel": "S",
        "daysOfWeek": ["Dom","Lun","Mar","Mie","Jue","Vie","Sab"],
        "monthNames": ["Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"],
        "firstDay": 1
    },
    opens: 'center'
  });
}

/*
 * Lightbox
 */
if ($('.lightbox')[0]) {
    $('.lightbox').lightGallery({
        enableTouch: true
    });
}

/*
 * Link prevent
 */
$('body').on('click', '.a-prevent', function(e){
    e.preventDefault();
});

/*
 * Collaspe Fix
 */
if ($('.collapse')[0]) {

    //Add active class for opened items
    $('.collapse').on('show.bs.collapse', function (e) {
        $(this).closest('.panel').find('.panel-heading').addClass('active');
    });

    $('.collapse').on('hide.bs.collapse', function (e) {
        $(this).closest('.panel').find('.panel-heading').removeClass('active');
    });

    //Add active class for pre opened items
    $('.collapse.in').each(function(){
        $(this).closest('.panel').find('.panel-heading').addClass('active');
    });
}

/*
 * Tooltips
 */
if ($('[data-toggle="tooltip"]')[0]) {
    $('[data-toggle="tooltip"]').tooltip();
}

/*
 * Popover
 */
if ($('[data-toggle="popover"]')[0]) {
    $('[data-toggle="popover"]').popover();
}

/*
 * Message
 */

//Actions
if ($('.on-select')[0]) {
    var checkboxes = '.lv-avatar-content input:checkbox';
    var actions = $('.on-select').closest('.lv-actions');

    $('body').on('click', checkboxes, function() {
        if ($(checkboxes+':checked')[0]) {
            actions.addClass('toggled');
        }
        else {
            actions.removeClass('toggled');
        }
    });
}

if($('#ms-menu-trigger')[0]) {
    $('body').on('click', '#ms-menu-trigger', function(e){
        e.preventDefault();
        $(this).toggleClass('open');
        $('.ms-menu').toggleClass('toggled');
    });
}

/*
 * Profile Edit Toggle
 */
if ($('[data-pmb-action]')[0]) {
    $('body').on('click', '[data-pmb-action]', function(e){
        e.preventDefault();
        var d = $(this).data('pmb-action');

        if (d === "edit") {
            $(this).closest('.pmb-block').toggleClass('toggled');
        }

        if (d === "reset") {
            $(this).closest('.pmb-block').removeClass('toggled');
        }

    });
}

/*
 * IE 9 Placeholder
 */
if($('html').hasClass('ie9')) {
    $('input, textarea').placeholder({
        customClass: 'ie9-placeholder'
    });
}

/*
 * Listview Search
 */
if ($('.lvh-search-trigger')[0]) {

    $('body').on('click', '.lvh-search-trigger', function(e){
        e.preventDefault();
        x = $(this).closest('.lv-header-alt').find('.lvh-search');

        x.fadeIn(300);
        x.find('.lvhs-input').focus();
    });

    //Close Search
    $('body').on('click', '.lvh-search-close', function(){
        x.fadeOut(300);
        setTimeout(function(){
            x.find('.lvhs-input').val('');
        }, 350);
    })
}

/*
 * Print
 */
if ($('[data-action="print"]')[0]) {
    $('body').on('click', '[data-action="print"]', function(e){
        e.preventDefault();

        window.print();
    })
}

/*
* Modal hide
*/
$('.modal').bind('shown.bs.modal', function (e) {
  $(this).find(':submit').attr("disabled",false);
});

}

const elementToObserve = document.querySelector(“body”);

if (elementToObserve != null) {

observer.observe(elementToObserve, {subtree: true, childList: true});

}

function start_load() {

if (!$("#loader")[0]) {
  $("html").append('<div id="loader" style="position: fixed;z-index: 100000000;padding:5px;top: 0;"><div class="preloader pl-lg pls-white"  style="left: 10px; top: 5px;"><svg class="pl-circular" viewBox="25 25 50 50"><circle class="plc-path" cx="50" cy="50" r="20"></circle></svg></div></div>');
}

}

function stop_load() {

$("#loader").remove();

}

$( document ).ajaxSend(function( event, jqxhr, settings ) {

if (!settings.url.includes(".json")) {
  start_load();
}

});

$( document ).ajaxStop(function() {

stop_load();

});

function rm_object(object,id) {

$(".modal").modal('hide');
$('body').append('<div aria-labelledby="loading" class="modal bounceIn animated" id="loading-modal" role="dialog" tabindex="-1" data-backdrop="static" data-keyboard="false"><div class="modal-dialog modal-sm" style="width:150px !Important;"><div class="modal-content"><div class="modal-body p-20 text-center"><div class="preloader pl-lg"><svg class="pl-circular" viewBox="25 25 50 50"><circle class="plc-path" cx="50" cy="50" r="20"></circle></svg></div></div><div class="modal-footer" style="text-align: center !Important;"><div class="btn btn-link waves-effect c-gray">Espere...</div></div></div></div></div>');
$('#loading-modal').modal('show');
$.ajax({
  url: '/' + object + '/' + id,
  type: 'DELETE',
  success: function(data) {
    $('#loading-modal').modal('hide');
    $('#loading-modal').remove();
    $('body').append('<div aria-labelledby="ok" class="modal bounceIn animated" id="ok-modal" role="dialog" tabindex="-1"><div class="modal-dialog modal-sm" style="width:150px !Important;"><div class="modal-content"><div class="modal-body p-20 text-center"><i class="zmdi zmdi-hc-3x zmdi-check-circle c-green"></i></div><div class="modal-footer" style="text-align: center !Important;"><div class="btn btn-link waves-effect c-gray">¡Listo!</div></div></div></div></div>');
    $('#ok-modal').modal('show');
    setTimeout(function () {
      location.reload();
    }, 1000)
  },
  error: function(data) {
    $('#loading-modal').modal('hide');
    $('#loading-modal').remove();
    $('body').append('<div aria-labelledby="error" class="modal bounceIn animated" id="error-modal" role="dialog" tabindex="-1"><div class="modal-dialog modal-sm" style="width:150px !Important;"><div class="modal-content"><div class="modal-body p-20 text-center"><i class="zmdi zmdi-hc-3x zmdi-alert-polygon c-red"></i></div><div class="modal-footer" style="text-align: center !Important;"><div class="btn btn-link waves-effect c-gray">Oops...</div></div></div></div></div>');
    $('#error-modal').modal('show');
  }
});

}

(function( $ ){

$.fn.disableSelect = function() {
   $(this).prop("disabled", true);
   $(this).selectpicker('refresh');
};

})( jQuery ); (function( $ ){

$.fn.enableSelect = function() { 
   $(this).prop("disabled", false);
   $(this).selectpicker('refresh');
};

})( jQuery );

function encodeQueryData(data) {

var ret = [];
for (var d in data)
   ret.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return ret.join("&");

}

(function ($) {

"use strict";
function centerModal() {
    $(this).css('display', 'block');
    var $dialog  = $(this).find(".modal-dialog"),
    offset       = ($(window).height() - $dialog.height()) / 2,
    bottomMargin = parseInt($dialog.css('marginBottom'), 10);

    // Make sure you don't hide the top part of the modal w/ a negative margin if it's longer than the screen height, and keep the margin equal to the bottom margin of the modal
    if(offset < bottomMargin) offset = bottomMargin;
    $dialog.css("margin-top", offset);
}

$(document).on('show.bs.modal', '.modal', centerModal);
$(window).on("resize", function () {
    $('.modal:visible').each(centerModal);
});

}(jQuery));

function buildFilterMap(offset) {

filter_map = {};
$("#form :input").each(function() {
  if ($(this).val() != null && $(this).val() != "") {
    if ($(this)[0].name != "") {
      filter_map[$(this)[0].name] = $(this).val();
    }
  }
});
$("#form input[type=radio]").each(function() {
  if ($(this).val() != null && $(this).val() != "") {
    if ($(this).is(':checked')) {
      filter_map[$(this)[0].name] = $(this).val();
    }
  }
});
if (offset != null) {
  filter_map["offset"] = offset;
}
return filter_map;

}

function advance_search(url,offset,format) {

filter_map = buildFilterMap(offset);
filter_map["format"] = format;
if (format != 'xls') {
  window.location.href = url + "?" + encodeQueryData(filter_map);
} else {
  window.open(
    url + "?" + encodeQueryData(filter_map),
    '_blank' // <- This is what makes it open in a new window.
  );
}

};

function read_notify(id,url) {

$.ajax({
  url: '/notifications/' + id,
  type: 'POST',
  data: {},
  success: function(result) {
    window.location = url;
  }
});

}

function capitalize(word) {

return word[0].toUpperCase() + word.slice(1).toLowerCase();

}