// 任信客户端API文件保存路径
var TaskMsgClientAPIDir = "/inc/taskmsg/";
// 是否启用调试
var TaskMsgIsDebug = false;

/**
 * 转换日期
 * @param  {[type]} str [description]
 * @return {[type]}     [description]
 */
Date.from = function (str) {
  if (str)
    return new Date(str.replace(/-/g, "\/"));
  else
    return new Date();
};

/**
 * 格式化日期
 * @param  {[type]} style [description]
 * @return {[type]}       [description]
 */
Date.prototype.format = function (style) {
  var y = this.getFullYear();
  var M = "0" + (this.getMonth() + 1);
  M = M.substring(M.length - 2);
  var d = "0" + this.getDate();
  d = d.substring(d.length - 2);
  var h = "0" + this.getHours();
  h = h.substring(h.length - 2);
  var m = "0" + this.getMinutes();
  m = m.substring(m.length - 2);
  var s = "0" + this.getSeconds();
  s = s.substring(s.length - 2);
  return style.replace('yyyy', y).replace('yy', (y + '').substring(2)).replace('MM', M).replace('dd', d).replace('hh', h).replace('mm', m).replace('ss', s).replace('S', this.getMilliseconds());
};

/**
 * 日期计算
 * @param  {[type]} strInterval   [description]
 * @param  {[type]} Number        [description]
 * @return {[type]}               [description]
 */
