// common javascript, 继承自prototype, prototype真的很牛:)
// 以下所有函数同时兼容firefox
// author

/////////////////////////////////扩展一些原型函数/////////////////////////////////

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

/////////////////////////////////定义一些系统变量/////////////////////////////////

var ContextPath;
var SkinPath;
var ResourcePath;

//////////////////////////////////一些系统级的函数////////////////////////////////

var IsIE, IsMozilla, IsOpera;
if (navigator.appName == "Microsoft Internet Explorer") {
  IsIE = true;
}
else if (navigator.appName == "Netscape") {
  IsMozilla = true;
}
else if (IsOpera == "Opera") {
  IsOpera = true;
}

// 更改样式
StyleInit = function(pObj) {
  pObj = $(pObj);
  if (pObj == null) {
    pObj = document;
  }

  var objs = pObj.getElementsByTagName("input");
  var styleClass = (IsIE) ? "className" : "class";
  for (var i = 0; i < objs.length; i++) {
    setInputAttr(objs[i], styleClass);
  }

  objs = pObj.getElementsByTagName("textarea");
  for (var i = 0; i < objs.length; i++) {
    setElementAttr(objs[i], styleClass, "textarea");
  }

  objs = pObj.getElementsByTagName("select");
  for (var i = 0; i < objs.length; i++) {
    setElementAttr(objs[i], styleClass, "select");
  }

  function setElementAttr(obj, clazz, value) {
    var tagValue = obj.getAttribute(clazz);
    var bb = tagValue == null || tagValue == "";
    if (bb) {
      obj.setAttribute(clazz, value);
    }
  }

  function setInputAttr(obj, clazz) {
    var tagValue = obj.getAttribute(clazz);
    var bb = tagValue == null || tagValue == "";
    if (bb) {
      if (obj.type == "text" ||
          obj.type == "password" || obj.type == "file") {
        obj.setAttribute(clazz, "input");
      }
      else if (obj.type == "button" ||
          obj.type == "submit" || obj.type == "reset") {
        obj.setAttribute(clazz, "button");
        obj.onmouseover = over;
        obj.onmouseout = out;
      }
    }
  }

  function over() {this.className = 'buttonover';}
  function out() {this.className = 'button';}
}

InitTriggerImg = function(id) {
  if (!id) {
    return;
  }
  var Imgs = $(id);
  if (Imgs.length) {
    for (var i = 0; i < Imgs.length; i++) {
      Imgs[i].onmouseover = function() {over(Imgs[i]);};
      Imgs[i].onmouseout = function() {out(Imgs[i]);};
    }
  }
  else {
    Imgs.onmouseover = function() {over(Imgs);};
    Imgs.onmouseout = function() {out(Imgs);};
  }

  function over(Img) {Img.src = SkinPath + '/images/select_btn_over.gif';}
  function out(Img) {Img.src = SkinPath + '/images/select_btn.gif'; }
}

// 初始化导航条的显示开关按钮
InitHideBar = function(NavTd, Img) {
  if (!NavTd || !Img) {
    return;
  }
  var display = readCookie("_NavDisplay");
  if (NavTd.length) {
    for (var i = 0; i < NavTd.length; i++) {
      if (NavTd[i]) {
        NavTd[i].style.display = display;
      }
    }
  }
  else {
    NavTd.style.display = display;
  }

  if (display != "none") {
    Img.src = SkinPath + "/images/close_menu.gif";
    Img.alt = "关闭导航";
  }
  else {
    Img.src = SkinPath + "/images/open_menu.gif";
    Img.alt = "展开导航";
  }
}

HideBarClick = function(NavTd, Img, Hidden) {
  if (Hidden) {
    hide();
  }
  else {
    var display = NavTd.length ? NavTd[0].style.display : NavTd.style.display;
    if (display != "none") {
      hide();
    }
    else {
      open();
    }
  }

  function hide() {
    if (NavTd.length) {
      for (var i = 0; i < NavTd.length; i++) {
        NavTd[i].style.display = "none";
      }
    }
    else {
      NavTd.style.display = "none";
    }
    Img.src = SkinPath + "/images/open_menu.gif";
    Img.alt = "展开导航";
    writeCookie("_NavDisplay", "none");
  }

  function open() {
    if (NavTd.length) {
      for (var i = 0; i < NavTd.length; i++) {
        NavTd[i].style.display = "";
      }
    }
    else {
      NavTd.style.display = "";
    }
    Img.src = SkinPath + "/images/close_menu.gif";
    Img.alt = "关闭导航";
    writeCookie("_NavDisplay", "");
  }
}

PlusBtnInit = function(ImgObj, TargetId, Opened, ImgName) {
  ImgObj = $(ImgObj);
  if (!ImgObj) {
    return;
  }
  if (!ImgName) {
    ImgName = "default";
  }

  // 从cookie里读取
  var _Opened = readCookie("__plusid_" + ImgObj.id);
  if (_Opened == '_plus') {
    click(true);
  }
  else if (_Opened == '_minus') {
    click(false);
  }
  else {
    if (Opened) click(true);
    else click(false);
  }

  Element.setStyle(ImgObj, {cursor : 'pointer'});
  if (!ImgObj.alt) {
    ImgObj.alt = '详细';
  }

  function click(plus) {
    var Tr = $(TargetId);
    if (!Tr) {
      return;
    }
    if (plus) {
      ImgObj.src = SkinPath + "/images/" + ImgName + "_minus.gif";
      if (Tr.length)
        for (var i = 0; i < Tr.length; i++)
          Element.show(Tr[i]);
      else
        Element.show(Tr);
    }
    else {
      ImgObj.src = SkinPath + "/images/" + ImgName + "_plus.gif";
      if (Tr.length)
        for (var i = 0; i < Tr.length; i++)
          Element.hide(Tr[i]);
      else
        Element.hide(Tr);
    }
  };

  ImgObj.onclick = function() {
    var plus = ImgObj.src.indexOf("_plus") != -1;
    click(plus);
    if (plus) {
      writeCookie("__plusid_" + ImgObj.id, "_plus");
    }
    else {
      writeCookie("__plusid_" + ImgObj.id, "_minus");
    }
  };
}

// 这个函数是在表单开发中, 通过这个链接直接转向普通的WebForm
LinktoWebForm = function(name) {
  window.location =
    ContextPath + "/webForm.do?" +
    "__action=load&__form=" + name;
}

// 打开一个流程的svg监控窗口
OpenSvgProcessMonitor = function(attri, id) {
  if (attri == null) {
    attri = "width=720,height=600,scrollbars=yes,resizable=yes";
  }
  var Page = '/framework/workflow/svg_monitor_open_window.jsp&id=' + id;
  OpenWindow(Page, "SvgProcessMonitor", attri, true);
}

