// Trim 함수 ##################################################
// Ex) str = "    테 스트   ".trim(); => str = "테 스트";
String.prototype.trim = function() {
    return this.replace(/(^\s*)|(\s*$)/g, "");
}

// 문자열 공백제거 함수 ##################################################
// Ex) str = "    테 스   트   ".stripspace(); => str = "테스트";
String.prototype.stripspace = function() {
	return this.replace(/ /g, "");
}

// 전체 문자열 바꾸기 함수 ##################################################
// Ex) str = "a테스트bcd테스트efg".replaceAll("테스트", ""); => str = "abcdefg";
String.prototype.replaceAll = function(a, b) {
	var s = this;
	var n1, n2, s1, s2;

	while (true) {
		if ( s=="" || a=="" ) break;
		n1 = s.indexOf(a);
		if ( n1 < 0 ) break;
		n2 = n1 + a.length;
		if ( n1==0 ) {
			s1 = b;
		}
		else {
			s1 = s.substring(0, n1) + b;
		}
		if ( n2 >= s.length ) {
			s2 = "";
		}
		else {
			s2 = s.substring(n2, s.length);
		}
		s = s1 + s2;
	}
	return s;
}

// Event 추가 ##################################################
function addEvent(obj, evt, exec) {
	if (window.attachEvent) obj.attachEvent('on'+evt, exec);
	else if (window.addEventListener) obj.addEventListener(evt, exec, false);
	else obj['on'+evt] = exec;
}

// 팝업 ##################################################
function MM_openBrWindow(theURL, winName, features) { //v2.0
	if (features && features.indexOf("status") < 0) features += features+",status=yes";
	var popup = window.open(theURL, winName, features);
	popup.focus();
}

// 팝업 - 팝업창 화면중앙 오픈 ##################################################
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 (remFeatures) features += ","+remFeatures;

	MM_openBrWindow(theURL, winName, features);
}

// 팝업 - 팝업창 사이즈 조정 ##################################################
function resizePopupWindow(width, height) {
	window.resizeTo(width+12, height+49);
}

// 팝업 - 팝업창 위치 조정 ##################################################
function movePopupWindow(left, top) {
	window.moveTo(left, top);
}

// 모달 ##################################################
function MM_openModal(theURL, obj, features) {
	window.showModalDialog(theURL, obj, features);
}

// 키 관련 함수 ##################################################
function blockKey() {
	event.returnValue = false;
}

function blockEnter() {
	if (event.keyCode == 13) event.keyCode = 0;
}

function blockNotNumber() {
	if (event.keyCode < 48 || event.keyCode > 57) event.returnValue = false;
}

function onEnter(nextItem) {
	if (event.keyCode == 13) {
		if (nextItem) nextItem.focus();
	}
}

// 페이지 이동 ##################################################
function gotoUrl(url) {
	if (url.stripspace() != "") {
		location.href = url;
	}
}

// 페이지 최상단으로 ##################################################
function goTop() {
	window.scrollTo(0, 0);
}

// 이미지 미리보기 ##################################################
function previewImage(item, elmId) {
	var img = document.getElementById(elmId);

	if (item.value.stripspace() == "") return;

	var ext = getFileExt(item.value).toUpperCase();

	if (ext == 'JPG' || ext == 'GIF' || ext == 'BMP' || ext == 'PNG') img.src = item.value;
}

// 이미지 사이즈 줄이기 ##################################################
function resizeImage(elmId, type, size) { // elmId(이미지 Id), type(제한 대상: W-가로, H-세로), size(제한 사이즈)
	var img = document.getElementById(elmId);

	if (img.complete == false)	{
		setTimeout("resizeImage('"+elmId+"', '"+type+"', "+size+")", 200);
		return;
	}

	if (type == "W") {
		if (img.width > size) img.width = size;
	}
	else {
		if (img.height > size) img.height = size;
	}
}

