var isLang = 0;

var isNS = (navigator.appName == "Netscape") ? 1 : 0;
if(isNS) document.captureEvents(Event.MOUSEDOWN||Event.MOUSEUP);

function mischandler() {
	return false;
}

function mousehandler(e) {
	var myevent = (isNS) ? e : event;
	var eventbutton = (isNS) ? myevent.which : myevent.button;
	if((eventbutton==2)||(eventbutton==3)) return false;
}

document.oncontextmenu = mischandler;
document.onmousedown = mousehandler;
document.onmouseup = mousehandler;

var setPng24 = function(o) {
	o.width = o.height = 1;
	o.className = o.className.replace(/\bpng24\b/i,'');
	o.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='"+ o.src +"', sizingMethod='image');";
	o.src = '';
	return '';
};

var viewAlert = function() {
	alert('게시물 내용을 볼 수 있는 권한이 없습니다.\n\n로그인 후 이용해 주세요.');
	return;
};

var checkAdminLogin = function(f) {
	if(!f.uid.value) { return alertMsg(f.uid,"아이디를 입력해 주셔야 합니다.",1); }
	if(!f.pass.value) { return alertMsg(f.pass,"비밀번호를 입력해 주셔야 합니다.",1); }
	return true;
};

var checkSetupForm = function() {
	var f = document.getElementById('standard');

	if(f.adminmail.value && !f.adminmail.value.mail()) { return alertMsg(f.adminmail,"관리자 이메일 주소를 바르게 입력해 주셔야 합니다.",1); }
	if(!f.lv1.value) { return alertMsg(f.lv1,"전체관리자에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv2.value) { return alertMsg(f.lv2,"관리자에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv3.value) { return alertMsg(f.lv3,"운영자에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv4.value) { return alertMsg(f.lv4,"부운영자에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv5.value) { return alertMsg(f.lv5,"그룹장에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv6.value) { return alertMsg(f.lv6,"보드장에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv7.value) { return alertMsg(f.lv7,"정회원에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv8.value) { return alertMsg(f.lv8,"준회원에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv9.value) { return alertMsg(f.lv9,"회원에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.lv10.value) { return alertMsg(f.lv10,"비회원에 해당하는 레벨 이름을 입력해 주세요."); }
	if(!f.smtp_server.value) { return alertMsg(f.smtp_server,"SMTP(보내는 메일 서버) 주소를 입력해 주셔야 합니다."); }
	if(!f.smtp_port.value) { return alertMsg(f.smtp_port,"SMTP(보내는 메일 서버) 포트번호를 입력해 주셔야 합니다."); }
	if(!f.spoint.value) { return alertMsg(f.spoint,"기본정보 입력후 가입시 적립되는 점수를 입력해 주세요."); }
	if(!f.spoint.value.num()) { return alertMsg(f.spoint,"기본정보 입력후 가입시 점수는 숫자로만 입력해 주세요.",1); }
	if(!f.bpoint.value) { return alertMsg(f.bpoint,"모든정보 입력후 가입시 적립되는 점수를 입력해 주세요."); }
	if(!f.bpoint.value.num()) { return alertMsg(f.bpoint,"모든정보 입력후 가입시 점수는 숫자로만 입력해 주세요.",1); }
	if(f.filter_idnick.value.trim()) f.filter_idnick.value = f.filter_idnick.value.replace(/\s/g,'');
	if(f.filter_word.value.trim()) f.filter_word.value = f.filter_word.value.replace(/\s/g,'');
	
	f.submit();
}

var checkRegMode = function() {
	var o = $('input[name=regmode]:radio:checked').val();

	if(o == 'email') $('#regmodeText').html('');
	else $('#regmodeText').html('이름,');
};

var checkKeywordSearch = function(f) {
	if(!f.keyword.value) { return alertMsg(f.keyword,"검색어를 입력해 주셔야 합니다."); }
	return true;
};

var checkMemberDelete = function(f) {
	if(confirm("'"+ f.username.value +"' 회원 정보를 삭제 하시겠습니까 ?")) return true;
	else return false;
};

var checkMemberData = function(f,v) {
	if(v.getByte() > ((f == 'userid')?3:2)) {
		$.ajax({
			type: "POST",
			url: "../_main/signup_check.php",
			data: "fid="+f+"&str="+v,
			success: function(req) {
				var msg, o = $('#txt_'+f);

				if(req == "OK") {
					o.html("<span style='color:#3333FF'>사용 가능한 "+ ((f == 'userid')?"아이디":"닉네임") +" 입니다.</span>");
					$('input[name=check_'+f+']').attr('value','1');
				} else {
					o.html("<span style='color:#FF3333'>존재하는 "+ ((f == 'userid')?"아이디":"닉네임") +" 입니다.</span>");
					$('input[name=check_'+f+']').attr('value','0');
				}
			}
		});
	} else {
		$('#txt_'+f).html(((f == 'userid')?"영문/숫자/영문,숫자 조합 4자 ~ 12자 이내":"한글/영문/숫자/영문,숫자 조합 16자 이내"));
		$('input[name=check_'+f+']').attr('value','0');
	}
};

var checkBoardMake = function(f) {
	if(!f.name.value) { return alertMsg(f.name,"게시판 식별 ID를 입력해 주셔야 합니다."); }
	if(f.name.value.getByte() < 4 || !f.name.value.userid()) { return alertMsg(f.name,"게시판 식별 ID 영문/숫자로 최소 4자 이상으로 입력 하셔야 합니다."); }
	if(!f.menuname.value) { return alertMsg(f.menuname,"게시판 이름을 입력해 주셔야 합니다."); }
	if(f.menuname.value.getByte() < 2) { return alertMsg(f.menuname,"게시판 이름은 영문기준 최소 2자 이상으로 입력 하셔야 합니다."); }
	return true;
};

var checkBoardDelete = function(f) {
	if(confirm("'"+ f.bid.value +"' 게시판을 삭제 하시겠습니까 ?\n\n(게시판의 모든 데이터가 삭제 됩니다.)")) return true;
	else return false;
};

var checkReportDelete = function(f) {
	if(confirm("'"+f+"'항목 신고 내용을 삭제 하시겠습니까 ?")) return true;
	else return false;
};

var checkPopupDelete = function(f) {
	if(confirm("선택하신 팝업 내용을 삭제 하시겠습니까 ?")) return true;
	else return false;
};

var centerWindow = function(u,x,y,o) {
	var xp = (screen.width / 2) - (x / 2);
	var hp = (screen.height / 2) - (y / 2);
	if(o != 'undefined') o = ','+o;
	var cw = window.open(u,'centerWin','width='+x+',height='+y+',left='+xp+',top='+hp+o);
	cw.focus();
};

var checkBoardSetup = function() {
	var f = document.getElementById('boardSetupForm');

	if(!f.menuname.value) { return alertMsg(f.menuname,"게시판 이름을 입력해 주셔야 합니다."); }
	if(f.bstyle.value == '2') {
		if(!f.twidth.value || !f.twidth.value.num()) { return alertMsg(f.twidth,"썸네일 가로 사이즈를 숫자로 입력해 주셔야 합니다.",1); }
		if(!f.theight.value || !f.theight.value.num()) { return alertMsg(f.theight,"썸네일 세로 사이즈를 숫자로 입력해 주셔야 합니다.",1); }
	}
	if(!f.table_width.value) { return alertMsg(f.table_width,"게시판 넓이를 입력해 주셔야 합니다."); }
	if(f.header_file.value) { if(!f.header_file.value.match(/\.(html|htm|php)$/i)) { return alertMsg(f.header_file,"게시판 상단에 적용할 파일은 확장자가 HTML / HTM / PHP 인것만 가능 합니다.",1); } }
	if(f.footer_file.value) { if(!f.footer_file.value.match(/\.(html|htm|php)$/i)) { return alertMsg(f.footer_file,"게시판 하단에 적용할 파일은 확장자가 HTML / HTM / PHP 인것만 가능 합니다.",1); } }
	if(!f.list_num.value || !f.list_num.value.num()) { return alertMsg(f.list_num,"게시물 출력수를 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.page_num.value || !f.page_num.value.num()) { return alertMsg(f.page_num,"페이지 출력수를 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.cut_subject.value.num()) { return alertMsg(f.cut_subject,"제목 표시 길이는 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.cut_memo.value.num()) { return alertMsg(f.cut_memo,"내용 표시 길이는 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.pds_size.value.num()) { return alertMsg(f.pds_size,"파일당 용량은 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.pds_num.value.num()) { return alertMsg(f.pds_num,"최대 업로드 개수는 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.point_write.value.num()) { return alertMsg(f.point_write,"게시물 작성시 점수는 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.point_comm.value.num()) { return alertMsg(f.point_comm,"댓글 작성시 점수는 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.point_down.value.num()) { return alertMsg(f.point_down,"파일 다운시 점수는 숫자로 입력해 주셔야 합니다.",1); }

	f.submit();
};

var checkPopupSetup = function() {
	var f = document.getElementById('popupSetupForm');
	tinyMCE.triggerSave();

	if(!f.subject.value) { return alertMsg(f.subject,"팝업 제목을 입력해 주셔야 합니다."); }
	if(!f.size_w.value || !f.size_w.value.num()) { return alertMsg(f.size_w,"창 크기 가로(Width)값은 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.size_h.value || !f.size_h.value.num()) { return alertMsg(f.size_w,"창 크기 세로(Height)값은 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.pos_x.value.num()) { return alertMsg(f.pos_x,"창 위치 왼쪽(Left)값은 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.pos_y.value.num()) { return alertMsg(f.pos_y,"창 위치 위쪽(Top)값은 숫자로 입력해 주셔야 합니다.",1); }
	if(!f.memo.value || f.memo.value == "&nbsp;") { alert("팝업 내용을 작성해 주셔야 합니다."); return; }

	f.submit();
};

var activeDate = function() {
	if($('input[name=active]:checkbox:checked').val()) {
		$('input[name=st_date]').attr('disabled','');
		$('input[name=ed_date]').attr('disabled','');
	} else {
		$('input[name=st_date]').attr('disabled','true');
		$('input[name=ed_date]').attr('disabled','true');
	}
};

var checkAdminWork = function(f) {
	var tmp, s;

	if(!$('input[name=chklist[]]:checkbox:checked').length) { alert("선택된 게시물이 없습니다."); return false; }

	tmp = $('input[name=ctype]:radio:checked').val();
	if(tmp == 1) s = "삭제";
	else if(tmp == 2) s = "이동";
	else s = "복사";

	if(!tmp) { alert("선택 게시물에 대한 삭제 / 이동 / 복사 항목을 선택해 주셔야 합니다."); return false; }
	if(tmp != 1 && !$('#boardid option:selected').val()) { alert("게시물을 이동할 게시판을 선택해 주셔야 합니다."); f.boardid.focus(); return false; }
	if(!confirm("선택한 게시물의 모든 데이터가 "+ s +" 됩니다.\n\n정말 실행 하시겠습니까 ?")) return false;

	return true;
};

var toggleCheck = function(v) {
	if(v.checked == true) {
		$('input[name=chklist[]]').attr('checked','checked');
	} else {
		$('input[name=chklist[]]').attr('checked','');
	}
};

var setThumbSize = function(v,dw,dh) {
	var o = $('#thumbSize');
	var str = "";

	switch(v) {
		case '2':
			str = '썸네일 사이즈 : <input type="text" name="twidth" value="'+dw+'" size="4" maxlength="4" />×<input type="text" name="theight" value="'+dh+'" size="4" maxlength="4" />';
			break;
		default:
	}
	
	o.html(str);
};

var changeLinkForm = function(v) {
	var o = $('#linkLists');
	var t = $('input[name=linktotal]');
	var n = t.val();
	var str = "";

	if(v == 2 && n && $('input[name=link['+(n-1)+']]').val()) {
		if(!confirm("링크 정보가 존재 합니다. 삭제 하시겠습니까 ?")) return;
		else {
			if($('input[name=linkidx['+ (n-1) +']]').val()) {
				$.ajax({
					type: "POST",
					url: "../_main/linkdel.php",
					data: "lidx="+$('input[name=linkidx['+ (n-1) +']]').val()
				});
			}
		}
	}

	if(v == 1) {
		n++;

		str = '							<div id="link_'+ n +'" style="padding-bottom:5px">';
		str += '								<input type="hidden" name="linkidx['+ (n-1) +']" value="0" />';
		str += '								Link'+ n +'.&nbsp; Title : <input type="text" name="title['+ (n-1) +']" value="" size="25" maxlength="150" class="darkInput" />, ';
		str += '								Url : <input type="text" name="link['+ (n-1) +']" value="" size="25" maxlength="150" style="ime-mode:inactive" class="darkInput" />';
		str += '							</div>';

		t.attr('value',n);
		o.html(o.html() + str);
	} else {
		if(n > 0) {
			$('#link_'+ n).remove();

			n--;
			t.attr('value',n);
		}
	}
};

var checkPassForm = function(f) {
	if(!f.userpass.value.trim()) { return alertMsg(f.userpass,"비밀번호를 입력해 주셔야 합니다.",1); }
	if(f.m.value == 'd') {
		if(confirm("해당 게시물 정보가 모두 삭제 됩니다.\n정말 삭제 하시겠습니까 ?")) return true;
		else return false;
	}
};

var deleteBoardData = function(u,n,o) {
	if(confirm("해당 게시물 정보가 모두 삭제 됩니다.\n정말 삭제 하시겠습니까 ?")) self.location.href="delete.php?id="+u+"&idx="+n+o;
	else return;
};

var alertMsg = function(f,msg,v) {
	if(!msg) return;

	alert(msg);
	if(v) f.value = "";
	f.focus();
	return false;
};

// 테그 제거
String.prototype.stip_tags = function ()
{
	return this.replace(/<[a-z|/]+[^<>]*>/gi, '');
};


// 문자열 자르기
String.prototype.cutStr = function(length)
{
	var result	= "";
	var strLen	= 0;
	var strSum	= 0;

	// 실제 길이를 추출합니다.
	for(var i=0; i<this.length; i++)
	{
		if( this.charCodeAt(i) < 255) strLen	+= 1;
		else strLen	+= 2;
	}

	if(strLen > length)
	{
		// 문자열 길이를 변경합니다.
		for(var i=0; i<this.length; i++)
		{
			if( this.charCodeAt(i) < 255) strSum += 1;
			else strSum	+= 2;

			if(strSum < length){
				result	+= this.charAt(i);
			}
			else
			{
				result	+= "...";
				break;
			}
		}
	}
	else
	{
		result = this;
	}

	return result;
}

// 숫자 체크
String.prototype.num = function()
{
	var em = this.trim().match(/^[0-9]+$/);

	return (em) ? true : false;
}

// 문자 앞,뒤 공백 제거
String.prototype.trim = function()
{
	return this.replace(/(^\s*)|(\s*$)/gi, "");
};

// 메일 유효성 체크
String.prototype.mail = function()
{
	var em = this.trim().match(/^[_\-\.0-9a-zA-Z]{1,}@[-.0-9a-zA-z]{2,}\.[a-zA-Z]{2,4}$/);
	return (em) ? true : false;
}

// 아이디 체크 영어와 숫자만 체크 첫글자는 영어로 시작
String.prototype.userid = function()
{
	var count = this.length;
	var result = (this.match(/^[a-z]{1}[_0-9a-z]+$/)) ? true : false;

	for (var i=0; i<count; i++)
	{
		char_ASCII = this.charCodeAt(i);
		if(char_ASCII >= 12592)
		{
			result = false;
			break;
		}
		// 같은문자가 4번 중복
		if (this.charAt(i) == this.charAt(i+1))
		{
			if (this.charAt(i+1) == this.charAt(i+2))
			{
				if (this.charAt(i+2) == this.charAt(i+3))
				{
					result = false;
					break;
				}
			}
		}
		// 4문자이상 순차
		if (char_ASCII+1 == this.charCodeAt(i+1))
		{
			if (char_ASCII+2 == this.charCodeAt(i+2))
			{
				if (char_ASCII+3 == this.charCodeAt(i+3))
				{
					result = false;
					break;
				}
			}
		}
	}
	return result;
}

// 내용이 있는지 없는지 확인
String.prototype.notNull = function()
{
	return (this == null || this.trim() == "") ? false : true; 
}

// 문자열 길이 구하기
String.prototype.getByte = function()
{
	var p, len = 0;

	for(p=0; p < this.trim().length; p++) {
		(this.charCodeAt(p) > 255) ? len += 2 : len++;
	}

	return len;
}

// 연락처 체크 XXX-XXXX-XXXX 형태로 체크
String.prototype.tel = function()
{
	var num = this.trim().onlyNum();
	num = num.substring(0, 3) + "-" + num.substring(3, num.length - 4) + "-" + num.substring(num.length - 4, num.length);
	num = num.trim().match(/^0[0-9]{2}-[0-9]{3,4}-[0-9]{4}$/);
	return (num) ? true : false;
}

// 핸드폰 체크 XXX-XXXX-XXXX 형태로 체크
String.prototype.mobile = function()
{
	var num = this.trim().onlyNum();
	num = num.substring(0, 3) + "-" + num.substring(3, num.length - 4) + "-" + num.substring(num.length - 4, num.length);
	num = num.trim().match(/^01[016789]{1}-[1-9]{1}[0-9]{2,3}-[0-9]{4}$/);
	return (num) ? true : false;
}

// 우편번호 체크 XXX-XXX 형태로 체크
String.prototype.zipcode = function()
{
	var num = this.trim().onlyNum();
	num = num.substring(0, 3) + "-" + num.substring(num.length - 3, num.length);
	num = num.trim().match(/^[1-9]{3}-[0-9]{3}$/);
	return (num) ? true : false;
}

// 모든 문자 제거(숫자 . - 제외)
String.prototype.toNum = function()
{
	var num = this.trim();
	return (this.trim().replace(/[^0-9\.-]/g,""));
}

String.prototype.toNum2 = function()
{
	var num = this.trim();
	return (this.trim().replace(/[^0-9\,]/g,""));
}

// 모든 문자 제거(숫자제외)
String.prototype.onlyNum = function()
{
	var num = this.trim();
	return (this.trim().replace(/[^0-9]/g,""));
}

// 숫자만 뺀 나머지 전부
String.prototype.noNum = function()
{
	var num = this.trim();
	return (this.trim().replace(/[0-9]/g,""));
}

// 숫자에 3자리마다 , 를 찍어서 반환
String.prototype.toMoney = function()
{
	var num = this.toNum();
	var pattern = /(-?[0-9]+)([0-9]{3})/;
	while(pattern.test(num))
	{
		num = num.replace(pattern,"$1,$2");
	}
	return num;
}

var checkJumin = function(obj1,obj2) {
    if (chksumID(obj1,obj2) == false) return false;

    strReg1 = obj1.value;
    strReg2 = obj2.value;

    sGender = strReg2.substring(0,1);
    sYear = strReg1.substring(0,2);

    if (sGender > 4) return false;

    if (sYear != '00') {
        if ((sGender != '1') && (sGender != '2')) return false;
    } else {
        if ((sGender != '3') && (sGender != '4')) return false;
    }

    if (ValidRegNo(obj1) == false) return false;

	return true;
};

var ValidRegNo = function(obj1) {
    strReg1 = obj1.value;

    a = new String(strReg1);

    if(a == '') return false;
    if(a.length != 6 ) return false;

    intYear = parseInt(a.substring(0,2) , 10);
    intMonth = parseInt(a.substring(2,4) , 10);
    intDay = parseInt(a.substring(4,6) , 10);

    if(intMonth < 0 || intMonth > 12) return false;

    switch(intMonth) {
        case 2 :
            if(intDay < 0 || intDay > 29) {
                return false;
                breake;
            }
        case 4 :
            if(intDay < 0 || intDay > 30) {
                return false;
                breake;
            }
        case 6 :
            if(intDay < 0 || intDay > 30) {
                return false;
                breake;
            }
        case 9 :
            if(intDay < 0 || intDay > 30) {
                return false;
                breake;
            }
        case 11 :
            if(intDay < 0 || intDay > 30) {
                return false;
                breake;
            }
        default :
            if(intDay < 0 || intDay > 31) {
                return false;
                breake;
            }
    }

    return true;
};

var chksumID = function(obj1,obj2) {
	var regExpr = /^[0-9]+$/;

    var str1 = obj1.value;
    var str2 = obj2.value;
    var li_lastid,li_mod,li_minus,li_last;
    var value0,value1,value2,value3,value4,value5,value6;
    var value7,value8,value9,value10,value11,value12;

    if (regExpr.test(str1) &&  regExpr.test(str2)) {
        li_lastid    = parseFloat(str2.substring(6,7));
        value0  = parseFloat(str1.substring(0,1))  * 2;
        value1  = parseFloat(str1.substring(1,2))  * 3;
        value2  = parseFloat(str1.substring(2,3))  * 4;
        value3  = parseFloat(str1.substring(3,4))  * 5;
        value4  = parseFloat(str1.substring(4,5))  * 6;
        value5  = parseFloat(str1.substring(5,6))  * 7;
        value6  = parseFloat(str2.substring(0,1))  * 8;
        value7  = parseFloat(str2.substring(1,2))  * 9;
        value8  = parseFloat(str2.substring(2,3))  * 2;
        value9  = parseFloat(str2.substring(3,4))  * 3;
        value10 = parseFloat(str2.substring(4,5))  * 4;
        value11 = parseFloat(str2.substring(5,6))  * 5;
        value12 = 0;

        value12 = value0+value1+value2+value3+value4+value5+value6+value7+value8+value9+value10+value11+value12 ;

        li_mod = value12 %11;
        li_minus = 11 - li_mod;
        li_last = li_minus % 10;

		if (li_last != li_lastid) return false;
        else return true;
    } else return false;
};

var __crtFileCnt = 0;
var totalFileCnt = 10;
var fileLists = [];
var totalSize = 0;
var fullUrl = "";
var upList, txtFileNum, txtFileSize, boardId, userId, regcode, comcode = '';


var getFileCnt = function() {
	return __crtFileCnt;
};

var jbUploadInit = function(tp) {
	fileLists = [];
	totalSize = 0;
	upList.html("");
	jbUploadStatus();

	$.ajax({
		type: "GET",
		url: "jbupload.php",
		data: "bid="+ boardId +"&userid="+ userId +"&ucode="+ regcode +"&ccode="+ comcode +"&mode=init",
		success: function(req) {
			var tmp = req;

			if(tmp != "error") {
				tmp = tmp.split("^");

				var a;

				for(var i=0; i < tmp.length; i++) {
					a = tmp[i].split(",");

					fileLists.push(tmp[i]);
					totalSize += parseInt(a[2]);
				}

				if(tp) jbUploadUpdate('upinit');
				else jbUploadUpdate('init');
			} else {
				jbUploadStatus();
			}
		}
	});
};

var jbUploadUpdate = function(mode, idx) {
	var a, str="";

	if(mode == "upinit") {
		for(var i=0; i < fileLists.length; i++) {
			a = fileLists[i].split(",");
			if(a[1].indexOf("img") != -1) insertImage(a[0]);
			str += jbUploadPreview(a[0]);
		}

		if(upList.html().indexOf("등록된 파일이 없습니다.") != -1) upList.html(str);
		else upList.html(upList.html() + str);

		jbUploadStatus();
	} else if(mode == "init") {
		for(var i=0; i < fileLists.length; i++) {
			a = fileLists[i].split(",");
			str += jbUploadPreview(a[0]);
		}

		if(upList.html().indexOf("등록된 파일이 없습니다.") != -1) upList.html(str);
		else upList.html(upList.html() + str);

		jbUploadStatus();
	} else if(mode == "del") {
		if(idx) {
			if(confirm("선택하신 파일을 정말 삭제 하시겠습니까 ?")) {
				$.ajax({
					type: "GET",
					url: "jbupload.php",
					data: "bid="+ boardId +"&userid="+ userId +"&ucode="+ regcode +"&ccode="+ comcode +"&mode=del&idx="+ idx,
					success: function(req) {
						var tmp = req;

						if(tmp == "ok") {
							var obj = document.getElementById("__"+ idx +"__");
							obj.parentNode.removeChild(obj);
							
							for(var i=0; i < fileLists.length; i++) {
								a = fileLists[i].split(",");

								if(parseInt(a[0]) == idx) {
									obj = document.getElementById("JOYBOARD_EDITOR_"+ idx);
									if(obj) obj.parentNode.removeChild(obj);

									totalSize -= parseInt(a[2]);
									fileLists.splice(i,1);
									break;
								}
							}

							jbUploadStatus();
						} else alert("삭제할 파일이 존재하지 않습니다.");
					}
				});
			}
		}
	}
};

var jbUploadStatus = function() {
	if(upList.html() == null) upList.html('<div align="center" style="color:#aaaaaa; font:normal 9pt Dotum; padding-top:30px">등록된 파일이 없습니다.</div>');
	txtFileNum.html(fileLists.length +' / '+ totalFileCnt);
	txtFileSize.html(getFileSize(totalSize));

	__crtFileCnt = fileLists.length;
};

var jbUploadGetdata = function(idx,num) {
	var a;

	for(var i=0; i < fileLists.length; i++) {
		a = fileLists[i].split(",");
		if(parseInt(a[0]) == parseInt(idx)) break;
	}

	return a[num];
};

var jbUploadPreview = function(idx) {
	var str, num = jbUploadGetdata(idx,0), icon = jbUploadGetdata(idx,1), fname = jbUploadGetdata(idx,4);

	str = '<div id="__'+ num +'__" style="width:52px; height:52px; margin-right:4px; padding:0; border:1px solid #dddddd; background:#ffffff; float:left" title="'+ fname +'">';
	str += '<div style="position:absolute; width:12px; border:0"><img src="../_images/del_check.gif" width="12" height="12" border="0" style="cursor:pointer" onClick="jbUploadUpdate(\'del\','+ num +')" alt="삭제" title="삭제" /></div>';
	str += '<table style="width:48px; height:48px; border:0; margin:0; padding:0"><tr><td align="center">';

	if(icon.indexOf("img") != -1) str += '<img src="loading.php?idx='+ num +'&thumb=1&ws=46&hs=46" style="cursor:pointer" onClick="insertImage('+ num +')" />';
	else str += '<img src="../_icons/'+ icon +'" height="16" />';

	str += '</td></tr></table>';
	str += '</div>';

	return str;
};

var insertImage = function(idx) {
	var num = jbUploadGetdata(idx,0), icon = jbUploadGetdata(idx,1), size = jbUploadGetdata(idx,3);

	var im = document.getElementById("JOYBOARD_EDITOR_"+ idx);

	if(!im) {
		var w = parseInt(size);
		var nw = 950;
		nw = (w && nw) ? Math.min(w,nw) : '';

		var tmp = '<img src="'+ fullUrl +'loading.php?idx='+ num +'" id="JOYBOARD_EDITOR_'+ num +'" name="JOYBOARD_EDITOR_'+ num +'" class="lightbox" width="'+ nw +'" style="cursor:pointer" border="0" />';

		$('#memo').html($('#memo').html() + tmp);
	}
};

var getFileSize = function(size) {
	if(!size) return "0 Byte";

	if(size < 1024) return size + " Bytes";
	else if(size > 1024 && size < 1024*1024) return Math.round(size/1024) + " KB";
	else return Math.round(size / (1024*1024)) + " MB";
};

var flexMessage = function(msg) {
	if(msg) alert(msg);
};

var tinyMCEinit = function(tp) {
	$('textarea.tinymce').tinymce({
		script_url : '../_js/tiny_mce/tiny_mce.js',
		theme : "advanced",
		skin : "o2k7",
		skin_variant : "black",
		language : (isLang) ? "ko" : "en",
		plugins : "safari,table,advimage,advlink,emotions,inlinepopups,media,searchreplace,contextmenu,noneditable,nonbreaking,xhtmlxtras",

		theme_advanced_buttons1 : (tp == 's') ? "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,|,bullist,numlist,|,outdent,indent,forecolor,backcolor,|,link,unlink,nonbreaking,charmap,emotions,image,media,|,cleanup,code" : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,|,bullist,numlist,|,outdent,indent,formatselect,fontselect,fontsizeselect,forecolor,backcolor",
		theme_advanced_buttons2 : (tp == 's') ? "" : "search,replace,|,tablecontrols,visualaid,|,hr,link,unlink,nonbreaking,charmap,emotions,image,media,|,cleanup,code",
		theme_advanced_buttons3 : "",
		theme_advanced_toolbar_location : "top",
		theme_advanced_toolbar_align : "left",
		theme_advanced_statusbar_location : "bottom",
		theme_advanced_resize_horizontal : false,
		theme_advanced_resizing : true,
		content_css : "../_css/board.css"
	});
};

function resizeIfr(obj, minHeight) {
	minHeight = minHeight || 10;

	try {
		var getHeightByElement = function(body) {
			var last = body.lastChild;
			try {
				while (last && last.nodeType != 1 || !last.offsetTop) last = last.previousSibling;
				return last.offsetTop+last.offsetHeight;
			} catch(e) {
				return 0;
			}
			
		}
				
		var doc = obj.contentDocument || obj.contentWindow.document;
		if (doc.location.href == 'about:blank') {
			obj.style.height = minHeight+'px';
			return;
		}
		
		if (/MSIE/.test(navigator.userAgent)) {
			var h = doc.body.scrollHeight;
		} else {
			var s = doc.body.appendChild(document.createElement('DIV'))
			s.style.clear = 'both';

			var h = s.offsetTop;
			s.parentNode.removeChild(s);
		}
		
		if (h < minHeight) h = minHeight;
	
		obj.style.height = h + 'px';
		if (typeof resizeIfr.check == 'undefined') resizeIfr.check = 0;
		if (typeof obj._check == 'undefined') obj._check = 0;

		setTimeout(function(){ resizeIfr(obj,minHeight) }, 200);
	} catch (e) { 
		//alert(e);
	}
}

(function($){
	$.cookie = function(key, value, options) {
		if(arguments.length > 1) {
			var o = $.extend({}, $.cookieOptions, options);
	        if (value === null || value === undefined) {
	            value = '';
	            o.expires = -1;
	        }
	        if (o.expires.constructor != Date) {
				var today = new Date();
				today.setDate(today.getDate() + o.expires);
				o.expires = today;
			}
			// Create the cookie string
			document.cookie = 
				key + '=' + value +
				'; expires=' + o.expires.toUTCString() +
				(o.path? '; path=' + (o.path) : '') +
				(o.domain? '; domain=' + (o.domain) : '') +
				(o.secure? '; secure' : '');
		} else {
			if(result = new RegExp(key+"=(.*?)(?:;|$)").exec(document.cookie))
				return decodeURIComponent(result[1]);
			return false;
		}
	};
	$.cookieOptions = {
		expires: 365,
		path: '/'
	}
})(jQuery);
