
tom.space.AddLabelWindow = tom.Class.create();
tom.extend(tom.space.AddLabelWindow.prototype, tom.widget.Window.prototype, {
  initialize: function(id, params) {
    //fields
    var fields = {
      label: null,
      handle: id + "_handle",
      btnClose: id + "_close",
      btnOk: id + "_ok",
      btnCancel: id + "_cancel",
      btnFrmTitle: id + "_frmTitle",
      isModal: true
    };
    tom.extend(fields, params);
    //call super()
    tom.widget.Window.prototype.initialize.apply(this, [id, fields]);
    //bind dom
    this.btnOk = $(this.btnOk);
    this.btnCancel = $(this.btnCancel);
    this.btnFrmTitle = $(this.btnFrmTitle);
    //bind events
    var _this = this;
    this.btnOk.onclick = function(e) {
      if (_this.btnFrmTitle.value.trim() == "") {
        tom.alert("请输入标题");
        return false;
      } else if (JHshStrLen(_this.btnFrmTitle.value.trim()) > 10) {
        tom.alert("标题不能超过10个字符");
        return false;
      }
      _this.btnFrmTitle.value = _this.btnFrmTitle.value.trim();
      _this.addLabel();
      _this.hide();
    }
  },
  addLabel: function() {
      var _this = this;
      var url = "/xhr/editLabel.php";
      var params = new tom.XHConn.Parameter();
      params.$("action", "addLabel")
//            .$("userID", tom.space.user.id)
            .$("title", _this.btnFrmTitle.value.trim())
            .$("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() {
                  document.location = "?user="+tom.space.user.id+"&label="+result.json.data.id;
                }, 1500);
            } else {
              tom.alert(result.json.data);
            }
          }
        );
    
  }
});
tom.extend(tom.space.AddLabelWindow, {
  _singleton: null,
  show: function(label) {
    if (!this._singleton) {
      this._singleton = new tom.space.AddLabelWindow("addLabelWin");
    }
    this._singleton.show();
    this._singleton.setCenter();
  },
  hide: function() {
    this._singleton.hide();
  }
});

tom.space.ChangeLabelTitleWindow = tom.Class.create();
tom.extend(tom.space.ChangeLabelTitleWindow.prototype, tom.widget.Window.prototype, {
  initialize: function(id, params) {
    //fields
    var fields = {
      label: null,
      handle: id + "_handle",
      btnClose: id + "_close",
      btnOk: id + "_ok",
      btnCancel: id + "_cancel",
      btnFrmTitle: id + "_frmTitle",
      isModal: true
    };
    tom.extend(fields, params);
    //call super()
    tom.widget.Window.prototype.initialize.apply(this, [id, fields]);
    //bind dom
    this.btnOk = $(this.btnOk);
    this.btnCancel = $(this.btnCancel);
    this.btnFrmTitle = $(this.btnFrmTitle);
    //bind events
    var _this = this;
    this.btnOk.onclick = function(e) {
      if (_this.btnFrmTitle.value.trim() == "") {
        tom.alert("请输入标题");
        return false;
      } else if (JHshStrLen(_this.btnFrmTitle.value.trim()) > 10) {
        tom.alert("标题不能超过10个字符");
        return false;
      }
      _this.label.setTitle(_this.btnFrmTitle.value.trim());
      _this.hide();
    }
  },
  setLabel: function(label) {
    this.label = label;
  },
  show: function() {
    tom.widget.Window.prototype.show.apply(this);
    this.btnFrmTitle.value = this.label.title;
  }
});
tom.extend(tom.space.ChangeLabelTitleWindow, {
  _singleton: null,
  show: function(label) {
    if (!this._singleton) {
      this._singleton = new tom.space.ChangeLabelTitleWindow("changeLabelTitleWin");
    }
    this._singleton.setLabel(label);
    this._singleton.show();
    this._singleton.setCenter();
  },
  hide: function() {
    this._singleton.hide();
  }
});

/////////////////////////////
/**
 * class LayoutSetupWindow
 */