// 이미지 사이즈 줄이기 (Editor) ##################################################
function resizeImageEditor(no) {
	var objImg = document.getElementById('editor_img'+no);
	var width = parseInt(objImg.width, 10);
	if (width > EDITOR_IMG_WIDTH) objImg.width = EDITOR_IMG_WIDTH;
}

// IFRAME RESIZE 함수 ##################################################
function resizeFrame(iframeWindow, minWidth, minHeight, fixWidth, fixHeight) {
	if (!iframeWindow.name) return false;

	var iframeElement = document.getElementById(iframeWindow.name);
	var resizeWidth = 0;
	var resizeHeight = 0;

	minWidth = (minWidth) ? parseInt(minWidth, 10) : 0;
	minHeight = (minHeight) ? parseInt(minHeight, 10) : 0;
	fixWidth = (fixWidth) ? parseInt(fixWidth, 10) : 0;
	fixHeight = (fixHeight) ? parseInt(fixHeight, 10) : 0;

	if (navigator.appName.indexOf("Netscape") == -1) { // ie
		if (iframeWindow.document.compatMode && iframeWindow.document.compatMode != 'BackCompat') {
			resizeWidth = iframeWindow.document.documentElement.scrollWidth;
			resizeHeight = iframeWindow.document.documentElement.scrollHeight;
		}
		else {
			resizeWidth = iframeWindow.document.body.scrollWidth;
			resizeHeight = iframeWindow.document.body.scrollHeight;
		}
	}
	else {
		resizeWidth = iframeWindow.document.body.scrollWidth;
		resizeHeight = iframeWindow.document.body.scrollHeight;
	}

	if (minWidth > 0 && resizeWidth < minWidth) resizeWidth = minWidth;			// 최소 폭
	if (minHeight > 0 && resizeHeight < minHeight) resizeHeight = minHeight;		// 최소 높이

	if (fixWidth > 0) resizeWidth = fixWidth;		// 고정 폭
	if (fixHeight > 0) resizeHeight = fixHeight;	// 고정 높이

	if (fixWidth > -1) iframeElement.style.width = resizeWidth + 'px';
	if (fixHeight > -1) iframeElement.style.height = resizeHeight + 'px';
}

// 현재 이벤트객체 Index 가져오기 ##################################################
function getDisObjIdx(item) {
	var i = 0;
	var result = 0;

	var arrTag = document.getElementsByTagName('*');

	if (item.sourceIndex) {
		while (arrTag[i].sourceIndex < item.sourceIndex) {
			if (arrTag[i].id == item.id) ++result;
			++i;
		}
	}
	else if (item.compareDocumentPosition) {
		while ((arrTag[i].compareDocumentPosition(item) & 6) - 3 > 0) {
			if (arrTag[i].id == item.id) ++result;
			++i;
		}
	}

	return result;
}

// 체크박스 전체선택 ##################################################
function checkCbAll(cbList, isChecked) {
	if (cbList) {
		if (typeof(cbList.length) == "undefined") {
			if (!cbList.disabled) cbList.checked = isChecked;
		}
		else {
			for (var i=0; i<cbList.length; i++) {
				if (cbList[i].type.toUpperCase() == 'CHECKBOX') {
					if (cbList[i].value.stripspace() != "" && !cbList[i].disabled) {
						cbList[i].checked = isChecked;
					}
				}
			}
		}
	}
}

// 텍스트 길이 확인 (일반) ##################################################
function checkTextLen(item, mLen) {
	if (item.value.length > mLen){
		alert("1~"+mLen+"자까지 입력이 가능합니다.");
		item.value = item.value.substring(0, mLen);
		item.focus();
		return false;
	}

	return true;
}

// 텍스트 길이 확인 (Byte) ##################################################
function checkTextLenByte(item, mLen) {
	var i, len;
	var byteLen = 0;
	var value = item.value;

	for (i=0, len=value.length; i<len; i++) {
		++byteLen;

		if ((value.charCodeAt(i) < 0) || (value.charCodeAt(i) > 127)) ++byteLen;

		if (byteLen > mLen) {
			alert("1~"+(mLen / 2)+"자의 한글, 또는 2~"+mLen+"자의 영문, 숫자, 문장기호로 입력이 가능합니다.");
			item.value = value.substring(0, i);
			item.focus();
			return false;
		}
	}

	return true;
}

