/**
 * 抽屉菜单
 * Copyright (c) 2020 xiaofanku
 * mail:xiaofanku@live.cn
 */
(function($) {
  "use strict";
  var drawerMenu={
    init : function(jqEle, config) {
      if(config.overlay && $('body').find('.drawer-overlay').length == 0){
        var $upper = $("<div>&nbsp;</div>").addClass('drawer-overlay');
        $('body').append($upper);
      }
      //
      if(config.opened){
          var f = window[config.opened];
          if(typeof f === 'function'){
              jqEle.bind('drawer.opened', f);
          }
      }
      if(config.closed){
          var fn = window[config.closed];
          if(typeof fn === 'function'){
              jqEle.bind('drawer.closed', fn);
          }
      }
      //是开是关
      if(jqEle.hasClass('drawer-open')){
        drawerMenu.close(jqEle);
      }else{
        drawerMenu.open(jqEle);
      }
    },
    open : function(jqEle){
      $('.drawer-overlay').css('display' , 'block');
      jqEle.addClass('drawer-open').removeClass('drawer-close').stop(true, true).delay(100).animate({bottom: 0}, 400, "swing").trigger("drawer.opened");
    },
    close : function(jqEle){
      var cv = jqEle.css('height'); 
      jqEle.addClass('drawer-close').removeClass('drawer-open').animate({bottom: '-'+cv}, 500, "swing").trigger("drawer.closed");
      $('.drawer-overlay').css('display' , 'none');
    },
    bindEvent : function(jqEle, config){
      //绑定关闭按钮
      jqEle.find('.'+config.closeBtn).bind('click', function(){
        drawerMenu.close(jqEle);
      }); 
    }
  };
  $.fn.drawer = function(option) {
    return this.each(function () {
      var self = $(this);
      if(drawerMenu[option] && option === 'close'){
          return drawerMenu[option].call(this, self, self);
      } 
      if (typeof option === "object" || !option) {
          var config = $.extend({direction : 'bottom', closeBtn : 'drawer-close-btn', duration : 500, overlay : true}, option);
          drawerMenu.init(self, config);
          drawerMenu.bindEvent(self, config);
      }
    });
  };
})(jQuery);