var taskMsgRepeaters = {};

/**
 * 信息列表控件
 */
function TaskMsgRepeater() {
  this.getDataService = null;  //获得数据的服务
  this.dataMember = null;      //表单对应的数据源对象名
  this.dataSource = null;      //数据源对象
  this.onLoadData = null;      //加载数据前执行的回调函数
  this.onBindData = null;      //加载数据后执行的回调函数
  this.jQueryObj = null;       //jQuery对象
  this.size = 5;               //最多显示多少行数据
  this.start = 0;              //开始索引

  var that = this;

  /**
   * 初始化控件
   * @param  {[type]} obj [description]
   * @return {[type]}     [description]
   */
  this.init = function(obj) {
    this.jQueryObj = obj;
    if(obj.attr("getDataService")) this.getDataService = obj.attr("getDataService");
    if(obj.attr("dataMember")) this.dataMember = obj.attr("dataMember");
    if(obj.attr("onLoadData")) this.onLoadData = obj.attr("onLoadData");
    if(obj.attr("onBindData")) this.onBindData = obj.attr("onBindData");
    if(obj.attr("size")) this.size = parseInt(obj.attr("size"));
    if(obj.attr("start")) this.start = parseInt(obj.attr("start"));
    if(this.getDataService) {
      var service = new TaskMsgService(this.getDataService);
      service.request(null, function(req, res) {
        that.onRequestData(req, res);
      });
    }
  };

  /**
   * 当收到服务器响应
   * @param  {[type]} req [description]
   * @param  {[type]} res [description]
   */
  this.onRequestData = function(req, res) {
    if(this.onLoadData) eval(this.onLoadData+"(req, res)");
    if(this.dataMember && res[this.dataMember]) {
      this.dataSource = res[this.dataMember];
    }
    this.dataBind();
    if(this.onBindData) eval(this.onBindData+"(req, res)");
  };

  /**
   * 绑定数据
   */
  this.dataBind = function() {
    var templateHtml = this.jQueryObj.get(0).innerHTML;
    this.jQueryObj.empty();
    if(this.dataSource.length==0) return;
    if(this.dataSource.length) {
      for(var i=this.start;i<this.dataSource.length && (i-this.start)<this.size;i++) {
        var item = this.dataSource[i];
        item._index = i;
        var itemHtml = replaceDataField(item, templateHtml);
        itemHtml = exeExpress(itemHtml);
        this.jQueryObj.append(itemHtml);
      }
    } else {
      var index = this.start;
      for(id in this.dataSource) {
        var item = this.dataSource[id];
        item._index = index;
        var itemHtml = replaceDataField(item, templateHtml);
        itemHtml = exeExpress(itemHtml);
        this.jQueryObj.append(itemHtml);
        index++;
        if((index-this.start)>=this.size) break;
      }
    }
    this.jQueryObj.show();
  };
}

$(function(){
  $(".TaskMsgRepeater").each(function(index) {
    var repeater = new TaskMsgRepeater();
    if($(this).attr("id")) {
      repeater.id = $(this).attr("id");
    } else {
      repeater.id = "TaskMsgRepeater_"+index;
    }
    taskMsgRepeaters[repeater.id] = repeater;
    repeater.init($(this));
  });
});