if(!("Wiki" in window)){window.Wiki = {};}
Wiki.SDEP= Object.inherit({
// SDEP XML parse
	__$$fun:function(node,type, cfun,vfun){
		var cnode = node?node[type=="first"?"firstChild":"nextSibling"]:null;
		while(cnode!=null && !cfun(cnode)){cnode = cnode.nextSibling;}
		return vfun(cnode);
	},
	__$$get:function(node, tagN, type){return tagN?this.__$$fun(node,type,function(cnode){return cnode.nodeName.toLowerCase()==tagN;},function(cnode){return cnode;}):node;},
	__$$text:function(node){return node?(isMSIE()?(node.firstChild!=null?node.firstChild.nodeValue:""):node.textContent):"";},
	__$$cdata:function(node){return node?this.__$$fun(node,"first",function(cnode){return cnode.nodeType==4;},function(cnode){return cnode?cnode.nodeValue:"";}):"";},

	__$first:function(node, tagN){return this.__$$get(node,tagN, "first");},
	__$next:function(node, tagN){return this.__$$get(node, tagN,"next");},
	__$cdata:function(node, tagN){return this.__$$cdata(this.__$first(node, tagN));},
	__$text:function(node, tagN){return this.__$$text(this.__$first(node, tagN));},
	__$attr:function(node, attN){if(!node){return "";}var val = node.getAttribute(attN);return (isEmpty(val))?"":val;}
},{	// handler for response from server;
	__TAGSPARAM: {
			tag:[["$attr", "id"],["cvtToArray", "lkw"]],
			titem:[["$cdata", "title"],["$cdata", "mapped"]],
			topics:[["cvtToArray", "titem"]],
			lkw:[["$attr", "id"],["$attr", "type"], ["$cdata",""]],
			poster:[["$attr", "id"],["$cdata", ""]],
			owner:[["$attr", "id"],["$cdata", ""]],
			section:[["$attr", "id"],["$cdata", "title"], ["$cdata", "content"], ["$attr", "version"], ["$attr", "pid"], ["$attr", "idx"], ["$attr", "tidx"]],
			attach:[["$attr", "id"],["$text", "url"], ["$cdata", "title"]],
			comment:[["$attr", "id"],["$cdata", "title"], ["$cdata", "content"], ["cvtToElem", "poster"], ["$text", "date"], ["$attr", "pid"], ["$attr", "idx"]],
			group:[["$attr", "id"],["$attr", "editable"],["$cdata", "title"],["cvtToArray","lkw"]],
			col:[["$attr", "id"],["$attr", "width"],["$attr", "type"],["$attr", "name"],["$attr", "nowrap"], ["$attr", "sortable"]],
			columns:[["$attr", "orderBy"],["$attr", "order"],["cvtToArray","col"]],
			img:[["$text", ""]],
			lkws:[["cvtToArray","lkw"]],
			qlkws:[["cvtToArray","group"]],
			rkws:[["cvtToArray","tag"]],
			attachs:[["cvtToArray","attach"]],
			itemlist:[["$attr", "total"], ["$attr", "noipp"], ["$attr", "curp"],["cvtToArray", "columns"], ["$attr", "incChild"], ["$attr", "imgType"],["$attr", "reqType"],["$attr", "specType"],["$attr", "refType"], ["$attr", "actionType"],["$attr", "cond"]],
			search:[["$attr", "total"], ["$attr", "noipp"], ["$attr", "curp"],["cvtToArray", "columns"], ["$attr", "cond"]],
			comments:[["$attr", "total"], ["$attr", "noipp"], ["$attr", "curp"]],
			wiki:[["$attr", "id"], ["$cdata", "title"], ["$cdata", "content"], ["$attr", "version"], ["$attr", "type"], ["$cdata", "topic"], ["cvtToElem", "topics"]]
	},
	__cvtToElem:function(node, tagN){
		var params = this.__TAGSPARAM;
		return (node && (tagN in params))?IX.Utils.loop(params[tagN], [], function(acc, item){
			acc[acc.length] = this["__"+ item[0]]((item[0]=="cvtToElem")?this.__$first(node, item[1]):node, item[1]);
			return acc;
		}.bind(this)):[] ;
	},
	__cvtToObject:function(node, tagN){ // simular with __cvtToElem;
		var cvt = function(xnode) {
			if(xnode==null){return null;}
			var attr= IX.Utils.loop(xnode.attributes, {}, function(acc, item){
				acc[item.nodeName] = item.nodeValue;
				return acc;
			});
			var childs = IX.Utils.loop(xnode.childNodes, {}, function(acc, item){
				var nv = [item.nodeName, item.nodeType, item.nodeValue];
				if (nv[0] !="#comment") {
					if (nv[1] != 3 && nv[1] != 4) {
						if (!(nv[0] in acc)){acc[nv[0]] = [];}
						acc[nv[0]].push(cvt(item));
					} else if (nv[2] && !nv[2].isSpaces()){
						var name = nv[1]==3?"_text":"_cdata";
						if (!(name  in acc)){ acc[name] = "";}
						acc[name] += nv[2];
					}
				}
				return acc;
			});
			return {_attrs:attr, _childs:childs};
		};
		return cvt(this.__$first(node, tagN));
	},
	__cvtToArray:function(node, tagN){
		if (node==null){return [];}
		var arr = [];
		var cnode = this.__$first(node, tagN);
		while(cnode!=null){
			var elem = this.__cvtToElem(cnode, tagN);
			if (elem.length>0) {arr[arr.length]=elem;}
			cnode = this.__$next(cnode, tagN);
		}
		return arr;
	}
},{ // handler to send to server
	__$model:function(node){return node._title.replaceAll("&lt;", "<").replaceAll("&gt;", ">").inPureTag("title")+ node._content.inPureTag("content");}
});

