/*************************************************************
util.js
--------------------------------=-------
script 유용한 함수 모음

만든날 	: 2009-10-13
만든이 	: devKim
홈페이지 	: http://devkim.co.kr
NateOn 	: gate7711@nate.com
*************************************************************/

/**
 * 브라우저 정보 보기
 * return [0] = 브라우저이름
 * return [1] = 버전 정보
 * */

//

//웹표준관련
var START_TAG = "<";
var AMP = "&";

var Debug = function(isDebug){
	this.div = null;
	this.divHeight;
	this.maxHeight = 100;
	this.minHeight = 20;
	this.isDebug = isDebug;
	this.timer;
	this.preMsg = new Array();
	this.sec = 500;
	this.msgBox;
};

Debug.prototype = {
	createDiv : function(){
		this.divHeight = this.maxHeight;
		this.div = document.createElement('div');
		this.div.setAttribute('id', 'debugLayer');
		this.div = this.setStyle(this.div);
		document.body.appendChild(this.div);
		this.div = $("debugLayer");
		this.div.insert("<div id='debugHead' style='height:20px'></div>");
		this.div.insert("<div id='debugContent' style=\"color:red;overflow:auto\;width:100%;\"></div>");
		this.headBox = $('debugHead');
		this.headBox.insert("#####@@@@@@@##### 디버그 콘솔 #####@@@@@@@##### &nbsp;");
		this.headBox.insert("[<a href='javascript:debug.toggle()'><span>닫기</span></a>]&nbsp;");
		this.headBox.insert("[<a href='javascript:debug.fold()'><span id='foldDebugSpan'>접기</span></a>]&nbsp;");
		this.headBox.insert("[<a href='javascript:debug.copy()'><span id='copyDebugSpan'>복사</span></a>]&nbsp;");
		this.headBox.insert("[<a href='javascript:debug.clear()'><span id='clearDebugSpan'>지우기</span></a>]");
		this.msgBox = $('debugContent');
		this.msgBox.style.height = this.divHeight-20+'px';
	}
	,setStyle : function(obj){
		obj.style.position = 'absolute';
		obj.style.display = 'none';
		//obj.style.color = 'red';
		obj.style.textAlign = 'left';
		//obj.style.overflow = 'auto';
		obj.style.background = '#000000';
		obj.style.width = '100%';
		obj.style.height = this.divHeight+'px';
		obj.style.filter = 'alpha(opacity=80)';
		obj.style.opacity = '0.8';
		obj.style.left = '0px';
		obj.style.top = this.position()+'px';
		return obj;
	}
	,toggle : function(){
		this.div.toggle();
	}
	,print : function(msg){
		if((msg==null || msg=='undefined') && this.preMsg.size()==0) return;
		msg = msg+"";
		if(!this.isDebug) return;
		if(!document.body){
			this.preMsg[this.preMsg.size()] = msg;
			return;
		}
		if(!this.div){
			this.createDiv();
			this.toggle();
		}
		for(debugLoop=0;debugLoop<this.preMsg.size();debugLoop++){
			var lineSizeBefore = $$('li[name="debugBeforeLi"]').size()+1;
			this.msgBox.insert("<li name='debugBeforeLi'>before Line "+lineSizeBefore+" ==> ["+this.preMsg[debugLoop]+"]</li>");
		}
		this.preMsg.clear();
		if(!this.timer){
			this.start();
		}
		if(!msg) return;
		var lineSize = $$('li[name="debugLi"]').size()+1;
		if(msg!=null && msg!='undefined')
			this.msgBox.insert("<li name='debugLi'>Line "+lineSize+" ==> ["+msg+"]</li>");
		if(this.msgBox.scrollHeight > this.divHeight-20){
			this.msgBox.scrollTop = this.msgBox.scrollHeight;
		}

	}
	,p : function(msg){
		this.print(msg);
	}
	,log : function(msg){
		this.print(msg);
	}
	,println : function(msg){
		this.print(msg);
	}
	,position : function(){
		var topWithScroll = document.documentElement.scrollTop || document.body.scrollTop;
		var heightWithScroll = document.documentElement.scrollHeight;
		var clientWithHeight = document.documentElement.clientHeight;
		return clientWithHeight-this.divHeight-1+topWithScroll;
	}
	,setPostion : function(){
		this.div.style.top = this.position()+"px";

	}
	,start : function(){
		this.timer = setInterval ("debug.setPostion()", this.sec);
	}
	,stop : function(){
		clearInterval(this.timer);
	}
	,fold : function(){
		if(this.divHeight==this.minHeight){
			this.divHeight = this.maxHeight;
			$('foldDebugSpan').update("접기");
		}else{
			this.divHeight = this.minHeight;
			$('foldDebugSpan').update("펼치기");
		}
		this.div.style.height  = this.divHeight+"px";
		this.setPostion();
	}
	,copy : function(){
		var msg = "";
		this.msgBox.getElementsBySelector('li').each(function(element){
			msg+=innerText(element)+"\n";
		});
		copy_clip(msg);
	}
	,clear : function(){
		this.msgBox.update('');
	}
	,setDebug : function(fg){
		this.isDebug  = fg;
	}
};


var innerText = function(element){
    //broswer == firefox
    if (navigator.userAgent.indexOf("Firefox")>-1)
    {
            var cvtTxt = element.textContent;
            return cvtTxt;
    }
    else
    { return element.innerText;}
}

var copy_clip = function(meintext)
{
 if (window.clipboardData)
   {
	   // the IE-manier
	   window.clipboardData.setData("Text", meintext);
	   alert("Following info was copied to your clipboard:\n\n" + meintext);
   }
   else if (window.netscape)
   {
	   alert("FF don't work, Let me know how do it~!\n\nCopy Following alert message instead of ClipBoard, use Ctrl+A And Ctrl+C\n\nDevKim forever;");
//	   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);
	   alert(meintext);
   }
   return false;
}