// 打开一个窗体
OpenWindow = function(page, name, attri, center, params) {
  var url = ContextPath + '/index.do?__action=open_window&page=' + page;
  if (params && params != '') {
    url += "&" + params;
  }
  if (center) {
    var array = attri.split(',');
    var width = 280, height = 400;
    for (i = 0; i < array.length; i++) {
      value = array[i].split('=');
      if (value[0] == 'width') width = value[1];
      if (value[0] == 'height') height = value[1];
    }

    var LeftPos = (screen.width) ? (screen.width - width) / 2 : 0;
    var TopPos = (screen.height) ? (screen.height - height) / 2 : 0;
    attri = "";
    for (i = 0; i < array.length; i++) {
      value = array[i].split('=');
      if (value[0] == "left") {
        attri += "," + value[0] + "=" + LeftPos;
      }
      else if (value[0] == "top") {
        attri += "," + value[0] + "=" + TopPos;
      }
      else if (value[0] == "width") {
        attri += "," + value[0] + "=" + width;
      }
      else if (value[0] == "height") {
        attri += "," + value[0] + "=" + height;
      }
      else {
        attri += "," + array[i];
      }
    }
    if (attri.indexOf("left") < 0) {
      attri += ",left=" + LeftPos;
    }
    if (attri.indexOf("top") < 0) {
      attri += ",top=" + TopPos;
    }
    attri = attri.substr(1);
  }
  var win = window.open(url, name, attri);
  if (win) win.focus();
  return win;
}

IntChecked = function(Input) {
  var Obj = $(Input);
  if (Obj) {
    var IntReg = new RegExp(/^[-\+]?\d+$/);
    var value = Obj.value;
    if (value.trim() == '' || !IntReg.test(value)) {
      alert('必须是一个整形！');Obj.focus();
      return false;
    }
    else {
      return true;
    }
  }
  return false;
}

///////////////////////////////////通用字段查询模块///////////////////////////////

FSearchPanel = function(options) {
  this.options = options;
};

FSearchPanel.prototype = {
  idSearchEx : 'idSearchEx',
  srchIdx : 0,
  cObj : null,

  add : function() {
    if (!this._validate()) {
      return;
    }
    if (!this.cObj) {
      this.cObj = $('_SearchEx');
    }

    var _Span = document.createElement("SPAN");
    this.cObj.appendChild(_Span);
    _Span.id = "_SPAN_srch" + this.srchIdx;

    var AIndex = '' + this.srchIdx;
    var _F0_idSearchEx = '_f0_' + this.idSearchEx + AIndex;
    var _F1_idSearchEx = '_f1_' + this.idSearchEx + AIndex;
    var _F2_idSearchEx = '_f2_' + this.idSearchEx + AIndex;
    var _F3_idSearchEx = '_f3_' + this.idSearchEx + AIndex;
    var _Span_idSearchEx = '_span_' + this.idSearchEx + AIndex;

    var innerHTML = "";
    innerHTML += '<input type="hidden" id="' + _F0_idSearchEx + '">';
    innerHTML += '<select id="' + _F1_idSearchEx + '" style="width:120px;" class="select" onchange="javascript:F1Change(\'' + this.srchIdx + '\');">';

    // this.options.fields 字段二维数组
    // 分别为字段名、显示名、类型(string,int,date)
    if (this.options.fields) {
      var fields = this.options.fields;
      if (fields.length) {
        innerHTML += '<option value=""></option>';
        for (var i = 0; i < fields.length; i++) {
          innerHTML += '<option value="' + fields[i][0] + '">' + fields[i][1] + '</option>';
        }
      }
    }
    innerHTML += '</select>&nbsp;';
    innerHTML += '<select id="' + _F2_idSearchEx + '" style="width:72px;" class="select">';
    innerHTML += '</select>&nbsp;';
    innerHTML += '<input id="' + _F3_idSearchEx + '" type="text" class="select">&nbsp;';
    innerHTML += '<a id="' + _Span_idSearchEx + '"></a>&nbsp;';
    innerHTML += '<img border="0" align="absmiddle" src="' + ResourcePath + '/images/_delete.gif" style="cursor:pointer;" onclick="javascript:DoDelete(\'' + this.srchIdx + '\');"/>';
    innerHTML += '<br>';
    _Span.innerHTML = innerHTML;

    while(true) {
      var PSpan = _Span.previousSibling;
      if (!PSpan) {
        break;
      }
      // 前一个SPAN节点
      if (PSpan.tagName == "SPAN") {
        var PIndex = PSpan.id.substring("_SPAN_srch".length);
        var ASpan = $('_span_' + this.idSearchEx + PIndex);
        if (ASpan) {
          var _F4_idSearchEx = '_f4_' + this.idSearchEx + PIndex;
          innerHTML = '<select id="' + _F4_idSearchEx + '" style="width:50px;" class="select">';
          innerHTML += '<option value="and">和</option>';
          innerHTML += '<option value="or">或</option>';
          innerHTML += '</select>';
          ASpan.innerHTML = innerHTML;
        }
        break;
      }
    }

    this.srchIdx += 1;

    F1Change = (function(Index) {
      this._change(Index);
    }).bind(this);

    DoDelete = (function(Index) {
      this._delete(Index);
    }).bind(this);
  },

  _change : function(Index) {
    var F0 = $('_f0_' + this.idSearchEx + Index);
    var F1 = $('_f1_' + this.idSearchEx + Index);
    var F2 = $('_f2_' + this.idSearchEx + Index);
    var F3 = $('_f3_' + this.idSearchEx + Index);

    F2.options.length = 0;
    if (F1.selectedIndex < 1) {
      return;
    }

    var Type = this.options.fields[F1.selectedIndex - 1][2];
    F0.value = Type;
    if (Type == 'string') {
      F2.options.add(new Option("包含", "like"));
      F2.options.add(new Option("不包含", "not like"));
      F2.options.add(new Option("等于", "="));
      F2.options.add(new Option("不等于", "<>"));
    }
    else if (Type == 'int' || Type == 'date') {
      F2.options.add(new Option("等于", "="));
      F2.options.add(new Option("不等于", "<>"));
      F2.options.add(new Option("大于", ">"));
      F2.options.add(new Option("小于", "<"));
      F2.options.add(new Option("大于等于", ">="));
      F2.options.add(new Option("小于等于", "<="));
    }

    F3.value = '';
    F3.onclick = null;
    if (Type == 'date') {
      F3.readOnly = true;
      Calendar.setup({
        inputField  : F3.id,
        button      : F3.id,
        ifFormat    : "%Y-%m-%d",
        showsTime   : false
      });
    }
    else {
      F3.readOnly = false;
      if (Type == 'string') {
        var ext = this.options.fields[F1.selectedIndex - 1][3];
        if (!ext) {
          return;
        } // 分析后缀, 如果是字典, 其格式为dict{oa.common;wenzhong}
        var jj = ext.indexOf('dict{');
        if (jj != -1) {
          jj = jj + 'dict{'.length;
          var ii = ext.indexOf('}');
          var dict = ii == -1 ? ext.substring(jj) : ext.substring(jj, ii);
          var dicts = dict.split(';');
          F3.onclick = function() {
            F3.options = null; // 清除缓存
            TriggerDictionayPopup(F3, {
              caption : ' 字典选取',
              dict : dicts[0],
              catalog : dicts[1],
              textId : F3.id
            });
          }
        }
      }
    }
  },

  _validate : function() {
    var _Spans = document.getElementsByTagName("SPAN");
    for (var i = 0; i < _Spans.length; i++) {
      var PIndex = _Spans[i].id.substring("_SPAN_srch".length);
      var F1 = $('_f1_' + this.idSearchEx + PIndex);
      if (F1.selectedIndex < 1) {
        alert("条件" + (i + 1) + "的字段没有选择！");
        F1.focus();
        return false;
      }
      var F3 = $('_f3_' + this.idSearchEx + PIndex);
      var F0 = $('_f0_' + this.idSearchEx + PIndex);
      if (F0.value == 'int') {
        var IntReg = new RegExp(/^[-\+]?\d+$/);
        if (!IntReg.test(F3.value)) {
          alert("条件" + (i + 1) + "的值必须是整形！");
          F3.focus();
          return false;
        }
      }
      else if (F3.value == '') {
        alert("条件" + (i + 1) + "的值不能为空！");
        F3.focus();
        return false;
      }
    }
    return true;
  },

  _delete : function(Index) {
    var _Spans = document.getElementsByTagName("SPAN");
    if (_Spans[_Spans.length - 1].id == "_SPAN_srch" + Index) {
      if (_Spans.length - 2 >= 0) {
        var id = _Spans[_Spans.length - 2].id;
        var PIndex = id.substring("_SPAN_srch".length);
        var ASpan = $('_span_' + this.idSearchEx + PIndex);
        if (ASpan) {
          ASpan.innerHTML = '';
        }
      }
    }
    Element.remove("_SPAN_srch" + Index);
  },

  retvalue : function() {
    var _Spans = document.getElementsByTagName("SPAN");
    ret = '';
    var dot = ';';
    var csplit = '@';
    for (var i = 0; i < _Spans.length; i++) {
      var PIndex = _Spans[i].id.substring("_SPAN_srch".length);
      var F0 = $('_f0_' + this.idSearchEx + PIndex); // type
      var F1 = $('_f1_' + this.idSearchEx + PIndex); // field
      var F2 = $('_f2_' + this.idSearchEx + PIndex); // ope
      var F3 = $('_f3_' + this.idSearchEx + PIndex); // value
      var F4 = $('_f4_' + this.idSearchEx + PIndex); // join
      ret += csplit + F0.value + dot + F1.value + dot +
         F2.value + dot + F3.value;
      if (F4) {
        ret += dot + F4.value;
      }
    }
    return encodeURIComponent(ret.substring(csplit.length));
  }
};