// 텍스트 Byte 길이 가져오기 ##################################################
function getTextByte(value) {
	var i, len;
	var byteLen = 0;

	for (i=0, len=value.length; i<len; i++) {
		if (escape(value.charAt(i)).length >= 4) {
			byteLen += 2;
		}
		else if (escape(value.charAt(i)) != "%0D") {
			++byteLen;
		}
	}

	return byteLen;
}

// 입력 문자길이 확인후 다음항목으로 포커스 옮기기 ##################################################
function goNextFocusChk(item, len, next_item) {
	if (item.value.stripspace().length == len){
		next_item.focus();
	}
}

// 영문 문자열 확인 ##################################################
function strEngCheck(value){
	var i;

	for(i=0;i<value.length-1;i++){
		// 한글 체크 (한글 ASCII코드 : 12593부터)
		if (value.charCodeAt(i) > 12592) return false;
		// 공백 체크
		if (value.charAt(i) == " ") return false;
	}
	return true;
}

// 파일명 확인 ##################################################
function checkFileName(item) {
	var result = false;

	if (item.value.stripspace() != "") {
		var fidx = item.value.lastIndexOf("\\")+1;
		var filename = item.value.substr(fidx, item.value.length);
		result = strEngCheck(filename);
	}

	if (!result) {
		alert("파일명을 반드시 영문 또는 숫자로 해주세요.");
		item.focus();
		return false;
	}
	return true;
}

// 파일 확장자 ##################################################
function getFileExt(value) {
	if (value != "") {
		var fidx = value.lastIndexOf("\\")+1;
		var filename = value.substr(fidx, value.length);
		var eidx = filename.lastIndexOf(".")+1;

		return filename.substr(eidx, filename.length);
	}
}

// 파일확장자 확인 ##################################################
function checkFileExt(item, exts, errMsg) {
	var arrExt = exts.toLowerCase().split(",");
	var result = false;

	if (item.value.stripspace() != "") {
		var ext = getFileExt(item.value).toLowerCase();

		for (var i=0; i<arrExt.length; i++) {
			if (arrExt[i].trim() == ext) result = true;
		}
	}

	if (!result) {
		alert(errMsg);
		item.focus();
		return false;
	}
	return true;
}

// 영문/숫자 혼용 확인 ##################################################
function checkEngNum(str) {
	var RegExpE = /[a-zA-Z]/i;
	var RegExpN = /[0-9]/;

	return (RegExpE.test(str) && RegExpN.test(str)) ? true : false;
}

// 특수문자 확인 ##################################################
function checkSpecialChar(value) {
	var specialChar = "`~!@#$%^&*_+=|\\[]{}:;,<.>/?'\"";
	for (var i=0, len=specialChar.length; i<len; i++) {
		if (value.indexOf(specialChar.substr(i, 1)) != -1) return true;
	}
	return false;
}

// 아이디 확인 ##################################################
function checkID(value, min, max) {
	var RegExp = /^[a-zA-Z0-9_]*$/i;
	var returnVal = RegExp.test(value) ? true : false;
	if (typeof(min) != "undefined" && value.length < min) returnVal = false;
	if (typeof(max) != "undefined" && value.length > max) returnVal = false;
	return returnVal;
}

// 비밀번호 확인 ##################################################
function checkPW(value, min, max) {
	var RegExp = /^[a-zA-Z0-9]*$/i;
	var returnVal = RegExp.test(value) ? true : false;
	if (typeof(min) != "undefined" && value.length < min) returnVal = false;
	if (typeof(max) != "undefined" && value.length > max) returnVal = false;
	return returnVal;
}