tom.space.LayoutSetupWindow = tom.Class.create();
tom.extend(tom.space.LayoutSetupWindow.prototype, tom.widget.Window.prototype, {
  initialize: function(id, params) {
    //fields
    var fields = {
      label: null,
      layoutID: 1,
      handle: id + "_title",
      elLayoutContainer: id + "_container",
      elLayoutBtns: new tom.util.Set(),
      btnClose: id + "_close",
      btnOk: id + "_ok",
      btnCancel: id + "_cancel",
      isModal: true
    };
    tom.extend(fields, params);
    //call super()
    tom.widget.Window.prototype.initialize.apply(this, [id, fields]);
    //bind dom
    this.btnOk = $(this.btnOk);
    this.btnCancel = $(this.btnCancel);
    this.elLayoutContainer = $(this.elLayoutContainer);
    this.elLayoutBtns = tom.util.Arrays.asSet($A(this.elLayoutContainer.getElementsByTagName("A")));
    //bind events
    var _this = this;
    this.btnOk.onclick = function(e) {
      _this.save();
      _this.hide();
    }
    var i = 1;
    this.elLayoutBtns.each(function(o) {
        o.layoutID = i++;
        o.onclick = function(e) {
          _this.layoutID = o.layoutID;
        }
      });
  },
  setLabel: function(label) {
    this.label = label;
  },
  show: function() {
    tom.widget.Window.prototype.show.apply(this);
    this.labelID = this.label.id;
  },
  save: function() {
    if (this.layoutID != this.label.layoutID) {
      this.label.changeLayout(this.layoutID);
    }
  }
});
tom.extend(tom.space.LayoutSetupWindow, {
  _singleton: null,
  show: function(label) {
    if (!this._singleton) {
      this._singleton = new tom.space.LayoutSetupWindow("setupLayoutWin");
    }
    this._singleton.setLabel(label);
    this._singleton.show();
    this._singleton.setCenter();
  },
  hide: function() {
    this._singleton.hide();
  }
});



/**
 * class LayoutSetupWindow
 */
tom.space.ThemeSetupWindow = tom.Class.create();
tom.extend(tom.space.ThemeSetupWindow.prototype, tom.widget.Window.prototype, {
  initialize: function(id, params) {
    //fields
    var fields = {
      label: null,
      themeID: 1,
      handle: id + "_title",
      elThemeContainer: id + "_container",
      elLayoutBtns: new tom.util.Set(),
      btnClose: id + "_close",
      btnOk: id + "_ok",
      btnCancel: id + "_cancel",
      isModal: true,
      opacity: false,
      maskOpacity: 0.1
    };
    tom.extend(fields, params);
    //call super()
    tom.widget.Window.prototype.initialize.apply(this, [id, fields]);
    //bind dom
    this.btnOk = $(this.btnOk);
    this.btnCancel = $(this.btnCancel);
    this.elThemeContainer = $(this.elThemeContainer);
    this.elLayoutBtns = tom.util.Arrays.asSet($A(this.elThemeContainer.getElementsByTagName("A")));
    //bind events
    var _this = this;
    this.btnOk.onclick = function(e) {
      _this.save();
      _this.hide();
    }
    var i = 1;
    this.elLayoutBtns.each(function(o) {
        o.themeID = i++;
        o.onclick = function(e) {
          _this.themeID = o.themeID;
          $("linkTheme").href = "/style/" + _this.themeID + ".css";
        }
      });
  },
  setLabel: function(label) {
    this.label = label;
  },
  show: function() {
    tom.widget.Window.prototype.show.apply(this);
    this.labelID = this.label.id;
  },
  save: function() {
    //TODO 请求后台修改labelid，如果成功，修改labelid
    if (this.themeID != this.label.themeID) {
//      tom.alert("请求后台修改themeID，如果成功，修改themeID");
      this.label.changeTheme(this.themeID);
    }
  },
  onClose: function(e) {
    $("linkTheme").href = "/style/" + this.label.themeID + ".css";
    return true;
  }
});
tom.extend(tom.space.ThemeSetupWindow, {
  _singleton: null,
  show: function(label) {
    if (!this._singleton) {
      this._singleton = new tom.space.ThemeSetupWindow("setupThemeWin");
    }
    this._singleton.setLabel(label);
    this._singleton.show();
    this._singleton.setCenter();
  },
  hide: function() {
    this._singleton.hide();
  }
});


