$(document).ready(function () {

	//iframe인경우
	if (self != top) {
		gcm.thisIframe = true;
	}

	//dwr에러처리
	dwr.engine.setErrorHandler(function(msg, ex) {
		com.alert("An unexpected exception occurred.");
	});

	//dwr로딩이미지
	dwr.engine.setPreHook(function() {
		if (gcm.useDwrProgressbar) {
			com.showProgressBar();
		}
	});
	dwr.engine.setPostHook(function() {
		if (gcm.useDwrProgressbar) {
			com.hideProgressBar();
		}
	});

	// 숫자만 입력
	$(".numeric").numeric();
	$(".numeric").css("ime-mode", "disabled");

	// 숫자만 입력
	$(".decimal").numeric({allow:"."});
	$(".decimal").css("ime-mode", "disabled");

	$(".alpha").alpha();
	$(".alpha").css("ime-mode", "disabled");

	$(".alphanum").alphanum();
	$(".alphanum").css("ime-mode", "disabled");

	//입력폼에서 첫번째 항목에 포커싱
	$("form[name='editForm']").find("input,select").not("[type=hidden]").eq(0).focus();

	//textarea 크기자동조절
	$(".resizable_textarea").autosize();

	//다이얼로그 버튼 이벤트처리
	$("a.btnDialog").on("click", function () {
		var url = $(this).attr("href");
		var dialogTitle = $(this).attr("dialog-title");
		var dialogWidth = $(this).attr("dialog-width");
		var dialogHeight = $(this).attr("dialog-height");
		com.openDialog(url,
			{
				title : dialogTitle,
				width: dialogWidth,
				height: dialogHeight,
				close : function(e) {
				}
			});

		return false;
	});

	//유효성검증 메세지 영문으로 변환
	$.validator.messages = {
		required: " [  <em>#TITLE#</em> ] is a required entry.",
		remote: " [ <em>#TITLE#</em> ] Please modify the item.",
		email: " [ <em>#TITLE#</em> ] is in the wrong email format.",
		url: " [ <em>#TITLE#</em> ] is in the wrong URL format.",
		date: " [ <em>#TITLE#</em> ] is not a valid date format or date.",
		dateISO: " [ <em>#TITLE#</em> ] is not a valid date (ISO) format.",
		number: " [ <em>#TITLE#</em> ] must be numeric.",
		digits: "[ <em>#TITLE#</em> ] must be numeric.",
		equalTo: "Please enter the same value.",
		creditcard: " [ <em>#TITLE#</em> ] is not a valid card number.",
		maxlength: " [ <em>#TITLE#</em> ] cannot be greater than {0}byte.",
		minlength: " [ <em>#TITLE#</em> ] cannot be less than {0} bytes.",
		rangelength: " [ <em>#TITLE#</em> ] please enter a value with a length of {0}~{1}.",
		range: " [ <em>#TITLE#</em> ] please enter a value between {0} and {1}.",
		max: " [ <em>#TITLE#</em> ] cannot be more than {0}.",
		min: " [ <em>#TITLE#</em> ] cannot be less than {0}."
	};

	//textarea 입력제한수 체크
	if ($("textarea.lengthMonitor").length > 0) {
		$("textarea.lengthMonitor").each(function() {
			var textareaObj = $(this);
			var maxlength = textareaObj.attr("data-maxlength");
			var textLength = com.getLength(textareaObj.val());
			if (!textareaObj.hasClass("lengthMonitorApply")) {
				textareaObj.wrap("<div class='textareaWrap' style='width:100%;'></div>");
				var statusHtml = "";
				statusHtml += "<div class=\"textareaLengthWrap\" style=\"text-align: right;\">";
				statusHtml += "    <span class=\"textareaLength\" style=\"color:red;\">" + com.formatNumber(textLength) + "</span> / " + com.formatNumber(maxlength) + " Byte";
				statusHtml += "</div>";
				textareaObj.after(statusHtml);
				textareaObj.addClass("lengthMonitorApply");

				textareaObj.keyup(function () {
					var length = com.getLength(textareaObj.val());
					textareaObj.parents(".textareaWrap").find(".textareaLength").text(length);
				});
			}
		});
	}

});
var gcm = {

	// 서버 통신 기본 모드 ( "asynchronous" / "synchronous")
	DEFAULT_OPTIONS_MODE : "asynchronous",

	// 서버 통신 기본 미디어 타입
	DEFAULT_OPTIONS_MEDIATYPE : "application/x-www-form-urlencoded;",

	// 서버 통신 기본 인코딩
	DEFAULT_ENCODING : "EUC-KR",

	//자바스크립트 로깅 사용여부 (전체)
	JAVASCRIPT_LOGGING : true,

	//자바스크립트 디버그 레벨
	JAVASCRIPT_DEBUG_LEVEL : ["debug", "log", "info", "warn", "error"],

	//로딩바 텍스트
	PROCESS_MSG : "Loading...",

	modalAlertIndex : 0,

	modalConfirmIndex : 0,

	modalDialogIndex : 0,

	thisIframe : false,

	useDwrProgressbar : true
};