///////////////////////////////////文件上传模块//////////////////////////////////

FileUpload = function() {};

FileUpload.prototype = {
  attaTopicId   : 'Topic_idAttachFile',
  attaFileId  : 'idAttachFile',

  spanObj       : null,
  attaIdx       : 0,
  topicSize     : 200,
  captionHas    : true,
  topicHas      : false,

  Add : function() {
    if (!this.spanObj) {
      this.spanObj = $('idFileSpan');
    }
    if(this.AddFile()) {
      this.attaIdx++;
    }
  },

  AddFile : function() {
    var eles = document.getElementsByTagName("input");
    if (!eles.length) {
      return false;
    }
    for (var i = 0; i < eles.length; i++) {
      if (eles[i].type == 'file' &&
          eles[i].id.indexOf('idAttachFile') != -1 && !eles[i].value) {
        alert('没有选择附件内容！');
        eles[i].focus();
        return false;
      }
    }

    var _Span = document.createElement("SPAN");
    this.spanObj.appendChild(_Span);
    _Span.id = "_SPAN_Attach" + this.attaIdx;

    var AIndex = '' + this.attaIdx;

    var innerHTML = "";
    if (this.topicHas) {
      if (this.captionHas) {
        innerHTML += "<span style='width:50px;'>题名 " + AIndex + ". </span>";
      }
      var uid = this.attaTopicId + AIndex;
      innerHTML += "<input type='text' class='input' id ='" + uid + "' name='" + uid + "' style='width:" + this.topicSize + "px;'>";
      innerHTML += "<span style='width:4px;'></span>";
    }

    var uid = this.attaFileId + AIndex;
    innerHTML += "<input type='file' class='input' id='" + uid + "' name='" + uid + "' onchange=\"javascript:DoAttachChange(this, '" + AIndex + "')\">";
    innerHTML += "<span style='width:2px;'></span>";
    innerHTML += "<input type='button' class='input' value='删 除' onclick=\"javascript:DoAttachDelete('" + AIndex + "');\">";
    innerHTML += "<br>";
    _Span.innerHTML = innerHTML;

    DoAttachDelete = (function(Index) {
      this.DelFile(Index);
    }).bind(this);

    DoAttachChange = (function(FileObj, Index) {
      this.ChangeFile(FileObj, Index);
    }).bind(this);

    var TopicObj = $(this.attaTopicId + AIndex);
    if (TopicObj) {
      TopicObj.focus();
    }
    return true;
  },

  ChangeFile : function(FileObj, Index) {
    var TopicObj = $(this.attaTopicId + Index);
    if (!TopicObj) {
      return;
    }
    if (TopicObj.value.length > 0) {
      return;
    }
    var Pos = FileObj.value.lastIndexOf('\\');
    if (Pos == -1) {
      Pos = FileObj.value.lastIndexOf('/');
    }
    if (Pos > -1) {
      TopicObj.value = FileObj.value.substring(Pos + 1);
      TopicObj.select();
    }
  },

  DelFile : function(Index) {
    var _Span = $("_SPAN_Attach" + Index);
    if (!_Span) {
      return;
    }

    var TopicObj = $(this.attaTopicId + Index);
    var FileObj = $(this.attaFileId + Index);
    if ((TopicObj && TopicObj.value.length > 0) || FileObj.value.length > 0) {
      if (!confirm('您确实想删除附件吗？')) {
        return;
      }
    }
    this.spanObj.removeChild(_Span);
  }
}

//////////////////////////////////一些通用的函数//////////////////////////////////