Wiki.SectionEditingParser = {
	__Parser_VIRTUAL_FUN:["getDoc"],

	__TITLE_EXAMPLE:'<h6 class="WIKI_section_title  WIKI_section_level_#LEVEL#" title="Title of section level #LEVEL#">#TITLE#</h6>',
	_isSection:function(node){
		return (node.nodeName.toLowerCase() == "h6") &&  IX.Utils.loop( node.attributes, false, function(acc, item){
			return acc || (item.nodeName.toLowerCase()=="class" && item.nodeValue.indexOf("WIKI_section_title")>=0)
		});
	},
	_getFirstSection:function(node){
		return IX.Utils.loop(node.childNodes, null, function(acc, item){
			return acc || (this._isSection(item)?item:this._getFirstSection(item));
		}.bind(this));
	},
	_keepPartOfDom:function(node, flag){ //flag  true-- the keep before first appears; false-- keep after first appears;
		var ntype= flag?"nextSibling":"previousSibling";
		var snode = this._getFirstSection(node);
		if (snode==null){return flag?node:null;}
		var pnode = snode;
		while(pnode!=node){
			var ppnode = pnode.parentNode;
			while(pnode[ntype]!=null){ppnode.removeChild(pnode[ntype]);}
			if(pnode==snode || pnode.firstChild==null){ppnode.removeChild(pnode);}
			pnode = ppnode;
		}
		return node;
	},
	_analytic:function(htmDoc){
		return IX.Utils.compact(IX.Utils.loop(htmDoc.childNodes,[], function(acc, item) {
			var node = item.cloneNode(true);
			while(true){
				var snode = this._getFirstSection(node);
				if (snode==null){break;}
				acc.push(this._keepPartOfDom(node.cloneNode(true), true));
				acc.push(snode.cloneNode(true));
				node = this._keepPartOfDom(node, false);
			}
			acc.push(node);
			return acc;
		}.bind(this)));
	},
	_createEdDiv:function(){return this.getDoc().createElement("DIV");},
	_getAllNodes:function(htmDoc) {
		var ed = this;
		var idx = 0;
		return IX.Utils.loop(ed._analytic(htmDoc), [], function(acc, item){
			if (ed._isSection(item)){
				if (!isEmpty(acc[idx])){idx+=1;}
				acc[idx]=item;
				idx+=1;
			}else{
				if (acc.length<=idx){acc[idx]="";}
				var div = ed._createEdDiv();
				div.appendChild(item);
				acc[idx] += div.innerHTML;
			}
			return acc;
		});
	},
	// return:[ [level, title, content],...]
	parseEditing:function(htmDoc){
		var nlist = [[-1, null, ""]];// [level, title, content]
		IX.Utils.loop(this._analytic(htmDoc), 0, function(acc, enode){
			var item = nlist[acc];
			if (!this._isSection(enode)){
				var div = this._createEdDiv();
				div.appendChild(enode);
				item[2] = (item[2]?item[2]:"") + div.innerHTML;
			} else {
				if(item[1]!=null || item[2] != "") {
					acc+=1;
					nlist[nlist.length] = [-1, null, ""];					
					item = nlist[acc];
				}
				var xlevel = enode.title.split(' ');
				item[0] = xlevel[xlevel.length-1];
				item[1]= isMSIE()?enode.innerText:enode.textContent;
			}
			return acc;
		}.bind(this));
		return nlist;
	},
	parseHTML:function(html){
		var div = this._createEdDiv();
		var fun = function(htm) {
			var txt = htm;
			var ptxt = "";
			var nidx = txt.indexOf("WIKI_section_title");
			while(nidx>0) {
				ptxt += txt.substring(0, nidx);
				txt = txt.substring(nidx);
				var kidx = txt.indexOf(">")+1;
				ptxt += txt.substring(0, kidx);
				txt = txt.substring(kidx);
				kidx = txt.toLowerCase().indexOf("</h6>");
				ptxt += txt.substring(0, kidx).replaceAll("<", "&lt;") + "</h6>";
				txt = txt.substring(kidx + 5);
				nidx = txt.indexOf("WIKI_section_title");
			}
			ptxt += txt;
			if (isMSIE()){// IE bug protection.
				var idx =  ptxt.toLowerCase().indexOf("<hr");
				if (idx > 0) {
					ptxt = ptxt.substring(0, idx) + "&nbsp;"+ ptxt.substring(idx);
				}
			}
			return ptxt;
		};
		div.innerHTML= fun(html);
		return this.parseEditing(div.cloneNode(true));
	},
	// in:[ [level, title, content],...]
	generateEditing:function(list){return IX.Utils.loop(list, "", function(acc, item){
		return acc+(item[0]==-1?item[2]: (this.__TITLE_EXAMPLE.loopReplace([["#LEVEL#", item[0]],["#TITLE#", item[1]]])+ item[2]));
	}.bind(this));},
	// node: instance of Wiki.Model.Section or Wiki.Model.Item;
	getSectionEdtingContent:function(node, dtype){
		var nlist = [];
		var fun = function(item){return item.isItem()?[-1, null, item.getContent()]:[item.getLevel(), item.getTitle(),item.getContent()];};
		if (dtype>=0) { // NEW
			var ls= [-1, 0, 0, 1];
			var nsec = Wiki.I18N.model.newSectionTemp;
			nlist[0] = [node.getLevel() - ls[dtype], nsec[0],nsec[1]];
		} else if (dtype==-1) { //EDIT			
			nlist[0] = fun(node);
		} else { // Edit All
			nlist = node[dtype==-2?"loopDeep":"loopAll"]((dtype==-2 && node.isItem())?[fun(node)]:[], function(acc, item){
				return IX.Utils.pushx(acc, fun(item));
			});
		}
		return this.generateEditing(nlist);
	}
};