var com = {

	/**
	 * 경고창을 띄운다.
	*/
	alert : function(_msg, _callback, _options) {

		//iframe인경우
		if (gcm.thisIframe) {
			top.com.alert(_msg, _callback, _options);
		} else {

			var options = {
				type : "",
				title : "message",
				okButton : "OK",
				icon : "",
				width: 0,
				height: 0,
				autoHide: false,
				hideDelay: 3000,
				callback: function(){
					if (_callback != undefined) {
						_callback();
					}
				}
			};
			if (_options) {
				options = jQuery.extend(options, _options);	//변수에 담긴값 셋팅
			}

			$('body').css({"overflow":"hidden"});
			jAlert(_msg, options, function(r){
				$('body').css({"overflow":"auto"});
				options.callback();
			});
		}

	},

	/**
	 * 확인창을 띄운다.
	*/
	confirm : function(_msg, _callback, _options) {

		//iframe인경우
		if (gcm.thisIframe) {
			top.com.confirm(_msg, _callback, _options);
		} else {
			var options = {
				title : "Confirm",
				okButton : "OK",
				cancelButton : "Cancel",
				icon : "",
				width: 0,
				height: 0
			};
			if (_options) {
				options = jQuery.extend(options, _options);	//변수에 담긴값 셋팅
			}

			$('body').css({"overflow":"hidden"});

			jConfirm(_msg, options, function(r){
				$('body').css({"overflow":"auto"});
				_callback(r);
			});
		}
	},

	notify : function(_msg, _options) {
		//iframe인경우
		if (gcm.thisIframe) {
			top.com.notify(_msg, _options);
		} else {
			/*
			var options = {
				text: "",
				type: 'info',
				styling: 'bootstrap3',
				delay: 1000
			};
			if (_options != undefined) {
				options = $.extend(options, _options);
			}
			options.text = _msg;
			new PNotify(options);
			 */
			com.alert(_msg);
		}
	},

	openDialog : function(url, opt, data) {
		//iframe인경우
		if (gcm.thisIframe) {
			top.com.openDialog(url, opt, data);
		} else {
			var top = 0 + "px"
			var left = 0 + "px";

			var width = window.innerWidth + 2;
			var height = window.innerHeight + 2;

			var deviceWidth = parseFloat($("body").css("width"));
			var deviceHeight = parseFloat($("body").css("height"));

			if (typeof opt.width != "undefined" && typeof opt.height != "undefined") {
				if (opt.width <= width) {
					width = opt.width;
				}
				if (opt.height <= height) {
					height = opt.height;
				}

				if (deviceWidth > 0 && opt.width >= deviceWidth) {
					width = (deviceWidth - 20);
				}

				var doc = document.documentElement;
				var body = document.body;

				left = Math.floor((document.body.clientWidth - width) / 2);
				scrollH=(doc && doc.scrollTop || body && body.scrollTop);
				top = Math.floor((document.body.clientHeight - height) / 2) + scrollH;
			}

			var options = {
				id : "",
				title : "",
				width : width,
				height : height,
				top : top,
				left : left,
				show : function(e) {},
				shown : function(e) {},
				hide : function(e) {},
				hidden : function(e) {
					$(e.target).remove();
				},
				close : function() {}
			};
			if (opt != undefined) {
				options = $.extend(options, opt);
			}
			options.width = width;
			options.height = height;

			var callbackClose = function(e){
				$(e.target).modal('hide');
			};
			if (options.close != undefined && typeof options.close == "function") {
				callbackClose = function(e){
					options.close();
				};
			}

			var dialogId = "modalDialog_" + (gcm.modalDialogIndex++);

			if (typeof options.title == "undefined") options.title = "";

			var targetObj = null;
			if (com.isEmpty(options.id) && com.isEmpty(options.html)) {
				targetObj = $('<iframe name="dialogIframe" id="' + dialogId + '" class="dialogIframe" frameBorder="0" scrolling="no" title=\"' + options.title + ' 레이어 팝업창\" src="' + url + '" tabindex="0" />');
			} else if (com.isNotEmpty(options.id)) {
				targetObj = $("#" + options.id);
				targetObj.addClass("dialogContainer");
			} else if (com.isNotEmpty(options.html)) {
				targetObj = $(options.html);
				targetObj.addClass("dialogContainer");
			}

			targetObj.dialog({
				title: options.title,
				autoOpen: true,
				width: options.width,
				height: options.height,
				modal: true,
				resizable: false,
				closeOnEscape: true,
				closeText: "레이어 팝업창 닫기",
				autoResize: true,
				overlay: {
					opacity: 0.5,
					background: "black"
				},
				close: function( event, ui ) {
					if (typeof callbackClose != "undefined") callbackClose();
					$('body').removeClass('stop-scrolling');
				},
				open: function(event, ui) {
					$('body').addClass('stop-scrolling');

					$(".ui-widget-overlay").bind("click", function(){
						com.closeDialog();
					});

					var ui_dialog = targetObj.parents(".ui-dialog");
					ui_dialog.attr("title", options.title + " 레이어 팝업창");

					//iframe 프로그래스바 출력
					if (ui_dialog.find(".dialogIframe").length > 0) {
						ui_dialog.append('<div class=\"dialogIframe-placeholder\" style="position:absolute;bottom:0;left:0;width:100%;height:100%;"></div>');
						ui_dialog.find("div.dialogIframe-placeholder").css({"height":options.height + "px"});
						targetObj.load(function(){
							ui_dialog.find("div.dialogIframe-placeholder").remove();
						});
					}

					var top = Math.max(0, (($(window).height() - (ui_dialog.outerHeight()+60)) / 2) + $(window).scrollTop());
					var left = Math.max(0, (($(window).width() - ui_dialog.outerWidth()) / 2) + $(window).scrollLeft());
					if (top < $(window).scrollTop()) {
						top = $(window).scrollTop();
					}
					ui_dialog.css("position","absolute");
					ui_dialog.css("top", top + "px");
					ui_dialog.css("left", left + "px");

					ui_dialog_titlebar_close = targetObj.parents(".ui-dialog").find(".ui-dialog-titlebar-close");
					ui_dialog_titlebar_close.css({"margin-right":"5px"});
					ui_dialog_titlebar_close.show();
					ui_dialog_titlebar_close.find(".ui-button-text").hide();
					ui_dialog_titlebar_close.attr("tabindex", "1");
					$("#" + dialogId).attr("tabindex", "2");

					ui_dialog_titlebar_close.focus();
					setTimeout(function(){
						ui_dialog_titlebar_close.focus();
					}, 10);

					$("#" + dialogId).on("load", function() {
						$("#" + dialogId).contents().find(".closeDialog").click(function(){
							com.closeDialog();
						});
					});

					$(window).on("resize", function(){
						var ui_dialog = targetObj.parents(".ui-dialog");
						var top = Math.max(0, (($(window).height() - ui_dialog.outerHeight()) / 2) + $(window).scrollTop());
						var left = Math.max(0, (($(window).width() - ui_dialog.outerWidth()) / 2) + $(window).scrollLeft());
						if (top < $(window).scrollTop()) {
							top = $(window).scrollTop();
						}
						ui_dialog.css("position","absolute");
						ui_dialog.css("top", top + "px");
						ui_dialog.css("left", left + "px");
					});

				}
			}).css({"padding":"0px", "margin":"0px", "width":options.width, "height":options.height}).attr("title", options.title + " 프레임").attr("data-width", options.width).attr("data-height", options.height).focus();
		}
	},

	closeDialog :function(_callback) {
		if (gcm.thisIframe) {
			top.com.closeDialog(_callback);
		} else {
			$(".dialogIframe:last").dialog("destroy");
			$('body').removeClass('stop-scrolling');

			if (typeof _callback != "undefined" && typeof _callback == "function") {
				_callback();
			}
		}
	},

	showProgressBar : function() {
		$("div.ajaxLoading").css({"display":"inline-block"});
	},

	hideProgressBar : function() {
		$("div.ajaxLoading").css({"display":"none"});
	},

	/**
	 * NULL 여부 체크
	*/
	isEmpty : function(value) {
		var rtnValue = false;
		if (typeof value != "object") {
			if (typeof value == "number" && !isNaN(Number(value)) || typeof value == "string") {
				value = value + "";
			}
		}

		var strLen = 0;
		if (typeof value == "string") {
			value = value.trim();
			if (value == "null") {
				rtnValue = true;
			} else {
				strLen = value.length;
			}

		} else if (Array.isArray(value)) {
			strLen = value.length;

		} else if (typeof value == "object") {
			var cnt = 0;
			for ( var i in value) {
				cnt++;
			}
			strLen = cnt;

		} else if (typeof value == "boolean") {
			strLen = 1;
		}

		if (strLen == 0) {
			if (com.isFunction(value)) {
				rtnValue = false;
			} else {
				rtnValue = true;
			}
		} else {
			rtnValue = false;
		}
		return rtnValue;
	},

	/**
	 * 함수 존재 여부 체크
	*/
	isFunction : function(_checkFunc) {
		try {
			var getType = {};
			return _checkFunc && getType.toString.call(_checkFunc) === '[object Function]';
			return false;
		} catch (e) {
		}
	},

	/**
	 * JSON Object인지 여부를 검사한다.
	*/
	isJSON : function(jsonObj) {
		if (typeof jsonObj !== 'object')
			return false;
		try {
			JSON.stringify(jsonObj);
			return true;
		} catch (e) {
			return false;
		}
	},
	/**
	 * NOT NULL 여부 체크
	*/
	isNotEmpty : function(value) {
		return !com.isEmpty(value);
	},

	/**
	 * 숫자 여부 체크
	*/
	isNumber : function(value) {
		try {
			var sReturnValue = false;
			if (typeof value == "number") {
				return true;
			}
			if (typeof value == "string") {
				var reg = new RegExp('^[0-9]+$');
				var iBit = value.charAt(0);
				if ((iBit == "-" || iBit == "+") && value.substr(1, 1) != ".") {
					value = value.substr(1);
				}
				var len = value.split(".").length;
				if (len == 1) {
					if (reg.test(value.split(".")[0])) {
						return true;
					} else {
						return false;
					}
				} else if (len == 2) {
					var num1 = value.split(".")[0];
					var num2 = value.split(".")[1];
					if (reg.test(num1) && reg.test(num2)) {
						return true;
					} else {
						return false;
					}
				} else {
					return false;
				}
			}

			var iBit;
			for (var i = 0; i < value.length; i++) {
				iBit = value.charAt(i);
				if (i == 0) {
					if (!isNaN(parseInt(iBit))
							|| (iBit == "-" && value.substr(1, 1) != ".")
							|| (iBit == "+" && value.substr(1, 1) != ".")) {
						sReturnValue = true;
					} else {
						sReturnValue = false;
						break;
					}
				} else {
					if (!isNaN(parseInt(iBit))
							|| (iBit == "." && com.isNull(value.substr(
									i + 1, 1))) === false) {
						sReturnValue = true;
					} else {
						sReturnValue = false;
						break;
					}
				}
			}
			return sReturnValue;
		} catch (e) {
		}
	},

	/**
	 * XML Document 객체인지 여부를 검사한다.
	*/
	isXmlDoc : function(data) {
		if (typeof data != 'object')
			return false;
		if ((typeof data.documentElement != 'undefined' && data.nodeType == 9) || (typeof data.documentElement == 'undefined' && data.nodeType == 1)) {
			return true;
		}
		return false;
	},

	/**
	 * 문자형 날짜를 포맷팅한다.
	 *
	 * sdate : 문자열
	 * parseFormat : 파싱 format
	 * outputFormat : 출력 format
	 */
	convertDate : function(sdate, parseFormat, outputFormat) {
		if (com.isEmpty(sdate)) {
			return "";
		} else {
			var d = moment(sdate, parseFormat);
			var result = d.format(outputFormat);
			return result;
		}
	},

	/**
	 * 문자형 날짜를 파싱한다.
	 *
	 * sdate : 문자열
	 * parseFormat : 파싱 format
	 */
	parseDate : function(sdate, parseFormat) {
		return moment(sdate, parseFormat);
	},

	/**
	 * 숫자 포맷팅
	 */
	formatNumber : function(value) {
		if (value == 0) return 0;

		var reg = /(^[+-]?\d+)(\d{3})/;
		var n = (value + '');

		while (reg.test(n)) n = n.replace(reg, '$1' + ',' + '$2');

		return n;
	},

	/**
	 * 문자열 치환
	*/
	replaceAll : function(str, s1, s2) {
		return str.split(s1).join(s2);
	},

	/**
	 * 원하는 자릿수만큼 왼쪽에 특정문자열로 채워넣어줍니다.
	 */
	leftPad : function(source, targetLength, padChar) {
		source = new String(source);
		if (!padChar) {
			padChar = " ";
		}
		if (source.length < targetLength)
		{
			var padding = "";

			while (padding.length + source.length < targetLength)
				padding += padChar;

			return padding + source;
		}
		return source;
	},

	/**
	 * 원하는 자릿수만큼 오른쪽에 특정문자열로 채워넣어줍니다.
	 */
	rightPad : function(source, targetLength, padChar) {
		source = new String(source);
		while (source.length < targetLength)
			source += padChar;

		return source;
	},

	/**
	 * html 문자열 unescape
	*/
	unescapeHtml : function(value) {
		return value
		.replace(/&lt;/g, "<")
		.replace(/&gt;/g, ">")
		.replace(/&amp;/g, "&")
		.replace(/&quot;/g, "\"")
		.replace(/&apos;/g, "'");
	},

	/**
	 * 문자의 길이를 구함(한글은 2자리 처리)
	 */
	getLength : function(strVal) {
		try
		{
			strVal = new String(strVal);
			if ((strVal == null) || ($.trim(strVal).length == 0))
			{
				return 0;
			}
			else
			{
				var li_length = 0 ;
				for (var ti_i = 0; ti_i < strVal.length; ti_i++)
				{
					if ((strVal.charCodeAt(ti_i)) > 128)
					{
						li_length += 2;
					}
					else
					{
						li_length += 1;
					}
				}
				return li_length;
			}
		}
		catch(e)
		{
			return 0;
		}
	}

};

