//한글
var langTable = {
    CODE_0001:"@1를(을) 입력해주세요.",
    CODE_0002:"@1는(은) 숫자만 입력가능합니다.",
    CODE_0003:"@1의 허용된 최소값은 @2 입니다.",
    CODE_0004:"@1의 허용된 최대값은 @2 입니다.",
    CODE_0005:"@1는(은) 영문과 숫자만 가능합니다.",
    CODE_0006:"@1는(은) 최소 @2자 이상입니다.",
    CODE_0007:"@1는(은) 최대 @2자까지 입니다.",
    CODE_0008:"@1는(은) 올바를 이메일 주소가 아닙니다.",
    CODE_0009:"범위가 잘 못 지정 되었습니다.",
    CODE_0010:"@1는(은) 염문과 숫자의 조합만 가능합니다."
}
//영어
/*
var langTable = {
	CODE_0001:"Please, Input @1.",
	CODE_0002:"@1 is only number.",
	CODE_0003:"The minimum @1 is @2.",
	CODE_0004:"The maximum @1 is @2.",
	CODE_0005:"@1 is only alphabet and number.",
	CODE_0006:"@1는(은) 최소 @2자 이상입니다.",
	CODE_0007:"@1는(은) 최대 @2자까지 입니다.",
	CODE_0008:"@1 is not valid Email.",
	CODE_0009:"Wrong range."
}
 */
/**
	[주의] 이 함수를 수정할 때는 kr.co.mz.jdf.Util.checkBox() 메소드도 동시에 수정해야 합니다.
	 
    id	    : object id
    cmt	    : object name or comment
    min	    : object의 문자열의 최소 허용길이
    max	    : object의 문자열의 최대 허용길이
    isKey   : 필수값여부(Y or N, default Y)
    isNum   : 숫자여부(Y or N, default N)
    minNum  : 숫자필드의 최소값
    maxNum  : 숫자필드의 최대값
    isEmail : 이메일필드여부(Y or N, default N)
    to      : 날짜일 경우 넘지 말아야 할 값.(maxNum과 유사)
    isEng   : 영어와 숫자만 가능
    isEngDot: 영어와 숫자 . _ 가능
    isSec   : 암호화 한다.
    isEngNum: 영문과 숫자가 동시에 있어야 합.
    isDate  : 날짜형
    isEngDotSpace : 영어와 숫자 . _ 공백 가능
 
    사용예)
	if(!checkNotNull({
		data:[ 
	    {id:"site_id",    cmt:"사이트ID"}, 
	    {id:"admin_id",   cmt:"관리자ID",	    min:4, max:6, isKey:"Y"}, 
	    {id:"admin_pw",   cmt:"관리자 패스워드",	min:4, max:6, isKey:"N"},
	    {id:"file_cnt",   cmt:"첨부파일 갯수",	isNum:"Y", minNum:0, maxNum:10},
	    {id:"start_date", to:"end_date", isDate:"Y"}, 
        {id:"site_name",  cmt:"사이트명"}'
		]
	})) return;
    
    이메일)
        re=/^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
 */