function getBrowserInfo(){
    var browser;
    var version;
    if(navigator.appName==""){
        browser="Unknown";
    } else {
        browser=navigator.appName;
    }

    version = parseFloat(navigator.appVersion);
    if ((Math.round(parseFloat(navigator.appVersion)*100)) - (parseInt(navigator.appVersion) * 100) == 0) {
        version = version + ".0";
    }

    if (navigator.appName.substring(0,9) == "Microsoft") {
        var msiestart = (navigator.appVersion.indexOf('(') + 1);
        var msieend = navigator.appVersion.indexOf(')');
        var msiestring = navigator.appVersion.substring(msiestart, msieend);
        var msiearray = msiestring.split(";");
        var platform = msiearray[2];
        var msieversion = msiearray[1].split(" ");
        version = msieversion[2];
    }
    return [browser,version];
};

/**
 * 해당 브라우저가 IE7 인지 확인
 * IE7일 경우 return true;
 * */
function isIE7(){
    var verInfo = getBrowserInfo();
    if( verInfo[0].indexOf("Microsoft") != -1 && verInfo[1].indexOf("7.0") != -1 ){
        return true;
    }
    return false;
}

/**
 * 해당 브라우저가 IE6 인지 확인
 * IE6일 경우 IE7,8과 호환이 안되서 만들었음.. IE6쓰지 않기 운동을!!!!
 * IE6일 경우 return true;
 * */
function isIE6(){
	var verInfo = getBrowserInfo();
	if( verInfo[0].indexOf("Microsoft") != -1 && verInfo[1].indexOf("6.0") != -1 ){
		return true;
	}
	return false;
}

/**
 * 해당 브라우저가 IE 인지 확인
 * IE일 경우 return true;
 * */
function isIE(){
    var info = getBrowserInfo();
    if( info[0].indexOf("Microsoft") != -1 ){
        return true;
    }
    return false;
}

/**
 * AJAX 폼생성.
 **/
function ajaxForm(url,map,methodType,method,p1,p2,p3,p4){
	var frmName = "frmAjaxTemp";
	var frmInput = createForm(frmName,url,'', map,methodType);
	callAjaxJson(url, frmName, methodType, method,p1,p2,p3,p4);
	document.body.removeChild(frmInput);
};

/**
 * AJAX 폼생성.
 **/
function ajaxFormNoWaitJson(url,map,methodType,method,p1,p2,p3,p4){
	var frmName = "frmAjaxTemp";
	var frmInput = createForm(frmName,url,'', map,methodType);
	callAjaxJsonNoWait(url, frmName, methodType, method,p1,p2,p3,p4);
	document.body.removeChild(frmInput);
};

/**
 * AJAX 폼생성.
 **/
function ajaxFormNoWait(url,map,methodType){
	var frmName = "frmAjaxTemp";
	var frmInput = createForm(frmName,url,'', map,methodType);
	callAjaxNoWait(url, frmName, methodType);
	document.body.removeChild(frmInput);
};

/**
 * AJAX 폼생성.
 **/
function ajaxFormWaitJson(url,map,methodType,method,p1,p2,p3,p4){
	var frmName = "frmAjaxTemp";
	var frmInput = createForm(frmName,url,'', map,methodType);
	callAjaxJsonWait(url, frmName, methodType, method,p1,p2,p3,p4);
	document.body.removeChild(frmInput);
};


/**
 * AJAX 호출 함수
 * param
 * url 		: 전송할 URL
 * frmName 	: 폼 submit시 해당 폼 이름 , 폼 submit이 아닐경우 빈값['']을 전달
 * _method	: ajax 호출 성공 후 호출 할 method
 * p1 ~ p4	: ajax 호출 성공 후 호출하는 method의 인자값. 없을시에는 전달 안함.
 *
 * Ex>
 * function submit(){
 * 	var url = "test.jsp";
 * 	var frmName = "";
 * 	var _method = submitSuccess;
 *  var p1 = $("user_id");
 *  var p2 = $("divMsg");
 *  callAjaxTxt(url,frmName,_method,p1,p2);
 * }
 *
 * function submitSuccess(ajaxMsg,p1,p2){
 * 	if(ajaxMsg=="success"){
 * 		p1.value="OK";
 * 		p2.insert("GOOD!!")
 *  }
 * }
 * */
var callAjaxTxt = function (url,frmName,methodType,_method,p1,p2,p3,p4){
	var param = "";
	if(frmName){
		param=Form.serialize($(frmName));
	}
	if(!methodType) methodType='GET';
	try{
	   new Ajax.Request(url,
			            {
						  //contentType:'application/x-javascript; charset=MS949',
						 // encoding:'MS949',
						  method:methodType,
			              parameters:param,
			              onComplete : function(objAjax) {
						    	if( objAjax.readyState == 4 && objAjax.status == 200 ) { //--서버 처리 종료, 성공적인 처리
									msg=objAjax.responseText;
						    		_method(msg,p1,p2,p3,p4);
								} else {
//									alert('서버와의 통신이 원할하지 않습니다.\n다시 시도해 주십시오.');
									_method();
								}

							}
			            }
	   );//Ajax.Update
	}catch(e){
		_method();
		//window.setTimeout(dataNext, 1000);
	}
};

/*
 * 비동기식  ajax call method
 */
var callAjaxNoWait = function (url,frmName,methodType){
	var param = "";
	if(frmName){
		param=Form.serialize($(frmName));
	}
	if(!methodType) methodType='GET';
	try{
		new Ajax.Request(url,
			{
				method:methodType,
				parameters:param,
				asynchronous : true //비동기식으로 구현
			}
		);
	}catch(e){}
};

//20110713, gilju81, post에서 sns 보내기 할때 익스플로러 이외의 장비에서 비동기식으로 하면 버그발생
/*
 * 동기식  ajax call method
 */
var callAjaxWait = function (url,frmName,methodType){
	var param = "";
	if(frmName){
		param=Form.serialize($(frmName));
	}
	if(!methodType) methodType='GET';
	try{
		new Ajax.Request(url,
			{
				method:methodType,
				parameters:param,
				asynchronous : false //동기식으로 구현
			}
		);
	}catch(e){}
};

/*
 * 비동기식  ajax call method
 */