// 숫자 확인 ##################################################
function checkNum(value, isDec) {
	var RegExp;

	if (!isDec) isDec = false;

	if (isDec) RegExp = /^-?[\d\.]*$/;
	else RegExp = /^-?[\d]*$/;

	return RegExp.test(value)? true : false;
}

// 이메일 확인 ##################################################
function checkEmail(email) {
	if (email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1) {
		return true;
	}
	else {
		return false;
	}
}

// URL 확인 ##################################################
function checkUrl(url) {
	var exp = new RegExp("^(http|https)\:\/\/");
	if (exp.test(url.toLowerCase())) {
		return true;
	}
	else {
		return false;
	}
}

// 공백 확인 ##################################################
function checkEmpty(item) {
	if (item.value.stripspace() == "") {
		return true;
	}
	else {
		return false;
	}
}

// Radio(CheckBox) 설정값 가져오기 ##################################################
function getRadioVal(item) {
	var i, value = "";

	if (item) {
		if (typeof(item.length) == "undefined") {
			if (item.checked) {
				value = item.value;
			}
		}
		else {
			for (i=0; i<item.length; i++) {
				if (item[i].checked) {
					value = item[i].value;
					break;
				}
			}
		}
	}
	return value;
}

// Radio 설정하기 ##################################################
function setRadioVal(item, value) {
	var i;

	if (item) {
		if (typeof(item.length) == "undefined") {
			if (item.value == value) {
				item.checked = true;
			}
		}
		else {
			for(i=0; i<item.length; i++) {
				if (item[i].value == value) {
					item[i].checked = true;
					break;
				}
			}
		}
	}
}

// Radio Disabled 설정하기 ##################################################
function setRadioDisabled(item, value, disabled) {
	var i;

	if (item) {
		if (typeof(item.length) == "undefined") {
			if (item.value == value) {
				item.disabled = disabled;
			}
		}
		else {
			for(i=0; i<item.length; i++) {
				if (item[i].value == value) {
					item[i].disabled = disabled;
					break;
				}
			}
		}
	}
}

// Form Disabled 전체 설정하기 ##################################################
function setRadioDisabledAll(item, disabled) {
	var i;

	if (item) {
		if (typeof(item.length) == "undefined") {
			item.disabled = disabled;
		}
		else {
			for(i=0; i<item.length; i++) {
				item[i].disabled = disabled;
			}
		}
	}
}

// Select 설정값 가져오기 ##################################################
function getSelectVal(item) {
	var value = "";
	var idx = item.selectedIndex;

	if (idx >= 0){
		value = item.options[idx].value;
	}

	return value;
}

// Select Option 추가 ##################################################
function selectAddList(item, text, value) {
	var newOpt = document.createElement("OPTION");
	newOpt.text = text;
	newOpt.value = value;
	item.options.add(newOpt);
}

// Select Option 전체삭제 ##################################################
function selectRemoveAll(item) {
	for (var i=item.length-1; i>=0; i--) {
		selectRemoveList(item, i);
	}
}

// Select Option 삭제 ##################################################
function selectRemoveList(item, i) {
	item.remove(i);
}

// Hidden 추가 ##################################################
function addHidden(f, name, value) {
	var input = document.createElement('INPUT');
	input.type = 'HIDDEN';
	input.name = name;
	input.value = value;
	f.appendChild(input);
}

// 숫자 문자열에서 문자열 제거 ##################################################
function stripCharFromNum(value, isDec) {
	var i;
	var minus = "-";
	var nums = "1234567890"+((isDec) ? "." : "");
	var result = "";

	for(i=0; i<value.length; i++) {
		numChk = value.charAt(i);
		if (i == 0 && numChk == minus) {
			result += minus;
		}
		else {
			for(j=0; j<nums.length; j++) {
				if(numChk == nums.charAt(j)) {
					result += nums.charAt(j);
					break;
				}
			}
		}
	}
	return result;
}