readCookie = function(name) {
  var cookieValue = "";
  var search = name + "=";
  if(document.cookie.length > 0) {
    offset = document.cookie.indexOf(search);
    if (offset != -1) {
      offset += search.length;
      end = document.cookie.indexOf(";", offset);
      if (end == -1) {
        end = document.cookie.length;
      }
      cookieValue = unescape(document.cookie.substring(offset, end))
    }
  }
  return cookieValue;
}

writeCookie = function(name, value, hours) {
  var expire = "";
  if(hours != null) {
    expire = new Date((new Date()).getTime() + hours * 3600000);
    expire = "; expires=" + expire.toGMTString();
  }
  document.cookie = name + "=" + escape(value) + expire;
}

// 这个函数的是根据内容动态调整IFRAME的高度
// 一般写在body标签的onload事件中
DynIFrameSize = function(FrameID) {
  var pTar = document.getElementById(FrameID);
  if (pTar) {
    var Height = -1;
    if (pTar.contentDocument && pTar.contentDocument.body.offsetHeight) {
      Height = pTar.contentDocument.body.offsetHeight;
    }
    else if (pTar.Document && pTar.Document.body.scrollHeight) {
      Height = pTar.Document.body.scrollHeight;
    }
    if (Height < 480) {
      Height = 480;
    }
    pTar.height = Height;
  }
}

// select相关的一些操作
ListSelectItems = function(From, To, Has) {
  From = $(From);
  To = $(To);
  var Index0 = From.selectedIndex;
  var Index;
  while ((Index = From.selectedIndex) != -1) {
    var MoveObj = From.options[Index];
    if (Has) { // 检测目标中是否有
      var _Has = false;
      for (var i = 0; i < To.options.length; i++) {
        if (To.options[i].value == MoveObj.value) {
          _Has = true;
          alert("“" + MoveObj.value + '”已经存在！');
          break;
        }
      }
      if (_Has) {
        From.options[Index].selected = false;
        continue;
      }
    }
    var Opt = new Option(MoveObj.text, MoveObj.value);
    To.options[To.length] = Opt;
    From.options[Index] = null;
  }

  if (Index0 > -1) {
    if (Index0 < From.options.length) {
      From.options[Index0].selected = true;
    }
    else if (From.options.length > 0) {
      From.options[From.options.length - 1].selected = true;
    }
  }
}

ListSelectAllItems = function(From, To) {
  From = $(From);
  for (var i = 0; i < From.options.length; i++) {
    From.options[i].selected = true;
  }
  ListSelectItems(From, To);
}

InitSelectValue = function(Id, Value) {
  if (!Value) {
    return;
  }
  var Obj = $(Id);
  if (!Obj || !Obj.options) {
    return;
  }
  for (i = 0; i < Obj.options.length; i++) {
    if (Obj.options[i].value == Value) {
      Obj.options[i].selected = true;
      break;
    }
  }
}

OptionsMoveUp = function(Select) {
  var Obj = $(Select);
  var Index = Obj.selectedIndex;
  var Options = Obj.options;
  var Opt0, Opt1;
  if (Index > 0) {
    Opt0 = new Option(Options[Index].text, Options[Index].value);
    Opt1 = new Option(Options[Index - 1].text, Options[Index - 1].value);
    Options[Index - 1] = Opt0;
    Options[Index] = Opt1;
    Options[Index - 1].selected = true;
  }
}

OptionsMoveDown = function(Select) {
  var Obj = $(Select);
  var Index = Obj.selectedIndex;
  var Options = Obj.options;
  var Opt0, Opt1;
  if (Index < Options.length - 1) {
    Opt0 = new Option(Options[Index].text, Options[Index].value);
    Opt1 = new Option(Options[Index + 1].text, Options[Index + 1].value);
    Options[Index + 1] = Opt0;
    Options[Index] = Opt1;
    Options[Index + 1].selected = true;
  }
}

///////////////////////////////一些关于界面的函数/////////////////////////////////

InitShim = function(_Div) {
  // 加一个垫片, 预防被select或iframe遮盖
  var Shim =  $('Shim.' + _Div.id);
  if (Shim == null) {
    if (!IsIE) {
      Shim = document.createElement("iframe");
      Shim.setAttribute("id", "Shim." + _Div.id);
      Shim.setAttribute("scrolling", "no");
      Shim.setAttribute("frameborder", "0");
      Shim.style.position = "absolute";
      Shim.style.top = 0;
      Shim.style.left = 0;
      Shim.style.display = "none";
      _Div.offsetParent.appendChild(Shim);
    }
    else {
      Shim = document.createElement(
        "<iframe scrolling='no' frameborder='0'"+
        "style='position:absolute; top:0px;"+
        "left:0px; display:none' src='" + ContextPath + "/index.do?__action=blank_html'></iframe>");
      Shim.id = "Shim." + _Div.id;
      document.body.appendChild(Shim);
    }
  }

  Shim.style.width = _Div.offsetWidth;
  Shim.style.height = _Div.offsetHeight;
  Shim.style.top = _Div.style.top;
  Shim.style.left = _Div.style.left;
  Shim.style.zIndex = _Div.style.zIndex - 1;
  Shim.style.position = "absolute";
  Shim.style.display = "block";
  return Shim;
}

addEvent = function(el, evname, func) {
  if (el.attachEvent) {
    el.attachEvent("on" + evname, func);
  }
  else if (el.addEventListener) {
    el.addEventListener(evname, func, true);
  }
  else {
    el["on" + evname] = func;
  }
};

removeEvent = function(el, evname, func) {
  if (el.detachEvent) {
    el.detachEvent("on" + evname, func);
  }
  else if (el.removeEventListener) {
    el.removeEventListener(evname, func, true);
  }
  else {
    el["on" + evname] = null;
  }
};

