/**
 * class Column
 */
tom.space.Column = tom.Class.create();
tom.extend(tom.space.Column.prototype, tom.dnd.Droppable.prototype, {
  initialize: function(id, params) {
    var fields = {
      id: id,
      mode: "vertical",
      withinMode: "vertical",
      label: null
    };
    tom.extend(fields, params);
    tom.dnd.Droppable.prototype.initialize.apply(this, ["col_" + fields.label.id + "_" + id, fields]);
  },
  addModuleObject: function(m) {
    this.draggables.add(m);
    m.droppable = this;
    m.column = this;
  },
  removeModule: function(m) {
    this.draggables.removeObject(m);
    m.column = null;
  },
  addModuleElement: function(el) {
    this.element.appendChild(el);
  },
  removeModuleElement: function(el) {
    this.element.removeChild(el);
  },
  getModules: function() {
    return this.draggables;
  }
});

/*
 * class Module
 */
tom.space.Module = tom.Class.create();
tom.extend(tom.space.Module.prototype, tom.dnd.Draggable.prototype, {
  initialize: function(id, params) {
    var fields = {
      id: id,
      typeID: 1,
      title: 'title',
      icon: 'http://www.tom.com/logo.jpg',
      color: '1',
      index: '1',
      parameter: '',
      autoRefresh: 0,
      minimum: 0,
      isMinimum: false,
      ext: '',
    
      revert: tom.fnTrue, 
      droppable: true,
      droppableFilter: function(dp) {
          return ((dp instanceof tom.space.Column) || (dp instanceof tom.space.LabelDrop)); 
        },    
      handle: "mod_handle_" + id,

      column: null,
      widget: null,
      onComplete: function() {
        this.element.style.width = "auto";
        if (tom.space.judge.isSelf() || tom.space.judge.isTomIndexServer()) {
          this._onCompleteAjax();
        } else if (tom.space.judge.isTomIndex()) {
          this._onCompleteCookie();
        }
      }
    };
    tom.extend(fields, params);
    tom.dnd.Draggable.prototype.initialize.apply(this, ["mod_" + id, fields]);
    //绑定dom对象
    this.elTitle = $("mod_title_" + id);
    this.elMinimum = $("mod_min_" + id);
    //this.elIcon = $("mod_icon_" + id);
    //this.elRefresh = $("mod_refresh_" + id);
    this.elEdit = $("mod_edit_" + id);
    //this.elEditTitle = $("mod_edit_title_" + id);
    this.elEditSave = $("mod_edit_save_" + id);
    this.elEditContentSave = $("mod_edit_content_save_" + id);
    this.elContent = $("mod_content_" + id);
    var _this = this;
    //绑定事件
    //this.elIcon.onmousedown = this.elRefresh.onmousedown = tom.fnEventStop;
    if (tom.space.judge.isSelf()) {
        this.elMinimum.onmousedown = tom.fnEventStop;
        this.elMinimum.onclick = function(e) {
          if (_this.isMinimum) {
            _this.elContent.style.display = "block";
            this.src = "images/unfold.gif";
          } else {
            _this.elContent.style.display = "none";
            _this.hideEditArea();
            this.src = "images/fold.gif";
          }
          _this.doMinimum(_this.isMinimum);
          _this.isMinimum = !_this.isMinimum;
        }
    }
    /*
    this.elRefresh.onclick = function(e) {
      _this.widget.onRefresh();
    }
    */
    /*
    if (tom.space.judge.isSelf() || tom.space.judge.isTomIndex() || tom.space.judge.isTomIndexServer()) {
        this.elBtnEdit = $("mod_btnedit_" +id);
        if (this.parameter.size() == 0) {
            this.elBtnEdit.style.display = "none";
        } else {
            this.elBtnEdit.onmousedown = tom.fnEventStop;
            this.elBtnEdit.onclick = function(e) {
              if (_this.elBtnEdit.innerHTML == "取消设置") {
                _this.hideEditArea();
              } else {
                _this.showEditArea();
              }
              tom.Event.stop(e||window.event);
              return false;
            }
        }
    } else {
        this.elBtnEdit = $("mod_btnedit_" +id);
        this.elBtnEdit.onmousedown = tom.fnEventStop;
        this.elBtnEdit.onclick = function(e) {
          tom.login("");
          tom.Event.stop(e||window.event);
          return false;
        } 
    }
    */
    /*
    this.elEditSave.onclick = function(e) {
      if (!tom.space.judge.isTomIndex()) {
          if (JHshStrLen(_this.elEditTitle.value.trim()) > 20) {
            tom.alert("标题不能多于20个字符", "INFO");
            return;
          }
          _this.editSave();
      }
      _this.editContentSave();
    }
    */
    if (this.elEditContentSave) {
      this.elEditContentSave.style.display = "none";
      this.elEditContentSave.onclick = function(e) {
//        _this.editContentSave();
      }
    }
    this.elClose = $("mod_close_" + id);
    this.elClose.onmousedown = tom.fnEventStop;
    this.elClose.onclick = function(e) {
      _this.onClose(e);
      return false;
    }
    
    this.handle.style.cursor = "move";
    //this.elIcon.style.display = "none";
    //this.elEditTitle.parentNode.style.display = "none";
  },
  setTitle: function(title) {
    this.elTitle.innerHTML = this.title = title;
  },
  setIcon: function(icon) {
    //this.elIcon.src = (this.icon = icon) + "?rdm=" + new Date().getTime();
  },
  setContent: function(content) {
    this.elContent.innerHTML = content;
  },
  showEditArea: function() {
    this.elBtnEdit.innerHTML = "取消设置";
    this.elEdit.style.display = "block";
    this.elEditTitle.value = this.title;
  },
  hideEditArea: function() {
    this.elBtnEdit.innerHTML = "设置";
    this.elEdit.style.display = "none";
  },
  editSave: function() {
      var _this = this; 
            var url = tom.space.judge.isTomIndexServer() ? "/xhr/change_module_set2.php" : "/xhr/change_module_set.php";
      var params = new tom.XHConn.Parameter();
      params.$("action", "change_module_title")
            .$("mid", _this.id)
            .$("title", _this.elEditTitle.value.trim())
            .$("length", _this.elEditTitle.value.length)
            .$("rdm", new Date().getTime());
            
      new tom.XHConn().connectAsync(
          url, 
          "get", 
          params.stringValue(), 
          function(xhr) {
            var result = tom.XHConn.parseResult(xhr, {json: true});
            if (result.json.code == 0) {
//              tom.alert("修改成功", "OK", function() {
                  _this.setTitle(_this.elEditTitle.value.trim());
                  _this.hideEditArea();
//                }, 1500);
            } else {
              tom.alert(result.json.data);
            }
          }
        );
  },
  editContentSave: function() {
      var _this = this;
      var sjson = "{";
      var ajson = [];
      this.parameter.each(
          function(k, v) {
            v = "" + _this.widget.getValue(k);
            ajson.push('"' + k + '":"' + v.replace('"', '\\"') + '"');
          }
        );
      ajson.push('"typeID":"' + this.id + '"');
      sjson += ajson.join(",");
      sjson += "}";
      
      var ojson = (eval("( " + sjson + " )"));
      
      tom.space.staticindex.saveParams2cookie(this.id, ojson);
      
      tom.alert("修改成功", "OK", function() {
          _this.hideEditArea();
          _this.widget.onRefresh();
        }, 1500);
      
  },
  doMinimum: function(min) {
      //TODO save to php
  },
  onClose: function() {
    if (tom.space.judge.isSelf() || tom.space.judge.isTomIndexServer()) {
      this._onCloseAjax();
    } else if (tom.space.judge.isTomIndex()) {
      this._onCloseCookie();      
    }
  },
  _onCloseCookie: function() {
    var _this = this;
    tom.confirm(
        "确定删除模块吗？",
        function() {
            _this.column.removeModuleElement(_this.element);
            _this.column.removeModule(_this);
            tom.space.modules.remove(_this.id);
            tom.space.modulesDelete.put(_this.id, _this);
            _this._onCompleteCookie();
        },
        function() {});
  },
  _onCloseAjax: function() {
    var _this = this;
    tom.confirm(
        "确定删除模块吗？",
        function() {
          var url = tom.space.judge.isTomIndexServer() ? "/xhr/change_module_set2.php" : "/xhr/change_module_set.php";
          var params = new tom.XHConn.Parameter();
          params.$("action", "del_module")
                .$("mid", _this.id)
                .$("rdm", new Date().getTime());
          new tom.XHConn().connectAsync(
              url, 
              "get", 
              params.stringValue(), 
              function(xhr) {
                var result = tom.XHConn.parseResult(xhr, {json: true});
                if (result.json.code == 0) {
                  _this.column.removeModuleElement(_this.element);
                  _this.column.removeModule(_this);
                  tom.space.modules.remove(_this.id);
                } else {
                  tom.alert(result.json.data);
                }
              }
            );
        },
        function() {
        }
      );
  },
  _onCompleteAjax: function() {
    this.column = this.droppable;
    //计算label drop位置
    var _this = this;
    var index = 1;
    this.column.getModules().sort(
        function(a, b) {
          return a.element.offsetTop - b.element.offsetTop;
        }
      ).each(
        function(o) {
          if (o == _this) {
            return false;
          }
          index++;
        }
      );
      var url = tom.space.judge.isTomIndexServer() ? "/xhr/change_module_set2.php" : "/xhr/change_module_set.php";
      var params = new tom.XHConn.Parameter();
      params.$("action", "change_module_column")
            .$("mid", _this.id)
            .$("cid", _this.column.id)
            .$("index", index)
            .$("rdm", new Date().getTime());
     new tom.XHConn().connectAsync(
          url, 
          "get", 
          params.stringValue(), 
          function(xhr) {
            var result = tom.XHConn.parseResult(xhr, {json: true});
            if (result.json.code != 0) {
              tom.alert(result.json.data);
            }
          }
        );
  },
  _onCompleteCookie: function() {
    this.column = this.droppable;
    tom.space.Module.saveModulesCookie();
  }
});
tom.extend(tom.space.Module, {
  saveModulesCookie: function() {
	var cookie=[];
	var curColumnId = 0;
	var i = 1;
    tom.space.modules.values().sort(
        function(a, b) {
          return (a.column.id - b.column.id != 0) ? (a.column.id - b.column.id) : (a.element.offsetTop - b.element.offsetTop);
        }
      ).each(
        function(m){
          if (m.column.id != curColumnId) {
            curColumnId = m.column.id;
            i = 1;
          }
          m.index = i++;
		  var id = parseInt(m.id).toString(16);
		  id = "0000".substr(0, 4 - id.length) + id;
		  cookie.push(id + m.column.id + m.index);
	    }
	  );
	tom.Cookie.write("TOM_SPACE_MODULE_" + tom.space.user.labelID, cookie.join("|"), 365 * 24, null, "tom.com");
  }
});