// 콤마(,) 제거 ##################################################
function stripComma(str) {
    var re = /,/g;
    return str.replace(re, "");
}

// 숫자 3자리수마다 콤마(,) 찍기 ##################################################
function formatComma(num, pos) {
	if (!pos) pos = 0;  //소숫점 이하 자리수
	var re = /(-?\d+)(\d{3}[,.])/;

	var strNum = stripComma(num.toString());
	var arrNum = strNum.split(".");

	arrNum[0] += ".";

    while (re.test(arrNum[0])) {
        arrNum[0] = arrNum[0].replace(re, "$1,$2");
    }

	if (arrNum.length > 1) {
		if (arrNum[1].length > pos) {
			arrNum[1] = arrNum[1].substr(0, pos);
		}
		return arrNum.join("");
	}
	else {
		return arrNum[0].split(".")[0];
	}
}

// 강제 소수점 이하 0채우기 ##################################################
// num: 대상숫자, pos: 출력을 원하는 소수점자리수
function setRoundZero(num, pos) {
	var strNum = stripComma(num.toString());
	var arrNum = strNum.split(".");

	if (arrNum.length <= 1) {
		num = arrNum[0]+".";
		for (var i=0; i<pos; i++) {
			num += "0";
		}
	}
	else {
		num = setRound(num, pos);
	}
	return num;
}

// 소수점 이하 반올림 ##################################################
// num: 대상숫자, pos:출력을 원하는 소수점자리수
function setRound(num, pos) {
	if(!pos) pos = 0;
	return (Math.round(num*(Math.pow(10,pos))))/(Math.pow(10, pos));
}

// 소수점 이하 자리수 확인 ##################################################
// num: 대상숫자, pos: 희망 소수점 이하자리수
function checkRound(num, len) {
	var strNum = stripComma(num.toString());
	var arrNum = strNum.split(".");

	if (arrNum.length > 1 && arrNum[1].length > len) return false;
	else return true;
}

// 숫자 문자열에서 "0" 시작문자 제거 ##################################################
function removePreZero(str) {
	var i, result;

	for (i = 0; i<str.length; i++) {
		if (str.substr(i,1) != "0") break;
	}

	result = str.substr(i, str.length-i);
	//if (result == "") result = "0";
	return result;
}

// 통화형태로 변환 ##################################################
function toCurrency(item) {
	if (isDirectionKey(event.keyCode)) return false;
	if (item.disabled) return false;

	var num = item.value.stripspace();
	if (num == "") return false;

	if (!checkNum(stripComma(num))) {
		alert ("숫자만 입력해주세요.");
		num = stripCharFromNum(num, false);
	}
	num = stripCharFromNum(stripComma(num), false);
	num = removePreZero(num);
	item.value = formatComma(num);
}

// 숫자입력 확인 ##################################################
function numberOnly(item, isDec) {
	if (!isDec) isDec = false;
	if (isDirectionKey(event.keyCode)) return false;
	if (item.disabled) return false;

	var num = item.value.stripspace();
	if (num == "") return false;

	if (!checkNum(num, isDec)) {
		alert ("숫자만 입력해주세요.");
		num = stripCharFromNum(num, isDec);
	}
	num = stripCharFromNum(stripComma(num), isDec);

	var arrNum = num.split(".");
	if (arrNum.length > 1) {
		item.value = arrNum[0]+"."+arrNum[1];
	}
	else {
		item.value = arrNum[0];
	}
}

// 방향키 Key Event 확인 ##################################################
function isDirectionKey(code) {
	switch(code){
		case 39: // 오른쪽
		case 37: // 왼쪽
		case 38: // 위
		case 40: // 아래
		case 9: // tab
			return true;
			break;
		default:
			return false;
			break;
	}
}

// 숫자 증감 처리 ##################################################
function controllNum(item, mode, isminus) {
	var num = item.value;
	if (!isminus) isminus = 0;

	num = (num.stripspace() == "") ? 0 : num;
	num = (isNaN(num)) ? 0 : parseInt(num, 10);

	if (mode == '+') ++num;
	else --num;

	if (isminus != 1 && num < 0) num = 0;

	item.value = num;
}