var callAjaxJsonNoWait = function (url,frmName,methodType,_method,p1,p2,p3,p4){
	var param = "";
	if(frmName!=''){
		param=Form.serialize($(frmName));
	}
	try{
	   new Ajax.Request(url,
			            {
		   				  method:methodType,
		   				  contentType:'application/x-www-form-urlencoded;charset=UTF-8',
			              parameters:param,
			              asynchronous : true,
			              onComplete : function(objAjax) {
						    	if( objAjax.readyState == 4 && objAjax.status == 200 ) { //--서버 처리 종료, 성공적인 처리
									msg=objAjax.responseText;
									var jsonData = eval('(' + msg + ')');
						    		_method(jsonData,p1,p2,p3,p4);
								} else {
//									alert('서버와의 통신이 원할하지 않습니다.\n다시 시도해 주십시오.');
									_method();
								}
							}
			            }
	   );//Ajax.Update
	}catch(e){
		_method();
		//window.setTimeout(dataNext, 1000);
	}
};

/*
 * 동기식  ajax call method
 */
var callAjaxJsonWait = function (url,frmName,methodType,_method,p1,p2,p3,p4){
	var param = "";
	if(frmName!=''){
		param=Form.serialize($(frmName));
	}
	try{
	   new Ajax.Request(url,
			            {
		   				  method:methodType,
		   				  contentType:'application/x-www-form-urlencoded;charset=UTF-8',
			              parameters:param,
			              asynchronous : false,
			              onComplete : function(objAjax) {
						    	if( objAjax.readyState == 4 && objAjax.status == 200 ) { //--서버 처리 종료, 성공적인 처리
									msg=objAjax.responseText;
									var jsonData = eval('(' + msg + ')');
						    		_method(jsonData,p1,p2,p3,p4);
								} else {
//									alert('서버와의 통신이 원할하지 않습니다.\n다시 시도해 주십시오.');
									_method();
								}
							}
			            }
	   );//Ajax.Update
	}catch(e){
		_method();
		//window.setTimeout(dataNext, 1000);
	}
};


/**
 * AJAX 호출 함수 [JSON]
 * param
 * url 		: 전송할 URL
 * frmName 	: 폼 submit시 해당 폼 이름 , 폼 submit이 아닐경우 빈값['']을 전달
 * _method	: ajax 호출 성공 후 호출 할 method
 * p1 ~ p4	: ajax 호출 성공 후 호출하는 method의 인자값. 없을시에는 전달 안함.
 *
 * Ex>
 * function submit(){
 * 	var url = "test.jsp";
 * 	var frmName = "";
 * 	var _method = submitSuccess;
 *  var p1 = $("user_id");
 *  var p2 = $("divMsg");
 *  callAjaxTxt(url,frmName,_method,p1,p2);
 * }
 *
 * function submitSuccess(ajaxMsg,p1,p2){
 * 	if(ajaxMsg=="success"){
 * 		p1.value="OK";
 * 		p2.insert("GOOD!!")
 *  }
 * }
 * */
var callAjaxJson = function (url,frmName,methodType,_method,p1,p2,p3,p4){
	var param = "";
	if(frmName!=''){
		param=Form.serialize($(frmName));
	}

	try{
	   new Ajax.Request(url,
			            {
		   				  method:methodType,
		   				  contentType:'application/x-www-form-urlencoded;charset=UTF-8',
			              parameters:param,
			              onComplete : function(objAjax) {
						    	if( objAjax.readyState == 4 && objAjax.status == 200 ) { //--서버 처리 종료, 성공적인 처리
									msg=objAjax.responseText;
									var jsonData = eval('(' + msg + ')');
						    		_method(jsonData,p1,p2,p3,p4);
								} else {
//									alert('서버와의 통신이 원할하지 않습니다.\n다시 시도해 주십시오.');
									_method();
								}
							}
			            }
	   );//Ajax.Update
	}catch(e){
		_method();
		//window.setTimeout(dataNext, 1000);
	}
};

/**
 * AJAX 호출 함수
 * XML결과값을 JSON형식으로 변경하여 method를 호출한다.
 * xml.js를 필히 포함하여야 함.
 * <script type="text/javascript" language="javascript" src="/inc/js/xml.js"></script>
 * param
 * url 		: 전송할 URL
 * frmName 	: 폼 submit시 해당 폼 이름 , 폼 submit이 아닐경우 빈값['']을 전달
 * _method	: ajax 호출 성공 후 호출 할 method
 * p1 ~ p4	: ajax 호출 성공 후 호출하는 method의 인자값. 없을시에는 전달 안함.
 *
 * Ex>
 * function submit(){
 * 	var url = "test.jsp";
 * 	var frmName = "frmWrite";
 * 	var _method = submitSuccess;
 *  var p1 = $("frmWrite");
 *  callAjaxTxt(url,frmName,_method,p1);
 * }
 *
 * function submitSuccess(jsonData,frmWrite){
 * 	var data = jsonData.DATA[0];
 * 	frmWrite.elements["productInfo.title"].value=data.title[0]["Text"];
 * 	frmWrite.elements["productInfo.thumbsFile"].value = data.thumbsFile[0]["Text"];
 * }
 * */
var callAjaxXml = function (url,frmName,methodType,_method,p1,p2,p3,p4){
	var param = "";
	if(frmName!=''){
		param=Form.serialize($(frmName));
	}
	try{
	   new Ajax.Request(url,
			            { method:methodType,
			              parameters:param,
			              onComplete : function(objAjax) {
						    	if( objAjax.readyState == 4 && objAjax.status == 200 ) { //--서버 처리 종료, 성공적인 처리
									msg=objAjax.responseText
									xml_doc = XMLObjectifier.textToXML(msg);
									jsonObj = XMLObjectifier.xmlToJSON(xml_doc);
						    		_method(jsonObj,p1,p2,p3,p4);
								} else {
//									alert('서버와의 통신이 원할하지 않습니다.\n다시 시도해 주십시오.');
									_method();
								}
							}
			            }
	   );//Ajax.Update
	}catch(e){
		_method();
		//window.setTimeout(dataNext, 1000);
	}
};