function checkNotNull() {
    if(arguments.length <= 0 || arguments[0].data == null) return true;
    var arrayObject = arguments[0].data;

    for(var i = 0; i < arrayObject.length; i++) {
        var obj = arrayObject[i];
        if(obj == null || obj.id == null || obj.id == '' || $(obj.id) == null) continue;
        var isKey   = nvl(obj.isKey, "Y");
        var isNum   = nvl(obj.isNum, "N");
        var isEmail = nvl(obj.isEmail, "N");
        var isDate  = nvl(obj.isDate, "N");
        var isEng   = nvl(obj.isEng, "N");
        var isEngDot= nvl(obj.isEngDot, "N") ;
        //var isSec   = nvl(obj.isSec, "N") ;
        var isEngNum= nvl(obj.isEngNum, "N") ;
        var isEngDotSpace = nvl(obj.isEngDotSpace, "N");

        var objVal  = null;
        try {
            objVal = $F(obj.id);
        }catch(e){
            continue;
        }

        if(isDate == "Y") objVal = objVal.replace(/[-|:|\/]+/g, '').replace(/\s/g, '');

        if(isKey == "N" && objVal == '') continue;	//필수값이 아니면 값의 입력이 없을때는 체크하지 않는다.
        if(objVal == '' && isKey == "Y") {
            viewMsg(langTable.CODE_0001, obj.cmt); $(obj.id).focus(); return false;
        }

        if(isNum == "Y") {  //숫자형일 경우
            if(isNaN(objVal)) {
                viewMsg(langTable.CODE_0002, obj.cmt); $(obj.id).focus(); return false;
            }else {
                var val = parseInt(objVal);
                if(obj.minNum != null && val < obj.minNum) {
                    viewMsg(langTable.CODE_0003, obj.cmt, obj.minNum); $(obj.id).focus(); return false;
                }else if(obj.maxNum != null && val > obj.maxNum) {
                    viewMsg(langTable.CODE_0004, obj.cmt, obj.maxNum); $(obj.id).focus(); return false;
                }
            }
        }else {		    //문자형일 경우
            if(isEng == "Y" || isEngNum == "Y") {
                var re= new RegExp('^[0-9a-z]+$','i');
                if(!re.test(objVal)) {
                    viewMsg(langTable.CODE_0005, obj.cmt); $(obj.id).focus(); return false;
                }
            }
            if(isEngNum == "Y") {
                var re0 = new RegExp('^[0-9]+$', 'i');
                var re1 = new RegExp('^[a-z]+$', 'i');
                if(re0.test(objVal) || re1.test(objVal)) {
                    viewMsg(langTable.CODE_0010, obj.cmt); $(obj.id).focus(); return false;
                }
            }
            if(isEngDot == "Y") {
                var re2= new RegExp('^[0-9a-z._]+$', 'i');
                if(!re2.test(objVal)) {
                    viewMsg(langTable.CODE_0005, obj.cmt); $(obj.id).focus(); return false;
                }
            }
            if(isEngDotSpace == "Y") {
                var re3= new RegExp('^[0-9a-z._ ]+$', 'i');
                if(!re3.test(objVal)) {
                    viewMsg(langTable.CODE_0005, obj.cmt); $(obj.id).focus(); return false;
                }
            }
        }
        
        //문자열 숫자 상관 없인 min, max를 체크하도록 변경.
        if(obj.min != null && objVal.length < obj.min) {
            viewMsg(langTable.CODE_0006, obj.cmt, obj.min); $(obj.id).focus(); return false;
        }else if(obj.max != null && objVal.length > obj.max) {
            viewMsg(langTable.CODE_0007, obj.cmt, obj.max); $(obj.id).focus(); return false;
        }

        if(isEmail == "Y") { //이메일 형일 경우
            var re3= /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/ig;
            if(!re3.test(objVal)) {
                viewMsg(langTable.CODE_0008, obj.cmt); $(obj.id).focus(); return false;
            }
        }

        if(obj.to != null) {
            var toVal	= $F(obj.to).replace(/[-|:]+/g, '').replace(/\s/g, '');
            if(parseInt(objVal) > parseInt(toVal)) {
                viewMsg(langTable.CODE_0009); $(obj.id).focus(); return false;
            }
        }

        /*
        if(isSec == "Y") {
            $(obj.id).value = doEnc(objVal, $F('jdf_sec_key'));
        }
        */
    }//for
    return true;
}//checkNotNull()

function encSecField() {
    if(arguments.length <= 0 || arguments[0].data == null) return true;
    var arrayObject = arguments[0].data;

    for(var i = 0; i < arrayObject.length; i++) {
        var obj = arrayObject[i];
        if(obj == null || obj.id == null || obj.id == '' || $(obj.id) == null) continue;
        var isSec   = nvl(obj.isSec, "N") ;
        if(isSec == 'N') continue;

        var objVal  = $F(obj.id);
        if(isSec == "Y") {
            $(obj.id).value = doEnc(objVal, $F('jdf_sec_key'));
        }
    }//for
}//encSecField()

blockSizeInBits = 128;
keySizeInBits = 128;

/* 암호화 관련 시작
 * aes-enc.js 필요
 * */