tom.space.cookie = {
    getCookie : function(varName){
        var cookieString=document.cookie.split(";");
        for(var i=0;i < cookieString.length;i++)
        {
            var tmparray=cookieString[i].split('=');
			
            if(tmparray[0].replace(/^\s*/,"")==varName)
            {
                return tmparray[1];
            }
        }
    },
    setCookie : function(varName,varValue){  
        document.cookie=varName+"="+varValue;
    },
    deleteModule : function(id){
        var cookie = this.getCookie("spaceSetting");
        var cookieArray = cookie.split(escape("|"));
        var tmparray = [];
        for(i=0;i<cookieArray.length;i++)
        {
            var moduleid = ("0x"+cookieArray[i].substr(0,4))-0;
            if(moduleid != id)
            {
                
                tmparray.push(cookieArray[i]);
            }
            
        }
        cookie = tmparray.join(escape("|"));
        document.cookie="spaceSetting="+cookie;


    },
    setModule : function(list)
    {
		var cookie=[];
        list.each(function(v){
			id = String(v.id.toString(16));
			id = "0000".substr(0,4-id.length)+id;
			cookie.push(id+v.column+v.index);
		})
		document.cookie="spaceSetting="+cookie.join(escape("|"));
		alert("spaceSetting="+cookie.join(escape("|")));
    }
}