Date.prototype.add = function (strInterval, Number) {
  var dtTmp = this;
  switch (strInterval) {
    case 's':
      return new Date(Date.parse(dtTmp) + (1000 * Number));
    case 'n':
      return new Date(Date.parse(dtTmp) + (60000 * Number));
    case 'h':
      return new Date(Date.parse(dtTmp) + (3600000 * Number));
    case 'd':
      return new Date(Date.parse(dtTmp) + (86400000 * Number));
    case 'w':
      return new Date(Date.parse(dtTmp) + ((86400000 * 7) * Number));
    case 'q':
      return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number * 3, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    case 'm':
      return new Date(dtTmp.getFullYear(), (dtTmp.getMonth()) + Number, dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
    case 'y':
      return new Date((dtTmp.getFullYear() + Number), dtTmp.getMonth(), dtTmp.getDate(), dtTmp.getHours(), dtTmp.getMinutes(), dtTmp.getSeconds());
  }
};

/**
 * 判断字符串是否以指定的子字符串开头
 * @param  {[type]} prefix [description]
 * @return {[type]}        [description]
 */
String.prototype.startWith = String.prototype.startsWith = function (prefix) {
  return this.indexOf(prefix) === 0;
};

/**
 * 判断字符串是否以指定的子字符串结尾
 * @param  {[type]} suffix [description]
 * @return {[type]}        [description]
 */
String.prototype.endWith = String.prototype.endsWith = function (suffix) {
  return this.match(suffix + "$") == suffix;
};

/**
 * 全部替换
 * @param  {[type]} s1 [description]
 * @param  {[type]} s2 [description]
 * @return {[type]}    [description]
 */
String.prototype.replaceAll = function (s1, s2) {
  return this.replace(new RegExp(s1, "gm"), s2);
};

String.prototype.trim = function () {
  return this.replace(/(^\s*)|(\s*$)/g, "");
};

String.prototype.toDate = function () {
  return new Date(this.replace(/-/g, '/'));
};

/**
 * 判断数组中是否存在指定的元素
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
Array.prototype.contains = function (obj) {
  var i = this.length;
  while (i--) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
};

/**
 * 删除数组中指定的元素
 * @param  {[type]} obj [description]
 * @return {[type]}     [description]
 */
Array.prototype.remove = Array.prototype.deleteMember = function (obj) {
  for (var i = 0; i < this.length; i++) {
    if (this[i] === obj) {
      this.splice(i, 1);
      return;
    }
  }
};

/**
 * 判断是否是有效的手机号
 * @param  {String}  num 手机号字符串
 * @return {Boolean}     判断结果
 */
isMobile = function (num) {
  var partten = /^1\d{10}$/;
  if (partten.test(num)) return true;
  return false;
};

/**
 * 判断是否是有效的邮箱地址
 * @param  {String}  mail 邮箱地址字符串
 * @return {Boolean}      判断结果
 */
isEmail = function (mail) {
  var partten = /^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$/;
  if (partten.test(mail)) return true;
  return false;
};

/**
 * 判断是否为邮政编码
 * @param  {String}  str 输入值
 * @return {Boolean}     判断结果
 */
isPostCode = function (str) {
  var result = str.match(/[1-9]\d{5}(?!\d)/);
  if (result === null) return false;
  return true;
};

/**
 * 是否是固定电话
 * @param  {String}  str 输入值
 * @return {Boolean}     判断结果
 */
isTel = function (str) {
  var result = str.match(/\d{3}-\d{8}|\d{4}-\d{7}/);
  if (result === null) return false;
  return true;
};

/**
 * 是否是身份证号
 * @param  {String}  str 输入值
 * @return {Boolean}     判断结果
 */
isIdCard = function (str) {
  var result = str.match(/\d{15}|\d{18}/);
  if (result === null) return false;
  return true;
};

/**
 * 判断是否是整数
 * @param  {[type]}  i [description]
 * @return {Boolean}   [description]
 */
isInt = function (i) {
  return i == parseInt(i);
};

/**
 * 是否存在指定函数
 * @param  {[type]}  funcName [description]
 * @return {Boolean}          [description]
 */
isExitsFunction = function (funcName) {
  try {
    if (typeof (eval(funcName)) == "function") {
      return true;
    }
  } catch (e) {}
  return false;
};

/**
 * 格式化金额
 * @param  {[type]} s 输入值
 * @param  {[type]} n 小数点位数
 * @return {[type]}   返回值
 */
formatMoney = function (s, n) {
  n = n > 0 && n <= 20 ? n : 2;
  s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
  var l = s.split(".")[0].split("").reverse();
  var r = s.split(".")[1];
  var t = "";
  for (var i = 0; i < l.length; i++) {
    t += l[i] + ((i + 1) % 3 === 0 && (i + 1) != l.length ? "," : "");
  }
  return t.split("").reverse().join("") + "." + r;
};

/**
 * 格式化日期
 * @param  {[type]} d 输入值
 * @param  {[type]} f 格式
 * @return {[type]}   返回值
 */
formatDate = function (d, f) {
  if (typeof (d) == "number")
    return (new Date(d)).format(f);
  else
    return (new Date(Date.parse(d.replace("T", " ").replace("+08:00", " ").replace(/-/g, "/")))).format(f);
};

/**
 * 格式化文件大小
 * @param  {[type]} bytes [description]
 * @return {[type]}       [description]
 */
formatFileSize = function (bytes) {
  if (bytes === 0) return '0 B';
  var k = 1000, // or 1024
    sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
    i = Math.floor(Math.log(bytes) / Math.log(k));
  return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
};

/**
 * 获得样式中的像素值，将px字母删掉，转换为整数
 * @param  {[type]} value [description]
 * @return {[type]}       [description]
 */
getPixel = function (value) {
  return parseInt((new String(value)).replace("px", ""));
};

/**
 * 获得URL中的所有参数
 * @param  {[type]} url [description]
 * @return {[type]}     [description]
 */
getUrlArgs = function (url) {
  var args = {};
  var start = url.indexOf("?");
  if (start < 0) return args;
  var str = url.substr(start + 1);
  if (str.indexOf("&") < 0) {
    var strArr = str.split("=");
    args[strArr[0]] = strArr[1];
    return args;
  }
  var strArr = str.split("&");
  for (var i = 0; i < strArr.length; i++) {
    var strArr2 = strArr[i].split("=");
    args[strArr2[0]] = strArr2[1];
  }
  return args;
};

/**
 * 获得URL中的指定参数的值
 * @param  {[type]} argName [description]
 * @return {[type]}         [description]
 */
getUrlArg = function (argName) {
  var url = window.location.href;
  var start = url.indexOf("?");
  if (start < 0) return null;
  var str = url.substr(start + 1);
  var strArr = str.split("&");
  for (var i = 0; i < strArr.length; i++) {
    let aname = strArr[i].substr(0, strArr[i].indexOf("="));
    if (aname == argName) return decodeURIComponent(strArr[i].substr(strArr[i].indexOf("=")+1));
  }
  return null;
};

/**
 * 替换字段变量
 * @param  {[type]} obj     [description]
 * @param  {[type]} str     [description]
 * @return {[type]}         [description]
 */
replaceDataField = function (obj, str, rowIndex) {
  var start = str.indexOf("{");
  if (start < 0) return str;
  var end = str.indexOf("}", start);
  if (end < 0) return str;
  var fieldStr = str.substr(start + 1, end - start - 1);
  var fieldName = fieldStr;
  var format = "";
  if (fieldStr.indexOf(",") > 0) {
    format = fieldStr.substr(fieldStr.indexOf(",") + 1);
    fieldName = fieldStr.substr(0, fieldStr.indexOf(","));
  }
  if (fieldName in obj && (obj[fieldName] || obj[fieldName] == 0)) {
    if (format == "datetime") {
      if ((obj[fieldName] + '').indexOf("T") > 0) {
        str = str.replace("{" + fieldStr + "}", (new Date(obj[fieldName] + '')).format("yyyy-MM-dd hh:mm"));
      } else {
        str = str.replace("{" + fieldStr + "}", (new Date((obj[fieldName] + '').replace(/-/g, '/'))).format("yyyy-MM-dd hh:mm"));
      }
    } else if (format == "date") {
      if ((obj[fieldName] + '').indexOf("T") > 0) {
        str = str.replace("{" + fieldStr + "}", (new Date(obj[fieldName] + '')).format("yyyy-MM-dd"));
      } else {
        str = str.replace("{" + fieldStr + "}", (new Date((obj[fieldName] + '').replace(/-/g, '/'))).format("yyyy-MM-dd"));
      }
    } else if (format == "time") {
      if ((obj[fieldName] + '').indexOf("T") > 0) {
        str = str.replace("{" + fieldStr + "}", (new Date(obj[fieldName] + '')).format("hh:mm:ss"));
      } else {
        str = str.replace("{" + fieldStr + "}", (new Date((obj[fieldName] + '').replace(/-/g, '/'))).format("hh:mm:ss"));
      }
    } else if ((format.indexOf("\"") >= 0 || format.indexOf("'") >= 0) &&
      (format.indexOf("yy") >= 0 || format.indexOf("MM") >= 0 ||
        format.indexOf("dd") >= 0 || format.indexOf("hh") >= 0 ||
        format.indexOf("ss") >= 0)) {
      format = format.replace(/"/g, "").replace(/'/g, "");
      var dateStr = obj[fieldName] + '';
      if (dateStr.indexOf("T") < 0) dateStr = dateStr.replace(/-/g, '/');
      str = str.replace("{" + fieldStr + "}", (new Date(dateStr)).format(format));
    } else if (format == "int") {
      str = str.replace("{" + fieldStr + "}", formatNumber(obj[fieldName], 0));
    } else if (format == "money") {
      str = str.replace("{" + fieldStr + "}", formatMoney(obj[fieldName], 2));
    } else if (format == "filesize") {
      str = str.replace("{" + fieldStr + "}", formatFileSize(obj[fieldName]));
    } else {
      str = str.replace("{" + fieldStr + "}", (obj[fieldName] + "").replace(/\{/g, "`(`").replace(/\}/g, "`)`"));
    }
  } else {
    if(fieldName=="_rowIndex" && (rowIndex || rowIndex==0)) {
      str = str.replace("{" + fieldStr + "}", ""+rowIndex);
    } else {
      str = str.replace("{" + fieldStr + "}", "");
    }
  }
  return replaceDataField(obj, str);
};

/**
 * 执行表达式
 * @param  {[type]} str     [description]
 * @return {[type]}         [description]
 */
exeExpress = function (str) {
  var start = str.indexOf("#[");
  if (start < 0) return str.replace(/\`\(\`/g, "{").replace(/\`\)\`/g, "}");
  var end = str.indexOf("]", start);
  if (end < 0) return str;
  var express = str.substr(start + 2, end - start - 2);
  var value = eval(express);
  var newStr = "";
  if (start > 0) newStr += str.substr(0, start);
  newStr += eval(express);
  if (end < (str.length - 1)) newStr += str.substr(end + 1);
  return exeExpress(newStr);
};

/**
 * 获取请求对象
 * @return {[type]}         [description]
 */
function getHttpRequest() {
  var httpRequest;
  if (window.XMLHttpRequest) {
    httpRequest = new XMLHttpRequest();
  } else if (window.ActiveXObject) {
    httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
    if (!httpRequest) {
      httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    }
  }
  if (!httpRequest) {
    alert("您的浏览器不支持Ajax，无法执行该操作！");
    return null;
  }
  return httpRequest;
}

/**
 * 引用
 * @param  {[type]} url     [description]
 * @return {[type]}         [description]
 */
function require(url) {
  if (!url) return;
  var fileType = "";
  if (url.toLowerCase().lastIndexOf(".js") > 0) {
    fileType = "js";
  } else if (url.toLowerCase().lastIndexOf(".css") > 0) {
    fileType = "css";
  } else {
    alert("不支持对路径[" + url + "]的引用！");
    return;
  }

  var isExist = false;
  if (fileType == "js") {
    $("script").each(function () {
      if ($(this).attr("src") == url) {
        isExist = true;
        return false;
      }
    });
  } else {
    $("link").each(function () {
      if ($(this).attr("href") == url) {
        isExist = true;
        return false;
      }
    });
  }
  if (isExist) return;

  var httpRequest = getHttpRequest();
  httpRequest.onreadystatechange = function () {
    if (httpRequest.readyState == 4) {
      if (httpRequest.status == 200 || httpRequest.status == 304) {
        if (!httpRequest.responseText) return;
        if (fileType == "js") {
          $("head").append("<script type=\"text/javascript\">" + httpRequest.responseText + "</script>");
        } else {
          $("head").append("<style>" + httpRequest.responseText + "</style>");
        }
      } else {
        alert("发送http请求时发生意外错误：" + httpRequest.statusText + "(" + httpRequest.status + ")");
      }
    }
  };
  httpRequest.open('GET', url, false);
  httpRequest.send(null);
}

/**
 * 服务对象
 * @param string serviceTagId 服务标签的编号
 */
function TaskMsgService(serviceTagId) {
  this.onError      = null;   //处理错误的回调函数
  this.autoShowErr  = true;   //是否自动显示错误提示
  this.srcElement   = null;   //请求服务的源节点
  this.serviceTag   = null;   //定义服务信息的标签
  this.app          = null;   //
  this.path         = null;   //服务的路径
  this.onResponse   = null;   //服务器端返回响应信息之后执行的回调函数
  this.notSessionId = false;  //不需要传递会话信息
  this.encArgs      = null;   //需要加密的参数

  /**
   * 显示错误信息
   * @param  {[type]} msg [description]
   * @return {[type]}     [description]
   */
  this.showError = function (msg) {
    tmClient.debug(msg);
    if (this.autoShowErr) alert(msg);
    if (this.onError) this.onError(msg);
  };

  /**
   * 设置请求参数
   * @param {[type]} argName [description]
   * @param {[type]} val     [description]
   */
  this.setArg = function (argName, val) {
    $("#" + serviceTagId).find("arg").each(function () {
      if ($(this).attr("name") == argName) {
        $(this).attr("type", "");
        if (typeof (val) == "string" ||
          typeof (val) == "number" ||
          typeof (val) == "boolean") {
          $(this).attr("value", val);
        } else {
          $(this).attr("value", JSON.parse(val));
        }
      }
    });
  };

  /**
   * 设置对象型请求参数
   * @param {[type]} obj [description]
   */
  this.setArgs = function (obj) {
    $("#" + serviceTagId).find("arg").each(function () {
      var val = obj[$(this).attr("name")];
      if (!val) val = "";
      $(this).attr("type", "");
      if (typeof (val) == "string" ||
        typeof (val) == "number" ||
        typeof (val) == "boolean") {
        $(this).attr("value", val);
      } else {
        $(this).attr("value", JSON.parse(val));
      }
    });
  };

  /**
   * 添加需要加密传输的参数
   * @param {[type]} arg   [description]
   * @param {[type]} value [description]
   */
  this.addEncArg = function(arg, value) {
    if(!this.encArgs) this.encArgs = {};
    this.encArgs[arg] = value;
  };

  /**
   * 请求
   * @param  {[type]} args       [description]
   * @param  {[type]} onResponse [description]
   * @return {[type]}            [description]
   */
  this.request = function (args, onResponse) {
    if (serviceTagId) {
      this.serviceTag = $("#" + serviceTagId);
      this.app = this.serviceTag.attr("app");
      if (this.serviceTag.attr("path"))
        this.path = this.serviceTag.attr("path");
      else
        this.path = this.serviceTag.data("path");
      if (this.serviceTag.attr("onResponse"))
        this.onResponse = this.serviceTag.attr("onResponse");
    }
    if (!this.path) {
      this.showError("请提供服务路径！");
      return;
    }

    if (window.event) this.srcElement = window.event.srcElement;
    if (onResponse) this.onResponse = onResponse;

    if (!args) args = {};
    if (this.app) args.app = this.app;

    if (this.serviceTag && this.serviceTag.children().length > 0) {
      this.serviceTag.find("arg").each(function () {
        if ($(this).attr("type") == "queryString") {
          args[$(this).attr("name")] = getUrlArg($(this).attr("field"));
        } else if ($(this).attr("type") == "formInput") {
          var formId = $(this).attr("form");
          var inputId = $(this).attr("input");
          if (formId) {
            var form = taskMsgForms[formId];
            if (form.inputs[inputId]) {
              args[$(this).attr("name")] = form.inputs[inputId].getValue();
            }
          } else {
            var haveGetVal = false;
            for (var _formId in taskMsgForms) {
              var form = taskMsgForms[_formId];
              if (form.inputs[inputId]) {
                args[$(this).attr("name")] = form.inputs[inputId].getValue();
                haveGetVal = true;
                break;
              }
            }
            if(!haveGetVal) {
              var val = $("#"+$(this).attr("input")).val();
              if(val) args[$(this).attr("name")] = val;
            }
          }
        } else {
          args[$(this).attr("name")] = $(this).attr("value");
        }
      });
    }

    this.args = args;
    if(top.taskMsgAuthObj && top.taskMsgAuthObj.haveLoad) {
      top.taskMsgAuthObj.setAuthData(this);
    } else {
      if(getUrlArg("_auth_data")) this.args._auth_data = getUrlArg("_auth_data");
      if(getUrlArg("_auth_org")) this.args._auth_org = getUrlArg("_auth_org");
      if(getUrlArg("_auth_ts")) this.args._auth_ts = getUrlArg("_auth_ts");
    }

    if ("undefined" != typeof RDASServiceHandlerPath) {
      this.requestRDASService(this.path, args, onResponse);
    } else if (args.noTmClient) {
      this.sendRequest();
    } else {
      if (tmClient) {
        if (tmClient.sessionId) {
          this.sendRequest();
        } else {
          if (tmClient.clientOSType == "iOS") {
            tmClient.waitProcessServices.push(this);
          } else {
            try {
              tmClient.getSessionId();
            } catch (e) {}
            this.sendRequest();
          }
        }
      }
    }
  };

  /**
   * 请求RDAS服务
   * @param  {[type]}   servicePath [description]
   * @param  {[type]}   serviceArgs [description]
   * @param  {Function} cb          [description]
   * @return {[type]}               [description]
   */
  this.requestRDASService = function (servicePath, serviceArgs, cb) {
    var request = new ServiceRequest();
    if (cb) request.cb = cb;
    if (serviceArgs) {
      request.args = serviceArgs;
      tmClient.debug("发送请求：\r\n" + JSON.stringify(serviceArgs));
    }
    if (serviceArgs) {
      for (objId in serviceArgs) {
        var obj = serviceArgs[objId];
        if (!obj || typeof (obj) == "undefined" || typeof (obj) == "function") continue;
        if (typeof (obj) == "number" || typeof (obj) == "string" || typeof (obj) == "boolean") {
          request.add(objId, obj);
        } else if (obj.constructor == Array) {
          request.addObjects(objId, obj);
        } else if (obj instanceof Date) {
          request.add(objId, formatDate(obj, "yyyy-MM-dd hh:mm:ss"));
        } else {
          request.addObject(objId, obj);
        }
      }
    }
    request.notResponseOnError = false;
    request.send(servicePath, this.onRDASResponse);
  };

  /**
   * 处理RDAS响应
   * @param  {[type]} request  [description]
   * @param  {[type]} response [description]
   * @return {[type]}          [description]
   */
  this.onRDASResponse = function (request, response) {
    var res = response.getJsonObject();
    tmClient.debug("接收响应：\r\n" + JSON.stringify(res));
    if (request.cb) {
      if (typeof request.cb == "function") {
        request.cb(request, res);
      } else {
        eval(request.cb + "(request, res)");
      }
    }
  };

  /**
   * 发送请求
   * @return {[type]} [description]
   */
  this.sendRequest = function () {
    this.args.service = this.path;

    var httpRequest = getHttpRequest();
    try {
      var self = this;
      httpRequest.onreadystatechange = function () {
        if (httpRequest.readyState == 4) {
          if (httpRequest.status == 200) {
            // tmClient.debug("接收响应：\r\n" + httpRequest.responseText);
            var response = JSON.parse(httpRequest.responseText);
            if (response.code === 0) {
              if (self.onResponse) {
                if (self.srcElement) self.args.srcElement = self.srcElement;
                if (typeof self.onResponse == "function") {
                  self.onResponse(self.args, response);
                } else {
                  if (self.onResponse.indexOf(".") < 0 && self.onResponse.indexOf(" ") < 0 &&
                    self.onResponse.indexOf("=") < 0 && self.onResponse.indexOf("(") < 0 &&
                    self.onResponse.indexOf(")") < 0) {
                    eval(self.onResponse + "(self.args, response)");
                  } else {
                    eval(self.onResponse);
                  }
                }
              }
            } else {
              if (response.code == 501) {
                if (tmClient.clientOSType == "PC") top.location = "/";
                return;
              }
              self.showError(response.message);
            }
          } else if (httpRequest.status == 404) {
            self.showError("请求的服务不存在！");
          } else {
            if (httpRequest.status !== 0)
              self.showError("向服务器发送请求时发生意外错误！\r\n错误代码：" + httpRequest.status);
          }
        }
      };

      var serverPath = location.toString();
      serverPath = serverPath.substr(0, serverPath.indexOf("/", 8) + 1);
      httpRequest.open("POST", serverPath + "Service", true);
      httpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
      tmClient.debug("发送请求：\r\n" + JSON.stringify(this.args));
      httpRequest.send(JSON.stringify(this.args));
    } catch (e) {
      this.showError("向服务器发送请求时发生意外错误！\r\n错误描述：" + e.message);
    }
  };
}

var taskMsgDetailInfos = {};

/**
 * 详细信息控件
 */
function TaskMsgDetailInfo() {
  this.getDataService = null; //获得数据的服务
  this.dataMember = null; //表单对应的数据源对象名
  this.dataSource = null; //数据源对象
  this.onLoadData = null; //加载数据前执行的回调函数
  this.onBindData = null; //加载数据后执行的回调函数
  this.jQueryObj = null; //jQuery对象

  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 (this.getDataService) {
      var service = new TaskMsgService(this.getDataService);
      service.request(null, function (req, res) {
        that.dataBind(req, res);
      });
    }
  };

  /**
   * 绑定数据
   * @param  {[type]} req [description]
   * @param  {[type]} res [description]
   */
  this.dataBind = function (req, res) {
    if (this.onLoadData) eval(this.onLoadData + "(req, res)");
    if (this.dataMember && res[this.dataMember]) {
      this.dataSource = res[this.dataMember];
    }
    var strHtml = replaceDataField(this.dataSource, this.jQueryObj.get(0).innerHTML);
    strHtml = exeExpress(strHtml);
    this.jQueryObj.empty();
    this.jQueryObj.append(strHtml);
    this.jQueryObj.show();
    if (this.onBindData) eval(this.onBindData + "(req, res)");
  };
}

$(function () {
  $(".TaskMsgDetailInfo").each(function (index) {
    var info = new TaskMsgDetailInfo();
    if ($(this).attr("id")) {
      info.id = $(this).attr("id");
    } else {
      info.id = "TaskMsgDetailInfo_" + index;
    }
    taskMsgDetailInfos[info.id] = info;
    info.init($(this));
  });
  if($(".pageContainer").length>0) {
    $("body").css("background-color", "#f6f6f6");
  }
  if($(".openFormBottomBar").length>0) {
    if(!$(".btnCancel").attr("onclick")) {
      $(".btnCancel").click(function(){
        top.closeCurForm();
      });
    }
    if(!$(".btnSubmit").attr("onclick")) {
      $(".btnSubmit").click(function(){
        for(fid in taskMsgForms) {
          var form = taskMsgForms[fid];
          form.submit();
          return;
        }
      });
    }
  }
});

/**
 * 任信客户端
 */
function TaskMsgClient() {
  this.version = "0.2.1"; //版本号
  this.sessionId = null; //会话编号
  this.clientOSType = "PC"; //客户端类型

  /**
   * 获得会话编号
   * @return {[type]}              [description]
   */
  this.getSessionId = function () {
    //如果是在电脑客户端里打开，则直接从电脑客户端取会话信息
    if (!this.sessionId && top.global && top.global.tm) {
      this.sessionId = top.global.tm.sessionId;
      localStorage.setItem("TaskMsgSessionId", this.sessionId);
    }
    //如果URL里传了会话信息，则从URL里取
    if (!this.sessionId && getUrlArg("sessionId")) {
      this.sessionId = getUrlArg("sessionId");
      localStorage.setItem("TaskMsgSessionId", this.sessionId);
    }
    this.sessionId = localStorage.getItem("TaskMsgSessionId");
    return this.sessionId;
  };

  /**
   * 输出调试信息
   * @param  {[type]} msg [description]
   * @return {[type]}     [description]
   */
  this.debug = function (msg) {
    if (TaskMsgIsDebug) console.log(msg);
  };

  this.isSameServer = function () {
    var serverPathTop = top.location.toString();
    serverPathTop = serverPathTop.substr(0, serverPathTop.indexOf("/", 8) + 1);
    var serverPathCur = location.toString();
    serverPathCur = serverPathCur.substr(0, serverPathCur.indexOf("/", 8) + 1);
    return serverPathTop == serverPathCur;
  };

  /**
   * 打开弹出窗口
   * @param  {[type]} title      [description]
   * @param  {[type]} url        [description]
   * @param  {[type]} icon       [description]
   * @param  {[type]} width      [description]
   * @param  {[type]} height     [description]
   * @param  {[type]} srcElement [description]
   * @param  {[type]} opener     [description]
   * @return {[type]}            [description]
   */
  this.openDialog = function (title, url, icon, width, height, srcElement, opener) {
    if (this.isSameServer) {
      top.openForm(title, url, icon, width, height, srcElement, opener);
    } else {
      //
    }
  };

  /**
   * 关闭当前弹出窗口
   * @return {[type]} [description]
   */
  this.closeCurDialog = function () {
    if (this.isSameServer) {
      top.closeCurForm();
    } else {
      //
    }
  };

  /**
   * 打开选项页
   * @param  {[type]} title [description]
   * @param  {[type]} url   [description]
   * @return {[type]}       [description]
   */
  this.openTabPage = function (title, url) {
    if (this.isSameServer) {
      top.openTabPage(title, url);
    } else {
      //
    }
  };

  /**
   * 关闭当前选项页
   * @return {[type]} [description]
   */
  this.closeCurTabPage = function () {
    if (this.isSameServer) {
      top.closeCurTabPage();
    } else {
      //
    }
  };
}

/**
 * 任信客户端浏览器扩展对象
 * @type {TaskMsgClient}
 */
var tmClient = new TaskMsgClient();