String.prototype.trim = function() {
	return this.replace(/(^ *)|( *$)/g, "");
};
String.prototype.ltrim = function() {
	return this.replace(/(^ *)/g, "");
};
String.prototype.rtrim = function() {
	return this.replace(/( *$)/g, "");
};
/**
 * 문자열에 , 를 추가 한다.
 * */
String.prototype.comma = function() {
    tmp = this.split('.');
    var str = new Array();
    tmp[0] = tmp[0].trim();
    var v = tmp[0].replace(/,/gi,'');
    for(var i=0; i<=v.length; i++) {
        str[str.length] = v.charAt(v.length-i);
        if(i%3==0 && i!=0 && i!=v.length) {
            str[str.length] = '.';
        }
    }
    str = str.reverse().join('').replace(/\./gi,',');
    return (tmp.length==2) ? str + '.' + tmp[1] : str;
};

/**
 * 문자열에서 , 를 제거한다.
 * */
String.prototype.removeComma = function(){
	return parseInt(this.replace(/,/g,""));
};


/**
 * 날짜의차이를 구한다. 몇일 지났는지.
 * param
 * 날짜 형식 yyyyMMdd OR yyyyMMddhhmmss
 * d1 startDate
 * d2 endDate
 * d2 값이 없으면 현재 날짜.
 * Ex>
 * var d1 = '20091014';
 * var d2 = '20091015';
 * var rst = dateDiff(d1,d2);  // rst = -1 return;
 * */
function dateDiff(d1,d2){
	// 공백 - . : 를 제거 한다.
	var date1 = new Date();
    var date2 = new Date();
    d1 = d1.replace(/[^0-9]/g,"");
    var startYear = d1.substring(0,4);
    var startMonth = d1.substring(4,6);
    var startDay = d1.substring(6,8);
    date1. setFullYear(startYear, startMonth-1, startDay);

    if(d1.length>8){
    	var startHour = d1.substring(8,10);
    	var startMin = d1.substring(10,12);
    	var startSec = d1.substring(12,14);
    	date1.setHours(startHour, startMin, startSec, 0);
    }
    if(d2 != null && d2 !='undefined' && d2!=''){
    	d2 = d2.replace(/[-.@: ]/g,"");
    	var endYear = d2.substring(0,4);
        var endMonth = d2.substring(4,6);
        var endDay = d2.substring(6,8);
        date2. setFullYear(endYear, endMonth-1, endDay);
        if(d2.length>8){
        	var endHour = d2.substring(8,10);
        	var endMin = d2.substring(10,12);
        	var endSec = d2.substring(12,14);
        	date2.setHours(endHour, endMin, endSec, 0);
        }
    }
    return Math.ceil((date1 - date2) / 1000 / 24 / 60 / 60);
}

 /**
  * inputbox에 포커스가 이동하면 class='over'
  * @param ele
  * @return
  */
 var addClassNameFocus = function(ele, nameClass){
	 ele.className = nameClass;
 };

 /**
  * inputbox에 포커스가 이동하면 class='default'
  * @param ele
  * @return
  */
 var addClassNameBlur = function(ele, nameClass){
	 ele.className = nameClass;
 };

 /**
  * 모든 input box 에 class가 className 이면 onfocus onblur를 적용한다.
  * @param className , objArray 배열 type
  * @return
  * 사용예>
  * document.observe( 'dom:loaded', function(){
		applyClassInputFocusBlur(['text','password']);
	});
  */
 var applyClassInputFocusBlur = function(className , typeStrs){
	 typeStrs.each( function(typeStr){
		 var inputTexts = $$('input[type="'+ typeStr +'"]');
		 inputTexts.each(function(inputText){
			 if(inputText.className == className){
				 inputText.onfocus = function(){
					 addClassNameFocus(this, 'txtOver');
				 };
				 inputText.onblur = function(){
					 addClassNameBlur(this, 'txt');
				 };
			 }
		 });
	 });
 };

/**
 * 클립보드에 URL 복사하기
 * @return
 */
var copyURL = function(){
	var locationURL = location.href;
	window.clipboardData.setData('Text',locationURL);
	alert('해당 캠페인 URL이 복사되었습니다. 주소창에 Ctrl+V 또는 붙혀넣기를 눌려주세요.');
};

/**
 * input type ="hidden" 객체를 만들어 준다.
 * @param name
 * @param val
 * @return
 */
var createHiddenForm = function(name, val){
	var createInput = document.createElement("input");
	createInput.type = "hidden";
	createInput.name = name;
	createInput.value = val;
	return createInput;
};

var createForm = function(forName,url,target, map,methodType){
	var createInput = document.createElement("form");
	createInput.name = forName;
	createInput.id = forName;
	var methodTypeTmp = 'get';
	if(methodType && methodType!=''){
		methodTypeTmp = methodType;
	}
	createInput.setAttribute('method',methodTypeTmp);
	if(target!='')	createInput.target = target;
	createInput.action = url;
	if(map){
		var isEncode = true;
		if(map.get('notEncode')){
			isEncode = false;
		}
		var keys = map.keys();
		for(keysLoop=0;keysLoop<keys.size();keysLoop++){
			var key = keys[keysLoop];
			var val = map.get(key);
			if(methodTypeTmp=='get' && isEncode) val = encodeURL(val);
			var input = createHiddenForm(key,val);
			createInput.appendChild(input);
		}
	}
	document.body.appendChild(createInput);
	return createInput;
}

/* window_open 100% 열기 */
function popPWin(url,target) {
	var tar = window.open(url, target, "fullscreen");
	return tar;
}

/* window_open 100% 열기 */
function popPWinFull(url,target) {
	var tar = window.open(url, target, "fullscreen, resizable=1,scrollbars=1");
	return tar;
}

/* window_open 스크롤이 없을 때 */
function popWin(url, target, intwidth, intheight) {
	var screenWidth = screen.width;
	var screenHeight = screen.height;
	var pos = [];
	pos[0] = (screenWidth - intwidth) / 2;
	pos[1] = (screenHeight - intheight) / 2;
	var option = "width="+intwidth+", height="+intheight+", left="+ pos[0] +", top="+ pos[1] +", resizable=0,scrollbars=0";
	var tar = window.open(url, target , option);
	return tar;
}