// 初始化一个可以移动的div层, 参考prototype的Event对象
InitMoveEvent = function(div) {
  var DivObj = $(div);
  if (!DivObj) {
    return;
  }

  var DownFlag = false;
  var dragClickX = 0;
  var dragClickY = 0;

  DivObj.mmove = function(e) {
    if (!e) {
      e = event;
    }
    if (DownFlag) {
    try {
      DivObj.style.left = (Event.pointerX(e) - dragClickX) + "px";
      DivObj.style.top = (Event.pointerY(e) - dragClickY) + "px";
    }
    catch(e) {alert(e);}
      var Shim = $('Shim.' + DivObj.id);
      if (Shim != null) {
        Shim.style.left = DivObj.style.left;
        Shim.style.top = DivObj.style.top;
      }
    }
    Event.stop(e);
  };

  var Hides = new Array();

  DivObj.mup = function(e) {
    if (IsIE) {
//      for (var i = 0; i < Hides.length; i++) {
//        Element.show(Hides[i]);
//      }
//      Hides.length = 0;
    }

    DownFlag = false;
    removeEvent(document, "mousemove", DivObj.mmove);
    removeEvent(document, "mouseup", DivObj.mup);
    Event.stop(e);
  };

  addEvent(DivObj, "mousedown", function(e) {
    if (!e) {
      e = event;
    }

    var Target = Event.element(e);
    if (Target) {
      var tn = Target.tagName.toLowerCase();
      if (tn == "input" || tn == "select" ||
         tn == "textarea" || tn == "img") {
        return;
      }
    }

    if (Event.findElement(e, "DIV").id != DivObj.id) {
      return;
    }

    // 在拖动的时候发现含有textarea元素, 就会造成ie的死机
    // 不知道是什么原因引起的, firefox下没有问题
    // 没有好的办法, 暂时把textarea隐藏
    if (IsIE) {
//      var tarea = DivObj.getElementsByTagName("textarea");
//      if (tarea.length) {
//        for (var i = 0; i < tarea.length; i++) {
//          Element.hide(tarea[i]);
//          Hides.push(tarea[i]);
//        }
//      }
    }

    DownFlag = true;
    var r = Position.cumulativeOffset(DivObj); // 偏移位
    dragClickX = Event.pointerX(e) - r[0];
    dragClickY = Event.pointerY(e) - r[1];

    addEvent(document, "mousemove", DivObj.mmove);
    addEvent(document, "mouseup", DivObj.mup);

    Event.stop(e);
  });
}

InitResizeEvent = function(eventImg, targetObj) {
  var clickX = 0;
  var clickY = 0;
  var DownFlag = false;

  eventImg.mmove = function(e) {
    if (!e) {
      e = event;
    }
    if (DownFlag) {
      var x = Event.pointerX(e);
      var y = Event.pointerY(e);
      var deltaX = x - clickX;
      var deltaY = y - clickY;
      clickX = x;
      clickY = y;
      targetObj.style.width = (targetObj.offsetWidth + deltaX) + "px";
      targetObj.style.height = (targetObj.offsetHeight + deltaY) + "px";
      var Shim = $('Shim.' + targetObj.id);
      if (Shim != null) {
        Shim.style.width = targetObj.style.width;
        Shim.style.height = targetObj.style.height;
      }
    }
    Event.stop(e);
  };

  eventImg.mup = function(e) {
    DownFlag = false;
    removeEvent(document, "mousemove", eventImg.mmove);
    removeEvent(document, "mouseup", eventImg.mup);
    Event.stop(e);
  };

  addEvent(eventImg, "mousedown", function(e) {
    if (!e) {
      e = event;
    }
    if (Event.findElement(e, "IMG").id != eventImg.id) {
      return;
    }

    DownFlag = true;

    clickX = Event.pointerX(e);
    clickY = Event.pointerY(e);

    addEvent(document, "mousemove", eventImg.mmove);
    addEvent(document, "mouseup", eventImg.mup);

    Event.stop(e);
  });
};

// 显示一个消息窗口, 参数表示被加载的内容jsp文件的路径
// align: left, center, right 表明对齐方式
// 如果设置了align的值, left, top代表不同的意思
// align = center, left, top没有意义
// align = left, left表示左边边距
// align = align, left表示右边边距
// closeEvent: 关闭事件, 返回值是true和false, 代表能否被关闭
WindowWidget = function(name, options) {
  if (!name) {
    return;
  }
  this.name = name;
  if (!options) {
    return;
  }
  this.options = options;

  this.widget = $("Widget." + name);
  if (this.widget) {
    return;
  }

  this.widget = document.createElement("DIV");
  document.body.appendChild(this.widget);
  this.widget.window = this;
  this.widget.id = "Widget." + this.name;
  this.widget.jspPage = this.options.jspPage;
  this.widget.className = "msg-info-div";
  this.widget.style.position = "absolute";
  this.widget.style.background = "white";
  this.widget.style.zIndex = 1001;

  this.widget.closeEvent = this.options.closeEvent;

  this.options.title = this.options.title || '无标题';
  var content = this.options.content || '无内容';

  var innerHTML = "";
  innerHTML += "<table width='100%' height='100%' border='0' cellpadding='0' cellspacing='0'>";
  if (!this.options.titleHidden) {
    innerHTML +=   "<tr>";
    innerHTML +=     "<td height='21' align='left'>";
    innerHTML +=       "<table width='100%' height='100%' border='0' cellpadding='0' cellspacing='0'>";
    innerHTML +=         "<tr>";
    innerHTML +=           "<td background='" + SkinPath + "/images/title.bg.gif' style='padding-left:2;'>" + this.options.title + "</td>";
    innerHTML +=           "<td background='" + SkinPath + "/images/title.bg.gif' align='right' valign='middle'>";
    innerHTML +=             "<img id='Close." + this.name + "' border='0' alt='关闭' align='absmiddle' src='" + SkinPath + "/images/close.gif'/ style='cursor:pointer;'>";
    innerHTML +=           "</td>";
    innerHTML +=           "<td background='" + SkinPath + "/images/title.bg.gif' width='3'></td>";
    innerHTML +=         "</tr>";
    innerHTML +=       "</table>";
    innerHTML +=     "</td>";
    innerHTML +=   "</tr>";
  }
  innerHTML +=   "<tr>";
  innerHTML +=     "<td>";
  innerHTML +=       "<div id='Content." + this.name + "' style='width:100%;height:100%;border-left:0px;border-right:0px;border-bottom:0px;'>";
  innerHTML +=          content;
  innerHTML +=       "</div>";
  innerHTML +=     "</td>";
  innerHTML +=   "</tr>";
  if (!this.options.resizeDisabled) {
    innerHTML +=   "<tr>";
    innerHTML +=     "<td height='14'>";
    innerHTML +=       "<div style='width:100%;height:100%'>";
    innerHTML +=         "<img id='Resize." + this.name +"' alt='拉伸窗体' align='right' src='" + SkinPath + "/images/resize.gif' style='cursor:se-resize;' />";
    innerHTML +=       "</div>";
    innerHTML +=     "</td>";
    innerHTML +=   "</tr>";
  }
  innerHTML += "</table>";
  this.widget.innerHTML = innerHTML;

  InitMoveEvent(this.widget); // 初始化div的鼠标事件
  if (!this.options.resizeDisabled) {
    var resizeImg = $('Resize.' + this.name);
    if (resizeImg) {
      InitResizeEvent(resizeImg, this.widget);
    }
  }

  var closeImg = $('Close.' + this.name);
  if (closeImg) {
    closeImg.onmouseover = function() {
      closeImg.src = SkinPath + "/images/close_over.gif";
    };
    closeImg.onmouseout = function() {
      closeImg.src = SkinPath + "/images/close.gif";
    };
    closeImg.onclick = (function() {
      this.hide();
    }).bind(this);
  }
};