Wiki.SDEPConverter = IX.Class.create();
Wiki.SDEPConverter.prototype = Object.inherit(Wiki.SDEP, Wiki.SectionEditingParser, {
	initialize:function() {},
	getDoc:function(){return document;},
	_convertSDEP2HTML:function(xml){
		var xmlDoc = IX.Xml.parser(xml);
		var wikiNode = xmlDoc.firstChild;
		//[id, title, content, version, pid, idx]
		var childDescArr = this.__cvtToArray(this.__$first(wikiNode, "sections"), "section");
		
		// [level, title, content, id, idx];
		var nodeList = [[-1, null, this.__$cdata(wikiNode, "content"), "root", -1]];
		var insToNodeList= function(pidx, level, node) {				
			var xnode = null;
			var nnode = [level, node[1], node[2],  node[0], node[5]];
			for(var i=pidx; i<nodeList.length; i+=1) {
				xnode = nodeList[i];
				if(level<xnode[0] || (level==xnode[0] &&node[5]<xnode[4])){break;}
				xnode = null;
			}
			if (xnode==null){nodeList.push(nnode);return;}
			for(var i=nodeList.length; i>0; i-=1) {
				nodeList[i] = nodeList[i-1];
				if (nodeList[i][3]==xnode[3]){
					nodeList[i-1] = nnode;
					break;
				}
			}
		};
		while(childDescArr.length>0) {
			var snode = childDescArr.shift();
			var pid = snode[4];
			if (pid==null || pid.length==0||pid==0 || pid.charAt(0)=='r'){
				insToNodeList(0, 1, snode);
				continue;
			}
			var isIns = false;
			for (var i=0; i<nodeList.length; i+=1){
				if(nodeList[i][3] == pid ){
					var level = nodeList[i][0]*1 +1;
					insToNodeList(i, level, snode);
					isIns = true;
					break;
				}
			}
			if(!isIns){childDescArr[childDescArr.length] = snode;}
		}
		return this.generateEditing(nodeList);
	},
	_convertHTML2SDEP:function(html){
		var  xmlbody = "";
		var list =  this.parseHTML(html);
		if (list==null || list.length==0){return "".inTag("wiki");}
		var section = list[0];
		if (section[0]==-1) {
			xmlbody += section[2].inPureTag("content");
			list.shift();
		}
		var sections = "";
		var idList = ["root"];
		idList.length =  6;
		IX.Utils.loop(list, [0],function(acc, item) {
			var level = acc.length+1;
			var idx = 0;
			if (level>item[0]) {
				level = item[0];
				acc.length = level;
				idx = acc[level-1];
			}
			acc[level-1] = idx*1+1;
			idList[level] = IX.Utils.UUID.generate();
			sections += (item[1].inPureTag("title") + item[2].inPureTag("content")).inTag("section", 
				[["id", idList[level]],["pid", idList[level-1]], ["idx", idx]]);
			return acc;
		});
		xmlbody += sections.inTag("sections");
		return xmlbody.inTag("wiki");
	},
	convert:function(type, data) {return this[(type=="xml")?"_convertSDEP2HTML":"_convertHTML2SDEP"](data);}
});

Wiki.IWrapper = {
	__Wrapper_VIRTUAL_FUN:["_resize"],
	getWikiImg:function(fname){return (isEmpty(_wiki_url)?"":(_wiki_url + "/")) + "images/"+ fname;},
	i18n:function(name){return wiki_i18n(name);},
	_initWrapper:function(qStr,keys){
		IX.Utils.loop(qStr.split("&"), this, function(acc, item){
			var param =item.split("=");
			var key = param.shift();
			if (key in keys){ acc["_"+key] = param.join("=");}
			return acc;
		});
		for (var key in keys) {
			if (!(("_" + key) in this)){this["_" + key] = keys[key];}
		}	
		this._resizeCount = 0;
	},
	resize:function(){
		var  rcnt =this._resizeCount;
		this._resizeCount = rcnt *1 + 1;
		setTimeout(function() {
			var count = this._resizeCount -1;
			if (count<=1){this._resize();}
			this._resizeCount = count>0?count:0;
		}.bind(this),10);
	}
};

