var isMSIE = (navigator.userAgent.toLowerCase().indexOf("msie") != -1);
var isGECKO = (navigator.userAgent.toLowerCase().indexOf('gecko') != -1);
var isOPERA = (navigator.userAgent.toLowerCase().indexOf('opera') != -1);

if (isMSIE) {
	try { document.execCommand('BackgroundImageCache', false, true); } catch(e) {}
}

Object.prototype.isArray = function () {
	try {
		return /^\s?function Array()/.test(this.constructor.toString());
	}
	catch(e) {
		return false;
	}
}

String.prototype.trim = function() {
	return this.replace(/(^[ \t\n\r]*)|([ \t\n\r]*$)/g,'');
}

String.prototype.stripspace = function() {
	return this.replace(/ /g, '');
}

String.prototype.replaceAll = function(a, b) {
	var s = this;
	if (navigator.userAgent.toLowerCase().indexOf("msie") != -1)
		return s.replace(new RegExp(a, 'gi'), b);
	else
		return s.split(a).join(b);
}

String.prototype.toNumeric = function() {
	var s = this;
	s = (typeof s == "undefined" ? '0' : s.toString().replace(/,/g, ''));
	if (isNaN(s) || s.replace(/ /g, '') == '') return 0;
	else	return parseFloat(s);
}

String.prototype.cut = function(len) {
	var s = this;
	var size = 0;
	for (var i=0; i<s.length; i++) {
		size += (s.charCodeAt(i)>128 ? 2 : 1);
		if (size > len) return s.substring(0, i)+"..";
	}
	return s;
}

String.prototype.bytes = function() {
	var s = this;
	var size = 0;
	for (var i=0; i<s.length; i++) size += (s.charCodeAt(i)>128 ? 2 : 1);
	return size;
}

Array.prototype.inArray = function (value) {
	for (var key in this) {
		if (this[key] == value) {
			return true;
		}
	}
	return false;
}

function $(id) { return document.getElementById(id); }
function $S(id) { return document.getElementById(id).style; }
function $$(id, tagName) {
	var parent = (typeof (id) == 'string' ? $(id) : id);
	if (parent) return parent.getElementsByTagName(tagName);
	else return [];
}

// 이벤트 추가 ##################################################
function addEvent(obj, type, listener) {
	if (window.addEventListener) obj.addEventListener(type, listener, false);
	else obj.attachEvent('on'+type, listener);
}

// 이벤트 제거 ##################################################
function removeEvent(obj, type, listener) {
	if (window.removeEventListener) obj.removeEventListener(type, listener, false);
	else obj.detachEvent('on'+type, listener);
}

// 숫자 확인 ##################################################
function isNumeric(value, isDec) {
	var RegExp = /^-?[\d\.]*$/;
	return RegExp.test(value)? true : false;
}

// 공백 확인 ##################################################
function isEmpty(obj) {
	var value = obj.value.stripspace();
	if (obj.disabled) value = '';
	return (value=='' ? true : false);
}

// 팝업 ##################################################
function openPopup(theURL, winName, width, height, remFeatures) {
	var features = "";
	if (typeof winName == "undefined") winName = "";
	if (typeof width != "undefined") features += (features ? "," : "")+"width="+width;
	if (typeof height != "undefined") features += (features ? "," : "")+"height="+height;
	if (typeof remFeatures != "undefined") features += (features ? "," : "")+remFeatures;
	if (features && features.indexOf("status") < 0) features += ",status=yes";

	var popup = window.open(theURL, winName, features);
	popup.focus();

	return popup;
}

// 팝업 - 팝업창 화면중앙 오픈 ##################################################
function openPopupCenter(theURL, winName, width, height, remFeatures) {
	var left = (screen.width/2) - (width/2);
	var top = (screen.availHeight/2) - (height/2);
	var features = "left="+left+",top="+top+",width="+width+",height="+height;
	if (typeof winName == "undefined") winName = "";
	if (typeof remFeatures != "undefined") features += ","+remFeatures;
	if (features && features.indexOf("status") < 0) features += ",status=yes";

	var popup = window.open(theURL, winName, features);
	popup.focus();

	return popup;
}