tom.space.AddModuleWindow = tom.Class.create();
tom.extend(tom.space.AddModuleWindow.prototype, tom.widget.Window.prototype, {
  initialize: function(id, params) {
  	var fields = {
  	  isModal: true,
  	  canDrag: false,
  	  moduleUl: "addModuleWin_modules",
  	  //所有模块checkbox
  	  modules: new tom.util.Map(),
	  configModules: null,
	  //生成column中存在的module id列表
  	  visibleModules: new tom.util.Set(),
	  
  	  btnCancel: "",
  	  btnOk: "addModuleWin_save",
  	  
  	  perPageCount: 6,
  	  moduleCount: tom.space.TOMINDEX_MODULETYPES.length,
  	  pageCount: (this.moduleCount % this.perPageCount == 0) ? (this.moduleCount / this.perPageCount) : (this.moduleCount / this.perPageCount + 1),
  	  realPageCount: 5,
  	  curPage: 1,
  	  pages: new tom.util.Set(),
  	  pageContainer: "addModule_pageContainer",
  	  nextPage: "addModule_nextPage",
  	  prevPage: "addModule_prevPage"
  	};
  	tom.extend(fields, params);
    tom.widget.Window.prototype.initialize.apply(this, [id, fields]);
    
    this.pageCount = parseInt((this.moduleCount % this.perPageCount == 0) ? (this.moduleCount / this.perPageCount) : (this.moduleCount / this.perPageCount + 1)),
    
    this.configModules = tom.util.Arrays.asSet(tom.space.TOMINDEX_MODULETYPES).filter(
        function(o) {
          return o.id;
        },
        function(o) {
          return o.enabled == true;
        }
      );
    
    var _this = this;
    
    this.moduleUl = $(this.moduleUl);
    tom.util.Arrays.asSet(tom.space.TOMINDEX_MODULETYPES).filter(
        function(o) {
          return o;
        },
        function(o) {
          return o.enabled == true;
        }
      ).each(function(o) {
        var amc = new tom.space.AddModuleCheckbox(o.id, {ul: _this.moduleUl, title: o.title, icon: o.icon});
        _this.modules.put(o.id, amc);
        if (tom.space.modules.containsKey(o.id)) {
//          amc.element.parentNode.removeChild(amc.element);
		  _this.hideModule(o.id);
        }
      });
    
    this.btnOk = $(this.btnOk);
    this.btnOk.onclick = function(e) {
      var amcs = document.getElementsByName("addModule_chk");
      var ids = tom.util.Arrays.filter(function(o) {
          return o.id.replace("addModule_chk_", "");
        }, 
        amcs, 
        function(o) {
          return o.checked;
        });
      if (ids.length == 0) {
      	tom.alert("请选择模块");
      	return false;
      }
      ids = tom.util.Arrays.asSet(ids);
      
      var ms = new tom.util.Set();
      
      var isAsyncLoadModule = false;
      var i = 0;
      ids.each(function(id) {
      	  if (tom.space.modulesDelete.containsKey(id)) {
      	    tom.space.columns.get(1).addModuleElement(tom.space.modulesDelete.get(id).element);
      	  	tom.space.columns.get(1).addModuleObject(tom.space.modulesDelete.get(id));
      	  	tom.space.modules.put(id, tom.space.modulesDelete.remove(id));
      	  } else {
      	    isAsyncLoadModule = true;
      	    var m = {
      	      id: id,
      	      column: { id: 1 },
      	      index: i,
      	      element: { offsetTop: i-- }
      	    };
      	    tom.space.modules.put(id, m);
      	  }
        });
      tom.space.Module.saveModulesCookie();
      
      if (isAsyncLoadModule) {
        document.location.reload();
      }
      _this.hide();
    }
   
    this.btnCancel = $(this.btnCancel);
    this.btnCancel.onclick = function(e) {
      _this.hide();
      var amcs = document.getElementsByName("addModule_chk");
      for (var i = 0; i < amcs.length; i++) {
      	amcs[i].checked = false;
      }
      return false;
    }
    
    //初始化分页
    /*
  	  perPageCount: 12,
  	  moduleCount: tom.space.TOMINDEX_MODULETYPES.length,
  	  pageCount: this.moduleCount / this.perPageCount,
  	  curPage: 1,
  	  pages: new tom.util.Set(),
  	  pageContainer: "addModule_pageContainer",
  	  nextPage: "addModule_nextPage",
  	  prevPage: "addModule_prevPage"
     */
    //分页容器
    this.pageContainer = $(this.pageContainer);
    //上页
    this.prevPage = document.createElement("A");
    this.prevPage.href = "#";
    this.prevPage.innerHTML = "[上页]";
    this.prevPage.onclick = function(e) {
      _this.curPage = --_this.curPage <= 1 ? 1 : _this.curPage;
  	  _this.resetModules();
  	  _this.resetPages();
      return false;
    }
    this.pageContainer.appendChild(this.prevPage);
    
    //页码
    for (var i = 1; i <= this.pageCount; i++) {
      var elem = document.createElement("A");
      elem = document.createElement("A");
      elem.href = "#";
      elem.innerHTML = "[" + i + "]";
      elem.id = "addModule_page_" + i;
      elem.onclick = function(e) {
      	_this.curPage = this.id.replace("addModule_page_", "");
      	_this.resetModules();
      	_this.resetPages();
        return false;
      }
      this.pages.add(elem);
      this.pageContainer.appendChild(elem);
    }
    
    //下页
    this.nextPage = document.createElement("A");
    this.nextPage.href = "#";
    this.nextPage.innerHTML = "[下页]";
    this.nextPage.onclick = function(e) {
      _this.curPage = ++_this.curPage >= _this.realPageCount ? _this.realPageCount : _this.curPage;
  	  _this.resetModules();
  	  _this.resetPages();
      return false;
    }
    this.pageContainer.appendChild(this.nextPage);
  },
  addModule: function(id) {
    this.moduleUl.appendChild(this.modules.get(id).getElement());
  },
  removeModule: function(id) {
  	var m = this.modules.get(id).getElement();
  	if (m.parentNode == this.moduleUl) {
  	  this.moduleUl.removeChild(m);
  	}
  },
  hideModule: function(id) {
  	this.modules.get(id).setVisible(false);
  },
  showModule: function(id) {
  	this.modules.get(id).setVisible(true);
  },
  resetModules: function() {
  	var _this = this;
  	var i = 1;
  	var startIndex = (this.curPage - 1) * this.perPageCount + 1;
  	var endIndex = startIndex + this.perPageCount - 1;

  	this.configModules.each(function(id) {
  	    if (_this.visibleModules.contains(id)) {
  	      _this.hideModule(id);
  	    } else {
  	      if (i >= startIndex && i <= endIndex) {
  	        _this.showModule(id);
  	        _this.modules.get(id).uncheck();
  	      } else {
  	        _this.hideModule(id);
  	      }
  	      i++;
  	    }
  	  });
  },
  show: function() {
  	var _this = this;
  	//取已显示的模块id列表
  	_this.visibleModules.clear();
  	tom.space.columns.each(function(k, v) {
  		v.getModules().each(function(o) {
  		      _this.visibleModules.add(o.id);
  		    }
  		  );
  	  });
  	//计算分页信息
  	this.curPage = 1;
  	var showModuleCount = this.modules.size() - this.visibleModules.size();
  	this.realPageCount = parseInt((showModuleCount % this.perPageCount == 0) ? (showModuleCount / this.perPageCount) : (showModuleCount / this.perPageCount + 1));
  	//重置check和page
  	this.resetModules();
  	this.resetPages();
  	
  	tom.widget.Window.prototype.show.apply(this);
  },
  resetPages: function() {
  	var _this = this;
  	var i = 1;
    this.pages.each(function(o) {
        if (i <= _this.realPageCount) {
          o.style.display = "";
        } else {
          o.style.display = "none";
        }
    	if (i == _this.curPage) {
    	  o.innerHTML = o.id.replace("addModule_page_", "");
    	} else {
    	  o.innerHTML = "[" + o.id.replace("addModule_page_", "") + "]";
    	}
        i++;
      });
  }
});
tom.space.AddModuleCheckbox = tom.Class.create();
tom.extend(tom.space.AddModuleCheckbox.prototype, tom.widget.Component.prototype, {
  initialize: function(id, params) {
  	var fields = {
  	  moduleCount: 8,
  	  fnCreateElement: function() {
	    var elem = document.createElement("LI");
	    elem.id = "addModule_li_" + id;
	    elem.innerHTML = '\
		    <a href="#" onclick="$(\'addModule_chk_' + id + '\').click();return false;"><img src="'+this.icon+'" alt="" /></a></label>\
		    <span>\
		    	<input type="checkbox" id="addModule_chk_' + id + '" name="addModule_chk" />\
				<label for="addModule_chk_' + id + '">' + this.title + '</label>\
			</span>';
	    
	    this.ul.appendChild(elem);
	    return elem;
	  }
  	};
  	tom.extend(this, fields, params);
    tom.widget.Component.prototype.initialize.apply(this, ["addModule_li_" + id, fields]);
  },
  uncheck: function() {
    this.getElement().checked = false;
  }
});