Wiki.IEditable = Object.inherit(Wiki.SectionEditingParser, {
	_Editable_VIRTUAL_FUN:["pf", "i18n" ],
	_pf:function(key, params){return this.pf("editor."+key, params);},
	_i18n:function(key){return this.i18n("editor."+key);},

	__getConfig:function(){return Wiki.Config;},
	__getEditorBase:function(){return Wiki.Config.editorbase;},
	__getEd:function(flag){
		var nid = 'editor_content_'+ this._id;
		var node = $X('wiki_'+ nid);
		if (!node){return $Frame(nid).Wiki.EditorWrapper[flag?"getEditNodeList":"getEditContent"]();}
		var v = node.value.unhtml();
		return flag?[v]:v;
	},
	__renderEdit:function(node){
		var conf =this.__getConfig();
		node.ifHtmlEdit = this._ifHtml;
		var eurlP = "id="+node.getId()+"&height="+ this._height + "&lang="+ conf.lang + ((node.isSection() || node.ifTidx)?("&tidx="+node.getTidxForce()):"");
		var body= this._pf("content",[this._id,  this.__getEditorBase() + "?"+ eurlP + "&t=" + (new Date()).getTime()]);
		return this._pf("edit",[this._id,this._height, body]);
	},
	_renderEdit:function(){
		var node =this._model;
		if(this._ifEditingSection){
			var nnode = node.getRoot().find("unknown");
			nnode.save("", this.getSectionEdtingContent(node, this._dtype));
			nnode.setTidxForce(node.getEdTidx(this._dtype));
			nnode.ifTidx = true;
			node = nnode;
		}
		return this._isReadOnly?node.getContent():this.__renderEdit(node, true);
	},
	__renderPreview:function(){
		if (!this._ifEditingSection){return this.getEditContent();}
		var pn = this._model;
		if (this._dtype==2 || this._dtype==0){pn = pn.getLastNode();}
		else if (this._dtype!=-2){pn = pn.getPrevSeqNode();}
		var tidxArr = (pn && pn.getLevel()>0)?pn.getTidxForce().split("."):[];		
		return  this.generateEditing(IX.Utils.loop(this.getEditNodeList(), [], function(acc, item){
			var level = item[0];
			var title = item[1];
			var content = (item[2]==null)?"":item[2];
			if(level>0){
				if(title==null) {title = Wiki.I18N.get("model."+(tidxArr.length==0?"first":"new") +"SectionTemp.0");}
				level = (level>tidxArr.length?(tidxArr.length+1):level);
				var idx = level>tidxArr.length?0:tidxArr[level-1];
				tidxArr[level-1] =idx*1 +1;
				tidxArr.length = level;
				title = "Section&nbsp;"+ tidxArr.join(".")+":&nbsp;"+title;
			} else {
				content =this.pf("item.content",["",this.pf("item.tr", [this.i18n("item.summary"), content]), ""]);
			}
			acc.push([level, title, content]);
			return acc;
		}.bind(this)));
	},
	_renderPreview:function(){return this._pf("preview", [this.__renderPreview()]);},
	setHeight:function(h, ifResize){
		this._height = h;
		if (ifResize){
			var nid = 'editor_content_'+ this._id;
			if (!$X('wiki_'+ nid) && $X("editor_" + this._id)){
				$X("editor_" + this._id).style.height = h +"px";
				 document.getElementsByName(nid)[0].style.height = h +"px";
				 $Frame(nid).Wiki.EditorWrapper.setHeight(h, true);
			}
		}
	},
	// dtype: 0~3: new as node's ...;-3: self and all sub-sections; -2: all sub-sections; -1: only self;
	_initEditor:function(node, dtype){ 
		this._model = node;		
		this._dtype =dtype; //used only when editing section
		this._height = 230;

		this._ifEditingSection = false;
		this._ifHtml = true;	
		this._ifPreview = false;
		this._isReadOnly = false;
	}
},{
	isEditorActive:function(){return $X("editor_"+this._id)!=null;},
	getEditNodeList:function(){return  this.__getEd(true);	},
	getEditContent:function() {return this.__getEd(false);},

	setIfEditingSection:function(flag){this._ifEditingSection = flag;},
	setIfPreview:function(flag){this._ifPreview = flag;},
	setDtype:function(dtype){this._dtype = dtype;},
	setReadOnly:function(flag){this._isReadOnly = flag;},

	renderBody:function(ifPreview){return this["_render"+ (!ifPreview?"Edit":"Preview")]();},
	render:function(){return this._pf("tmpl",[this._id, this.renderBody(this._ifPreview)]);},
	refresh:function() {this._refresh($X("wiki_"+this._id), this.renderBody(this._ifPreview));}
});