// 날자 유효성 확인 ##################################################
function isDate(strDate){
	var tmpArr;
	var tmpYear, tmpMon, tmpDay;

	if (strDate.length != 10) return false;

	tmpArr = strDate.split("-");

	if (tmpArr.length != 3 ) return false;

	tmpYear = tmpArr[0];
	tmpMon = tmpArr[1];
	tmpDay = tmpArr[2];

	var tDateString = tmpYear+'/'+tmpMon+'/'+tmpDay+' 8:0:0';
	var tmpDate = new Date(tDateString);

	if (isNaN(tmpDate)) return false;

	if (((tmpDate.getFullYear()).toString() == tmpYear) && (tmpDate.getMonth() == parseInt(tmpMon, 10)-1) && (tmpDate.getDate() == parseInt(tmpDay, 10))) {
		return true;
	}
	else {
		return false;
	}
}

// # 날짜 기간 계산 ##################################################
function inputDate(svrdate, sdate, edate, type, term) {
	today = new Date(svrdate);
	now_year = today.getYear();
	now_month = today.getMonth()+1;
	now_day = today.getDate();

	if (isNaN(term)) term = 0;

	month_temp = now_month-1;
	day_temp = getLastDay(now_year, month_temp);

	the_day = now_day;
	the_month = now_month;
	the_year = now_year;

	if (type == 'T') {
		opt_day = now_day-term;
		if(opt_day>0) {
			the_day = opt_day;
		}
		else {
			opt_month = now_month-1;
			the_day = day_temp+opt_day;
			if(opt_month>0) {
				the_month = opt_month;
			}
			else {
				the_year = now_year-1;
				the_month = 12;
			}
		}
	}
	else if (type=='D') {
		opt_day = now_day-term;
		if(opt_day>0) {
			the_day = opt_day;
		}
		else {
			opt_month = now_month-1;
			the_day = day_temp+opt_day;
			if(opt_month>0) {
				the_month = opt_month;
			}
			else {
				the_year = now_year-1;
				the_month = 12;
			}
		}
	}
	else if (type == 'M') {
		opt_month = now_month-term;
		if(opt_month>0) {
			the_month = opt_month;
		}
		else {
			the_year = now_year-1;
			the_month = 12+opt_month;
		}
	}
	else if (type=='Y'){
		the_year = now_year-term;
	}

	the_ymLastDay = getLastDay(the_year, the_month);
	if (the_ymLastDay < the_day) the_day = the_ymLastDay;

	if(the_month<10) the_month='0'+the_month;
	if(the_day<10) the_day = '0'+the_day;

	the_date = the_year+'-'+the_month+'-'+the_day;
	sdate.value = the_date;

	if(now_month<10) now_month = '0'+now_month;
	if(now_day<10) now_day = '0'+now_day;

	if (type == 'W') {
		sdate.value='';
		if (edate) edate.value='';
	}
	else if (type == 'T' && term > 0) {
		if (edate) edate.value = the_date;
	}
	else {
		now_date = now_year+'-'+now_month+'-'+now_day;
		if (edate) edate.value = now_date;
	}
}

// # 월별 일자수 추출 ##################################################
function getLastDay(year, mon) {
	var last_day = 31;

	switch(mon) {
		case(1): last_day=31; break;
		case(2):
			// 윤년 확인
			if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
				last_day=29;
			}
			else{
				last_day=28;
			}
			break;
		case(3): last_day=31; break;
		case(4): last_day=30; break;
		case(5): last_day=31; break;
		case(6): last_day=30; break;
		case(7): last_day=31; break;
		case(8): last_day=31; break;
		case(9): last_day=30; break;
		case(10): last_day=31; break;
		case(11): last_day=30; break;
		case(12): last_day=31; break;
		default: last_day=31; break;
	}

	return last_day;
}