//tom.space.config.MODULE_CONTENT_PATH = "hp/";
tom.space.TOMINDEX_MODULETYPES_ICON_PATH = "images/icon/";
tom.space.TOMINDEX_MODULETYPES = [
  { id: 1, 
    title: "新闻", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod01.gif",
	enabled: true,
    isLoad: true },
  { id: 2, 
    title: "体育", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod02.gif",
	enabled: true,
    isLoad: true },
  { id: 3, 
    title: "女性", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod03.gif",
	enabled: true,
    isLoad: true },
  { id: 4, 
    title: "博客", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod04.gif",
	enabled: true,
    isLoad: true },
  { id: 5, 
    title: "娱乐", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod05.gif",
	enabled: true,
    isLoad: true },
  { id: 6, 
    title: "汽车", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod06.gif",
	enabled: true,
    isLoad: true },
  { id: 7, 
    title: "玩乐吧", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod07.gif",
	enabled: true,
    isLoad: true },
  { id: 8, 
    title: "论坛", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod08.gif",
	enabled: true,
    isLoad: true },
  { id: 9, 
    title: "美术同盟", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod09.gif",
	enabled: true,
    isLoad: true },
  { id: 10, 
    title: "围棋", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod10.gif",
	enabled: true,
    isLoad: true },
  { id: 11, 
    title: "星座", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod11.gif",
	enabled: true,
    isLoad: true },
  { id: 12, 
    title: "笑话", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod12.gif",
	enabled: true,
    isLoad: true },
  { id: 13, 
    title: "Flash", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod13.gif",
	enabled: true,
    isLoad: true },
  { id: 14, 
    title: "看小说", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod14.gif",
	enabled: true,
    isLoad: true },
  { id: 22, 
    title: "08校园巡演", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod22.gif",
	enabled: true,
    isLoad: true },
  { id: 23, 
    title: "图吧", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod23.gif",
	enabled: true,
    isLoad: true },
  { id: 21, 
    title: "能打多远", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod13.gif",
	enabled: true,
    isLoad: true },
  { id: 24, 
    title: "超级玛丽", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod13.gif",
	enabled: true,
    isLoad: true },
  { id: 25, 
    title: "泡泡龙", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod13.gif",
	enabled: true,
    isLoad: true },
  { id: 45, 
    title: "2008车展", 
	icon: tom.space.TOMINDEX_MODULETYPES_ICON_PATH + "mod45.gif",
	enabled: true,
    isLoad: true }
];