Wiki.IDialogBase = {
	__Dialog_VIRTUAL_FUN:["_pf", "_i18n"],
	__NewSection:0,
	__MoveSection:1,
	__EditSection:2,
	__DeleteSection:3,
	__AddAttach:4,
	__PostComment:5,
	__ReplyComment:6,
	__EditComment:7,
	__EditAllSections:8,
	__EditSummary:9,
	__EditTopic:10,
	__EditExtTopic:11,
	__EditExtTags:12,


	__MAX:13,
	__MethodList:["New","Move", "Edit", "Delete", "Attach", "Post" ,"Reply", "EditCmt", "EditAll", "EditSummary", "EditTopic", "EditExtTopic", "EditTags"],
	__FunList: ["saveNew","moveto","saveEdit", "realDelete","addAttached","saveNewComment", "saveReplyComment", "afterEditComment", "saveAll", "saveSummary", "saveTopic", "saveExtTopic", "saveTags"],

	_getMType:function(method){return IX.Utils.loop(this.__MethodList, -1, function(acc, item, idx) {return acc>=0?acc:(method==item?idx:-1);});},
	_getMName:function(mtype){return this.__MethodList[mtype>0?mtype:0];},
	_getMFun:function(mtype){return this.__FunList[mtype>0?mtype:0];}	
};

Wiki.IDialogPlugin = Object.inherit(Wiki.IDialogBase, {
	__Dialog_Plugin_VIRTUAL_FUN:["renderContent", "renderButtons", "_init_extra"],

	setHeight:function(h, ifResize){
		var offH = {1:135, 3:125, 4:140, 5:115, 6:135, 7:115, 9:120, 0:130, 2:80, 8:120, 10:140, 11:40, 12:40};
		this._aux.setHeight(h - offH[this._mtype], ifResize);
	},
	_renderContent:function(pfsList){return IX.Utils.loop(pfsList, "", function(acc, item){return acc + this._pf("info", [item]);}.bind(this));},
	_renderBtns:function(btns, ifAddCancel){ //btns:[[name,namedBtnFun],...]
		var dp = this;
		if (ifAddCancel){btns.push(["cancel", "closeDialog"]);}
		return IX.Utils.loop(btns, [], function(acc, item){
			return IX.Utils.pushx(acc, dp._pf("btn", [dp.__genFunStr(item[1]), dp._nid, dp.i18n_op(item[0])]));
		}).join(dp._pf("btnsep"));
	},
	_renderRS:function(wh) {
		var t = this._mtype;
		var nlevel = this._node.getLevel();
		var rsItems= [["below", 2], ["above",1], ["child",0], ["parent",3]];
		if (nlevel<2 && t==0){
			var arrS=(nlevel==0?[2,3]:[0,3]);
			rsItems=rsItems.slice(arrS[0],arrS[1]);
		}
		return IX.Utils.loop(rsItems, "", function(acc, item){
			var param= (t==0)?["rsOpts", "selected"]:["rsRadio", "checked"];
			return acc + this._pf(param[0], [item[1], (item[1]==wh)?param[1]:"",this._i18n(item[0]+"RS")]);
		}.bind(this));
	},
	_renderXitt:function(tname, txt){
		var titles=["cur","normal","tag","reply", "topic", "exttopic"];
		var tids = ["target", "edit_title", "edit_exttopic"];
		var xparams = {TGT_SITT:[0,0,true, 60], TTL_ITT:[1,1,false,100], TAG_ITT:[2,0,false,80], 
			TGT_ITT:[3,0,true,100], Disabled_TTL_ITT:[1,1,true,100],
			TPC_ITT:[4, 0, false, 40], ETP_ITT:[5,2, false, 80]
		};
		var params = xparams[tname];
		return this._pf("itt", [
			this._pf("name",[this._i18n(titles[params[0]]+"ITTName")]), 
			tids[params[1]], 
			'value="'+(txt?txt.replaceAll('"', '&quot;'):"") +'"' + (params[2]?" disabled":"") +" size="+params[3]
		]);
	},
	_ittValue:function(partId){return $X(this._id+"_"+ partId).value;},

	renderTitle:function() {return this._i18n("d"+this._method+"Title");},
	_extraPreChecker:function(){return true;},
	_extraPostChecker:function(){return true;},
	_init_extra:function(model){},
	initialize:function(did, mtype, model, nodeId){
		this._mtype= mtype;
		this._method = this._getMName(this._mtype);
		
		this._id = did;
		this._nid = nodeId;
		this._node = model.find(nodeId);

		this._init_extra(model);
	}
});
Wiki.IDP_Input= Object.inherit(Wiki.IDialogPlugin, {
	//__EditTopic:10,
	//__EditExtTopic:11,
	//__EditTags:12,
	__checkLength:function(value, mtype) {
		var mlen = mtype==12?50:100;
		if (!IX.Utils.loop(mtype==10?[value]:value.split(","),  true, function(acc, item) {return acc && item.trim().length<mlen;})) {
			alert("Each of "+ (mtype==12?"tag":"topic") +" can't exceed the length limitation(" + mlen +" characters).");
			return false;
		}
		return true;
	},
	_extraPostChecker:function(){
		var value=this.getInput();
		if (!this.__checkLength(value, this._mtype) ) {return false;}
		if (this._mtype==10) {
			//if (!this.__checkLength(this.getExtTopic(), 11) ) {return false;}
			if (value.length>0 && value.indexOf(",")>=0) {
				alert("Can't input comma as part of primary topic. Please remove it.");
				return false;
			}
			if (value.indexOf(' ')>=0){
				return window.confirm("Blank is not allowed for a topic ID. System will auto replace it with '_'. \nDo you want to continue?");
			}
		}
		return true;
	},
	_renderTopicsList:function() {
		return 	this._node.loopExtTopics("", function(acc, item, idx){
			return acc + this._pf("exttopiclistitem", [item[0], item[1], this.__genFunStr("chkDlgTopic"), this._id, idx]);
		}.bind(this));
	},
	renderContent:function() {
		var node = this._node;
		var info =  '&nbsp;&nbsp;<i>('+  this._i18n("tagTitleInfo") + ')</i>';
		var pfs= [];
		if (this._mtype==12) {
			pfs.push(this._renderXitt("TAG_ITT", node.getTags().join(",")) + info);
		} else {
			//pfs.push(this._renderXitt("TPC_ITT", node.getTopic()).inTag("span", [["style", "float:left;display:inline-block;"]])+ this._renderBtns([["ok", this._getMFun(this._mtype)]], true).inTag("span", [["style","float:right;"]]));
			//pfs.push(this._renderXitt("ETP_ITT", node.getExtTopic()) + info);
			{
				var fun = function(n){return this._pf("name",[this._i18n(n + "ITTName")]);}.bind(this); 	
				
				var  htm = this._pf("exttopiclist", ["Topic", "Mapped Section", this._renderTopicsList(), this._id]);
				htm = this._pf("exttopic", [fun("topic"),
					this._pf("topicitt",[node.getTopic().replaceAll('"', '&quot;'), this._id, this._renderBtns([["ok", this._getMFun(this._mtype)]], true)]),
					fun("exttopic"), htm]); 
				pfs.push(htm);
			}
		}
		return this._renderContent(pfs);
	},
	renderButtons:function() {
		if (this._mtype== 10) {
			return this._renderBtns([["addTopic", "addExtTopic"], ["editTopic", "editExtTopic"], ["removeTopic",  "removeExtTopic"]], false);
		}
		return this._renderBtns([["ok", this._getMFun(this._mtype)]], true);
	},
	getInput:function(){return this._ittValue("target");},
		
	chkTopic:function(topicId){
		var node = $X(this._id + "_" + topicId + "_check");
		if (node){
			var flag = node.checked;
			node.checked = !flag;
			node.parentNode.parentNode.style.backgroundColor= flag?"white":"#ADADAD";
		}
	},
	getFirstCheckedTopicInfo:function() {
		return this._node.loopExtTopics(null, function(acc, item, idx){
			return acc?acc:($X(this._id + "_" + idx + "_check").checked?[idx, item[0], item[1]]:null);
		}.bind(this));
	},
	getAllCheckedTopicInfo:function() {
		return this._node.loopExtTopics([], function(acc, item, idx){
			if ($X(this._id + "_" + idx + "_check").checked) {
				acc.push([idx, item[0], item[1]]);
			}
			return acc;
		}.bind(this));
	},
	refreshTopics:function() {this._refresh($X(this._id + "_topiclist"),this._renderTopicsList().inTag("table"));}
	//getExtTopic:function(){return this._ittValue("edit_exttopic");}
});