// 팝업 사이즈 조정 ##################################################
function resizePopup(width, height) {
	var userAgent = navigator.userAgent.toLowerCase();
	var isMSIE = (userAgent.indexOf('msie') != -1);
	var agentVer = 0;
	if (isMSIE) {
		var pos_msie = userAgent.indexOf('msie ');
		agentVer = parseInt(userAgent.substring(pos_msie+5, userAgent.indexOf(".", pos_msie)), 10);
	}
	var isMoz = (userAgent.indexOf('gecko') != -1);
	var isChrome = (userAgent.indexOf('chrome') != -1);

	var resizeWidth = width + ((isMSIE && agentVer>6) ? 20 : 10);
	var resizeHeight = height + ((isMSIE && agentVer>6) ? 71 : (isMoz ? (isChrome ? 55 : 81) : 49));

	window.resizeTo(resizeWidth, resizeHeight);

	if (!isChrome) {
		var lastHeight = resizeHeight - (parseInt(document.body.clientHeight, 10) - height);
		if (resizeHeight != lastHeight) { window.resizeTo(resizeWidth, lastHeight); }
	}
}

// 팝업 - 팝업창 위치 조정 ##################################################
function movePopup(left, top) {
	window.moveTo(left, top);
}

// 모달 ##################################################
function openModal(theURL, obj, features) {
	window.showModalDialog(theURL, obj, features);
}

// 키 관련 함수 ##################################################
function blockKey(e) {
	var e = window.event || e;
	if (window.event) {
		e.returnValue = false;
	}
	else {
		if (e.which != 8) e.preventDefault(); // 8 : Back Space
	}
}

function blockEnter(e) {
	var e = window.event || e;
	if (window.event) {
		if (e.keyCode == 13) e.returnValue = false;
	}
	else {
		if (e.which == 13) e.preventDefault();
	}
}

function blockNotNumber(e) {
	var e = window.event || e;
	if (window.event) {
		if (e.keyCode < 48 || e.keyCode > 57) e.returnValue = false;
	}
	else {
		if (e.which != 8 && (e.which < 48 || e.which > 57)) e.preventDefault(); // 8 : Back Space
	}
}

function onEnter(e, exec) {
	var e = window.event || e;
	var keyCode = (window.event) ? e.keyCode : e.which;
	if (keyCode == 13) eval(exec);
}

// 즐겨찾기 추가 ##################################################
// 예) <a href="javascript:;" onClick="addFavorites('홈페이지', 'http://www.homepage.com'); return false;">즐겨찾기 등록</a>
function addFavorites(title, url) {
	if (isMSIE) { // IE
		window.external.AddFavorite(url, title);
	}
	else if (window.sidebar) { // Firefox
		window.sidebar.addPanel(title, url, "");
	}
	else { // Opera, Safari ...
		alert("현재 브라우져에서는 이용할 수 없습니다.");
		return;
	}
}

// 시작페이지 설정 ##################################################
// 예) <a href="javascript:;" onClick="setStartPage(this, 'http://www.homepage.com'); return false;">시작페이지로</a>
function setStartPage(obj, url) {
	if (isMSIE && window.external) { // IE
		obj.style.behavior = "url(#default#homepage)";
		obj.setHomePage(url);
	}
	else { // Firefox, Opera, Safari ...
		alert("현재 브라우져에서는 이용할 수 없습니다.");
		return;
    }
}

// 클립보드복사 ##################################################
function copyClipboard(value, msg) {
	if (isMSIE) { // IE
		window.clipboardData.setData('Text', value);
		if (msg) alert(msg);
	}
	else { // Firefox, Opera, Safari ...
		alert("현재 브라우져에서는 이용할 수 없습니다.");
		return;
    }
}

// 페이지 이동 ##################################################
function goUrl(url) {
	if (url.stripspace() != "") {
		location.href = url;
	}
}

// 페이지 최상단으로 ##################################################
function goTop() {
	window.scrollTo(0, 0);
}

// 객체 Offset ##################################################
function getOffset(obj) {
	var objOffset = { left : 0, top : 0 };
	var objOffsetParent = obj.offsetParent;

	objOffset.left = parseInt(obj.offsetLeft, 10);
	objOffset.top = parseInt(obj.offsetTop, 10);

	while (objOffsetParent) {
		objOffset.left += parseInt(objOffsetParent.offsetLeft, 10);
		objOffset.top += parseInt(objOffsetParent.offsetTop, 10);

		objOffsetParent = objOffsetParent.offsetParent;
	}

	return objOffset;
}

// 부모 객체 ##################################################
function getParentElement(obj, tag) {
	var result = null;

	var parent = obj.parentNode;
	while (parent) {
		if (parent.tagName.toLowerCase() == tag) {
			result = parent;
			break;
		}
		parent = parent.parentNode;
	}

	return result;
}

// 입력 문자길이 확인후 다음항목으로 포커스 옮기기 ##################################################
function goNextFocus(obj, len, next) {
	if (obj.value.stripspace().length == len){
		next.focus();
	}
}