/* window_open 스크롤이 있을 때 */
function popWinS(url, target, intwidth, intheight) {
	var screenWidth = screen.width;
	var screenHeight = screen.height;
	var pos = [];
	pos[0] = (screenWidth - intwidth) / 2;
	pos[1] = (screenHeight - intheight) / 2;
	var tar = window.open(url, target , "width="+intwidth+",height="+intheight+", left="+ pos[0] +", top="+ pos[1] +",resizable=0,scrollbars=1");
	return tar;
}

/**
 * 팝업
 * Ex>
 * var url = '/test/test.kth'
 * var param = $H({test:'1',postNo:'1111'});
 * popForm(url,100,100,'testPop',param,'get');
 * */
var popForm = function(url,width, height,popName, map,methodType){
	var target = popName;
	popTarget = popWin("about:blank",target,width,height,methodType);
	var formEl = createForm(popName,url,popName,map);
	formEl.submit();
	popTarget.focus();
//	formEl.remove();
	return popTarget;
};

/**
 * 스크롤 팝업
 * Ex>
 * var url = '/test/test.kth'
 * var param = $H({test:'1',postNo:'1111'});
 * popForm(url,100,100,'testPop',param,'get');
 * */
var popSForm = function(url,width, height,popName, map,methodType){
	var target = popName;
	popTarget = popWinS("about:blank",target,width,height);
	var formEl = createForm(popName,url,popName,map,methodType);
	formEl.submit();
	popTarget.focus();
	document.body.removeChild(formEl);
	return popTarget;
};

/**
 * location 대체
 * Ex>
 * var url = '/test/test.kth'
 * var param = $H({test:'1',postNo:'1111'});
 * loc(url,param,'get');
 * */
var loc = function(url, map,methodType,target){
	var formEl;
	if(target){
		formEl = createForm('templateForm',url,target,map,methodType);
	}else{
		formEl = createForm('templateForm',url,'',map,methodType);
	}
	formEl.submit();
};


/**
 * 문자를 숫자로 변경
 * */
var parseInteger = function(val){
	if(!val) return 0;
	val = val.replace(/,/g,"");
	if(!/^\s*$/.test(val)){
		if(isNaN(val)) return 0;
		return parseInt(val)
	}
	return 0;
}


/**
 * 이미지가 limitImageSize 보다 클 경우  limitImageSie로 resize 한다.
 * */
var limitImageSize = 650;
var contentsImgReSize = {
	initImgReSize : function(){
		var divClassViewImgs = $$('div.view img');
		if( divClassViewImgs != null && divClassViewImgs.length > 0 ){
			for( var i = 0; i < divClassViewImgs.length; i++ ){
				if( divClassViewImgs[i].width > limitImageSize  ){
					this.setImgReSize(divClassViewImgs[i]);
				}
			}
		}
	},
	setImgReSize : function( obj ){
		var width = obj.width;
		var height = obj.height;
		var temp = 0;
		if( width > limitImageSize ){
			height = height/( width / limitImageSize );
			obj.width = limitImageSize;
			obj.height = height;
		}
	}
};

/**
 * 자신의 인덱스 가지고 오기
 **/
var getObjIndex = function(objs, obj){
	var idx=-1;
	if(objs && objs.length>0){
		var size = objs.length;
		for(i=0;i<size;i++){
			if(objs[i]==obj){
				idx=i;
				break;
			}
		}
	}
	return idx;
}

/**
 * 셀렉트 테그 동적 제어.. IE 호환.
 **/
var contorlSelet = {
	remove : function(selectBox,idx){
		/*IE에서는 다르게 작동.*/
		if(isIE()){
			selectBox.options.remove(idx);
		}else{
			selectBox.options[idx].remove();
		}
	}
	,add : function(selectBox,text, value){
		var opt = document.createElement("option");
		opt.text = text;
		opt.value = value;
		if(isIE()){
			selectBox.add(opt);
		}else{
			selectBox.insert(opt);
		}
	}
}


var enableObj = function(id, type){
	id.getElementsBySelector(type).each(function(obj){
		obj.enable();
	});
}

var disableObj = function(id, type){
	id.getElementsBySelector(type).each(function(obj){
		obj.disable();
	});
}

/*
 * 조상DOM의 첫번째 tagName의 DOM 객체를 반환한다.
 * */
var getFirstElement = function(obj,tagName){
	var objs = parentNodes(obj);
	for(i=0;i<objs.size();i++){
		if(objs[i].tagName.capitalize()==tagName.capitalize()){
			trObj = objs[i];
			return trObj;
		}
	}
	return;
}

/**
 * 날짜를 비교 한다.
 **/
var validateDate = function(fromDate, toDate, minDays, maxDays){
	fromDate = fromDate.replace(/[^0-9]/g,"");
	toDate = toDate.replace(/[^0-9]/g,"");
	if(fromDate.length!=8){
		alert('시작날짜 형식이 잘못되었습니다. [형식 : 2000-01-01]');
		return false;
	}
	if(toDate.length!=8){
		alert('종료날짜 형식이 잘못되었습니다. [형식 : 2000-01-01]');
		return false;
	}
	if(!fromDate || fromDate.blank()){
		alert('시작날짜를  입력해 주세요!');
		return false;
	}
	if(!toDate || toDate.blank()){
		alert('종료날짜를  입력해 주세요!');
		return false;
	}
	var cnt = dateDiff(toDate,fromDate);
	if(cnt<0){
		alert('시작 종료일 날짜가 잘못 되었습니다.');
		return false;
	}
	if(minDays > cnt){
		alert('종료일을  '+minDays+'일 이상 입력해주세요!');
		return false;
	}
	if(cnt > maxDays){
		alert('종료일을  '+maxDays+'일 이하로 입력해주세요!');
		return false;
	}
	return true;
}

