/**
 * 发送私信相关的API，引入该文件可发送私信。
 * @fileOverview
 */

XWB.MSGS = (function($){
  return {
    
      //  data control model
      model : {
        /**
         * 发送私信
         */
          send : function(data, callback){
            XWB.apiCall('sendDirectMessage', {
              data:data,
              success: callback
            });
          },
      
        /**
         * 测试对方是否我的粉丝
         * @param {String} name or uid, specified by param useId
         * @param {Function} callback
         * @param {Boolean} useId true to use id ,false to use name ,default to name
         */
          isMyFans : function(name, callback, useId){
            var data = {};
            data[useId?'t_id':'t_name'] = name;
            XWB.apiCall('friendShip', {
              data : data,
              success : function(ret){
                if(!ret.rst){
                  callback(ret.rst, ret);
                }
              }
            });
          },
        /**
         * 删除私信
         */
          delMsg : function(id, callback){
            XWB.apiCall('deleteDirectMessage', {
              data : {id:id},
              success : callback
            });
          }
      },
  
      
    /**
     * 弹出对话框，发送私信给指定用户。
     */
      showPopup : function(){
        this.getPopup(true).show();
        this.findEl('sender').focus();
      },
      
      reply : function(name, uid){
        this.showPopup();
        this.findEl('sender').val(name).attr('disabled', true);
        this.findEl('uid').val(uid);
        this.findEl('content').focus();
      },
      
    
    /**
     * 获得"发私信"对话框。
     * @param {Boolean} reset reset the form
     * @return {jQueryElement}
     */
      getPopup : function(reset){
        var $box = this._sndPopEl ? this._sndPopEl : this._createSendPopup();
        if(reset){
          this.findEl('sender').val('').attr('disabled', false);
          this.findEl('content').val('');
          this.findEl('uid').val('');
          $box.find('.warn-pos').hide();
        }
        return $box;
      },
  
  /**
   * 主动发送当前弹出框中的信息。
   */
      send : function(){
        var data = this._validateForm();
        if(data !== false){
          this.model.send(data, this._getSendCallHandler());
        }
      },
      
      delMsg : function(mid, callback){
        this.model.delMsg(mid, callback);
      },
      
      findEl : function(key){
        switch (key) {
          case 'sender':
            return this.getPopup().find('#xwm_msgs_sender');
          case 'content' :
            return this.getPopup().find('#xwm_msgs_ct');
          case 'uid' :
            return this.getPopup().find('#xwm_msgs_uid');
        }
      },
      
      // private
      _getSendCallHandler : function(){
         if(!this._sndCallCb)
           this._sndCallCb = $.proxy(function(ret){
             if(this._checkSendStatus(ret)){
               this.getPopup().hide();
               location.reload();
             }
           }, this);
  
         return this._sndCallCb;
      },
      
      // private
      _checkSendStatus : function(ret){
          if (ret.errno != 0) {
            var msg;
            switch(ret.errno){
              case 20013 : 
                msg = '此昵称不存在，请核对';
                break;
              case 20016 :
                msg = '他还没有关注你,暂时不能发私信';
                break;
              case 20014 :
                XWB.alert({
                  msg: '请不要重复输入。'
                });
                break;
              default :
                XWB.alert({
                  msg: '发生错误: ' + XWB.escape(ret.err.error || ret.err)
                });
            }
            
            if(msg)
              this._showSnderTip(true, msg);
            return false;
          }else {
            this._showSnderTip(false);
            return true;
          }
      },
      
      // private
      _createSendPopup : function(){
        var self = this;
        var el = $([
          '<div class="pop-window send-window fixed-window ">',
            '<div class="pop-t"></div>',
            '<div class="pop-content">',
              '<h4 class="pop-title x-bg"><a href="#" class="close-btn icon-bg"></a>&nbsp;发私信</h4>',
              '<div class="send-box">',
                '<div class="field"><label>发私信给:</label><input type="text" id="xwm_msgs_sender"><em class="warn warn-pos" style="display:none;"></em></div>',
                '<input type="hidden" id="xwm_msgs_uid">',
                '<div class="field"><label>私信内容:</label><textarea id="xwm_msgs_ct"></textarea></div>',
                '<div class="field pad">',
                  '<div class="choose-emotion all-bg fl"></div>',
                  '<div class="fr">',
                    '<span class="tips fl">您还可以输入300个字</span>',
                    '<em class="warn fl hidden">这里是提示信息</em>',
                    '<a href="javascript:;" class="general-btn highlight fl" id="xwm_msgs_sndbtn"><span>发送</span></a>',
                  '</div>',
                '</div>',
              '</div>',
            '</div>',
            '<div class="pop-b"></div>',
            '<div class="pop-tl all-bg"></div>',
            '<div class="pop-tr all-bg"></div>',
            '<div class="pop-bl all-bg"></div>',
            '<div class="pop-br all-bg"></div>',
          '</div>'
          ].join(''));
        
        // bind events
        el.find('.close-btn')
          .click(function(e){
            self.getPopup().hide();
            e.preventDefault();
          });
        el.find('#xwm_msgs_sndbtn')
          .click(function(e){
            e.preventDefault();
            self.send();
          });
        
        var tip      = el.find('.tips'),
            textarea = el.find('#xwm_msgs_ct');
        
        textarea.keyup(function(){
          var left = textarea.checkText(300);
          tip.html(
            left >= 0 ? '您还可以输入'+left+'个字' : '已超出' + Math.abs(left) + '字'
          );
        });
        
        var txt = el.find('#xwm_msgs_sender'),
            self = this;
            
        txt.blur(function(){
          var name = $.trim(txt.val());
          if(name.length){
            self.model.isMyFans(name, function(b, ret){
              if(!b){
                self._checkSendStatus(ret);
              }
            });
          }
        });
        
        el.find('.choose-emotion').click(function(e){
          var xy = $(this).offset();
          XWB.subjoin.showEmotion(document.body, textarea, xy.left - 22, xy.top + 28);
          e.stopPropagation();
          e.preventDefault();
        });
        
        el.appendTo(document.body);
        
        var mask = el.toXwin();
        
        el.show = (function(chain){ return function(){mask.show(); chain.call(el);}; })(el.show);
        el.hide = (function(chain){ return function(){mask.close(); chain.call(el);}; })(el.hide);
        
        this._sndPopEl = el;
        return el;
      },
      
      _showSnderTip : function(show, msg){
        var el = this.getPopup().find('.warn-pos');
        if(msg)
          el.html(msg);
        show?el.show() : el.hide();
      },
      
      // private
      _validateForm : function(){
        var $box     = this.getPopup(),
            textarea = this.findEl('content');
            name     = $.trim(this.findEl('sender').val()),
            ct       = $.trim(textarea.val()),
            left     = textarea.checkText(300),
            uid      = this.findEl('uid').val();
  
        if(!name){
          alert('请输入对方昵称。');
          this.findEl('sender').focus();
          return false;
        }
        
        if(!ct){
          alert('请输入私信内容。');
          textarea.focus();
          return false;
        }
        
        if(left < 0){
          alert('内容不能超过300个汉字。');
          textarea.focus();
          return false;
        }
        
        if(uid)
            return {id:uid, text:ct};
        return {name:name, text:ct};
      }
  };
})(jQuery);