Wiki.IControllerBase = {
	getCid:function(nodeId){
		return !nodeId?Wiki.Config.componentDef[this.__TOC][2]:(nodeId=="root"?this.find("root").getId():nodeId);
	},
	_getView:function(id){return this._view.getView(this.getCid(id));},
	_getNodeView:function(node){return this._view.getNodeView(node);},
	_getAppxView:function(type){return this._view.getAppxView(type);},
	_getCmtsView:function(){return this._getAppxView(this.__COMMENTS);},
	_isAppxVisible:function(type){return this._view.isAppxVisible(type);},
	_ifAppxViewIsExt:function(type){
		var view  = this._view;
		var list =view.getAppxList();
		return IX.Utils.loop(list, false, function(acc, item){
			return acc || type==view["__"+item];
		});
	},

	getPrefix:function(type){return this._model.getPrefix(type);},

	find:function(id){return this._model.find(id);},
	callServer:function(op,params){this._model.callServer(op, params);},
	refresh:function(nodeId){
		var view = this._getView(nodeId);
		if (view){view.refresh();}
	},
	i18n:function(key){return Wiki.I18N.get("ctrl."+key);},
	__errFun:function(msg){alert(msg+this.i18n("err0"));return false;},
	_errFun:function(key){return this.__errFun(this.i18n(key));}
};

Wiki.Worker = IX.Class.create();
Wiki.Worker.prototype = Object.inherit(Wiki.Object,  Wiki.IControllerBase, {
	initialize:function(model, view){
		this._model= model;
		this._view = view;
	},
	// Move, delete and save
	moveItem:function(node, dst, dtype){// direction: 0:child; 1:above sibling; 2:below sibling; 3: parent
		var view = this._getNodeView(node);
		view.removeAll();
		node.move(dst, dtype);
		view.showAll();
		this.callServer("saveSections",[]);
		return node.getId();
	},
	deleteItem:function(node){
		this._getNodeView(node).removeAll();
		node.suicide();
		this.callServer("saveSections",[]);
		return "";
	},
	extForTitleChanged:function() {
		var view = this._getAppxView(this.__KITEMS);
		if (view) { view.updateSelfItemTitle();}
	},
	// Save operation for sections
	saveItem:function(node, dtype, content) {
		if (dtype==-2){this._getView("root").cleanChilds();}
		if (dtype==-1){this._getNodeView(node).remove();}
		var updIds = node.saveSection(content,dtype);

		if (updIds.length>0){
			this.callServer("saveSections", updIds);
			IX.Utils.loopDsc(Wiki.Config.ifHTMLSection?[]:updIds, 0, function(acc, item){
				var view = this._getView(item);
				if (view && !view.isExist()) {
					view.show();
				}
			}.bind(this));
			return updIds[0];
		}
		return "";
	},
	_saveTopic:function(node, topic, exttopic) {
		var ifRoot = false;
		if (!node.isFolder()){
			ifRoot = node.saveTopic(topic.replaceAll(" ", "_")) || ifRoot; 
			//ifRoot = node.saveExtTopic(exttopic) || ifRoot;
		}
		if (ifRoot) {
			var rid = node.getId();
			this.callServer("saveTopic", [rid]);
			this.refresh(rid);
			return rid;
		}
		return "";
	},
	saveTopic:function(node,topic,exttpic) {
		return  this._saveTopic(node, topic, exttpic);
	},
	saveExtTopic:function(node, topic) {
		return this._saveTopic(node, node.getTopic(), topic);
	},	
	saveTags:function(node, tags) {
		if (node.hasAppx(this.__TAGS) &&node.saveTags(tags)){
			var nid = this.getPrefix(this.__TAGS);
			this.callServer("saveItem", [nid]);
			this.refresh(node.getId());
			this.refresh(nid);
			return node.getId();
		}
		return "";
	},
	saveSummary:function(node, title, content, tags) {
		var tid ="";
		if (tags && node.hasAppx(this.__TAGS) &&node.saveTags(tags)){
			tid = this.getPrefix(this.__TAGS);
			this.refresh(tid);
		}
		var ifRoot = node.save(title, content);
		var nid = node.getId();
		var ids = [];
		if (tid) {ids.push(tid);}
		if (ifRoot) {
			ids.push(nid);
			this.extForTitleChanged();
		}
		if(ids.length>0) {
			this.callServer("saveItem", ids);
			this.refresh(nid);
			return nid;
		}
		return "";
	},
	saveNItem:function(nodeId){
		this._getView(nodeId).toSave();
		this.refresh();
		return nodeId;
	},
	previewNItem:function(nodeId, stat){
		var view = this._getView("edall");
		if (stat==1) {view.save();}
		view.setIfPreview(stat);
		view.refresh();
		this._getView(nodeId)[stat==1?"toSave":"toEdit"]();
	},
	newCommentItem:function(cmtId, title, content) {
		var pcmt = this.find(cmtId);
		var cmt = pcmt.post(title, content);
		var view = this._getCmtsView();
		view.vctl(true);
		if (pcmt.getLevel()==0){pcmt.jumpTo("last");}
		view.refresh(1);
		if (pcmt.getLevel()>0){this._getView(cmtId).stCtl(Wiki.Config.name +"_"+ cmtId+ "_f", 1);}
		this.callServer("postComment", [cmt.getId()]);
		return cmtId;
	},
	editCommentItem:function(cmtId, title, content){
		this.find(cmtId).save(title, content);
		this.refresh(cmtId);
		this.callServer("saveComment", [cmtId]);
		return cmtId;
	},
	removeAppx:function(appId, appxId){
		this.callServer("remove", [appId, appxId]);
		this.refresh(appId);
		return appId;
	}
});