Wiki.IDP_List= Object.inherit(Wiki.IDialogPlugin, {
	//__MoveSection:1,
	//__DeleteSection:3,

	renderContent:function() {
		var pfs= [];
		var node = this._node;
		pfs.push(this._i18n(this._method.toLowerCase()+"DstInfo").replace("#0#", node.getTidxForce() + "&nbsp;"+node.getTitle()));
		pfs.push(this._aux.render());
		if (this._mtype == this.__MoveSection) {pfs.push(this._pf("moveDst", [this._i18n("moveRSTitle"), this._renderRS(0)]));}
		else {pfs.push(this._i18n("deleteQstInfo"));}
		return this._renderContent(pfs);
	},
	renderButtons:function() {return this._renderBtns([["ok", this._getMFun(this._mtype)]], true);},
	getDtype:function(){
		for (var i=0; i<4; i+=1){if ($X(this._id + "_rs_" + i).checked){return i;}}
		return 0;
	},
	getDstId:function(){return this._aux.getSelected();},
	select:function(nodeId){return this._aux.select(nodeId);}
});

Wiki.IDP_Edit = Object.inherit(Wiki.IDialogPlugin, {
	//__AddAttach:4,
	//__PostComment:5,
	//__ReplyComment:6,
	//__EditComment:7,
	//__EditSummary:9
	_extraPostChecker:function(){
		if( this._mtype==4) {
			var value = this.getContent();
			if (value.trim().length==0) {
				alert("The description of attachment can't be empty or composed by blank space. Please input something.");
				return false;
			}
		} else if (this._mtype!=9) {
			var title = this.getTitle();
			if (title.length>200) {
				alert("Title is too long (>200 letters). Please make it short.");
				return false;
			}
			if (title.trim().length==0){
				alert("Title must not be empty or composed by blank space when posting/editing comment. Please input something.");
				return false;
			}
		}
		return true;
	},
	getEditingContent:function(){
		return (this._mtype==this.__EditSummary||this._mtype==this.__EditComment)?this._node.getContent():"";
	},
	renderContent:function() {
		var pfs= [];
		var node = this._node;

		var ntitle =node.getTitle();
		if (this._mtype==this.__ReplyComment) {
			pfs.push(this["_renderXitt"]("TGT_ITT",ntitle));
			ntitle = "RE: " + ntitle;
		}
		var xtitle = (this._mtype==this.__AddAttach||this._mtype==this.__PostComment)?"":ntitle;
		pfs.push(this._renderXitt(this._isReadOnly?"Disabled_TTL_ITT":"TTL_ITT",xtitle));

		if (this._mtype==this.__AddAttach){
 			pfs.push(this._pf("spline"));
			pfs.push(this._pf("attachCmt", ["", this._id, this._aux._height]));
			pfs.push(this._pf("attachFile",[(this._i18n("attachName")+": ").inTag("span", [["style","float:left;font-weight:bold;margin-right:10px;"]]), this._param]));
		} else {
			pfs.push(this._aux.renderBody(false));
		}
		return this._renderContent(pfs);
	},
	renderButtons:function() {return this._renderBtns([["ok", this._isReadOnly?"closeDialog":this._getMFun(this._mtype)]], true);},
	setParam:function(param){this._param = param;},
	
	getTitle:function(){return this._ittValue("edit_title");},
	getContent:function(){return this._mtype==this.__AddAttach?this._ittValue("comment"):this._aux.getEditContent();}
});