String.prototype.string = function(len){var s = '', i = 0; while (i++ < len) { s += this; } return s;};
String.prototype.zf = function(len){return "0".string(len - this.length) + this;};
Number.prototype.zf = function(len){return this.toString().zf(len);};
Date.prototype.format = function(f) {
	if (!this.valueOf()) return " ";

	var weekName = ["SUN", "MON", "TUE", "WED", "THU", "FRI", "SAT"];
	var d = this;

	return f.replace(/(yyyy|yy|MM|dd|E|hh|mm|ss|a\/p)/gi, function($1) {
	switch ($1) {
		case "yyyy": return d.getFullYear();
		case "yy": return (d.getFullYear() % 1000).zf(2);
		case "MM": return (d.getMonth() + 1).zf(2);
		case "dd": return d.getDate().zf(2);
		case "E": return weekName[d.getDay()];
		case "HH": return d.getHours().zf(2);
		case "hh": return ((h = d.getHours() % 12) ? h : 12).zf(2);
		case "mm": return d.getMinutes().zf(2);
		case "ss": return d.getSeconds().zf(2);
		case "a/p": return d.getHours() < 12 ? "AM" : "PM";
		default: return $1;
	}
	});
};

/* map 프로토타입 선언 */
Map = function() {
	this.map = new Object();
};
Map.prototype = {
	put : function(key, value) {
		this.map[key] = value;
	},
	get : function(key) {
		return this.map[key];
	},
	containsKey : function(key) {
		return key in this.map;
	},
	containsValue : function(value) {
		for ( var prop in this.map) {
			if (this.map[prop] == value)
				return true;
		}
		return false;
	},
	isEmpty : function(key) {
		return (this.size() == 0);
	},
	clear : function() {
		for ( var prop in this.map) {
			delete this.map[prop];
		}
	},
	remove : function(key) {
		delete this.map[key];
	},
	keys : function() {
		var keys = new Array();
		for ( var prop in this.map) {
			keys.push(prop);
		}
		return keys;
	},
	values : function() {
		var values = new Array();
		for ( var prop in this.map) {
			values.push(this.map[prop]);
		}
		return values;
	},
	size : function() {
		var count = 0;
		for ( var prop in this.map) {
			count++;
		}
		return count;
	}
};
