//********************************************************//
//	유틸리티 사용함수 정의
//********************************************************//

///////////////////////////////////////////////////////////////
//////  클립보드로 내용 저장 (CTRL + C)
///////////////////////////////////////////////////////////////
function copyClip(meintext) {
	if (window.clipboardData)  {

		window.clipboardData.setData("Text", meintext);

	} else if (window.netscape) { 
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');
		var clip = Components.classes['@mozilla.org/widget/clipboard;1'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;
		var trans = Components.classes['@mozilla.org/widget/transferable;1'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;
		trans.addDataFlavor('text/unicode');

		var str = new Object();
		var len = new Object();
		var str = Components.classes["@mozilla.org/supports-string;1"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;
		str.data=copytext;
		trans.setTransferData("text/unicode",str,copytext.length*2);

		var clipid=Components.interfaces.nsIClipboard;
		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);
	}
	return false;
}


//popup
function popWindow(pop,width,height,scroll) {
	var url = pop;  
	var wd = width;
	var he = height;
	window.open(url,"","toolbar=0,menubar=0,scrollbars=" + scroll + ",resizable=no,width=" + wd +",height=" + he + ";")
}


//popup
function popWindowCoord(pop,width,height,top,left,scroll) {
	var url = pop;  
	var wd = width;
	var he = height;
	window.open(url,"","toolbar=0,menubar=0,scrollbars=" + scroll + ",top="+top+",left="+left+",resizable=no,width=" + wd +",height=" + he + ";")
}

//popup
function popWindowCenter(pop,width,height,scroll) {
	var url = pop;  
	var wd = width;
	var he = height;
	var top = (window.screen.height-he)/2;
	var left = (window.screen.width-wd)/2;
	window.open(url,"","toolbar=0,menubar=0,scrollbars=" + scroll + ",resizable=no,top="+top+",left="+left+",width=" + wd +",height=" + he + ";")
}

///////////////////////////////////////////////
///////// 숫자키만 허용 함수
///////////////////////////////////////////////
function checkKeyDownNumber(e) {
	ev = (e||window.event);
	if(ev.srcElement) {
		var key = ev.keyCode;
		if ((key >= 48 && key <= 57) // 키보드 상단 숫자키
	       //|| (key >= 96 && key <= 105) // 키패드 숫자키
	       || key == 8  // 백스페이스 키
	       || key == 37 // 왼쪽 화살표 키
	       || key == 39 // 오른쪽 화살표 키
	       || key == 46 // DEL 키
	       || key == 13 // 엔터 키
	       || key == 9  // Tab 키
	       )
			ev.returnValue=true;
		else
			ev.returnValue=false;
	}
}

///////////////////////////////////////////////
///////// 지정키 입력시 함수실행 함수
///////////////////////////////////////////////
function keyPressHandler(code, funcName) { 
   if(isNaN(code)) {
    	return false;
   } else if(event.keyCode == code) {
     if(funcName){
     	eval(funcName);
     }
     return false;
   }
}

///////////////////////////////////////////////
///////// 쿠키관련 함수
///////////////////////////////////////////////
// 쿠키를 생성한다 (활성주기는 일단위로 설정)
	function setCookie( name, value, expiredays ){
		var todayDate = new Date();

		todayDate.setDate( todayDate.getDate() + expiredays );

		document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
	}

// 생성된 쿠키값을 가져온다.
function getCookie(name){ 
	var nameOfCookie = name + "="; 
	var x = 0; 

	while ( x <= document.cookie.length ) {
		var y = (x+nameOfCookie.length); 
		if ( document.cookie.substring( x, y ) == nameOfCookie ) { 
			if ( (endOfCookie=document.cookie.indexOf( ";", y )) == -1 ) 
				endOfCookie = document.cookie.length; 
			return unescape( document.cookie.substring( y, endOfCookie ) ); 
		} 
		x = document.cookie.indexOf( " ", x ) + 1; 
		if ( x == 0 ) 
			break; 
	}
	return ""; 
}

function deleteCookie( cookieName ){
	var expireDate = new Date();
	expireDate.setDate( expireDate.getDate() - 1 );
	document.cookie = cookieName + "= " + "; path=/; expires=" + expireDate.toGMTString();
}

// 현제 브리우져가 쿠키를 사용할 수 있는지 체크한다.
function checkCookieEnabled() {
	setCookie("checkCookie","Y",5);
	var value = getCookie("checkCookie");
	return value == "Y" ? true : false;
}

//-------------------------------------------------------
//바이트 계산, return 총바이트수
//-------------------------------------------------------
function getByte(instr) {
    var len = 0;
    for(i=0; i<instr.length; i++) {
        var chr = instr.charAt(i);
        if (escape(chr).length > 4) {
                len += 2;
        }
        else  {
                len++;
        }
    }
    return len;
}

//-------------------------------------------------------
// 문자열에서 앞뒤 공백 제거 , return 공백 제거된 문자열
// 사용법 : "string".trim();
//-------------------------------------------------------
String.prototype.trim = function() {
	return this.replace(/\s/g, "");
}

//-------------------------------------------------------
// 문자열에서 앞 공백 제거 , return 공백 제거된 문자열
// 사용법 : "string".ltrim();
//-------------------------------------------------------
String.prototype.ltrim = function() {
	var i, j = 0;
	var objstr
	for (i = 0; i < this.length; i++) {
		if (this.charAt(i) == ' ') j = j + 1;
		else break;
	}
	return this.substr(j, this.length - j + 1)  
}


//-------------------------------------------------------
// 문자열에서 뒤 공백 제거 , return 공백 제거된 문자열
// 사용법 : "string".rtrim();
//-------------------------------------------------------
String.prototype.rtrim = function() {
	var i, j = 0;
	for (i = this.length - 1; i >= 0; i--) {
		if (this.charAt(i) == ' ') j = j + 1;
		else break;
	}
	return this.substr(0, this.length - j);
}

//-------------------------------------------------------
// 숫자(소수점 존재)에 , 추가된 포맷으로 변경
//-------------------------------------------------------
function formatNumber(strOrg) {
	strOrg = "" + strOrg;
	if(strOrg == "")	return "";

	var strNum = "";
	for(i=0; i<strOrg.length; i++) {
		if(strOrg.charAt(i) == ",")
			continue;
		strNum += strOrg.charAt(i);
	}

	if(!Validate.isNum(strNum))	return strOrg;

	var dot = strNum.indexOf(".");
	var strInt = "";
	var strFlt = "";
	if(dot > 0) {
		strInt = strNum.substring(0,dot);
		strFlt = strNum.substring(dot);
	}
	else
		strInt = strNum;

	var smod = strInt.length % 3;
	var strRtn = "";
	if(smod > 0)	strRtn = strInt.substring(0,smod);
	for(i=smod; i<strInt.length; i++) {
		if(smod != 0 && i == smod)	strRtn += ",";
		else if(i > 0 && (i - smod) % 3 == 0)
			strRtn += ","
		strRtn += strInt.charAt(i);
	}
	if(dot > 0)	strRtn += strFlt;

	return strRtn;
}

//-------------------------------------------------------
// 숫자에서  , 제거
//-------------------------------------------------------
function removeComma(str) {
	var len = str.length;
	var rstr = "";
	if (len > 0) {
		for (var i = 0; i < len; i++) {
			var ch = str.charAt(i);
			if (ch != ',') rstr += ch;
		}
	}
	return rstr;
}


//-------------------------------------------------------
// 숫자에  , 추가
//-------------------------------------------------------
function insertComma(vstr) {
	var str = vstr;
	str += "";

	var comval = "";
	var inversecomval = "";

	for ( k = 0 ; k < str.length ; k++ ) {
		if ( k != 0 && k%3 == 0 ) {
			comval += ",";
		}
		comval += str.charAt(str.length-(k+1));
	}

	for ( k = 0 ; k < comval.length; k++ ) {
		inversecomval += comval.charAt(comval.length-(k+1));
	}
	return inversecomval;
}


function getFillZero(value, length) {
	var val = new String(value);
	var valLength = val.length;
	for(var i = 1; i <= length - valLength; i++) {
		val = "0"+val;
	}
	return val;
}

//-------------------------------------------------------------------------
//이미지 리사이즈  : 가로/세로 제한을 파라미터로 넘김 
//-------------------------------------------------------------------------
function imgResizeTo(obj, limit) {
	var imgWidth = 0;
	var imgHeight = 0;
	var imgRatio = 0;
	var i = 0;

	if(obj == null) return;
	
	imgWidth = obj.width;
	imgHeight = obj.height;

	//작은 사이즈를 기준으로 사이즈 변경
	if(imgWidth >=  imgHeight) {
		obj.width = limit;
		obj.height = (limit * imgHeight) / imgWidth;
	} else {
		obj.height = limit;
		obj.width = (limit * imgWidth) / imgHeight;
	}
	
}

//-------------------------------------------------------------------------
//이미지 리사이즈  : 가로 제한을 파라미터로 넘김, num 바꿀 이미지 개수 
//-------------------------------------------------------------------------
function imgResizeToNumW(idName, limitWidth, num) {
	var obj
	var imgWidth = 0;
	var imgHeight = 0;
	var imgRatio = 0;
	var i = 0;

	for(i = 0; i <= num; i++) {
		obj = document.getElementById(idName + i);
		if(obj == null) continue;

		imgWidth = obj.width;
		imgHeight = obj.height;
		imgRatio = 0
	
		if (imgWidth > limitWidth) {
			imgRatio= imgHeight * limitWidth / imgWidth;
			obj.width= limitWidth;
			obj.height= imgRatio;
		}
	}
}

//-------------------------------------------------------------------------
//이미지 리사이즈  : 세로 제한을 파라미터로 넘김, num 바꿀 이미지 개수 
//-------------------------------------------------------------------------
function imgResizeToNumH(idName, limitHeight, num) {

	var obj
	var imgWidth = 0;
	var imgHeight = 0;
	var imgRatio = 0;
	var i = 0;

	for(i = 0; i <= num; i++) {
		obj = document.getElementById(idName + i);
		if(obj == null) continue;

		imgWidth = obj.width;
		imgHeight = obj.height;
		imgRatio = 0
	
		if (imgHeight > limitHeight) {
				imgRatio= imgWidth * limitHeight  /  imgHeight;
				obj.height= limitHeight;
				obj.width= imgRatio;
		}
	}
}

//-------------------------------------------------------------------------
//iframe 사이즈 높이 조절 
// 사용법 : <iframe src="url" onload="resizeiFrameHeight(this)"></iframe>
//-------------------------------------------------------------------------
function resizeiFrameHeight(obj){

	var innerBody = obj.contentWindow.document.body;

	var innerHeight = innerBody.scrollHeight + (innerBody.offsetHeight - innerBody.clientHeight);

	if (navigator.appName != "Microsoft Internet Explorer") {	//ie가 아닐 경우 
		innerHeight = innerBody.offsetHeight 
	}

	obj.style.height = innerHeight;

}

//-------------------------------------------------------------------------
//윈도우 창크기 조절 
// 사용법 : <body onload="resizeWin()">
//-------------------------------------------------------------------------
function resizeWin(){

	var winW, winH, sizeToW, sizeToH;

	if ( parseInt(navigator.appVersion) > 3 ) {
		if ( navigator.appName=="Netscape" ) {
			winW = window.innerWidth;
			winH = window.innerHeight;
		}
		if ( navigator.appName.indexOf("Microsoft") != -1 ) {
			winW = document.documentElement.scrollWidth;
			winH = document.documentElement.scrollHeight;
		}
	}

	sizeToW = 0;
	sizeToH = 0;

	if ( winW > 1000 ) sizeToW = 1000 - document.documentElement.clientWidth;
	else if ( Math.abs(document.documentElement.clientWidth - winW ) > 3 ) sizeToW = winW - document.documentElement.clientWidth;

	if ( winH > 680 ) sizeToH = 680 - document.documentElement.clientHeight;
	else if ( Math.abs(document.documentElement.clientHeight - winH) > 4 ) sizeToH = winH - document.documentElement.clientHeight;

	if ( sizeToW != 0 || sizeToH != 0 ) window.resizeBy(sizeToW, sizeToH);

}

// Debug 용. 우측에 메세지 박스를 띄운 후 내용을 뿌려준다.
var trace = function(text) {
	var debug = true;
	if(debug) {
		if(!$("traceMsg")) {
			var objDiv = new Element("div",{id:"traceMsg"});
			objDiv.setStyle({overflow:"auto",zIndex:"1200",position:"absolute",top:"30px",right:"30px",width:"300px",height:"500px",
							backgroundColor:"#FFFFFF",filter:"Alpha(opacity=70)",opacity:(70/100)});
			objDiv.update("<table border='1' width='100%' height='500'><tr><td valign='top' id='traceMsgOut'></td></tr></table>");
			$$("body")[0].insert(objDiv);
		}
		$("traceMsgOut").innerHTML = text+"<br>"+$("traceMsgOut").innerHTML;
	}
}

// 입력폼에 대한 문자열 길이 제한 (한글처리)
var checkValueLength = function(obj,title,maxLength) {
	var str = new String();
	var strLength = 0;
	for(i=0; i < obj.value.length; i++) {
		var addLength = Validate.isKor(obj.value.charAt(i)) ? 2 : 1;
		strLength += addLength 
		if(strLength > maxLength) {
			alert(title+"은(는) 영문기준 "+maxLength+"자, 한글기준 "+Math.floor(maxLength/2)+"자 이하 입력가능합니다.");
			obj.value = str;
			strLength -= addLength;
			break;
		}
		str += obj.value.charAt(i);
	}
	return strLength;
}


/*select box 위로 레이어 띄우기 */
// Internet Explorer에서 셀렉트박스와 레이어가 겹칠시 레이어가 셀렉트 박스 뒤로 숨는 현상을 해결하는 함수
// 레이어가 셀렉트 박스를 침범하면 셀렉트 박스를 hidden 시킴
// 사용법 :
// <div id=LayerID style="display:none; position:absolute;" onpropertychange="selectbox_hidden('LayerID')">
var selectboxHidden = function(layer_id, tagName)
{
	tagName = (tagName||"SELECT");
	var ly = eval(layer_id);
	
	var selectBoxs = $(layer_id).getElementsByTagName(tagName);

	// 레이어 좌표
	var ly_left  = ly.offsetLeft;
	var ly_top    = ly.offsetTop;
	var ly_right  = ly.offsetLeft + ly.offsetWidth;
	var ly_bottom = ly.offsetTop + ly.offsetHeight;

	// 셀렉트박스의 좌표
	var el;

	for (i=0; i<document.forms.length; i++) {
		for (k=0; k<document.forms[i].length; k++) {
			el = document.forms[i].elements[k];
			if(tagName == "OBJECT") {
				var id = "CLSID:4D68446C-92A2-4A32-BD61-E18708016387";
				if(el.getAttribute("CLASSID") != id) continue;
			}
			if (el.tagName == tagName) {
				var checkSame = false;
				for(z = 0; z < selectBoxs.length; z++) {
					if(selectBoxs.item(z).name == el.name) {
						checkSame = true;
						break;
					}
				}
				if(!checkSame) {
					var el_left = el_top = 0;
					var obj = el;
					if (obj.offsetParent) {
						while (obj.offsetParent) {
							el_left += obj.offsetLeft;
							el_top  += obj.offsetTop;
							obj = obj.offsetParent;
						}
					}
					el_left  += el.clientLeft;
					el_top    += el.clientTop;
					el_right  = el_left + el.clientWidth;
					el_bottom = el_top + el.clientHeight;
	
					// 좌표를 따져 레이어가 셀렉트 박스를 침범했으면 셀렉트 박스를 hidden 시킴
					if ( (el_left >= ly_left && el_top >= ly_top && el_left <= ly_right && el_top <= ly_bottom) ||
						(el_right >= ly_left && el_right <= ly_right && el_top >= ly_top && el_top <= ly_bottom) ||
						(el_left >= ly_left && el_bottom >= ly_top && el_right <= ly_right && el_bottom <= ly_bottom) ||
						(el_left >= ly_left && el_left <= ly_right && el_bottom >= ly_top && el_bottom <= ly_bottom) )
						el.style.visibility = 'hidden';
				}
			}
		}
	}
}

// 감추어진 셀렉트 박스를 모두 보이게 함
var selectboxVisible = function (tagName)
{
	tagName = (tagName||"SELECT");
	for (i=0; i<document.forms.length; i++) {
		for (k=0; k<document.forms[i].length; k++) {
			el = document.forms[i].elements[k];
			if (el.tagName == tagName && el.style.visibility == 'hidden')
				el.style.visibility = 'visible';
		}
	}
}

var zoomSize = 100; 
function zoom(obj,method) { 
    if(method == "in") { 
        zoomSize = zoomSize+10; 
    } else if(method == "out") { 
        if(zoomSize > 10) { 
			zoomSize = zoomSize-10;
        } 
    } else if(method == "reset") { 
        zoomSize = 100; 
    } 
    document.getElementById(obj).style.zoom = zoomSize + "%"; //특정 영역만 설정시
} 

// 입력폼 자동 포커스 변환
function autoFocus(e, length, target) {
	ev = (e||window.event);
	var obj = ev.srcElement; 
	if(obj.value.length >= length 
			&& !$A([0,8,9,16,17,18,37,38,39,40,46]).include(ev.keyCode)) {
		target.focus();
	}
}

	
function onlyNumber() {
	var ev = window.event;
	if(ev.srcElement) {
		var key = ev.keyCode;
		if ((key >= 48 && key <= 57) // 키보드 상단 숫자키
	       //|| (key >= 96 && key <= 105) // 키패드 숫자키
	       || key == 8  // 백스페이스 키
	       || key == 37 // 왼쪽 화살표 키
	       || key == 39 // 오른쪽 화살표 키
	       || key == 46 // DEL 키
	       || key == 13 // 엔터 키
	       || key == 9  // Tab 키
	       )
			ev.returnValue=true;
		else
			ev.returnValue=false;
	}
}

// 날짜변환
function calculate(start, end) {
	var start = start.split("-");  
	var end = end.split("-");   

	var startdate = new Date(start[0], start[1]-1, start[2]);
	var enddate = new Date(end[0], end[1]-1, end[2]);
	return result = (enddate.getTime() - startdate.getTime() ) / 1000 / 60 / 60 / 24;    // Date 객체는 밀리초단위임
}


// 나이 계산
// strDate-YYYYMM, todate-YYYYMMDD, isFullAge-Y/N(만나이여부)
function getAge(strDate, todate, isFullAge){
	var Fage, Fage2, Ndate, Ndate2;

	Fage	= strDate.substring(0,2);
	Fage2	= strDate.substring(2,4);
	Fage3	= strDate.substring(2,6);
	Ndate	= todate.substring(0,4);
	Ndate2	= todate.substring(4,8);

	Fage2	= "20" + Fage;

	if(Fage2 >= Ndate){
		Fage2 = "19" + Fage;
	}

	Fage = Ndate - Fage2 + 1

	if(Fage > 100){
		Fage = Fage - 100;
	}

	// 만 나이 계산 [isFullAge = Y]
	if(isFullAge == "Y"){
		if(Ndate2 > Fage3){
			Fage = Fage - 1;
		} else {
			Fage = Fage - 2;
		}
	}
	return Fage;
}


function setURL(param) {
	var query = $H(param).toQueryString();
	document.location.href = "#"+query;
}

function getURL() {
	var href = document.location.href;
	var param = $H({});
	if(href.indexOf("#") > 0) {
		query = href.substr(href.indexOf("#")+1);
		param = query.toQueryParams();
	}
	return param;
}