Wiki.IDP_EditSection = Object.inherit(Wiki.IDialogPlugin, {
	//__NewSection:0,
	//__EditSection:2,
	//__EditAllSections:8,
	_renderEditing:function(){
		var pfs= [];
		var node = this._node;
		if (this._mtype==this.__NewSection){
			pfs.push(this._pf("newDst", [this._i18n("newRSTitle"), this._renderRS( this._dtype), this._renderXitt("TGT_SITT", this._node.getTitle())]));
			pfs.push(this._pf("spline"));
		}
		if (this._mtype==8) {
			pfs.push(this._renderXitt(this._isReadOnly?"Disabled_TTL_ITT":"TTL_ITT",node.getTitle()));
		}
		pfs.push(this._aux.renderBody(false));
		return this._renderContent(pfs);
	},
	_renderPreview:function(){return this._aux.renderBody(true);},
	renderTitle:function() {return this._i18n("d"+(this._ifPreview?"Preview":this._method)+"Title");},
	renderContent:function() {return this[this._ifPreview?"_renderPreview":"_renderEditing"]();},
	renderButtons:function() {
		var btns = [["ok", this._getMFun(this._mtype)]];
		if (Wiki.Config.ifPreview) {
			btns.push(this._ifPreview?["back2edit","cancelPreview"]:["preview","preview"]);
		}
		return this._renderBtns(btns,!this._ifPreview);
	},
	setIfPreview:function(flag){this._ifPreview = flag;},
	setDtype:function(dtype){
		dtype = (dtype>0 && (this._node.isItem() ||(this._node.getLevel()==1 && dtype==3))) ?0:dtype;
		this._dtype = dtype;
		this._aux.setDtype(dtype);
	},

	__getConfig:function(){return Wiki.Config;},

	__oversizeI18N:function(key, clen){
		var maxSize = this.__getConfig().max_edit_size + "";
		return this._i18n(key).replace("#0#", maxSize).replace("#1#",  cvtToKMG(clen, maxSize.substring(maxSize.length-2)));
	},
	getEditingContent:function(){return this._aux.getSectionEdtingContent(this._node, this._dtype);},
	_extraPreChecker:function(){
		return !(this.getEditingContent().length > this.__getConfig().maxSizeofEditing && !confirm(this.__oversizeI18N("tryToEditOversized",0)));
	},
	_extraPostChecker:function(){
		var content = this._aux.getEditContent();
		var clen = content.length;
		var flag = (clen >this.__getConfig().maxSizeofEditing);
		if (flag){alert(this.__oversizeI18N("editOversized", clen));}
		return !flag;
	},
	
	getTitle:function(){return this._ittValue("edit_title");},
	getContent:function(){return this._aux.getEditContent();},
	getDtype:function(){
		if (this._mtype==0){
			var xnode =$X(this._id + "_rs");
			return xnode.options[xnode.selectedIndex].value;
		}
		return 0;
	}
});

Wiki.IDialog = Object.inherit(Wiki.IDialogBase, {
	__Plugins:["EditSection", "List", "EditSection", "List", "Edit", "Edit", "Edit", "Edit", "EditSection", "Edit", "Input", "Input", "Input"],
	_callFun:function(fname, param){
		var pview = this._pView;
		return (pview && (fname in pview) && isFunction(pview[fname]))?pview[fname](param):"";
	},
	checkEditing:function(type){return this._pView["_extra" + type + "Checker"]();},
	_getPlugin:function(t, nodeId, param) {
		var ptype = this.__Plugins[t];
		var pview = new Wiki.View["DP_"+ ptype](this._id, t, this._model, nodeId);
		if (ptype=="EditSection"){pview.setDtype(param);}
		else if (ptype=="Edit"){pview.setParam(param);}
		return pview;
	}
});

