(function($) {
  var panelOpts = {
    'extendContainer': true,
    'width': 300,
    'height': 300,
    'layout': 'autolayout',
    'layoutCfg': {},
    'icon': '',
    'tbar': [{id: 'close'}],
    'cls': '',
    'left': 0,
    containment: 'parent',
    'top': 0,
    autoWidth: false,
    'cmpCls': 'jq-panel',
    'renderTo': null,
    'style': {},
    'tools': [],
    activeCls: 'window-active',
    lazyContainer: false,
    'autoHideBorders': false,
    'autoHideToolbar': false,
    'isMaximize': false,
    'listeners': {
      resize: $.noop
    }
  };
  T9.createComponent("Panel", panelOpts, T9.Component.prototype, {
    'initComponent': function() {
      this.el.addClass('extend-container');
      this.doRender();
    },
    'doRender': function() {
      if (this.parentCmp) {
        this.parentCmp.addItems(this);
      }
      
      var css = {'height': 'auto'};
      
      if (!this.autoWidth) {
        css.width = this.width;
      }
      
      this.el.css(css);
      this.createHeader();
      this.createBody();
      this.lazyContainer || this.doContainer();
      this.createFooter();
      
      if (this.draggable) {
        this.clickActive();
      }
    },
    doInitStatus: function() {
      if (this.autoHideBorders) {
        this.setAutoHideBorders();
      }
      
      if (this.autoHideTools) {
        this.setAutoHideTools();
      }
      
      if (this.isPin) {
        this.pin();
        this.tools.pin && this.tools.pin.hide();
      }
      else {
        this.tools.unpin && this.tools.unpin.hide();
      }
      
      if (this.top || this.left || this.right || this.bottom) {
        this.posCenter = false;
      }
      
      if (this.posCenter) {
        var ctn;
        if (!this.containment || this.containment == 'parent') {
          ctn = (this.parentCmp || this.parentEl) ? 'parent' : null;
        }
        else {
          ctn = $(this.containment);
        }
        this.setPosCenter(ctn);
      }
      else {
        this.el.css({
          left: this.left,
          top: this.top,
          bottom: this.bottom,
          right: this.right
        });
      }
     
      //初始化最大化最小化填充满父元素和还原图标的显示状态
      if (!this.isFillCtn && !this.isMaximize) {
        this.tools.restore && this.tools.restore.hide();
      }
      else if (this.isFillCtn) {
        this.tools.plus && this.tools.plus.hide();
        this.maximize(this.containment);
      }
      else if (this.isMaximize) {
        this.tools.maximize && this.tools.maximize.hide();
        this.maximize();
      }
      
      this.doDbclick();
    },
    /**
     * 双击窗口标题栏的最大化的处理
     */
    doDbclick: function() {
      var self = this;
      if (this.tools.plus && this.tools.restore) {
        this.headerEl.dblclick(function() {
          if (self.status.maximize) {
            return;
          }
          if (self.status.fillCtn) {
            self.restore();
            self.tools.restore && self.tools.restore.hide();
            self.tools.plus && self.tools.plus.show();
          }
          else {
            self.maximize(self.containment);
            self.tools.restore && self.tools.restore.show();
            self.tools.plus && self.tools.plus.hide();
          }
        });
      }
      else if (this.tools.maximize) {
        this.headerEl.dblclick(function() {
          if (self.status.maximize) {
            self.restore();
          }
          else {
            self.maximize();
          }
        });
      }
    },
    'doDraggable': function() {
      if (this.draggable) {
        if (typeof this.draggable == 'boolean') {
          this.draggable = {};
        }
        this.draggable.handle = this.draggable.handle || '.' + this.cmpCls + '-header'; 
        this.draggable.containment = this.draggable.containment || 'body';
      }
      T9.Component.prototype.doDraggable.call(this);
    },
    'clickActive': function() {
      this.status.clickActive = true;
      //当点击的时候,窗口变为激活状态
      var self = this;
      this.el.mousedown(function() {
        self.active();
      });
    },
    'doResizable': function() {
      if (this.resizable) {
        var self = this;
        this.resizable.alsoResize = this.resizable.alsoResize || this.contentEl;
        this.resizable.minWidth = this.resizable.minWidth || this.minWidth || 200;
        this.resizable.minHeight = this.resizable.minHeight || this.minHeight || 100;
        
        T9.Component.prototype.doResizable.call(this);
        
        //当resize后设置contentEl宽度,防止最大化还原后contentEl宽度超出
        this.el.resizable('option', {stop: function(e, ui) {
          self.contentEl.css({
            width: '100%'
          });
          self.height = self.contentEl.height();
          self.width =self.el.width();
          self.el.css({height: 'auto'});
        }});
        
        this.el.css({
          'position': 'absolute'
        });
      }
    },
    'setPosCenter': function(ctn) {
	    ctn = ctn || $('body');
	    if (ctn == 'parent') {
	      ctn = this.getParentEl();
	    }
	    ctn = $(ctn);
	    
	    //窗口居中暂时处理办法
	    if (ctn[0] && ctn[0].tagName == 'BODY') {
	      ctn = $('body');
	    }
      T9.Panel.lastLeft = T9.Panel.lastLeft || 0;
      T9.Panel.lastTop = T9.Panel.lastTop || 0;
      var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      this.top = (ctn.height() - this.el.height() - 100) / 2 + scrollTop + (T9.Panel.lastTop += 10);
      this.left = (ctn.width() - this.el.width()) / 2 + (T9.Panel.lastLeft += 20);
      this.top = this.top < 0 ? 0 : this.top;
      var pos = ctn.position();
      this.top += pos.top;
      this.left += pos.left;
      this.el.css({
        'top': this.top,
        'left': this.left
      });
    },
    'toggle': function(speed) {
      this.el.toggleClass(this.cmpCls + '-collapsed');
      this.contentEl.toggle(speed);
    },
    'createHeader': function() {
      this.headerEl = $('<div class="' + this.cmpCls + '-header"></div>');
      //拖动的class
      this.headerEl.addClass('drag-handle');
      this.initTools();
      var title = $('<span></span>');
      if (this.icon) {
        var img = $('<img></img>');
        img.attr('src', this.icon);
        img.attr('align', 'absmiddle');
        this.headerEl.append(img);
      }
      else if (this.iconCls) {
        var div = $('<div style="float: left;"></div>');
        div.addClass(this.iconCls);
        this.headerEl.append(div);
      }
      title.attr('class', this.cmpCls + '-header-text');
      title.append(this.title);
      this.headerEl.append(title);
      var tl = $('<div class="' + this.cmpCls + '-tl"></div>');
      var tr = $('<div class="' + this.cmpCls + '-tr"></div>');
      var tc = $('<div class="' + this.cmpCls + '-tc"></div>');
      tl.append(tr);
      tr.append(tc);
      tc.append(this.headerEl);
      this.el.append(tl);
    },
    'createBody': function() {
      this.contentEl = $('<div class="' + this.cmpCls + '-content"></div>');
      this.contentEl.addClass(this.cmpCls + '-mc');
      this.contentEl.css({
        height: this.height
      });
      
      var ml = $('<div class="' + this.cmpCls + '-ml"></div>');
      var mr = $('<div class="' + this.cmpCls + '-mr"></div>');
      
      this.el.append(ml);
      ml.append(mr);
      mr.append(this.contentEl);
    },
    doContainer: function(reload) {
      if (!this.status.container || reload) {
        var t = this;
        this.container = new T9.Container({
          renderTo: t.contentEl,
          items: t.items,
          url: t.url,
          html: t.html,
          loadCallback: t.loadCallback,
          iframeSrc: t.iframeSrc || t.src,
          layout: t.layout,
          param: t.param,
          layout: t.layout,
          owner: t,
          layoutCfg: t.layoutCfg,
          contentEl: t.content
        });
        T9.compose(this, this.container);
        this.status.container = true;
      }
    },
    'createFooter': function() {
      var bl = $('<div class="' + this.cmpCls + '-bl"></div>');
      var br = $('<div class="' + this.cmpCls + '-br"></div>');
      var bc = $('<div class="' + this.cmpCls + '-bc"></div>');
      var bcP = $('<div class="' + this.cmpCls + '-pointer-bc"></div>');
      bl.append(br);
      br.append(bc);
      this.el.append(bl);
      this.pointerBc && this.el.append(bcP);
    },
    'maximize': function(ctn, evt) {
      var type = !!ctn ? 'fillCtn' : 'maximize';
      ctn = ctn || $('body');
      if (ctn == 'parent') {
        ctn = this.parentEl;
      }
      ctn = $(ctn);
      //从正常窗口到最大化时,记录正常位置,绑定window的resize事件
      if (!this.status.fillCtn && !this.status.maximize) {
        //在初始化完毕的状态下才记录模块原来的位置
        if (this.status.initialized) {
          this.left = this.el.position().left;
          this.top = this.el.position().top;
        }
        this.replacer = {};
        this.replacer.offset = this.el.offset();
        this.replacer.css = {
          height: this.contentEl.css('height'),
          width: this.el.css('width'),
          position: this.el.css('position')
        };
      }
      
      if (!evt) {
        //$(window).unbind('resize', this.maxEvt);
        $(window).bind('resize', {scope: this, ctn: ctn}, this.maxEvt);
        this.drag && this.drag.disable();
        this.resize && this.resize.disable();
      }
      
      if (type == 'maximize') {
        this.layer = 'middle';
        //因为显示和隐藏需要修改status,不能直接改变show函数,需要专门增加效果函数
        this.active();
      }
      else {
        this.layer = 'lower';
        !this.status.hidden && this.active();
      }
      
      //当ctn是父元素的时候不用append
      //(this.el.parent()[0] != ctn[0]) && this.el.appendTo(ctn);
      this.maximize.height = ctn.height() - 68
      var css = ctn.position();
      
      if (this.animate && !this.status.hidden) {
        var self = this;
        this.contentEl.find('.jq-container-iframe').hide();
        this.el.animate({
          width: ctn.width(),
          left: css.left
        }, 'fast', function() {
          self.contentEl.animate({
            height: self.maximize.height
          }, 'fast');
          self.el.animate({
            top: css.top
          }, 'fast', function() {
            self.contentEl.find('.jq-container-iframe').show();
          });
        });
      }
      else {
        this.contentEl.height(this.maximize.height);
        css.width = '100%';
        this.el.css(css);
      }
      this.status[type] = true;
    },
    getCrtHeight: function() {
      if (this.status.fillCtn || this.status.maximize) {
        return this.maximize.height;
      }
      return this.height;
    },
    'restore': function() {
      this.status.fillCtn = this.status.maximize = false;
      if (this.replacer) {
        this.el.css({
          height: 'auto',
          position: this.replacer.css.position
        });
        if (this.animate && !this.status.hidden) {
          var self = this;
          this.contentEl.find('.jq-container-iframe').hide();
          this.el.animate({
            top: this.top
          }, 'fast');
          this.contentEl.animate({
            height: this.replacer.css.height
          }, 'fast', function() {
            self.el.animate({
              left: self.left,
              width: self.replacer.css.width
            }, 'fast', function() {
              self.contentEl.find('.jq-container-iframe').show();
            });
          });
        }
        else {
          this.contentEl.css({
            height: this.replacer.css.height
          });
          this.el.css({left: this.left, top: this.top, width: this.replacer.css.width});
        }
        //当ctn是父元素的时候不用append
        (this.el.parent()[0] != $(this.parentEl)[0]) && this.el.appendTo(this.parentEl);
      }
      this.drag && this.drag.enable();
      this.drag && this.resize.enable();
      this.active('lower');
      //当绑定了window的resize事件则取消绑定      $(window).unbind('resize', this.maxEvt);
      //this.el.width(this.width);
      //this.contentEl.height(this.height);
    },
    /**
     * 模块最大化后
     */
    maxEvt: function(e) {
      var ctn = e.data.ctn;
      var self = e.data.scope;
      self.el.width(ctn.width());
      self.maximize.height = ctn.height() - 68
      self.contentEl.height(self.maximize.height);
    },
    'minimize': function() {
      this.hide();
    },
    'pin': function() {
      this.active('upper');
    },
    'unpin': function() {
      this.active('lower');
    },
    /**
     * 为了兼容目前桌面模块的实现方法,以后再用更好的处理     */
    'autoLoad': function() {
    },
    'getAbsContentHeight': function() {
      return this.contentEl.height() + 'px';
    },
    'getTitle': function() {
      return this.title || '';
    },
    'setTitle': function(title) {
      this.title = title || '';
      this.headerEl.find('span').html(this.title);
    },
    'setWidth': function(width) {
      this.width = width;
      this.el.css({
        'width': this.width
      });
    },
    'setHeight': function(height) {
      this.height = height;
      this.contentEl.css({
        'height': this.height
      });
    },
    'scrollIn': function(speed, callback) {
      var top = (this.status.fillCtn || this.status.maximize) ? 0 : this.top;
      this.el.css({
        top: (document.documentElement || document.body).clientHeight + 'px'
      });
      this.el.show();
      this.el.animate({
        top: top
      }, speed || 'slow', function() {
        callback && callback();
      });
    },
    'scrollOut': function(speed, callback) {
      var self = this;
      var top = (this.status.fillCtn || this.status.maximize) ? 0 : this.top;
      this.el.animate({
        top: (document.documentElement || document.body).clientHeight + 'px'
      }, speed || 'slow', function() {
        self.el.hide();
        self.el.css({
          top: top
        });
        callback && callback();
      });
    },
    collapse: function(speed, callback) {
      var self = this;
      var top = this.getPosY();
      var height = this.getCrtHeight();
      this.el.animate({
        top: parseInt(top + this.getCrtHeight()) / 2
      }, speed);
      this.contentEl.animate({
        height: 0
      }, speed, function() {
        self.el.css({
          display: 'none'
        });
        self.contentEl.css({
          height: height
        });
        self.el.css({top: top});
        callback && callback();
      });
      this.contentEl.find('.jq-container-iframe').hide();
    },
    expand: function(speed, callback) {
      var self = this;
      var height = this.getCrtHeight();
      this.contentEl.css({
        height: 0
      });
      this.el.show();
      var top = this.getPosY();
      this.el.css({top: top + parseInt(this.getCrtHeight()) / 2});
      this.el.animate({
        top: top
      }, speed, function() {
      });
      this.contentEl.animate({
        height: height
      }, speed, function() {
        self.doContainer();
        self.contentEl.find('.jq-container-iframe').show();
        callback && callback()
      });
    },
    /**
     * 关闭函数先hide再destroy
     */
    'close': function(speed) {
      var self = this;
      this.hide(speed, function() {
        self.destroy();
      });
    },
    'initTools': function() {
      var tools = this.tbar || [];
      var t = this;
      t.tools = {};
      $.each(tools, function(i, e){
        if (T9.Tools[e.id]) {
          t.tools[e.id] = {
            el: $('<a href="javascript:void(0)">&nbsp;</a>'),
            show: function() {
              this.el.show();
            },
            hide: function() {
              this.el.hide();
            },
            initTool: function() {
              t.headerEl.append(this.el);
              this.el.attr('class', 'jq-tool jq-tool-' + e.id);
              this.el.attr('title', T9.Tools[e.id].title);
              if (e.hidden) {
                this.hide();
              }
              this.el.bind('click', function(){
                if (!e.preventDefault) {
                  T9.Tools[e.id].defaultHandler(e, t.tools[e.id].el, t, e.params);
                }
                if (e.handler){
                  e.handler(e, t.tools[e.id].el, t, e.params);
                }
              });
            }
          };
          t.tools[e.id].initTool();
        }
      });
    },
    'active': function(layer) {
      this.layer = layer || this.layer;
      this.zIndex = T9.topZIndex(this.layer);
      this.el.css({
        'z-index': this.zIndex
      });
      this.addClass(this.activeCls);
      this.status.hidden && this.show();
    },
    deactive: function() {
      this.removeClass(this.activeCls);
    },
    'hide': function(speed, callback) {
      if (this.status.hidden) {
        callback && callback();
        return;
      }
      var self = this;
      this.trayBtn && this.trayBtn.disable();
      this.hideEffect(speed, function() {
        self.trayBtn && self.trayBtn.enable();
        callback && callback();
      });
      this.status.hidden = true;
    },
    'show': function(speed, callback) {
      if (this.status.hidden) {
        this.status.hidden = false;
        var self = this;
        this.trayBtn && this.trayBtn.disable();
        this.showEffect(speed, function() {
          self.trayBtn && self.trayBtn.enable();
          callback && callback()
        });
      }
    },
    /**
     * 设置自动隐藏工具栏     */
    'setAutoHideTools': function() {
      var self = this;
      this.headerEl.hide();
      this.el.hover(function() {
        self.headerEl.show();
      }, function() {
        self.headerEl.hide();
      });
    },
    /**
     * 设置自动隐藏边框
     */
    'setAutoHideBorders': function() {
      this.el.addClass('window-tsp');
      this.el.hover(function() {
        $(this).removeClass('window-tsp');
      }, function() {
        $(this).addClass('window-tsp');
      });
    },
    /**
     * 重写容器的销毁函数
     */
    destroy: function() {
      //如果存在repalcer就先销毁replacer
      //(this.status.fillCtn || this.status.maximize) && $(window).unbind('resize', this.maxEvt);
      //调用通用的销毁函数
      if (this.container && this.container.iframeDom) {
        this.container.iframeDom.src = 'about:blank';
      }
      T9.Component.prototype.destroy.call(this);
    }
  });
})(jQuery);