function doEnc(input, aesKey) {
   if(input == null)return input;
   var text = padding16(input);
   text = byteArrayToHex(rijndaelEncrypt(text, aesKey, "ECB"));
   return text.replace(/^\s+|\s+$/g,"");
}

// 공백 문자 padding
function padding16(sVal) {
    var len = sVal.length;
    var size = (len - 1)/16;
    var nCount = (Math.floor(size) + 1) * 16 - len;
    for (i=0;i<nCount;i++) {
        sVal += ' ';
    }    
    return sVal;
}
/* 암호화 관련 끝 */

/**
 * protoype-ui를 이용하여 alert()을 대체한다.
 */
function alertVista(str) {
    var w = 0;
    w = (str.length * 13);
	 
    try {
        new UI.Window({theme:  "vista",  shadow: true, 
            width:  w, 
            height: 25}).center().setContent(str).show(true);
    }catch(e) {
        alert(str);
    }
}			

/**
 * 화면에 message를 표시한다.
 * ex) veiwMsg('@1은 @2가 아닙니다.', 'siva6', '메일 주소');
 * @1에서부터 시작함.
 * 현재는 alert()을 사용하지만 추후 변경될 가능성 있음.
 */
function viewMsg() {
    if(arguments.length < 1) return;
    var msg = arguments[0];
    //@11을 @1보다 먼저 치환하기 위해서 역으로 돌림.
    for(var i = arguments.length - 1; i > 0; i--) {
        msg = msg.replace('@' + i, arguments[i]);
    }
    //alertVista(msg);
    alert(msg);
}//viewMsg()

/**
	val이 null이거나 ''이면 def를 반환한다.
 */
function nvl(val, def) {
    if(val == null || val == '') return def;
    return val;
}

/**
 * EnterHandler
 */
function enterHandler() {
	
}

/**
	주어진 이름으로 객체들을 얻는다.
 */
function $N() {
    var result = new Array();
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'string') {
            result = document.getElementsByName(arguments[i]);
        }
        if (arguments.length == 1) return result;
        for(var j = 0; j < result.length; j++) {
            result.push(result[j]);
        }
    }
    return result;
}

/**
	Object의 id들을 넣어서 객체를 화면에서 숨긴다.
 */
function hideObject() {
    var result = new Array();
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'string') {
            if($(arguments[i]) == null) continue;
            Element.hide(arguments[i]);
        }
    }
}

/**
	Object의 id들을 넣어서 객체를 화면에 표시한다.
 */
function showObject() {
    var result = new Array();
    for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'string') {
            if($(arguments[i]) == null) continue;
            Element.show(arguments[i]);
        }
    }
}

/**
	_obj에 객체ID와 내용을 받아서 innerHTML를 변경한다.
 */
function setHTMLToObject(_obj, value) {
    var obj = $(_obj);
    if(obj != null) obj.innerHTML = value;
}

/**
	특정 객체에 value를 세팅한다.
 */
function setValueToObject(_obj, value) {
    var objs = $N(_obj);
    if(objs.length > 1) {
	if(objs[0].tagName.toUpperCase() == 'INPUT') {
	    if(objs[0].type.toUpperCase() == 'RADIO') {
		for(var i = 0; i < objs.length; i++) {
		    if(objs[i].value == value) {
			objs[i].checked = true;
			break;
		    }//if
		}//for
	    }//if
	}//if
    }else {
	var obj = $(_obj);
	if(obj != null) {
	    if(obj.tagName.toUpperCase() == 'INPUT') {
		if(obj.type.toUpperCase() == 'CHECKBOX') {
		    if(obj.value == value) obj.checked = true;
		}else {
		    obj.value = value;
		}//if
	    }else if(obj.tagName.toUpperCase() == 'SELECT') {
		for(var i = 0; i < obj.options.length; i++) {
		    if(obj.options[i].value == value) {
			obj.selectedIndex = i;
			break;
		    }//if
		}//for
	    }else {
		obj.value = value;
	    }//if
	}//if
    }//if
}

/**
	객체의 innerHTML에 value를 추가한다.
 */