Wiki.IController = Object.inherit(Wiki.Object, Wiki.IControllerBase, {
	openDialog:function(op, id, param){
		this._currentDid = "";
		if (Wiki.Config.useLayerDialog){
			this._dialog.open(op, id, param);
			window.location.hash= "wiki_anchor_"+this._dialog.getFocus();
			return;
		}
		var did = [op, id, op=="Attach"?"":param].join(",");
		if(!(did in this._dialogList && this._dialogList[did]!=null)){
			this._dialogList[did] = new Wiki.View.ModalDialog(this._model, op, id, param, did);
		}
		this._currentDid = did;
		return this._dialogList[did].open();
	},
	_closeDialog:function(did) {
		if (Wiki.Config.useLayerDialog){
			this._dialog.close();
		}else {
 	 		this._dialogList[did].close();
 	 		this._dialogList[did] = null;
		}
		return true;
	},
	closeDialog:function(id, did){
		this._closeDialog(did);
		this.focus(id);
	},
	closeAllDialog:function(){
		if (Wiki.Config.useLayerDialog){
			return this._dialog.close();
		}
		for (var did in this._dialogList){
			this._closeDialog(did);
		}
		return true;
	},
	getCurrentDid:function(){return this._currentDid;},
	getDialog:function(did){
		if (Wiki.Config.useLayerDialog){return this._dialog;}
		return (did in this._dialogList)?this._dialogList[did]:null;
	},
	resetDialog:function(oldId, newId){
		if(Wiki.Config.useLayerDialog){return this._dialog.resetId(oldId, newId);}
		for(did in this._dialogList){
			var d = this._dialogList[did];
			if(d==null){continue;}

			d.resetId(oldId, newId);
			if (did.indexOf(oldId)){continue;}
			this._dialogList[did.replace(oldId, newId)] = d;
			this._dialogList[did] = null;
		}
		return true;
	},
	_finishDialog:function(id, did){
		if (this._isAppxVisible(this.__TOC)){this._getAppxView(this.__TOC).refresh();}
		this._getView("root").refreshAllTidx();
		this.closeDialog(id,did);
	}
});