/* 객체 멤버 추가 변경 시작 */
Number.prototype.to2 = function() { return (this > 9 ? "" : "0")+this; };
Date.MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
Date.DAYS   = ["Sun", "Mon", "Tue", "Wed", "Tur", "Fri", "Sat"];
Date.prototype.getDateString = function(dateFormat) {
  var result = "";

  dateFormat = dateFormat == 8 && "YYYY.MM.DD" ||
               dateFormat == 6 && "hh:mm:ss" ||
               dateFormat ||
               "YYYY.MM.DD hh:mm:ss";
  for (var i = 0; i < dateFormat.length; i++) {
    result += dateFormat.indexOf("YYYY", i) == i ? (i+=3, this.getFullYear()                     ) :
              dateFormat.indexOf("YY",   i) == i ? (i+=1, String(this.getFullYear()).substring(2)) :
              dateFormat.indexOf("MMM",  i) == i ? (i+=2, Date.MONTHS[this.getMonth()]           ) :
              dateFormat.indexOf("MM",   i) == i ? (i+=1, (this.getMonth()+1).to2()              ) :
              dateFormat.indexOf("M",    i) == i ? (      this.getMonth()+1                      ) :
              dateFormat.indexOf("DDD",  i) == i ? (i+=2, Date.DAYS[this.getDay()]               ) :
              dateFormat.indexOf("DD",   i) == i ? (i+=1, this.getDate().to2()                   ) :
              dateFormat.indexOf("D"   , i) == i ? (      this.getDate()                         ) :
              dateFormat.indexOf("hh",   i) == i ? (i+=1, this.getHours().to2()                  ) :
              dateFormat.indexOf("h",    i) == i ? (      this.getHours()                        ) :
              dateFormat.indexOf("mm",   i) == i ? (i+=1, this.getMinutes().to2()                ) :
              dateFormat.indexOf("m",    i) == i ? (      this.getMinutes()                      ) :
              dateFormat.indexOf("ss",   i) == i ? (i+=1, this.getSeconds().to2()                ) :
              dateFormat.indexOf("s",    i) == i ? (      this.getSeconds()                      ) :
                                                   (dateFormat.charAt(i)                         ) ;
  }
  return result;
};

//////////////////////////////////////////
function rpad(newValue, len, ch){
	//////////////////////////////////////////
	//  오른쪽에 ch문자로 채우기
	var strlen = newValue.trim().length;
	newValue = newValue.substr(0,len);
	//debug.print("len = "+len);
	//debug.print("strlen = "+len);
	var ret = "";
	var alen = len - strlen;
	var astr = "";
	//부족한 숫자만큼  len 크기로 ch 문자로 채우기
	for (rpadLoop=0; rpadLoop<alen; rpadLoop++)
	{
	 astr = astr + ch;
	}
	ret = newValue.trim() + astr; //뒤에서 채우기
	return ret;
}

//////////////////////////////////////////
function lpad(newValue, len, ch){
	//////////////////////////////////////////
	// 왼쪽에 ch 문자 채우기
	var strlen = newValue.trim().length;
	newValue = newValue.substr(0,len);
	var ret = "";
	var alen = len - strlen;
	var astr = "";

	//부족한 숫자만큼  len 크기로 ch 문자로 채우기
	for (rpadLoop=0; rpadLoop<alen; rpadLoop++)
	{
		astr = astr + ch;
	}
	ret = astr + newValue.trim(); //앞에서 채우기
	return ret;
}

//JSON 에러 메세지를 처리
var showException = function(jsonData){
	alert(jsonData.response.description);
	//0x02024
	if(jsonData.response.errCode=='0x02024'){
		makePuding.open();
	}
};

//로그인페이지로 이동
function goLogin(params)
{
	var url = "/pud/LoginUser.kth?rtUrl="+params;
	location.href=url;
	return;
}

// 다른 페이지이동
function otherPageMove(url, formNm)
{
	$(formNm).action=url;
	$(formNm).target="_self";
	$(formNm).submit();
}

/**
 * 문자열의 바이트를 구한다.
 * */
function getByteLength(str)
{
  var rv = 0;
  for ( var n = 0, sz = str.length; n < sz; n++ )
  {
    rv += str.charCodeAt(n) > 0x00ff ? 2 : 1;
  }
  return rv;
};

/**
 * 숫자체크
 * */
function numCheck(input)
{
	var i;
    var ch;
    var isNumeric = true;
    for (i = 0; i < input.length; i++)
    {
    	ch = input.charAt(i);
    	if (!((ch >= '0') && (ch <= '9')))
    		isNumeric = false;
    }
    return isNumeric;
}

/**
 * 선행 0 제거
 * */
function deletePrecedingZero(numstr)
{
	var replaced = numstr.replace(/^0+/, "");
	return numstr && ! replaced ? "0" : replaced;
}

/**
 * 해당 문자에 콤마를 붙여서 반환한다.
 * */
function formatComma(numstr)
{
	numstr = numstr+"";
	numstr = deletePrecedingZero(numstr.replace(/\D/g, ""));// 선행하는 zero 를 지운다.
	return numstr.comma();
}

function focus(input)
{
  try { input.select(); } catch(e) {}
  try { input.focus(); } catch(e) {}
}

//로그인으로 가기
var goLogin = function(rtUrl,rtType,ismobile){
	var param = $H({rtUrl:rtUrl,notEncode:true});
	if(rtType) param.set('rtType',rtType);
	var url = "/pud/LoginUser.kth";
	if(ismobile) url = "/pud/mloginparan.kth";
	loc(url,param,'get');
};

/**
 * 폼내용을 Map으로 변환.
 * */
var convertFormToMap = function(formObj){
	var rstMap = new Hash();
	//폼에 정의된 input 만큼 루팅.
	for ( var n = 0, sz = formObj.elements.length; n < sz; n++ )
	{
		input = formObj.elements[n];
	    if ( ! input.name && ! input.id ) continue;
	    //disable 된 객체는 체크에서 제외시킨다.
	    // alert(input.id+" = "+input.disabled)
	    if(input.disabled) continue;

	    //input type이 button , image , submit , reset 일 경우 체크를 안한다.
	    switch ( input.type )
	    {
	    	case "button":
	    	case "image":
	    	case "submit":
	    	case "reset": continue; break;
	    	case "checkbox":
	    	case "radio":
	    		if(!input.checked){
	    			continue; break;
	    		}
	    }
	    var nm = input.name;
	    var val = input.value;
	    rstMap.set(nm,val);
	}
	return rstMap;
};