function appendHTMLToObject(_obj, value) {
    new Insertion.Bottom(_obj, value);
    //var obj = $(_obj);
    //if(obj != null) obj.innerHTML = obj.innerHTML + value;
}

function funcCheckEditorValue( instanceName, targetName ) 
{                           
    try{            
        var oEditor = FCKeditorAPI.GetInstance( instanceName ) ;   
        var str = oEditor.GetXHTML( true );
        $(targetName).value = funcChangeChar(str);  
        oEditor.SetHTML( '' );
        str = $(targetName).value;
        return str !='' ;  
    }catch(ex){    
        return $(targetName).value!='';
    }              
}

function getEvent(loadevt) {
    var crossevt=(window.event)? event : loadevt
    return loadevt;
}

function getEventTarget(crossevt) {
    return (crossevt.currentTarget)? crossevt.currentTarget : crossevt.srcElement;
}


function resizeIframe()
{return;
    var oBody	= (document.getElementsByTagName('BODY'))[0];//document.documentElement;
    var iWidth  = 0;
    var iHeight = 0;
    
    iWidth  = oBody.scrollWidth;
    iHeight = oBody.scrollHeight;
    try {
	var ifrm = parent.document.getElementsByTagName('IFRAME')[0];
	ifrm.style.height= iHeight+ 'px';
	//parent.style.width = iWidth + 'px';
	//parent.style.height= iHeight+ 'px';
	//window.resizeTo(ifrm.style.width,iHeight + 'px');
	//alert(ifrm.tagName + ':::::' + ifrm.height);
    }catch(ex){}
}

function lpad(val, len, ch) {
    if(val == null) val = '';
    val += '';
    if(val.length >= len) return val;
    var tmp = '';
    for(var i = val.length; i < len; i++) {
        tmp += ch;
    }
    return tmp + '' + val;
}

function getParameter(key) {
    var str = location.href;
    if(key == null || key == '' || str.indexOf('?') < 0) return '';
    str = str.substring(str.indexOf('?'));
    var retVal = str.parseQuery()[key];
    return (retVal == null)?'':retVal;
}

function enc(str) {
    str = str.replace(/%/g, '<*>');
    str = escape(str);
    return str;
}

function dec(str) {
    str = unescape(str);
    str = str.replace(/<*>/g, '%');
    return str;
}

//SELECT에 있는 모든 옵션을 제거한다.
function clearOptions(str)
{
    var obj = $(str);
    if(obj == null || obj.type.indexOf('select') < 0) return;
    var opts = obj.options;
    while(opts.length > 0) {
        obj.remove(opts.length - 1);
    }
}

//SELECT tag에 옵션을 추가한다.
function addOption(str, value, text)
{
    var obj = $(str);
    if(obj == null || obj.type.indexOf('select') < 0) return;
    var opts = obj.options;
    var option = new Option(text, value, null, null);
    opts.add(option);
}

function viewImage(imageFileName)
{
    var imgFileName = encodeURI(imageFileName);
    var img_win = window.open( 'about:blank', 'img_pop', 'height=5,width=5,top=60,left=100,scrollbars=no,status=no,menubar=no,location=top,toolbar=no,directory=no,resizable=no');
    img_win.document.write("<HTML>\n");
    img_win.document.write("<HEAD>\n");
    //img_win.document.write("<META http-equiv='Content-Type' content='text/html; charset=UTF-8'>\n");
    img_win.document.write("<SCRIPT>\n");
    img_win.document.write("    function funcInit()\n");
    img_win.document.write("    {\n");
    img_win.document.write("        var imgWidth  = document.map.width;\n");
    img_win.document.write("        var imgHeight = document.map.height;\n");
    img_win.document.write("        window.resizeTo(imgWidth + 40, imgHeight + 60);\n");
    img_win.document.write("    }\n");
    img_win.document.write("</SCRIPT>\n");
    img_win.document.write("</HEAD>\n");
    img_win.document.write("<BODY>\n");
    img_win.document.write("<CENTER>\n");
    img_win.document.write("<IMG name='map' src='"  + imgFileName + "' onLoad='funcInit()'>\n");
    img_win.document.write("</CENTER>\n");
    img_win.document.write("</BODY>\n");
    img_win.document.write("</HTML>\n");
}