Wiki.IDialogView = Object.inherit(Wiki.IDialog, {
	__DialogView_VIRTUAL_FUN:["_render", "_refeshTitle", "_resize"],
	
	__render:function(){return this._pf("body",[this._callFun("renderButtons"), this._callFun("renderContent"), this._id]);},
	_doPreview:function(ifPreview){IX.Utils.loop([false, true], 0, function(acc, item, idx){
		this._display(ifPreview==item?this._preview:this._win, item);
	}.bind(this));},
	_showDialog:function(pStat){
		if (!this.checkEditing(pStat?"Post":"Pre")) {return false;}
		this._callFun("setIfPreview", pStat);
		this._refresh(pStat?this._preview:this._win, this._render());
		this._refeshTitle(pStat);
		this._doPreview(pStat);		
		return true;
	},
	_open:function(){return this._showDialog(false);},
	preview:function(nodeId){return this._showDialog(true);},
	cancelPreview:function(){this._doPreview(false);},	
	open:function(method, nodeId, param){
		var t= this._getMType(method);		
		if (t<0){return alert(this._i18n("unknownType"));}
		this._mtype = t;	
		this._pView =this._getPlugin(t, nodeId, param);
		this.setHeight();	
		this._open();
		this.show();
		return true;
	},
	close:function(){this._mtype=-1;this._pView = null; this.hide();},
	_init_DialogView:function(model, dialogId, maskId){
		this._model=model;
		this._initDialog(dialogId, maskId);
		this._previewId = this._id+"_preview";
		this._preview = this._getDiv(this._layer,this.__getCSS(), this._previewId);
	}
},{
	getTitle:function(){return this._callFun("getTitle");},
	getContent:function(){return this._callFun("getContent");},	
	getDstId:function(){return this._callFun("getDstId");},
	getDtype:function(){return this._callFun("getDtype");},
	getInput:function(){return this._callFun("getInput");},
	//getExtTopic:function(){return this._callFun("getExtTopic");},
	getFirstCheckedTopicInfo:function(){return this._callFun("getFirstCheckedTopicInfo");},
	getAllCheckedTopicInfo:function(){return this._callFun("getAllCheckedTopicInfo");},
	refreshTopics:function() {return this._callFun("refreshTopics");},
	selectItem:function(nodeId){this._callFun("select", nodeId);},
	chkDlgTopicItem:function(topicId){this._callFun("chkTopic", topicId);},
	resetId:function(oldId, newId){this._win.innerHTML = this._win.innerHTML.replaceAll(oldId, newId);}
});

Wiki.IMovableBar = {
	__VBAR:0,
	__HBAR:1,

	_initBar:function(barId, type, posFun, moveFun) {
		this._id = barId;
		this._type = type;
		var bar = $X(barId);
		var startPos = 0;
		var startMove  = false;
		var regFun= function(name, ifReg) {document.body["onmouse"+name] = funList[ifReg?name:"empty"];};
		var setCursor=function(c){document.body.style.cursor=c;};
		var getPos = function(evt){return type==0?evt.clientX:evt.clientY;};
		var funList = {down:function(evt){
			if(!evt){evt = window.event;}
			//alert( evt.clientX+":" + evt.clientY);
			startMove = true;
			setCursor((type==0?"e":"n")+"-resize");
			startPos = posFun() - getPos(evt);
			log("down:" + startPos +" ="  +posFun() + "-" +  getPos(evt) + "...."+  (type==0?evt.clientX:evt.clientY));
			regFun("move", true);
			regFun("up", true);
		}, move:function(evt){
			if(!evt){evt = window.event;}
			//log("move:" + getPos(evt));
			moveFun(startPos + getPos(evt));
		},up:function(){
			log("up:");
			startMove = false;
			setCursor("default");
			regFun("move", false);
			regFun("up", false);
		}, empty:function(){}};
		bar.onmousedown=funList.down;
	}
};

Wiki.HBarView = IX.Class.create();
Wiki.HBarView.prototype= Object.inherit(Wiki.IMovableBar, {
	initialize:function(barId, posFun, moveFun){
		this._initBar(barId, 1, posFun, moveFun);
	}
});
Wiki.StopEvent = function(evt){
	if (window.event){
		event.cancelBubble = true;
		event.returnValue = false;
	}else {
		evt.cancelBubble = true;
		evt.returnValue = false;
	}	
	return false;
}
Wiki.RightClick = function(evt, fun) {
	if(!fun){return true;}	
	if (!evt) {evt=window.event;}
	var btn = evt[("which" in evt)?"which":"button"];	
	if (btn == 2 || btn == 3){
		Wiki.StopEvent(evt);
		fun(evt);
		return false;
	}
	return true;
};
//document.oncontextmenu = Wiki.StopEvent;
//document.onmousedown = function(evt){Wiki.RightClick(evt, null);};