var encodeForm = function(formObj){
	//폼에 정의된 input 만큼 루팅.
	for ( var n = 0, sz = formObj.elements.length; n < sz; n++ )
	{
		input = formObj.elements[n];
	    if ( ! input.name && ! input.id ) continue;
	    //disable 된 객체는 체크에서 제외시킨다.
	    // alert(input.id+" = "+input.disabled)
	    if(input.disabled) continue;

	    //input type이 button , image , submit , reset 일 경우 체크를 안한다.
	    switch ( input.type )
	    {
	    	case "button":
	    	case "image":
	    	case "submit":
	    	case "reset": continue; break;
	    	case "checkbox":
	    	case "radio":
	    		if(!input.checked){
	    			continue; break;
	    		}
	    }
	    var val = input.value;
	    input.value = encodeURL(val);
	}
};

//배열 정렬 DESC
var orderBy = function(fg){
	for(i=0;i<array.length-1;i++) {
		for(k=0;k<array.length-1;k++){
			frontVal=array[k];
			backVal = array[k+1];
			if(fg=='DESC'){
				if(frontVal>backVal){
					array[k]=backVal;
					array[k+1]=frontVal;
				}
			}else{
				if(frontVal<backVal){
					array[k]=backVal;
					array[k+1]=frontVal;
				}
			}
		}
	}
};

/**
 * 객체 상단에 넣기.
 * */
var insertTop = function(parentObj,html){
	var curHtml = parentObj.innerHTML;
	var html = html + curHtml;
	parentObj.update(html);
};

/**
 * 숫자만 입력 가능.
 * */
function numericOnlyExt(e){
	var charCode = (window.event) ?  event.keyCode : e.which;
	if (charCode > 31 && (charCode < 48 || charCode > 57)) {
		if(charCode != 46){
			return false;
		}
	}
	return true;
};

/*
 * 글자수 byte 표기, 한계치 이후 자동 자르기
 * sel : object
 * cutlen : maxbyte
 * txtObj : byte수를 표기해줄 객체명
 */
var inputcut = function(sel, cutlen, txtobj){
	var realcutlen = cutlen/2;
	if(getByteLength(sel.value)>cutlen) {
		var string="한글 "+realcutlen+"자("+cutlen+"byte) 까지 입력 가능합니다.";
		alert(string);
		sel.value=strCutString(sel.value,cutlen);
		if($(txtobj)) {
			$(txtobj).innerHTML=(cutlen-getByteLength(sel.value));
		}
	} else {
		if($(txtobj)) {
			$(txtobj).innerHTML=(cutlen-getByteLength(sel.value));
		}
	}
};

/*
 * 글 자르기
 */
var strCutString = function(str,max){
	var tmpStr;
	var temp=0;
	var onechar;
	var tcount;
	tcount = 0;

	tmpStr = new String(str);
	temp = tmpStr.length;
	for(k=0;k<temp;k++) {
		onechar = tmpStr.charAt(k);
		if(escape(onechar).length > 4) {
			tcount += 2;
		} else if(onechar!='\r\n') {
			tcount++;
		}
		if(tcount>max) {
			tmpStr = tmpStr.substring(0,k);
			break;
		}
	}

	return tmpStr;
};
// Top버튼 위치지정
function moveRightEdge(topDiv, bottom)
{
	var yMenuFrom, yMenuTo, yOffset, timeoutNextCheck;
	//현재위치 체크
	if($(topDiv)) yMenuFrom = parseInt($(topDiv).style.top,10);
 	// Y축 위치 설정(위로부터 270픽셀을 의미)
	var top = document.documentElement.scrollTop || document.body.scrollTop;
	yMenuTo = top + bottom;
	//움직임을 시작할때까지의 시간
	timeoutNextCheck = 500;
	if (yMenuFrom != yMenuTo)
	{
	  	yOffset = Math.ceil(Math.abs(yMenuTo - yMenuFrom) / 12);
	  	if (yMenuTo < yMenuFrom)
	  		yOffset = -yOffset;
	  	//설정된 시간마다 변경된 위치를 입력하여 부드러운 움직임을 보여줌
	  	if($(topDiv)) $(topDiv).style.top = parseInt($(topDiv).style.top, 10) + yOffset;
	  	//위치를 체크하는 속도(숫자가 적을수록 움직임이 부드럽지만 홈페이지에 무리를 줘 버벅거릴수있음)
	  	timeoutNextCheck = 10;
	}
	setTimeout ("moveRightEdge('"+topDiv+"', "+bottom+")", timeoutNextCheck);
};
//최초한번과 익스플로러 창의 크기가 바뀔때마다 실행됨
function setRightX(topDiv, right, bottom)
{
	if($(topDiv)) $(topDiv).style.left = document.documentElement.clientWidth/2 + right;
	moveRightEdge(topDiv, bottom);
};
//Y축위치 및 여타 최초 설정 함수 한번만 실행함
function setRightY(topDiv, right, bottom)
{
	var top = document.documentElement.scrollTop || document.body.scrollTop;
	if($(topDiv)) $(topDiv).style.top = top+ bottom;
	setRightX(topDiv, right, bottom);
};

//입력제한 체크하기(this, 2000, '내용은')
function checkByteLength(inputNm, max, msg)
{
    var liByte     = 0;
    var liLen      = 0;
    var lsOneChar  = "";

    for(i=0; i< inputNm.value.length; i++)
    {
        lsOneChar = inputNm.value.charAt(i);
        if (escape(lsOneChar).length > 4)
        {
            liByte += 2;
        }else
        {
            liByte++;
        }
        if(liByte <= max)
        {
            liLen = i + 1;
        }
    }
    if(liByte > max)
    {
        no1 = max/2;
        var item = {msg:msg,max:max};
        puddingLayer = new LayerHelper('puddingLayer',contentsTempLayer);
        puddingLayer.call(puddingLayer,item);
        //alert(msg+" 최대 한글"+no1+"자, 영문"+max+"자("+max+"Byte)까지만 입력할 수 있습니다.");
        inputNm.value = inputNm.value.substr(0, liLen);
        inputNm.focus();
        return max;
    }else
    {
    	return liByte;
    }
};