GetWindowWidget = function(name, options) {
  var Widget = $("Widget." + name);
  if (!Widget) {
    Widget = (new WindowWidget(name, options)).widget;
  }
  return (Widget) ? Widget.window : null;
}

WindowWidget.prototype = {
  show : function() {
    if (!this.widget) {
      return;
    }

    this.widget.style.width = (this.options.width || 420) + "px";
    this.widget.style.height = (this.options.height || 240) + "px";
    if (this.options.align == "center") { // 居中对齐
      this.widget.style.left = (document.body.scrollLeft +
        (document.body.offsetWidth - this.widget.offsetWidth) / 2) + "px";
      this.widget.style.top = (this.options.top || (document.body.scrollTop +
        (document.body.offsetHeight - this.widget.offsetHeight) / 2)) + "px";
    }
    else if (this.options.align == "right") { // 右对齐
      this.widget.style.left = (document.body.scrollLeft +
        document.body.offsetWidth - this.widget.offsetWidth -
        (this.options.left || 5) - 19) + "px";
      this.widget.style.top = (this.options.top || 5) + "px";
    }
    else {
      this.widget.style.left =  (this.options.left || 5) + "px";
      this.widget.style.top = (this.options.top || 5) + "px";
    }
    InitShim(this.widget);

    setTimeout((function() {
      if (this.options.mode) {
        CreateDisabledDiv(this.widget.style.zIndex - 1);
      }
      this.widget.style.visibility = "visible";
      this.loading();
    }).bind(this), 10); // 异步装载页面
  },

  hide : function() {
    if (!this.widget) {
      return;
    }

    // 触发close事件
    if (this.widget.closeEvent) {
      if (!(this.widget.closeEvent || Prototype.emptyFunction)()) {
        return;
      }
    }

    var DisabledDiv = $('DisabledDivID');
    if (DisabledDiv) {
      DisabledDiv.style.visibility = "hidden";
    }

    this.widget.style.visibility = "hidden";
    var Shim = $('Shim.' + this.widget.id);
    if (Shim != null) {
      Shim.style.display = "none";
    }
  },

  loading : function() {
    if (!this.options.jspPage || !this.name) {
      return;
    }
    if (this.options.content || this.widget.style.visibility == "hidden") {
      return;
    }

    var Content = $("Content." + this.name);
    if (!Content) {
      return;
    }

    var innerHTML = "正在获取数据...";
    innerHTML += "<img border='0' align='absmiddle' src='" + ResourcePath + "/images/waiting.gif'/>";
    Content.innerHTML = innerHTML;

    var Params = "__action=load_assistant&page=" + this.options.jspPage +
      "&name=" + this.name;
    if (this.options.params && this.options.params != '') {
      Params += "&" + this.options.params;
    }
    new AjaxInvoker(
      ContextPath + "/index.do",
      {
        method: 'post',
        requestHeaders: ['uri-encoding', 'utf-8'],
        postBody: Params,
        asynchronous: true,
        evalScripts: true
      },
      Content
    );
  }
};

// 显示一个等待的层
// 这个函数一般用在post页面中, 所以直接创建了对象
ShowWaiting = function(msg) {
//  if (IsIE && document.readyState != "complete") {
//    return;
//  }

  var ShowWaitingDiv = $("MessageDivID");
  if (ShowWaitingDiv == null) {
    ShowWaitingDiv = document.createElement("DIV");
    document.body.appendChild(ShowWaitingDiv);
    ShowWaitingDiv.id = "MessageDivID";
    ShowWaitingDiv.className = "msg-info-div";
    ShowWaitingDiv.style.position = "absolute";
    ShowWaitingDiv.style.zIndex = 5000;
    ShowWaitingDiv.style.width = 451;
    ShowWaitingDiv.style.height = 120;
    var innerHTML = "";
    innerHTML += "<table width='100%' height='100%' border='0' cellpadding='0' cellspacing='0'>";
    innerHTML +=   "<tr>";
    innerHTML +=     "<td background='" + SkinPath + "/images/msg_info_div.gif'>";
    innerHTML +=       "<table width='100%' border='0' cellspacing='0' cellpadding='0'>";
    innerHTML +=         "<tr><td colspan='4' height='6'></td></tr>";
    innerHTML +=         "<tr>";
    innerHTML +=           "<td width='4'></td>";
    innerHTML +=           "<td>";
    innerHTML +=             "<img style='width:60px;height:60px;' src='" + ResourcePath + "images/msg_waiting.gif' />";
    innerHTML +=           "</td>";
    innerHTML +=           "<td width='4'></td>";
    innerHTML +=           "<td align='left'>";
    innerHTML +=             "<table width='100%' border='0' cellspacing='0' cellpadding='0'>";
    innerHTML +=               "<tr>";
    innerHTML +=                 "<td width='4'></td>";
    innerHTML +=                 "<td valign='middle'>" + msg + "</td>";
    innerHTML +=                 "<td width='4'></td>";
    innerHTML +=               "</tr>";
    innerHTML +=             "</table>";
    innerHTML +=           "</td>";
    innerHTML +=         "</tr>";
    innerHTML +=         "<tr><td colspan='4' height='6'></td></tr>";
    innerHTML +=         "<tr>";
    innerHTML +=           "<td colspan='4' align='center'>";
    for(i = 0; i < 30; i++) {
      innerHTML +=           "<input name='__proccess_id' style='background:#ffffff;border-bottom:1px solid;border-left:1px solid;border-right:1px solid;border-top:1px solid;height:8px;width:8px;margin:3px;'>";
    }
    innerHTML +=           "</td>";
    innerHTML +=         "</tr>";
    innerHTML +=       "</table>";
    innerHTML +=     "</td>"
    innerHTML +=   "</tr>";
    innerHTML += "</table>";
    ShowWaitingDiv.innerHTML = innerHTML;

    InitMoveEvent(ShowWaitingDiv); // 初始化div的鼠标事件

    var _elements = document.getElementsByName('__proccess_id');
    var c = new Array("lightskyblue", "white");
    var p = 0;
    var j = 0;
    setInterval(function() {
      if(p == 30) {
        p = 0;
        j = 1 - j;
      }

      if (_elements[p] == null) {
        return;
      }
      _elements[p++].style.background = c[j];
    }, 100);
  }

  ShowWaitingDiv.style.top = document.body.scrollTop +
    (document.body.offsetHeight - ShowWaitingDiv.offsetHeight) / 2;
  ShowWaitingDiv.style.left = document.body.scrollLeft +
    (document.body.offsetWidth - ShowWaitingDiv.offsetWidth) / 2;
  InitShim(ShowWaitingDiv);

  ShowWaitingDiv.style.visibility = "visible";

  // 在提交的时候创建一个禁止层
  CreateDisabledDiv(ShowWaitingDiv.style.zIndex - 1);
};