Wiki.Controller = IX.Class.create();
Wiki.Controller.prototype = Object.inherit(Wiki.IController, {
	initialize: function(wikiPageDesc, layout){
		log("Start!");
		this._model= new Wiki.Model.Page(wikiPageDesc);
		this._view = new Wiki.View.Page(this._model, layout[0][1],layout[0][0]);
		if(Wiki.Config.useLayerDialog){	this._dialog = new Wiki.View.Dialog(this._model, layout[1][1], layout[1][0]);
		}else {this._dialogList = {};	}
		this._pop = new Wiki.View.Popup(layout[2][1], layout[2][0]);
		this._worker = new Wiki.Worker(this._model, this._view);		
		log("continue;!");
	},
	hasExtView:function() {return this._view.getAppxList()[2].length>0;},
	getExtView:function(extLayout){return ("_extView" in this)?this._extView:null;},
	openExtView:function(extLayout){
		return ("_extView" in this) ? this._extView: this.reopenExtView(extLayout);
	},
	reopenExtView:function(extLayout) {
		this._extView = new Wiki.View.ExtWikiView(this._model, extLayout[1],extLayout[0]);
		this._extView.show();
		this._extView.resize(this._view._win.offsetWidth);
		this._extView.setVisible(false);
		return this._extView;
	},
	getWorker:function(){return this._worker;}
},{
	focus:function(id){window.location.hash= "wiki_anchor_"+ Wiki.Config.name+"_" + this.getCid(id);},
	show:function(){this._view.show();},
	resize:function(width){
		this._view.resize(width);
		if(Wiki.Config.useLayerDialog){this._dialog.resize(width);}
		//if("_extView" in this){this._extView.resize(width);}
	},	
	popHide:function(){this._pop.hide();}
},{// for callback!
	getSubmitData:function(){
//		this._getView("root").toSave();
		if(this._model.isNew()){
			this._getView("edall").save();
		}
		return this._model.getNodeInXml("new");
	},
	getContentEditAll:function() {
		var view = this._getView("edall");
		return view?view.getEditContent():"";
	},
	reset:function(desc){
log("reset 1 :"+ (new Date()).getTime());
		this._model.reset(desc);
log("reset 2 :"+ (new Date()).getTime());
		this.closeAllDialog();
log("reset 3 :"+ (new Date()).getTime());
		this._view.show();
log("reset 4 :"+ (new Date()).getTime());
		this._doUserAction("reset",0,[1,2]);
	},
	loaditem:function(desc){
		var idList = this._model.loaditem(desc);
		this._getAppxView(this.__KITEMS).addNodes(idList);
	},
	// edit: [idx, title, section, did]
	// remove: [did]
	updateTopicInfo:function(op, param){
		var pos = op=="remove"?0:3;
		var d = this.getDialog((param&& param.length>pos)?param[pos]:null);
		var node = this.find("root");
		if (op=="remove"){
			var items = d.getAllCheckedTopicInfo();
			if (!items || items.length==0){
				return alert("Please choose one topic to be removed.");
			}
			if (!window.confirm("Are you sure you want to remove such topics?")){
				return;
			}
			node.removeTopics(items);
		} else {
			if (!node.updateTopic(param[0], param[1], param[2])) {
				return;
			}
		}
		d.refreshTopics();
	},
	//[-2, title, section, nodeId]
	updateKItemsTopicInfo:function(param){
		view = this._getView("ki");
		view.setMapped(param[3], param[2]);
	},
	update:function(desc) {
		var view = this._getView("root");
		var ifNeedClean = this._model.checkUpdate(desc);
		if(ifNeedClean) {view.cleanChilds();}

		var ids = this._model.update(desc);
		var ctl = this;
		IX.Utils.loop(ids[0], 0, function(acc, item){
			var xid = item.split("=");
			if (xid.length==2){
				ctl._view.resetId(xid[1],xid[0]);
				ctl.resetDialog(xid[1],xid[0]);
			}
		});
		IX.Utils.loop(ids[1], 0, function(acc, item){
			if (ifNeedClean && item=="sections"){view.showAll();}
			else {ctl.refresh(item);}
		});
		if (ifNeedClean) {this.refresh();}
		//this.focus(ifNeedClean?"root":"ids[1][0]);
		this._doUserAction("update",0,null);
	}
},{// Move and delete operations
	_workItem:function(did, ifEditing, anchorFun){
		var d= this.getDialog(did);
		if(!d || (ifEditing && !d.checkEditing("Post"))){return;}
		var anchorId = anchorFun(this, d, this._worker);
		if (anchorId==null){return;}
		this._finishDialog(anchorId, did);
	},

	_checkActionAcceptable:function(act, dst, dtype){
		var errStr ="" ;
		if (dst.isItem() && dtype!=0){errStr = this.i18n("err1");}
		if (dst._level<=1 && dtype==3){errStr = this.i18n("err2");}
		return isEmpty(errStr)?true:this.__errFun(errStr.replace("#0#", act.toLowerCase()));
	},
	_checkMoveAcceptable:function(node, dst, dtype){
		if (!dst){return alert(this.i18n("err3"));}
		if (!this._checkActionAcceptable("Move", dst, dtype)){return false;}
		var dstIds = dst._tidx.split(".");
		dstIds[dstIds.length-1] = dstIds[dstIds.length-1]*1 + ((dtype==0)?0:((dtype==1)?-1:1));
		if (node._id==dst._id){return this._errFun("err4");}
		if (dtype==0 && node._parent._id==dst._id){return this._errFun("err5");}
		if (dtype==3 && node._id==dst._parent._id){return this._errFun("err6");}
		if ((dtype==1 || dtype==2) && node._tidx == dstIds.join(".")){return this._errFun("err7");}
		if (dst._tidx.indexOf(node._tidx+".")==0){return this._errFun("err8");}
		return true;
	},
	movetoItem:function(nodeId, did){// direction: 0:child; 1:above sibling; 2:below sibling; 3: parent
		this._workItem(did, false, function(obj, d, worker){
			var node = obj.find(nodeId);
			var dst = obj.find(d.getDstId());
			var dtype = d.getDtype();
			if (!obj._checkMoveAcceptable(node, dst, dtype)){return null;}
			return worker.moveItem(node, dst, dtype)
		});		
	},
	realDeleteItem:function(nodeId, did){		
		this._finishDialog(this._worker.deleteItem(this.find(nodeId)), did);
	},
	_saveSection:function(did, nodeId, ndtype){
		this._workItem(did, true, function(obj, d, worker){
			var node = obj.find(nodeId);
			var  dtype = ndtype==0?d.getDtype():ndtype;
			if (ndtype==0 && !obj._checkActionAcceptable("New", node, dtype)){return null;}
			
			var flag = (dtype==-2 && node.save(d.getTitle(), node.getContent()));
			if (flag) {
				worker.extForTitleChanged();
			}
			var res = worker.saveItem(node, dtype, d.getContent());
			if (!res && flag) {
				res = nodeId;
				worker.callServer("saveSections", [res]);
			}
			return res;
		});
	},
	saveAllItem:function(nodeId, did){this._saveSection(did, nodeId, -2);},
	saveNewItem:function(nodeId,did){this._saveSection(did,nodeId, 0);},
	saveEditItem:function(nodeId, did) {this._saveSection(did, nodeId, -1);},

	saveSummaryItem:function(nodeId, did) {
		this._workItem(did, true, function(obj, d, worker){
			return worker.saveSummary(obj.find("root"), d.getTitle(),  d.getContent());	
		});
	},
	_saveExtItem:function(nodeId, did, type) {
		this._workItem(did, true, function(obj, d, worker){
			return worker["save" + type](obj.find("root"), d.getInput());
		});
	},
	saveTagsItem:function(nodeId, did) {this._saveExtItem(nodeId, did, "Tags");},
	saveTopicItem:function(nodeId, did) {this._saveExtItem(nodeId, did, "Topic");},
	//saveExtTopicItem:function(nodeId, did) {this._saveExtItem(nodeId, did, "ExtTopic");},
	//[idx, title, section, did, toc]
	addExtTopicItem:function(nodeId, did){this.callServer("editTopic", [-1, "", "", did]);},
	editExtTopicItem:function(nodeId, did){
		var d = this.getDialog(did);
		var firstItem = d.getFirstCheckedTopicInfo();
		if (firstItem){
			firstItem.push(did);
			this.callServer("editTopic", firstItem);
		}else{
			alert("Please choose one topic to be edited.");
		}
	},
	removeExtTopicItem:function(nodeId, did){this.updateTopicInfo("remove", [did]);},

	saveNItem:function(nodeId){this.focus(this._worker.saveNItem(nodeId));}, 
	previewNItem:function(nodeId){this._worker.previewNItem(nodeId, 1);},
	back2editNItem:function(nodeId){this._worker.previewNItem(nodeId, 0);}
},{// Command for Sections
	editAllItem:function(nodeId){this.openDialog("EditAll", nodeId, -2);},
	wnewItem:function(nodeId){this.openDialog("New", nodeId, 2);},
	editItem:function(nodeId){this.openDialog((nodeId.charAt(0)=='r')?"EditSummary":"Edit", nodeId,-1);},
	editTagsItem:function(){this.openDialog("EditTags",  "root", 0);},
	editTopicItem:function(nodeId) {this.openDialog(nodeId=="topic"?"EditTopic":"EditExtTopic",  "root", 0);},
	wdeleteItem:function(nodeId){this.openDialog("Delete", nodeId,0);},
	moveItem:function(nodeId){this.openDialog("Move", nodeId, 2);},
	propertyItem:function(){this.callServer("property");},

	editAllNItem:function(nodeId){this.editAllItem(nodeId);},
	editNItem:function(nodeId){this._getView(nodeId).toEdit();},
	cancelNItem:function(nodeId){this._getView(nodeId).toView();},

	wnewNItem:function(nodeId){this.wnewItem(nodeId);},
	wdeleteNItem:function(nodeId){this.wdeleteItem(nodeId);},
	moveNItem:function(nodeId){this.moveItem(nodeId);},

	popNewChildItem:function(nodeId){this.openDialog("New", nodeId, 0);},
	popNewParentItem:function(nodeId){this.openDialog("New",nodeId, 3);},
	popNewAboveSiblingItem:function(nodeId){this.openDialog("New",nodeId, 1);},
	popNewBelowSiblingItem:function(nodeId){this.wnewItem(nodeId);},

	popEditItem:function(nodeId){this.editItem(nodeId);},
	popDeleteItem:function(nodeId){this.wdeleteItem(nodeId);},
	popMoveItem:function(nodeId){this.moveItem(nodeId);},
	popEditAllItem:function(nodeId){this.editAllItem(nodeId);},
	popEditSummaryItem:function(nodeId){this.editItem(nodeId);}
},{// for appendix special except comment
	
	_removeAppendix:function(appId, appxId){
		if (!confirm(this.i18n("confirmRemoving").replace("#0#",this.i18n(appId+"name")))){return;}
		this.focus(this._worker.removeAppx(appId, appxId));
	},
	addLinkedItem:function(){this.callServer("toAddLinks");},
	addQuickLinksItem:function(){this.callServer("addQuickLinksItem");},
	toLinkedItem:function(kwId){this.callServer("toLink", [kwId]);},
	removeLinkedItem:function(kwId) {this._removeAppendix(this.getPrefix(this.__LINKS), kwId);},
	popAddKnowledgeItem:function(){this.addLinkedItem();},

	chkIncludeChildFolderItem:function(){this._getAppxView(this.__KITEMS).setIncludeChild();},
	chkItemInFolderItem:function(nodeId){if(nodeId.length ==2) {this._getView(nodeId).selectAllItems();}},
	
	_kiAction:function(param){
		this.callServer("actionki",param);
		this._pop.hide();
	},
	_kiActionItem:function(nodeId, act){
		var view = this._getView(nodeId.substring(0,2));
		var param = view.getActionParam(act);
		var errF = function(errN){alert(this.i18n(errN).replace("#0#", view.getActionName(act)));}.bind(this);
		if(param !=null && param.length>1 && (act=="edit" || act=="forward")){errF("err10");}
		else if (param==null || param.length==0) {errF("err9");}
		else {this._kiAction([act, param]);}
	},
	actionNewItem:function(nodeId){this._kiAction(["new",null]);},
	actionForwardItem:function(nodeId){this._kiActionItem(nodeId, "forward");},
	actionEditItem:function(nodeId){this._kiActionItem(nodeId,"edit");},
	actionDeleteItem:function(nodeId){this._kiActionItem(nodeId,"delete");},
	actionCloneItem:function(nodeId){this._kiActionItem(nodeId,"clone");},
	actionMoveItem:function(nodeId){this._kiActionItem(nodeId,"move");},
	actionCustomizeItem:function(nodeId){this._kiAction(["customize",null]);},
	actionRefreshItem:function(nodeId){this._kiAction(["refresh",null]);},

	_sortKiItem:function(nodeId, ifAsc){
		var arr = nodeId.split("_");		
		this.callServer("sort"+ arr[0], [arr[1], ifAsc?"asc":"dsc"]);
	},
	sortKilistItem:function(nodeId){this._sortKiItem(nodeId, true);},
	ascOrderKilistItem:function(nodeId){this._sortKiItem(nodeId, true);},
	dscOrderKilistItem:function(nodeId){this._sortKiItem(nodeId, false);},

	reqTypeReset4KilistItem:function(nodeId){this.find(nodeId).resetViewParam("req");},
	specTypeReset4KilistItem:function(nodeId){this.find(nodeId).resetViewParam("spec");},
	refTypeReset4KilistItem:function(nodeId){this.find(nodeId).resetViewParam("ref");},
	imgTypeReset4KilistItem:function(nodeId){this.find(nodeId).resetViewParam("img");},
	choseKilistItem:function(nodeId){
		var arr = nodeId.split("_");
		this.find(arr[0]).setViewParam(arr[1], arr[2]);
		this._pop.hide();
	},
	grapListItem:function(params) {this.callServer("grapki", params);},
	releaseGrapListItem:function(params){this.callServer("releasegrapki", params);},
	
	mappingTopicItem:function(nodeId){wiki_mappedTopicInfo(nodeId);},
	link2TopicItem:function(nodeId) {this._getView(nodeId).link2Topic();},
	newItem4TopicItem:function(nodeId){this.callServer("newItem4Topic");},

	_checkItemInList:function(node, mode) {
		var view = this._getView(node.getId().substring(0,2));
		if (mode || !view.itemIsChecked(node)){
			view.setStat4AllItems(false);
			view.setStat4Item(node, true);
		}
	},
	toLinkedAndCheckItem:function(kwId) {
		var node = this.find(kwId.replace("_", ""));
		this._checkItemInList(node, false);
		this.callServer("toLink", [kwId]);
	},
	rightClickItem:function(params) {
		log("right ClickItem");
		var evt = params[0];		
		if (!evt) {evt=window.event;}
		var nodeId = params[1];
		var node = this.find(nodeId);

		this._checkItemInList(node,false);

		var type = params[2]=="topic"?"topic":"kipop";
		var wh = [];
   		if (!isMSIE()){
   			wh = [evt.pageX, evt.pageY];
   		} else {
   			var offsetN = evt.srcElement;
			wh = this._pop.getPos(offsetN);
			//debugger;
			wh[0] += evt.offsetX - offsetN.offsetWidth;
			wh[1] += evt.offsetY;
			//wh=  [event.clientX, event.clientY];
		}
		this._pop.show(type, node.getParent(), wh[0], wh[1]);
		if (!node.isFolder()){
			this.callServer("toLink", [nodeId.replace("ki","ki_")]);
		}
	},

	addQuickLinksItem:function(qlinkId){	this.callServer("addQGroup",[]);},
	editQuickLinksItem:function(qlinkGid){this.callServer("editQGroup",[qlinkGid]);},
	removeQuickLinkItem:function(qlinkItemId){
		var arr = qlinkItemId.split("_");
		this.callServer("removeQItem",[arr[0], arr[1]]);
	},

	addAttachmentItem:function() {this.callServer("toAddAttach"); },
	addAttachmentWithUrl:function(aUrl){this.openDialog("Attach", this.getPrefix(this.__ATTACHMENTS), aUrl);},
	addAttachedItem:function(attId, did) {// will not used in modal dialog
		var d= this.getDialog(did);
		if(!d){return;}
		//d.giveReminder("Uploading file, wait please ... ");
		if (Wiki.Config.useLayerDialog){
			this._model.find("unknown").save(d.getTitle(), d.getContent());
			this.callServer("addAttach");
		} else {
			d.tryToAddAttach();
		}
	},
	removeAttachedItem:function(attachId) {this._removeAppendix(this.getPrefix(this.__ATTACHMENTS), attachId);},
	popAddAttachmentItem:function(){this.addAttachmentItem();}
},{// for comment appendix
	_refreshCmt:function(cmtId){this._getCmtsView().refresh(0);this.focus(cmtId);},

	viewCommentItem:function(cmtId){this._getView(cmtId).view();},
	editCommentItem:function(cmtId){this.openDialog("EditCmt", cmtId, 0);},
	replyCommentItem:function(cmtId) {this.openDialog("Reply", cmtId, 0);},
	postCommentItem:function(cmtId){this.openDialog("Post", cmtId, 0);},

	_getCmtsView:function(){return this._getAppxView(this.__COMMENTS);},
	expandCommentItem:function(cmtId) {
		this._getCmtsView().vctl(true);
		if (this.find(cmtId).expandAll()){this._refreshCmt(cmtId);}
	},
	collapseCommentItem:function(cmtId) {
		this._getCmtsView().vctl(true);
		this.find(cmtId).collapseAll();
		this._refreshCmt(cmtId);
	},
	saveNewCommentItem:function(cmtId, did) {
		this._workItem(did, true, function(obj, d, worker){
			worker.newCommentItem(cmtId, d.getTitle(), d.getContent());
			return cmtId;
		});
	},
	afterEditCommentItem:function(cmtId, did){
		this._workItem(did, true, function(obj, d, worker){
			return worker.editCommentItem(cmtId, d.getTitle(), d.getContent());
		});
	},
	saveReplyCommentItem:function(cmtId,did){this.saveNewCommentItem(cmtId, did);},
	popPostCommentItem:function(cmtId){this.postCommentItem(cmtId);}
},{// for pop up menu and some ST link
	_stCtlItem:function(sid, stat){
		var ids = sid.split("_");
		var vid = ids.pop();
		ids.shift();
		var stId = ids.shift();
		if (vid=="i"){
			Wiki.Config.ifShowTidx = stat;
			this._model.callServer("config", ["ifShowTidx"]);
			this._view.setShowIdx(stat);
		} else if(vid=="v"){this._getView(stId).vctl(stat);}
		else if(vid=="f"){this._getView(stId).stCtl(sid, stat);}
	},
	hideItem:function(sid){this._stCtlItem(sid, false);},
	showItem:function(sid){this._stCtlItem(sid, true);},
	expandSTItem:function(sid){this._stCtlItem(sid, 1);},
	collapseSTItem:function(sid){this._stCtlItem(sid, 2);},

	_jumToItem:function(nodeId, key){if(this.find(nodeId).jumpTo(key)){this._getView(nodeId).refresh(1);}},
	jumpToFirstItem:function(nodeId){this._jumToItem(nodeId, "first");},
	jumpToPreviousItem:function(nodeId){this._jumToItem(nodeId,"previous");},
	jumpToNextItem:function(nodeId){this._jumToItem(nodeId,"next");},
	jumpToLastItem:function(nodeId){this._jumToItem(nodeId,"last");},

	showMenuItem:function(params) {
		var type = params[2];
		var nodeId = params[1];
		var offsetN =  type=="toc"?this._getView().getViewNode(nodeId):this._getView(nodeId).getMenuNode();
		if (type.indexOf("chose")==0){offsetN = this._getView(nodeId).getChoseNode(type.substring("chose".length));}
		var wh = this._pop.getPos(offsetN);
		this._pop.show(type, this.find(nodeId), wh[0], wh[1]);
	},
	hideMenuItem:function(params){this._pop.tryHide(params[0]);}
},{ // SWITCHER:
	__getUserFunList:function(type){
		var tname = type + "FunList";
		return (tname in this)?this[tname]:[];
	},
	register:function(type, name, fun, obj) { // type: "pre"/"post"
		if (!isFunction(fun)){alert("The 3rd parameter must be a function. Register handle function fail!");return;}
		var list = this.__getUserFunList(type);
		list.push([name, fun, obj]); 
		this[type + "FunList"] = list;
	},
	_doUserAction:function(type, act, param){
		return IX.Utils.loop(this.__getUserFunList(type), true, function(acc, item){
			//log("Call function:" + item[0]);
			return item[1](this, act, param, item[2]) && acc;
		}.bind(this));
	},
	_action:function(act, param){
		switch(act){
		case "closeDialog": this.closeDialog(param);break;
		case "preview":this._dialog.preview(param);break;
		case "cancelPreview":this._dialog.cancelPreview(param);break;
		case "selectDialog":this._dialog.selectItem(param);break;
		case "chkDlgTopic":this._dialog.chkDlgTopicItem(param); break;

		case "editAll":
		case "edit":
		case "editTags":
		case "editTopic":
		case "wnew":
		case "wdelete":
		case "move":
		case "property":

		case "editAllN":
		case "editN":
		case "wnewN":
		case "wdeleteN":
		case "moveN":
		case "saveN":
		case "cancelN":
		case "previewN":
		case "back2editN":

		case "saveAll":
		case "saveNew":
		case "moveto":
		case "saveEdit":
		case "saveSummary":
		case "saveTags":
		case "saveTopic":
		case "saveExtTopic":
		case "addExtTopic":
		case "editExtTopic":
		case "removeExtTopic":
		case "realDelete":

		case "popNewBelowSibling":
		case "popNewAboveSibling":
		case "popNewChild":
		case "popNewParent":
		case "popEdit":
		case "popDelete":
		case "popMove":
		case "popEditAll":
		case "popEditSummary":

		case "addLinked":
		case "addQuickLinks":
		case "toLinked":
		case "toLink":
		case "toLinkedAndCheck":
		case "removeLinked":
		case "popAddKnowledge":

		case "addAttachment":
		case "removeAttached":
		case "addAttached":
		case "popAddAttachment":

		case "editComment":
		case "viewComment":
		case "replyComment":
		case "postComment":
		case "collapseComment":
		case "expandComment":

		case "saveNewComment":
		case "saveReplyComment":
		case "afterEditComment":

		case "popPostComment":

		case "addQuickLinks":
		case "editQuickLinks":
		case "removeQuickLink":

		case "chkIncludeChildFolder":
		case "chkItemInFolder":
		case "actionNew":
		case "actionForward":
		case "actionEdit":
		case "actionDelete":
		case "actionClone":
		case "actionMove":
		case "actionChangeType":
		case "actionCustomize":
		case "actionRefresh":
		case "sortKilist":
		case "ascOrderKilist":
		case "dscOrderKilist":
		case "reqTypeReset4Kilist":
		case "specTypeReset4Kilist":
		case "refTypeReset4Kilist":
		case "imgTypeReset4Kilist":
		case "choseKilist":
		case "grapList":
		case "releaseGrapList":
		case "rightClick":

		case "mappingTopic":
		case "link2Topic":
		case "newItem4Topic":

		case "show":
		case "hide":
		case "expandST":
		case "collapseST":
		
		case "jumpToFirst":
		case "jumpToPrevious":
		case "jumpToNext":
		case "jumpToLast":		

		case "hideMenu":
		case "showMenu":this[act+"Item"](param);break;
		case "void":break; //void function to do nothing
		default:alert("unknown action:" + act+"("+ param +")");
		}
	},
	_localAction:function(act, param){
		switch(act){
		case "editAll":
		case "edit":
		case "editTags":
		case "editTopic":
		case "wnew":
		case "wdelete":
		case "move":
		case "property":

		case "popNewBelowSibling":
		case "popNewAboveSibling":
		case "popNewChild":
		case "popNewParent":
		case "popEdit":
		case "popDelete":
		case "popMove":
		case "popEditAll":
		case "popEditSummary":

		case "addLinked":
		case "toLinked":
		case "removeLinked":
		case "popAddKnowledge":

		case "addQuickLinks":
		case "editQuickLinks":
		case "removeQuickLink":

		case "addAttachment":
		case "removeAttached":
		case "toAttached":
		case "popAddAttachment":

		case "editComment":
		case "replyComment":
		case "postComment":
		case "popPostComment":
			if ((Wiki.Config.name+"Client") in window) {window[Wiki.Config.name+"Client"].action(act, param);}
		case "void":break; //void function to do nothing
		default:this._action(act,param);break;
		}
	},
	_actionM:function(act, param){
		switch(act){
		case "closeDialog": this.closeDialog(param[0], param[1]);break;
		case "saveAll":
		case "saveNew":
		case "moveto":
		case "saveEdit":
		case "saveSummary":
		case "saveTags":
		case "saveTopic":
		case "saveExtTopic":
		case "addExtTopic":
		case "editExtTopic":
		case "removeExtTopic":
		case "realDelete":
		case "addAttached":
		case "saveNewComment":
		case "saveReplyComment":
		case "afterEditComment": this[act+"Item"](param[0], param[1]);break;
		case "void":break; //void function to do nothing
		default:alert("unknown action:" + act+"("+ param[0] +","+ param[1] +")");
		}
	},
	actionM:function(act, param){ // used for modal dialog only!
		log("WikiActionM("+act+",["+param +"])" );
		if (this._doUserAction("pre", act, param[0])) {
			this._actionM(act, param);
			this._doUserAction("post", act, param[0]);
		}
	},
	action: function(act, param){
		log("WikiAction("+act+","+param +")" );
		if (act.indexOf("pop")==0 && act.indexOf("TocMenu")<0){this.popHide();}
		if(this._doUserAction("pre", act, param)){
			this[(Wiki.Config.isLocalMode)?"_localAction":"_action"](act, param);
			this._doUserAction("post", act, param);
		}
	}
});