//주소복사 (기존 ie만 가능)
function copyCurUrl(szUrl)
{
	try
	{
		var bResult = false;
		if( window.clipboardData )  // IE
		{
			bResult = window.clipboardData.setData("Text", szUrl);
			if( bResult == true)
			{
				alert("게시물 주소가 복사되었습니다.\nCtrl+V 로 붙여넣기 할 수 있습니다.");
				return;
			}
		}else
		{
			window.alert( "URL 복사는 IE 에서만 사용 가능하십니다.");
		}
	}catch(e)
	{
		alert( e.description );
	}
};

var zeroclip;

// 주소복사 (모든 브라우저에서 가능)
function clipboard() {
	try
	{
		ZeroClipboard.setMoviePath('/common/swf/ZeroClipboard.swf');
		zeroclip = new ZeroClipboard.Client();
		zeroclip.setHandCursor( true );

		zeroclip.addEventListener('complete', function(client, text) {
			alert("게시물 주소가 복사되었습니다.\nCtrl+V 로 붙여넣기 할 수 있습니다.");
		});

		zeroclip.addEventListener('mouseOver', function(client) {
			zeroclip.setText( document.getElementById('temp_url').value);
			$(copybt).className="ov";
		});
		
		zeroclip.addEventListener('mouseOut', function(client) {
			$(copybt).className="";
		});

		// glue specifying our button AND its container
		zeroclip.glue( 'copybt' );

	}catch(e)
	{
		//alert( e.description );
	}
};

Array.prototype.inArray = function(needle){
    for(var i=0, len=this.length ; i < len ; i++){
         if(this[i] === needle){
              return true;
         }
    }
    return false;
};

function Keycode(e){
	var result;
	if(window.event)
    	result = window.event.keyCode;
   	else if(e)
    	result = e.which;
   	return result;
 };

 var checkLenNm = function(obj,len,e){
	var charCode = (window.event) ?  event.keyCode : e.which;
	if(getByteLength(obj.value)>len){
		if(charCode=='8'
			|| charCode=='46'
		){
			return true;
		}

		var realcutlen = len/2;
		var val = getByteLength(obj.value.trim().replace(/,/g, ""));
		if(parseInt(val)> parseInt(len)) {
		    var string="한글 "+realcutlen+"자("+len+"byte) 까지 입력 가능합니다.";
		    alert(string);
		    obj.focus()
		    obj.value=strCutString(obj.value,len);
		}

		obj.value = strCutString(obj.value,len);
		return false;
	}else{
//			obj.title = obj.value;
		return true;
	}
};

var checkLenNmByLen = function(obj,len,e){
	var charCode = (window.event) ?  event.keyCode : e.which;
	if(obj.value.length>len){
		if(charCode=='8'
			|| charCode=='46'
		){
			return true;
		}
		if(parseInt(obj.value.length)> parseInt(len)) {
			var string="한글 "+len+" 까지 입력 가능합니다.";
			alert(string);
			obj.value=obj.value.substring(0,len);
		}
		return false;
	}else{
//			obj.title = obj.value;
		return true;
	}
};

//zIndex변경
var setZIndex = function(obj, idx){
	$(obj).style.zIndex = idx;
};


/**
 * <> ' " 문자열 처리.
 * */
var esc = function(str){
	str = str.replace("<", "&#60;");
	str = str.replace(">", "&#62;");
	str = str.replace("'", "&#39;");
	str = str.replace("\"", "&#34;");
	return str;
};

var CookieLayer = function(id,template){
	this.id = id;
	this.template = template;
	this.cookieLayer;
};

CookieLayer.prototype = {
	open : function(){ //		이웃소개 레이어
		if (getCookie(this.id)!= "ok" ){
			this.cookieLayer = new LayerHelper(this.id,this.template);
			var item = {
					msg:''
			}
			this.cookieLayer.call(this.cookieLayer,item);
		}


	}
	,close : function(isSet){
		if(isSet){
			setCookie(this.id,"ok", 86400);
		}
		this.cookieLayer.hide(this.cookieLayer);
	}
};


function flash_trans_fail() {
	var flashStr= ' <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="540" height="405" id="변환중" align="middle">'
	 + ' <param name="allowScriptAccess" value="sameDomain" />'
	 + ' <param name="allowFullScreen" value="false" /> '
	 + ' <param name="movie" value="http://pudding.paran.com/swf/trans_fail.swf" /><param name="quality" value="high" />'
     + ' <param name="bgcolor" value="#000000" />	'
	 + ' <embed src="http://pudding.paran.com/swf/trans_fail.swf" quality="high" bgcolor="#000000" width="540" height="405" name="변환중" align="middle" allowScriptAccess="sameDomain" allowFullScreen="false" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" />'
	 + ' </object> ';
	document.write(flashStr);
};



/**
 * 해당 브러우저 확인 후 twtkr 인증 팝업창 사이즈 지정하여 resize 하기
 * */
var winResize = function(x,y){
	  try
    {
        // tool box and border length
        var deltaHeight, deltaWidth;

        if (window.outerHeight) {
            deltaWidth = window.outerWidth - window.innerWidth;
            deltaHeight = window.outerHeight - window.innerHeight;
        }
        else {
            // if ie..
            if (document.documentElement.clientWidth) {

                // window fake outer size
                var fakeOuterWidth = document.documentElement.clientWidth;
                var fakeOuterHeight = document.documentElement.clientHeight;

                // resize to innerSize
                window.resizeTo(fakeOuterWidth, fakeOuterHeight);

                // window fake inner size
                var fakeInnerWidth = document.documentElement.clientWidth;
                var fakeInnerHeight = document.documentElement.clientHeight;

                // 작업표시 라인 크기
                deltaWidth = fakeOuterWidth - fakeInnerWidth;
                deltaHeight = fakeOuterHeight - fakeInnerHeight;
            }
            else {
                throw "browser does not support!"
            }
        }

        window.resizeTo(x + deltaWidth, y + deltaHeight);
    }catch(e){}
}