CreateDisabledDiv = function(zIndex) {
  var DisabledDiv = $('DisabledDivID');
  if (!DisabledDiv) {
    var DisabledDiv = document.createElement("DIV");
    document.body.appendChild(DisabledDiv);
    DisabledDiv.id = "DisabledDivID";
    DisabledDiv.style.position = "absolute";
    if (IsIE) {
      DisabledDiv.className = "trans-div"; // 半透明效果
    }
    else {
      DisabledDiv.setAttribute("class", "trans-div");
    }
  }
  DisabledDiv.style.top = 0;
  DisabledDiv.style.left = 0;
  DisabledDiv.style.width = document.body.scrollWidth;
  DisabledDiv.style.height = document.body.scrollHeight;
  DisabledDiv.style.zIndex = zIndex;
  DisabledDiv.style.visibility = "visible";
};

// Tooltip对象, 用ajax获取数据
Tooltip = function() {};
Tooltip.prototype = {
  parent: document,
  clientX : 0,
  clientY : 0,

  delay : 1000,
  timer : null,

  defaultMsg: '',

  url : '#', // 请求链接
  params: '', // 请求链接的参数

  _div : null,

  show : function(id) {
    if (IsIE && document.readyState != "complete") {
      return;
    }

    this._div = $('TooltipID');
    if (this._div == null) {
      this._div = document.createElement('div');
      document.body.appendChild(this._div);
      this._div.id = "TooltipID";
      this._div.style.cssText = "position:absolute;background:#ffffff;" +
        "width:240;height:120;visibility:hidden;z-index:1001;";
      this._div.className = 'msg-info-div';
    }

    // 设置容器的onmousemove事件
    if (this.parent.onmousemove == null) {
      this.parent.onmousemove = (function (e) {
        if (!e) {
          e = event;
        }
        this.clientX = Event.pointerX(e);
        this.clientY = Event.pointerY(e);
      }).bind(this);
    }

    if (this._div.style.visibility == "hidden") {
      this.timer = setTimeout((function() {this._show(id)}).bind(this), this.delay);
    }
  },

  _show : function(id) {
    if (this._div.style.visibility == "visible") {
      return;
    }

    this._div.style.left = this.clientX + 8;
    this._div.style.top = this.clientY + 8;

    if (this[id]) {
      this._div.innerHTML = this[id];
    }
    else {
      this._div.innerHTML = this.defaultMsg;
      var options = {
        method: 'post',
        asynchronous: true
      };
      options.postBody = this.params;
      options.onComplete = (function(transport) {
        this._div.innerHTML = transport.responseText;
        // 缓存该属性
        this[id] = this._div.innerHTML;
      }).bind(this);
      new Ajax.Request(this.url, options);
    }
    this._div.style.visibility = "visible";
  },

  hide : function() {
    if (this._div == null) {
      return;
    }
    if (this.timer) {
      clearTimeout(this.timer);
    }

    if (this._div.style.visibility == "visible") {
      this._div.style.visibility = "hidden";
    }
  }
};

//////////////////////////////////扩展的ajax实现/////////////////////////////////

// 继承自Ajax.Request对象
var AjaxInvoker = Class.create();
Object.extend(Object.extend(AjaxInvoker.prototype, Ajax.Request.prototype), {
  initialize: function(url, options, container) {
    if (container) {
      this.containers = {
        success: container.success ? $(container.success) : $(container),
        failure: container.failure ? $(container.failure) :
          (container.success ? null : $(container))
      }
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    this.request(url);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function() {
      if (this.responseIsFailure()) { // 如果失败
        AjaxInvoker.Message.showError();
      }
      else {
        if (this.containers) {
          this.updateContent();
        }
        onComplete(this.transport);
      }

      //延迟长一点, 总是感觉不到
      setTimeout(function() {AjaxInvoker.Message.hideLoading()}, 100);
    }).bind(this);
  },

  // 这段代码改写了Ajax.Request的request实现
  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      if (this.options.method == 'get')
        url += '?' + parameters;

      this.transport.open(this.options.method, url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        // 设置回调函数onStateChange
        this.transport.onreadystatechange = this.onStateChange.bind(this);

        setTimeout((function() {
          if (this.options.showLoadingPane) {
            AjaxInvoker.Message.showLoading();
          }
          // 执行onLoading
          this.respondToReadyState(1);
        }).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
    }
  },

  // 这段代码来自 Ajax.Updater , 并做了些必要的补充
  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success :
      this.containers.failure;

    var ScriptFragment = '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)';
    var match    = new RegExp(ScriptFragment, 'img');
    var response = this.transport.responseText.replace(match, '');
    var scripts  = this.transport.responseText.match(match);

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        receiver.innerHTML = response;
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout((function() {this.onComplete(
          this.transport)}).bind(this), 10);
    }

    if (this.options.evalScripts && scripts) {
      setTimeout((function() {
        for (var i = 0; i < scripts.length; i++) {
          if (!scripts[i]) {
            continue;
          }
          // 在document中增加一个script元素
          var scriptElement = document.createElement("script");
          scriptElement.type = "text/javascript";

          // 匹配的是src属性
          var re = new RegExp('[srcSRC]=["\'](.*)["\']');
          var sTag = scripts[i].match(re);
          if (sTag) {
            scriptElement.src = sTag[1];
          }

          // 匹配的是 <script> 标记中的 script 代码
          re = new RegExp(ScriptFragment, 'im');
          var script = scripts[i].match(re)[1];
          if (script) {
            // 加入dom中
            if (scriptElement.canHaveChildren == null || scriptElement.canHaveChildren) {
              scriptElement.appendChild(document.createTextNode(script));
            } else {
              scriptElement.text = script; // 好像不必调用 eval(script);
            }
          }
          document.getElementsByTagName('head')[0].appendChild(scriptElement);
        }
      }).bind(this), 10);
    }
  }
});

AjaxInvoker.Message = {
  loadingPane : null,
  showing : false,

  showLoading : function() {
    if (this.showing) {
      return;
    }
    this.loadingPane = $("ajax_ck_loading");
    if (this.loadingPane == null) {
      var el = document.createElement('div');
      el.setAttribute("id", "ajax_ck_loading");
      el.style.cssText = "position:absolute;background:#ffffff;" +
        "right:1px;top:1px;width:160px;height:14px;z-index:999";
      el.className = "msg-info-div";
      el.innerHTML = "加载中, 请稍候... ";
      document.body.appendChild(el);
      this.loadingPane = el;
    }
    this.loadingPane.style.display = "block";
    this.showing = true;
    this.loadingPane.style.top = document.body.scrollTop + 1;
  },

  hideLoading : function() {
    this.loadingPane = $("ajax_ck_loading");
    if (this.loadingPane != null) {
      this.loadingPane.style.display = "none";
      this.showing = false;
    }
  },

  showError: function() {}
};

