/**
* form 优化类，其他代码不要放入
* select 必须指定id，id和name的值要一样
*/
var currentShowSelectList;
Jade.Form = {
	doBeautySelect: function (dom) {
		/**
		* 美化下拉框
		*/
		var sels = Easy.Array.toArray(dom.getElementsByTagName("select"));
		Easy.each(sels, function (s, i) {
			Jade.Form.beautySelect(s);
		});
	},
	doBeautyInput: function (dom) {
		var inps = Easy.Array.toArray(dom.getElementsByTagName("input"));
		Easy.each(inps, function (ip, i) {
			if (!Jade.Form.readonly) {
				var xtype = Easy.DOM.getAttribute(ip, "xtype");
				if (xtype) {
					switch (xtype) {
						case "file":
							var createFile = function () {
								var f = Easy.DOM.create({
									tag: 'input',
									type: 'file',
									cls: 'file',
									name: 'f' + ip.name
								});
								Easy.DOM.insertAfter(f, ip);
								Easy.on(f, "change", function (p) {
									var ext = p.value.substring(p.value.lastIndexOf(".") + 1);
									if (Easy.Array.has(Jade.allowExtension, ext)) {
										ip.value = p.value;
										Jade.V.valid(ip);
									} else {
										Jade.Msg.warn("您上传的文件类型不支持,请重新选择!", function () {
											Easy.removeNode(p);
											createFile();
										});
									}
								});
							}
							Easy.DOM.addClass(ip, "txtfile");
							createFile();
							break;
						case "n":
							Easy.DOM.on(ip, "keypress", function (p, e) {
								var t = String.fromCharCode(e.keyCode);
								if (!/[\-\+\.\d]/mg.test(t)) {
									e.preventDefault();
									return false;
								}
							});
							break;
						case "date":
							Easy.on(ip, "focus", function (p, e) {
								var md = Easy.DOM.getAttribute(p, "maxdate");
								var mid = Easy.DOM.getAttribute(p, "mindate");
								var op = {
									dateFmt: Easy.DOM.getAttribute(p, "format") || "yyyy-MM-dd",
									onpicked: function () {
										Jade.V.valid(p, null, 1);
									}
								};
								if (md) {
									op.maxDate = md;
								}
								if (mid) {
									op.minDate = mid;
								}
								WdatePicker(op);
							})
							break;
						case "auto":
							var cn = Easy.DOM.getAttribute(ip, "classname");
							var mn = Easy.DOM.getAttribute(ip, "methodname");
							Easy.DOM.setAttribute(ip, "autocomplete", "off");
							Easy.DOM.create({
								tag: 'div',
								cls: 'wrap autowrap',
								id: 'w' + ip.name,
								style: 'display:none;'
							}, Easy.DOM.getParent(ip));
							Easy.on(ip, "keyup", function (p, e) {
								if (p.value) {
									var param = Easy.String.parseQueryString(Easy.DOM.getAttribute(ip, "params")) || {};
									Jade.ajax(cn, mn, Easy.apply({ key: p.value }, param), function (d) {
										Jade.Form.showAutoWrap(d, p);
									});
								} else {
									var hideid = Easy.DOM.getAttribute(p, "hideid");
									if (hideid) {
										Easy.get(hideid).value = "";
									}
								}
							});
							Easy.on(ip, "blur", function (p, e) {
								if (p.value) {
									var hideid = Easy.DOM.getAttribute(p, "hideid");
									if (hideid) {
										var hd = Easy.get(hideid);
									}
								}
							});
							break;
						case "tree":
							var w = Easy.DOM.getParent(ip), name = ip.name, id = ip.id;
							ip.name = "t" + name, ip.id = "t" + id;
							var defaultValue = "";
							var input = Easy.DOM.create({
								tag: 'input',
								type: 'hidden',
								name: name,
								id: name
							}, w), closeb = Easy.DOM.create({
								tag: 'a',
								href: 'javascript:;',
								cls: 'toggle'
							}, w), list = Easy.DOM.create({
								tag: 'div',
								cls: 'wrap',
								id: 'w' + name,
								style: { 'display': 'none', 'max-height': '145px', 'overflow': 'auto' }
							}, w);

							Easy.DOM.setAttributes(ip, { binded: true });
							var onc = Easy.DOM.getAttribute(ip, "onchange");
							var cn = Easy.DOM.getAttribute(ip, "classname");
							var mn = Easy.DOM.getAttribute(ip, "methodname");
							var param = Easy.String.parseQueryString(Easy.DOM.getAttribute(ip, "params"));
							var slmdl = Easy.DOM.getAttribute(ip, "selectModel");
							var multi = !!Easy.DOM.getAttribute(ip, "multi");
							var loaded = Easy.DOM.getAttribute(ip, "loaded");
							var tree = new Easy.tree.Panel({
								renderTo: list,
								id: name + '_tree',
								singleSelect: !multi,
								selectModel: slmdl || "leaf",
								loader: {
									url: Jade.url,
									params: Easy.applyIf({
										classname: cn.replace(/\+/g, "Server"),
										methodname: mn
									}, (param || {}))
								},
								listeners: {
									click: function (node) {
										var txt = [], val = [];
										if (multi) {
											var txt = [], val = [];
											Easy.each(this.selectedNodes, function (n, i) {
												var vid = n.id.replace(tree.id + "_node_", "");
												if (!Easy.Array.has(val, vid) && n.checkBox.checked) {
													txt.push(n.text);
													val.push(vid);
												}
											});
											txt = txt.join(',');
											val = val.join(',');
										} else {
											txt = node.text;
											val = node.id.replace(tree.id + "_node_", "");
											if (currentShowSelectList) {
												Easy.DOM.hide(currentShowSelectList);
											}
										}
										ip.value = txt;
										input.value = val;
										Jade.V.valid(ip, null, 1);
										if (onc) {
											Easy.decode(onc)(ip, val, txt);
										}
									},
									load: function () {
										if (Easy.get(id).value) {
											input.value = ip.value;
											ip.value = defaultValue;
										}
										if (loaded) {
											var fn = Easy.decode(loaded);
											if (Easy.isFunction(fn)) {
												fn(this.root, id);
											}
										}
										if (!Jade.Form.readonly) {
											Easy.on(ip, "focus", function (p, e) {
												if (currentShowSelectList) {
													Easy.DOM.hide(currentShowSelectList);
												}
												Easy.DOM.show(list);
												currentShowSelectList = list;
											});
											Easy.on(closeb, "click", function (p, e) {
												if (currentShowSelectList) {
													Easy.DOM.hide(currentShowSelectList);
												}
												Easy.DOM.show(list);
												currentShowSelectList = list;
											});
										}
									}
								}
							});
							break;
						case "region":
							var onc = Easy.DOM.getAttribute(ip, "onchange");
							new Jade.Region(ip, function (a, c, p) {
								var rl = true;
								if (onc) {
									rl = onc(a, c, p);
								}

								if (rl == true) {
									var hidid = Easy.DOM.getAttribute(ip, "hideid");
									if (hidid) {
										Easy.get(hidid).value = a.id;
										Jade.V.valid(Easy.get(hidid), null, 1, ip);
									}
								}

							});
							Easy.DOM.addClass(ip, "local");
							break;
						default:
					}
				}
			} else {
				Easy.DOM.setAttributes(ip, { "readonly": true })
			}
		});
	},
	doBeautyArea: function (dom) {
		/**
		* 初始化编辑器
		*/
		var txtas = Easy.Array.toArray(dom.getElementsByTagName("textarea"));
		Easy.each(txtas, function (t, i) {
			if (!Jade.Form.readonly) {
				var xtp = Easy.DOM.getAttribute(t, "xtype");
				var ued;
				if (xtp) {
					if (xtp == "ues") {
						ued = UM.getEditor(t.id, {
							initialFrameWidth: Easy.DOM.getWidth(t),
							initialFrameHeight: Easy.DOM.getHeight(t),
							lang: 'zh-cn',
							langPath: UMEDITOR_CONFIG.UMEDITOR_HOME_URL + "lang/",
							focus: true,
							toolbar: [
                            'source | undo redo | bold italic underline strikethrough | superscript subscript | forecolor backcolor | removeformat |',
							'insertorderedlist insertunorderedlist | selectall cleardoc paragraph | fontfamily fontsize',
							'| justifyleft justifycenter justifyright justifyjustify |', "image insertvideo", '| preview fullscreen']
						});
					} else {
						ued = UM.getEditor(t.id, {
							initialFrameWidth: Easy.DOM.getWidth(t),
							initialFrameHeight: Easy.DOM.getHeight(t),
							lang: 'zh-cn',
							langPath: UMEDITOR_CONFIG.UMEDITOR_HOME_URL + "lang/",
							focus: true
						});
					}
					if (ued) {
						ued.ready(function () {
							ued.setContent(t.value);
						});
					}
				}
			} else {
				Easy.DOM.setAttributes(t, { "readonly": true })
			}
		});
	},
	readonly: false,
	resetSelect: function (el) {
		var isb = Easy.DOM.getAttribute(el, "binded"), name = el.name;
		if (isb) {
			var w = Easy.get("w" + name);
			var t = Easy.get("t" + name);
			var tg = Easy.DOM.getNext(t, "a");
			if (w) {
				Easy.removeNode(w);
				Easy.removeNode(t);
				Easy.removeNode(tg);
				Easy.DOM.show(el);
				Easy.DOM.removeAttribute(el, "binded");
			}
		}
	},
	beautySelect: function (s) {
		var isb = Easy.DOM.getAttribute(s, "binded");
		var isdisabled = Easy.DOM.getAttribute(s, "disabled");
		var bind = function (sl, lw) {
			var ar = [];
			var onc = Easy.DOM.getAttribute(sl, "onchange");
			Easy.each(sl.options, function (o, i) {
				ar.push("<li class='" + (i % 2 == 0 ? "a" : "b") + "'><a href='javascript:;' data-value='"
                        + o.value + "' onclick=\"Jade.Form.selectItem(this,'" + s.name + "',event,'" + onc + "');\">" + o.text + "</a></li>");
			});
			if (lw) {
				lw.innerHTML = "<ul>" + ar.join("") + "</ul>";
				var h = Easy.DOM.getAttribute(s, "maxheight") || "130";
				var mh = parseInt((h.replace("px", "") - 0) / 26);
				if (ar.length > mh) {
					Easy.DOM.setStyle(lw, {
						height: h,
						overflow: "auto"
					});
				}
			}
			var defaultValue = "";
			if (sl.value) {
				defaultValue = Jade.getSelectText(s);
			}
			if (defaultValue && Easy.get("t" + sl.name)) {
				Easy.get("t" + sl.name).value = defaultValue;
			}
		}
		if (!isb) {
			var w = Easy.DOM.getParent(s);
			var iid = "t" + s.name;
			var input = Easy.DOM.create({
				tag: 'input',
				type: 'text',
				name: iid,
				id: iid,
				placeholder: Easy.DOM.getAttribute(s, "placeholder"),
				readonly: "readonly"
			}, w), closeb = Easy.DOM.create({
				tag: 'a',
				href: 'javascript:;',
				cls: 'toggle'
			}, w), list = Easy.DOM.create({
				tag: 'div',
				cls: 'wrap',
				id: 'w' + s.name,
				style: 'display:none;'
			}, w);
			Easy.DOM.setAttributes(s, { binded: true });
			bind(s, list);
			if (!isdisabled && Jade.Form.readonly === false) {
				Easy.on(input, "focus", function (p, e) {
					if (!Easy.DOM.getAttribute(s, "readonly")) {
						if (currentShowSelectList) {
							Easy.DOM.hide(currentShowSelectList);
						}
						Easy.DOM.show(list);
						currentShowSelectList = list;
					}
				});
				Easy.on(closeb, "click", function (p, e) {
					if (!Easy.DOM.getAttribute(s, "readonly")) {
						if (currentShowSelectList) {
							Easy.DOM.hide(currentShowSelectList);
						}
						Easy.DOM.show(list);
						currentShowSelectList = list;
					}
				});
			} else {
				Easy.DOM.hide(closeb);
				Easy.DOM.setAttributes(input, { disabled: true });
			}
		} else {
			var list = Easy.get('w' + s.name)
			bind(s, list);
		}
	},
	selectItem: function (dom, name, ev, cb) {
		var v = Easy.DOM.getAttribute(dom, "data-value");
		Easy.get("t" + name).value = dom.innerHTML;
		Easy.get(name).value = v;
		var list = Easy.get("w" + name);
		Easy.DOM.hide(list);
		currentShowSelectList = null;
		if (cb) {
			Easy.tryDo(function () {
				Easy.decode(cb)(Easy.get(name), v, dom.innerHTML);
			});
		}
	},
	showAutoWrap: function (d, s) {
		if (d) {
			if (currentShowSelectList) {
				Easy.DOM.hide(currentShowSelectList);
			}
			lw = Easy.get("w" + s.name);
			var ar = [];
			var hideid = Easy.DOM.getAttribute(s, "hideid");
			Easy.each(d, function (o, i) {
				ar.push("<li class='" + (i % 2 == 0 ? "a" : "b") + "'><a href='javascript:;' data-value='"
                    + o.value + "' onclick=\"Jade.Form.selectAutoItem(this,'" + s.name + "','" + hideid + "',event);\">" + o.text + "</a></li>");
			});
			if (lw) {
				lw.innerHTML = "<ul>" + ar.join("") + "</ul>";
				var h = Easy.DOM.getAttribute(s, "maxheight") || "130";
				var mh = parseInt((h.replace("px", "") - 0) / 26);
				if (ar.length > mh) {
					Easy.DOM.setStyle(lw, {
						height: h,
						overflow: "auto"
					});
				}
				Easy.DOM.show(lw);
				currentShowSelectList = lw;
			}
		}
	},
	selectAutoItem: function (dom, name, id, ev) {
		var p = Easy.get(name);
		var onc = Easy.DOM.getAttribute(p, "onchange");
		var v = Easy.DOM.getAttribute(dom, "data-value");
		p.value = dom.innerHTML;
		Easy.get(id).value = v;
		var list = Easy.get("w" + name);
		Easy.DOM.hide(list);
		if (Jade.V) {
			Jade.V.valid(Easy.get(id), null, 1, Easy.get(name))
		}
		currentShowSelectList = null;
		if (onc) {
			Easy.decode(onc).call(p, v, dom.innerHTML);
		}
	},
	submitBtn: function (cn, txt, bc, ac) {
		Jade.create.formButton({
			text: txt || "提 交",
			isBlue: true,
			el: 'btns',
			fn: function (p, e) {
				if (Easy.DOM.getAttribute(p, "doing") != "true") {
					Jade.Form.submit(p, Easy.get("theForm"), cn, bc, ac);
				}
			}
		});
	},
	backBtn: function (txt) {
		var isrdt = Jade.request("isRdt");
		Jade.create.formButton({
			text: txt || (isrdt == "true" ? "返 回" : "关 闭"),
			el: 'btns',
			fn: function () {
				if (isrdt != "true") {
					if (parent.editingWin && parent.editingWin.close) {
						parent.editingWin.close();
					}
				} else {
					history.back();
				}
			}
		});
	},
	getValues: function (fid) {
		var f = Easy.get(fid);
		var vs = Easy.Form.getValues(f);
		return vs;
	},
	submit: function (btn, form, cn, bc, ac) {
		Easy.DOM.setAttributes(btn, { "doing": "true" });
		var enctype = Easy.DOM.getAttribute(form, "enctype");
		var methodName = Easy.DOM.getAttribute(form, "methodName") || "Save";
		var callback = function (r) {
			Easy.DOM.removeAttribute(btn, "doing");
			if (r.exception) {
				top.Jade.Msg.error(r.message, function () {
					if (Easy.isFunction(ac)) {
						ac(false, vs, r);
					}
				});
			} else {
				var dfac = function () {
					Easy.tryDo(function () {
						if (window.parent.Grid) {
							window.parent.Grid.load();
						}
					});
					Easy.tryDo(function () {
						if (window.parent.editingWin) {
							window.parent.editingWin.close();
						}
					});
				}
				top.Jade.Msg.alert(r.message || "保存成功", function () {
					if (Easy.isFunction(ac)) {
						if (ac(true, vs, r)) {
							dfac();
						}
					} else {
						dfac();
					}
				});
			}
		};
		if (!(Jade.Validation && Jade.Validation.validForm)) {
			alert("请引入验证的js文件");
			return false;
		} else {
			if (Jade.Validation.validForm(form)) {
				if (enctype == "multipart/form-data") {
					var extpam = {};
					if (Easy.isFunction(bc)) {
						var f = bc(extpam);
						if (f !== false) {
							Easy.Ajax.upload({
								form: form,
								url: Jade.url,
								params: Easy.apply({
									classname: cn.replace(/\+/img, "Server"),
									methodname: methodName
								}, extpam),
								success: function (r) {
									var o = Easy.decode(r);
									callback(o);
								}
							});
						} else {
							Easy.DOM.removeAttribute(btn, "doing");
						}
					} else {
						Easy.Ajax.upload({
							form: form,
							url: Jade.url,
							params: Easy.apply({
								classname: cn.replace(/\+/img, "Server"),
								methodname: methodName
							}, extpam),
							success: function (r) {
								var o = Easy.decode(r);
								callback(o);
							}
						});
					}
				} else {
					var vs = this.getValues(form);
					if (Easy.isFunction(bc)) {
						var f = bc(vs);
						if (f !== false) {
							Jade.ajax(cn, methodName, vs, callback);
						} else {
							Easy.DOM.removeAttribute(btn, "doing");
						}
					} else {
						Jade.ajax(cn, methodName, vs, callback);
					}
				}
			} else {
				Easy.DOM.removeAttribute(btn, "doing");
			}
		}
	}
}


//实例化编辑器
window.UMEDITOR_HOME_URL = "/js/plugs/ueditormini/";

Easy.ready(function () {
	if (Easy.isIE6) {
		Easy.DOM.addClass(document.body, "ie6");
	} else if (Easy.isIE7) {
		Easy.DOM.addClass(document.body, "ie7");
	} else if (Easy.isIE && !Easy.isIE6 && !Easy.isIE7) {
		Easy.DOM.addClass(document.body, "iec");
	}

	Jade.Form.doBeautyInput(document);
	Jade.Form.doBeautySelect(document);
	Jade.Form.doBeautyArea(document);

	Easy.on(document, "click", function (p, e) {
		if (!Easy.DOM.hasClass(Easy.DOM.getParent(e.target), "select")
            || Easy.DOM.getAttribute(Easy.DOM.getParent(e.target), "deep") == "2") {
			var cls = e.target.className;
			if (cls.indexOf("e-tree") == -1) {
				if (currentShowSelectList) {
					Easy.DOM.hide(currentShowSelectList);
					currentShowSelectList = null;
				}
			}
		}
	});

});