//-------------      Cookie 시작  from pbfJs.js        ---------------------//
//  절대 삭제 불가
//  var today = new Date()
//  var expire = new Date(today.getTime() + 60*60*1000*24*3650)//60*60*1000*시간*월
function setCookieOfDay(name,value,expiredays)
{
    var todayDate = new Date();
    todayDate.setDate(todayDate.getDate() + expiredays);
    document.cookie = name + "=" + escape( value ) + "; path=/; expires=" + todayDate.toGMTString() + ";"
}

//cookie등록
function register(name, value, expire)
{
    document.cookie = name + "=" + encodeURIComponent(value)+" ;path=/"
        + ( (expire) ? ";expires=" + expire.toGMTString() : "")
}

//cookie가져오기
function getCookie(name) {
    var flag = document.cookie.indexOf(name+'=');
    if (flag != -1) {
        flag += name.length + 1
        end = document.cookie.indexOf(';', flag)

        if (end == -1) end = document.cookie.length
        return unescape(document.cookie.substring(flag, end))
    }
    return '';
}
//cookie등록
function setCookie(name,value,hour,day)
{//day==0 : 시간단위로 쿠키지정
    if (hour == 0)  hour=1;
    if (day > 0)    hour=24;//day에 값을 설정(0이외값)시 hour에 상관 없다
    var today = new Date()
    var expire = new Date(today.getTime() + 60*60*1000*hour*day)//60*60*1000*시간*일

    register(name, value, expire)
}
//-------------      Cookie 끝          ---------------------//

// DATE ////////////////////////////////////////////////////////////////////////////////////////////////////
function getToday() {
    var dt = new Date();
    return dt.getFullYear() + '' +
        lpad(dt.getMonth() + 1, 2, '0')  + '' +
        lpad(dt.getDate(), 2, '0') + '' +
        lpad(dt.getHours(), 2, '0') + '' +
        lpad(dt.getMinutes(), 2, '0') + '' +
        lpad(dt.getSeconds(), 2, '0');
}

// from pbfJs.js ///////////////////////////////////////////////////////////////////////////////////////////
String.prototype.trim = (function(){ return this.replace(/^\s*/ ,"").replace(/\s*$/ ,""); });
String.prototype.lTrim = (function(){ return this.replace(/^\s*/,""); });
String.prototype.rTrim = (function(){ return this.replace(/\s*$/,""); });
String.prototype.stripWhite = (function(){ return this.replace(/\s/g,""); });

function switchAllCheckbox(name, bln) {
    var obj = $N(name);
    if(obj == null) return;
    
    var max = obj.length;
    if(max == null) {
        obj.checked = bln;
    }else {
        for(var i = 0; i < max; i++) {
            obj[i].checked = bln;
        }
    }
}

function checkAll(name) {
    switchAllCheckbox(name, true);
}

function unCheckAll(name) {
    switchAllCheckbox(name, false);
}

function checkAllByObj(name, obj) {
    if(obj == null) return;
    switchAllCheckbox(name, obj.checked);
}
//FCK EDITOR 설정 //////////////////////////////////////////////////////////////////////////////////////////
var isFCKEditor	    = false;
var bbsWriteArea    = 'FCKEditorArea';	    //글 작성 영역
var bbsWirteData    = 'taContent';	    //실제 그 저장영역

function funcSetEditorValue(instanceName, value) {
    try{            
        var oEditor = FCKeditorAPI.GetInstance( instanceName ) ; 
        oEditor.SetHTML(value);
    }catch(ex){}
}

function funcOpenImageUpload(instanceName) {
    try{            
        var oEditor = FCKeditorAPI.GetInstance( instanceName ) ; 
        oEditor.Commands.GetCommand( 'Image' ).Execute();
    }catch(ex){alert(ex);} 
}

function openImageUpload() {
    funcOpenImageUpload(bbsWirteData);
}

