var VIEW = VIEW || {};

VIEW.dom = VIEW.dom ||
(function () {
	return {
		setFocus: function (formId, hide) {
			var expr = (hide ? ":input:enabled:visible" : ":input:enabled");
			var target = null;
			$("#" + formId).find(expr).each(function() {
				if (!target) {
					if (0 <= this.tabIndex || $(this).hasClass("E")) {
						target = this;
					}
				} else if (!$(target).hasClass("E")) {
					if ($(this).hasClass("E")) {
						target = this;
					} else if (0 < this.tabIndex) {
						if (target.tabIndex <= 0) {
							target = this;
						} else if (this.tabIndex < target.tabIndex) {
							target = this;
						}
					}
				}
				if (-100 === this.tabIndex) {
					this.tabIndex = 0;
				}
			});

			if (target) {
				if (!hide && !$(target).is(":visible")) {
					for (var ele = $(target); typeof ele.parent() !== "undefined"; ele = ele.parent()) {
						if (ele.css("display") === "none") {
							ele.show();
							break;
						}
					}
				}
				$(target).focus();
				if ($(target).attr("type") === "text") {
					$(target).select();
				}
			}
		},
		loadOptions: function (req, tid) {
			var clearOptions = function(id) {
				var target = (typeof id === "string" ? document.getElementById(id) : id);
				while (target && 0 < target.length &&
						(target.length !== 1 || target.options[target.length - 1].value !== "")) {
					target.options[target.length - 1] = null;
				}
			};

			clearOptions(tid);
			for (var i = 2, len = arguments.length; i < len; i += 1) {
				clearOptions(arguments[i]);
			}

			var target = (typeof tid === "string" ? document.getElementById(tid) : tid);
			if (target) {
				$.ajax({type:"get", url:req, dataType:"text"}).done(function(response) {
					var list = $.parseJSON(response);
					var frag = document.createDocumentFragment();
					for (var i = 0, len = list[0].length; i < len; i += 1) {
						var opt = document.createElement("option");
						opt.setAttribute("value", list[1][i]);
						opt.appendChild(document.createTextNode(list[0][i]));
						frag.appendChild(opt);
					}
					target.appendChild(frag);
				});
			}
		}
	};
}());