// 체크박스 전체선택 ##################################################
function checkCbAll(cb, checked) {
	if (cb) {
		if (typeof(cb.length) == "undefined") {
			if (!cb.disabled) cb.checked = checked;
		}
		else {
			for (var i=0; i<cb.length; i++) {
				if (cb[i].type.toUpperCase() == 'CHECKBOX' && cb[i].value.stripspace() != "" && !cb[i].disabled) {
					cb[i].checked = checked;
				}
			}
		}
	}
}

// 선택된 체크박스 값 추출 ##################################################
function getCbChecked(cb, attributes) {
	var arr = new Array();
	arr[0] = new Array();

	var attrs = (attributes ? attributes.split(',') : new Array());
	for (var a in attrs) {
		var name = attrs[a];
		if (typeof (name) == 'string') {
			arr[name] = new Array();
		}
	}

	if (cb) {
		if (typeof(cb.length) == "undefined") {
			if (cb.checked) {
				arr[0][arr[0].length] = cb.value;

				for (var a in attrs) {
					var name = attrs[a];
					if (typeof (name) == 'string') {
						arr[name][arr[name].length] = cb.getAttribute(name).toString();
					}
				}
			}
		}
		else {
			for (var i=0; i<cb.length; i++) {
				if (cb[i].checked) {
					arr[0][arr[0].length] = cb[i].value;

					for (var a in attrs) {
						var name = attrs[a];
						if (typeof (name) == 'string') {
							arr[name][arr[name].length] = cb[i].getAttribute(name).toString();
						}
					}
				}
			}
		}
	}

	return arr;
}

// Input 추가 ##################################################
function addInput(f, type, name, value) {
	var input = document.createElement('input');
	input.type = type;
	input.name = name;
	input.value = value;
	f.appendChild(input);
}

// Input 제거 ##################################################
function removeInput(f, type, name, target) {
	var index = 0;
	if (typeof (target) == "undefined") target = -1;

	var inputs = f.getElementsByTagName('INPUT');
	if (inputs) {
		for (var i=inputs.length-1; i>=0; i--) {
			if (inputs[i].type == type && inputs[i].name == name) ++index;
		}
		for (var i=inputs.length-1; i>=0; i--) {
			if (inputs[i].type == type && inputs[i].name == name) {
				--index;
				if (target < 0) f.removeChild(inputs[i]);
				else if (index == target) {
					f.removeChild(inputs[i]);
					break;
				}
			}
		}
	}
}

// Select Option 추가 ##################################################
function addSelectOption(obj, text, value) {
	var option = document.createElement('option');
	option.text = text;
	option.value = value;
	obj.options.add(option);
	return option;
}

// Select Option 삭제 ##################################################
function removeSelectOption(obj, index) {
	obj.remove(index);
}

// Select Option 전체삭제 ##################################################
function removeSelectOptionAll(obj) {
	for (var i=obj.length-1; i>=0; i--) {
		removeSelectOption(obj, i);
	}
}

// Radio(CheckBox) 설정값 가져오기 ##################################################
function getRadio(obj) {
	var i, value = "";

	if (obj) {
		if (typeof(obj.length) == "undefined") {
			if (obj.checked) value = obj.value;
		}
		else {
			for (i=0; i<obj.length; i++) {
				if (obj[i].checked) {
					value = obj[i].value;
					break;
				}
			}
		}
	}
	return value;
}

// Radio 설정하기 ##################################################
function setRadio(obj, value) {
	if (obj) {
		if (typeof(obj.length) == "undefined") {
			if (obj.value == value) obj.checked = true;
		}
		else {
			for(var i=0; i<obj.length; i++) {
				if (obj[i].value == value) {
					obj[i].checked = true;
					break;
				}
			}
		}
	}
}

// Radio Disabled 설정하기 ##################################################
function setRadioDisabled(obj, value, disabled) {
	if (obj) {
		if (typeof(obj.length) == "undefined") {
			if (obj.value == value) {
				obj.disabled = disabled;
			}
		}
		else {
			for(var i=0; i<obj.length; i++) {
				if (obj[i].value == value) {
					obj[i].disabled = disabled;
					break;
				}
			}
		}
	}
}

// Radio Disabled 전체 설정하기 ##################################################
function setRadioDisabledAll(obj, disabled) {
	if (obj) {
		if (typeof(obj.length) == "undefined") {
			obj.disabled = disabled;
		}
		else {
			for(var i=0; i<obj.length; i++) {
				obj[i].disabled = disabled;
			}
		}
	}
}

