// Items Quantity
function itemsQuantity() {
  var $sortable = $('.sortable'),
      $host = $sortable.children('.navbar').eq(0),
      $navbar = $('.sortable li').children('.navbar'),
      $quantity = $sortable.find('li').length; 
  $host.find('.badge').text($quantity);
  $navbar.each(function(i) {
    if($navbar.eq(i).next('ol').length>0) {
      var $amount = $navbar.eq(i).next('ol').find('li').length;
      $navbar.eq(i).find('.badge').text($amount);
    }else{
      $navbar.eq(i).find('.badge').text('0');
    }
    $navbar.eq(i).find('.badge').text()>0 ? $navbar.eq(i).find('.badge').addClass('badge-info'):$navbar.eq(i).find('.badge').removeClass('badge-info');
  })
}
function tip() {
  if(!$.support.touch) {
    $('.tip').tooltip({
      position: {
        my: "center bottom-4",
        at: "center top",
      }
    });
  };
}
function touchSupport() {
  if($.support.touch) {
    $('.item-menu').css({
        'display': 'inline-block'
    })
  }
}

$(function(){
  $('.sortable').nestedSortable({
    handle: '.brand',
    items: 'li',
    maxLevels: 3,
    opacity: .6,
    toleranceElement: '> div',
    placeholder: 'placeholder',
    startCollapsed: true,
    disableNesting: 'no-nest',
    stop: function(event, ui) {
      $.post("<%= Rails.application.routes.url_helpers.admin_update_position_path %>", { id: ui.item.attr('id'), parent_id: (ui.item.parent().closest('li').attr('id') || ui.item.parent().closest('ol').attr('id')), position: ui.item.index() } );
    }
  });
  $(".sortable").delegate(".brand, .delete", clickEvent, function(e){
    if($(this).hasClass('delete')) {
      $target = $(this);
      $('#dialog a.delete-item').attr("href", $(this).attr("rel"));
      $('#dialog').modal('show');
    } else {
      if($(this).closest('li').children('ol').length > 0){
        $(this).closest('li').toggleClass('collapsed');
      }
    }
    e.preventDefault();
  });

  tip();
  touchSupport()
  itemsQuantity();
});

function reloadStructure(){
  $.pageslide.close();
  openSlide();
  tip();
  touchSupport()
  itemsQuantity();
};