////////////////////通过返回XML数据实现java和javascript数据之间映射/////////////////

AjaxInvoker.Reply = Class.create();
AjaxInvoker.Reply.prototype = {
  // xmldoc是Document对象, 来自responseXML
  initialize : function(xmldoc) {
    this.xmldoc = xmldoc;
    this.root = xmldoc.documentElement;
  },

  // 这个函数返回一个javascript数组对象
  getResult : function() {
    var result = new Array();
    var children = this.root.childNodes;
    for (var i = 0; i < children.length; i++) {
      // 只加入带有标签的元素
      if(children[i].tagName) {
        result[result.length] = this.deserialize(children[i]);
      }
    }
    return result;
  },

  deserialize : function(dataNode) {
    var ret;
    switch (dataNode.tagName.toLowerCase()) {
      case "boolean":
        ret = this.doBoolean(dataNode);
        break;
      case "string":
        ret = this.doString(dataNode);
        break;
      case "list":
        ret = this.doList(dataNode);
        break;
      case "map":
        ret = this.doMap(dataNode);
        break;
    }
    return ret;
  },

  doBoolean : function(dataNode) {
    var value = this.getNodeText(dataNode);
    return value == "true";
  },

  doString : function(dataNode) {
    var value = this.getNodeText(dataNode);
    return value == null ? "" : value;
  },

  doList : function(dataNode) {
    var arr = new Array();
    var children = dataNode.childNodes;
    for (var i = 0; i < children.length; i++) {
      // 只加入带有标签的元素
      if(children[i].tagName) {
        arr[arr.length] = this.deserialize(children[i]);
      }
    }
    return arr;
  },

  doMap : function(dataNode) {
    // java.util.Map类型映射javascript的对象类型
    var obj = new Object();
    var children = dataNode.childNodes;
    for (var i = 0; i < children.length; i++) {
      var tag = children[i].tagName;
      if (tag && tag.toLowerCase() == 'key') {
        // 表示对象的属性
        var key = children[i].getAttribute("name");
        if (key) {
          // 对象的值
          var child = children[i].firstChild;
          while (child && !child.tagName) {
            child = child.nextSibling;
          }
          if (child) {
            obj[key] = this.deserialize(child);
          }
        }
      }
    }
    return obj;
  },

  getNodeText : function(dataNode) {
    return  dataNode.childNodes.length == 0 ?
      null : dataNode.firstChild.nodeValue;
  }
}

///////////////////////////////绑定对象简化Form元素的赋值//////////////////////////

BindFromAjax = function(id, xmldoc) {
  var Results = new AjaxInvoker.Reply(xmldoc).getResult();
  BindObject.bind(id, Results);
}

AjaxOperateSuccess = function(xmldoc) {
  var Result = new AjaxInvoker.Reply(xmldoc).getResult();
  return (Result.length && Result[0] == true);
}

AjaxOperateString = function(xmldoc) {
  var Result = new AjaxInvoker.Reply(xmldoc).getResult();
  return Result;
}

var BindObject = {
  bind : function(id, value) {
    var ele = $(id);
    if (!(ele && value)) {
      return;
    }
    var eles;
    // 是数组对象
    if (ele.constructor == Array) {
      eles = ele;
    }
    else {
      eles = new Array();
      eles[0] = ele;
    }
    for (var i = 0; i < eles.length; i++) {
      if (!eles[i]) {
        continue;
      }
      switch(eles[i].tagName) {
        case "INPUT":
          switch (eles[i].type.toLowerCase()) {
            case "text":
              this.bindText(eles[i], value[i]);
              break;
          }
          break;
        case "SELECT":
          this.bindSelect(eles[i], value[i]);
          break;
      }
    }
  },

  bindText : function(ele, value) {
    ele.value = value;
  },

  bindSelect : function(ele, value) {
    // 删除现有的对象
    while (ele.childNodes.length > 0) {
      ele.removeChild(ele.childNodes[0]);
    }

    if (value.length) {
      for (var i = 0; i < value.length; i++) {
        var option = document.createElement("OPTION");
        var data = value[i];
        if (!data) {
          option.value = "";
          option.text = "";
        }
        if (typeof(data) != 'object') {
          option.value = data;
          option.text = data;
        }
        else { // 对象类型来自java.util.Map的映射
          for (property in data) {
            option[property] = data[property];
          }
        }
        ele.options.add(option);
      }
    }
  }
};

GetSerializeElement = function(elements) {
  elements = $(elements);
  var queryComponents = new Array();
  for (var i = 0; i < elements.length; i++) {
    var queryComponent = Form.Element.serialize(elements[i]);
    if (queryComponent) {
      queryComponents.push(queryComponent);
    }
  }
  return queryComponents.join('&');
}

/////////////////////////////与Jcommon.dll对应的一些操作//////////////////////////

function StartHttpFile(Clazz, FileKey, Param, HideWidget) {
  var Params = '__action=http_file_download';
  if (typeof(Clazz) == 'string') {
    Params += '&class=' + Clazz;
  }
  if (typeof(FileKey) == 'string') {
    Params += '&key=' + FileKey;
  }
  if (typeof(Param) == 'string') {
    Params += '&' + Param;
  }

  if (!HideWidget) {
    var Widget = GetWindowWidget('_start_http_file',
      {
        titleHidden      :      true,
        resizeDisabled   :      true,
        content          :      '<br>&nbsp;正在后台准备文件数据<br>&nbsp;如果文件很大&nbsp;可能需要等待一段时间&nbsp;请稍候',
        width            :      280,
        height           :      75,
        align            :      'center'
      }
    );
    Widget.show();
  }

  new AjaxInvoker(
    ContextPath + "/httpFile.do",
    {
      method: 'post',
      postBody: Params,
      asynchronous: true,
      onComplete: function(transport) {
        if (Widget) Widget.hide();
        setTimeout(function() {
          try {
            var HttpFile = new ActiveXObject("Jcommon.HttpFile");
            HttpFile.DoHttpFile(transport.responseText);
          }catch (e) {
            GetWindowWidget('_Warn_Info', {
              title      :      '警告！',
              content    :      '部分功能需要正确安装客户端组件『Jcommon.dll』您可以手动<a href=\"' + ContextPath + '/framework/resource/downloads/jcommon.EXE\"><span style=\"text-decoration:underline;\">安装</span></a>！',
              resizeDisabled : true,
              width      :      280,
              height     :      70,
              align      :      'center'}).show();
          }
          if (Widget) Widget.hide();
        }, 20);
      }
    }
  );
}