// Text Focus/Blur Event ##################################################
function focusText(item) {
	var txt = item.getAttribute('words').toString();
	if (item.value == txt) item.value = '';
}

function blurText(item) {
	var txt = item.getAttribute('words').toString();
	if (isEmpty(item)) item.value = txt;
}

// IFRAME RESIZE 함수 ##################################################
function resizeFrame(frameWindow, frameBody, params) {
	if (!frameWindow.name) return false;

	var frameElement = document.getElementById(frameWindow.name);
	if (typeof (frameBody) == 'undefined') {
		var frameDoc = (frameElement.contentWindow.document || frameElement.contentDocument);
		frameBody = (frameDoc.documentElement || frameDoc.body);
	}

	if (frameElement.style.display == 'none') frameElement.style.display = '';

	var minWidth = (params && params.minWidth ? parseInt(params.minWidth, 10) : 0);
	var minHeight = (params && params.minHeight ? parseInt(params.minHeight, 10) : 0);
	var maxWidth = (params && params.maxWidth ? parseInt(params.maxWidth, 10) : 0);
	var maxHeight = (params && params.maxHeight ? parseInt(params.maxHeight, 10) : 0);
	var fixWidth = (params && params.fixWidth ? parseInt(params.fixWidth, 10) : 0);
	var fixHeight = (params && params.fixHeight ? parseInt(params.fixHeight, 10) : 0);

	var resizeWidth = 0;
	var resizeHeight = 0;

	if (frameBody.nodeName.toUpperCase() == 'BODY') {
		resizeWidth = frameBody.scrollWidth + (frameBody.offsetWidth - frameBody.clientWidth);
		resizeHeight = frameBody.scrollHeight + (frameBody.offsetHeight - frameBody.clientHeight);
	}
	else {
		resizeWidth = frameBody.offsetWidth;
		resizeHeight = frameBody.offsetHeight;
	}

	if (minWidth > 0 && resizeWidth < minWidth) resizeWidth = minWidth;			// 최소 폭
	if (minHeight > 0 && resizeHeight < minHeight) resizeHeight = minHeight;		// 최소 높이
	if (maxWidth > 0 && resizeWidth > maxWidth) resizeWidth = maxWidth;			// 최소 폭
	if (maxHeight > 0 && resizeHeight > maxHeight) resizeHeight = maxHeight;		// 최소 높이

	if (fixWidth > 0) resizeWidth = fixWidth;		// 고정 폭
	if (fixHeight > 0) resizeHeight = fixHeight;	// 고정 높이

	if (fixWidth > -1) frameElement.style.width = resizeWidth + 'px';
	if (fixHeight > -1) frameElement.style.height = resizeHeight + 'px';
}

// Loading ##################################################
function displayLoading(msg) {
	if (!msg) msg = "데이터를 처리하고 있습니다.<br />잠시만 기다려주세요.";

	var box = $('loadings');

	if (box) {
		box.visibility = "hidden";
	}
	else {
		var box = document.createElement("div");
		box.id = "loadings";
		with (box.style) {
			position = "absolute";
			visibility = "hidden";
		}
			var table = document.createElement("table");
			with (table.style) {
				borderCollapse = "collapse";
				border = "1px solid #D0D0D0";
				backgroundColor = "#F7F7F7";
			}
				var tbody = document.createElement("tbody");
					var tr = document.createElement("tr");
						var td = document.createElement("td");
						with (td.style) {
							textAlign = "center";
							padding = "30px 45px 30px 45px";
						}
							var div = document.createElement("div");
							div.id = "loadings_msg"
							with (div) {
								with (style) {
									fontSize = "12px";
									fontFamily = "dotum";
									fontWeight = "bold";
									color = "#5E5E5E";
								}
							}
						td.appendChild(div);
							var div = document.createElement("div");
							div.style.marginTop = "5px";
								var img = document.createElement("img");
								img.src = PATH_GLOBAL+"/images/loadingB.gif";
							div.appendChild(img);
						td.appendChild(div);
					tr.appendChild(td);
				tbody.appendChild(tr);
			table.appendChild(tbody);
		box.appendChild(table);

		document.body.appendChild(box);
	}

		$("loadings_msg").innerHTML = msg;

	box.style.top = ((document.body.offsetHeight / 2) - (box.offsetHeight / 2))+'px';
	box.style.left = ((document.body.offsetWidth / 2) - (box.offsetWidth / 2))+'px';
	box.style.visibility = "visible";
}

function hideLoading() {
	if ($('loadings')) {
		$S('loadings').visibility = "hidden";
	}
}