function funcOpenPreview(instanceName) {
    try{            
        var oEditor = FCKeditorAPI.GetInstance( instanceName ) ; 
        oEditor.Commands.GetCommand( 'Preview' ).Execute();
    }catch(ex){alert(ex);} 
}

function openPreview() {
    funcOpenPreview(bbsWirteData);
}

function FCKEditorInit(value, bln) {
    if(!isFCKEditor) {
	if(bln == null) bln = true;
	var oFCKeditor = new FCKeditor( bbsWirteData );
	oFCKeditor.BasePath	= '/megaBoard/pbf/fckeditor/';
	oFCKeditor.ToolbarSet	= (bln)?'Basic2':'Basic';
	oFCKeditor.Height	= '400' ;
	oFCKeditor.Value	= value ;
	oFCKeditor.IsUpload	= true;
	var cssObj		= getCSSObj();
	oFCKeditor.CSS		= (cssObj == null)?'':cssObj.href;
	oFCKeditor.Create($(bbsWriteArea));
	isFCKEditor = true;
    }else {
	funcSetEditorValue(bbsWirteData, value);
    }
}

function getCSSObj() {
    var retVal = null;
    var altVal = null;
    var linkObjs = document.getElementsByTagName('LINK');
    if(linkObjs != null) {
	for(var i = 0; i < linkObjs.length; i++) {
	    if(linkObjs[i].type == 'text/css') {
		if(linkObjs[i].title == 'FrontStyle') {
		    retVal = linkObjs[i];
		    break;
		}
		if(altVal == null) altVal = linkObjs[i];
	    }
	}
    }
    return (retVal == null)?altVal:retVal;
}

function funcChangeChar(str) {
    str = str.replace(/케잌/g, '케이크');
    str = str.replace(/샾/g, '숍');
    str = str.replace(/%/g, '<*>');
    return str;
}
//FCK EDITOR 설정 끝///////////////////////////////////////////////////////////////////////////////////////
/* toggle background 관련 시작 */
/*
Event.observe(document, 'dom:loaded', function() {
	var sDiv = '<div id="megaBackgroundDiv" style="width:100%;height:100%;position:absolute;top:0px;left:0px;display:none;background-color:gray;filter:alpha(opacity=50);-moz-opacity:0.5;opacity:0.5;-khtml-opacity:0.5;"></div>';
	new Insertion.Bottom(document.getElementsByTagName('BODY')[0], sDiv);
});

function toggleBackgroundDiv(bln) {
    var obj = $('megaBackgroundDiv');
    if(obj == null) return;
    var isOpen = !bln;
    if(isOpen) {
	hideObject('megaBackgroundDiv');
    }else {
	//var iHeight = getInnerHeight();
	//if(iHeight > document.body.scrollHeight) {
	//	obj.style.height = iHeight +'px';
	//}else {
	//	obj.style.height = document.body.scrollHeight+'px';
	//}
	setOpacity(obj, 50);
	showObject('megaBackgroundDiv');
    }
}

function setOpacity(obj,value) {
    obj.style.filter = "alpha(opacity=" + value + ")";
    obj.style.opacity = (value / 100);
    obj.style.MozOpacity = (value / 100);
    obj.style.KhtmlOpacity = (value / 100);
    obj.style.display="block";
}

function getInnerHeight() {
    var result = new Object;
    if(self.innerWidth){
	    return self.innerHeight;
    }else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict 모드
	    return document.documentElement.clientHeight;
    }else if (document.body) { // 다른 IE 브라우저
	    return document.body.clientHeight;
    }
}

function getInnerWidth() {
    if(self.innerWidth){
	    return self.innerWidth;
    }else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict 모드
	    return document.documentElement.clientWidth;
    }else if (document.body) { // 다른 IE 브라우저
	    return document.body.clientWidth;
    }
}

function getScrollTop() {
    if (self.pageYOffset) { // IE 외 모든 브라우저
	    return self.pageYOffset;
    }else if(document.documentElement && document.documentElement.scrollTop) { // Explorer 6 Strict
	    return document.documentElement.scrollTop;
    }else if(document.body) { // IE 브라우저
	    return document.body.scrollTop;
    }
}
 */
/* toggle background 관련 끝 */
