/**
* xml을 가지고 게시물 리스트를 그린다.
* made by jung(vinyl)
* @param {Object} formName 해당 폼 명
* @param {Object} element DIV ID
* @param {Object} listXml 리스트 XML
*/

function ListTableCreate(formName, element, listXml) {
	$(element).innerHTML = listXml;
	$('board_list_paging').innerHTML = PagingCreate('Board.page', 'board_list', ACTION_URL, 'list_form', $('list_form').totalCount.value ,$('list_form').page.value, $('list_form').rowLimit.value, $('list_form').groupLimit.value, 'String');
	
	TooltipManager.init("tooltip");
	adjustContentsHeight($('left_side'), $('board_list'), $('contents'));
}

//제목글에 각종 체크하여 타이틀과 링크 값을 반환
function makeTitleLinkStrForArdorList(list_item,deleteFg,listOpenFg,choiceFg,strCmtYn,xmlelem,cg_nm,btype){
    
	var returnTitle = "";
    var titleHtml = "";
    var oldTableId = "";
    //삭제 여부 체크
    if(deleteFg == "X") {
        titleHtml += message["board.alert.delete.withReply.byWriter"];
    } else if(deleteFg == "Z") {
        titleHtml += message["board.alert.delete.withReply.byAdmin"];
    } else if(deleteFg == "N") {
        if(xmlelem["CATEGORY_NAME"] != "")
            titleHtml += "[" + xmlelem["CATEGORY_NAME"] + "] ";
        titleHtml += xmlelem["TITLE"];
    }
    var classStr = "";
    if(xmlelem["ALWAY_FG"] != "N"){     //공지글
        returnTitle += "<img src='/ysrimg/common/ico_notice.gif' alt='notice' /> ";
    }
    if(listOpenFg == "N"){
        returnTitle += "<img src='/images/icon/lock.gif' alt='' class='lock' /> ";
    }
	$('list_form').page.value = "1"; //view의 목록열기는 1페이지로 셋팅
    returnTitle += "<a href=\"javascript:Board.view('" + ACTION_URL + "?cmd=view&seq="+xmlelem["SEQ"]+"&memId="+xmlelem["MEM_ID"]+"&categoryId="+xmlelem["CATEGORY"]+"', 'list_form', "+xmlelem["SEQ"]+", 'view', 'post');\">";

    returnTitle += titleHtml;
    if(strCmtYn == "Y" && xmlelem["CMT_CNT"] != "0"){
        returnTitle += " ["+ xmlelem["CMT_CNT"] +"]";
    }
    returnTitle += "</a>";
    if(btype == "L" && xmlelem["MOVIE_CNT"]){
        var cnt = parseInt(xmlelem["MOVIE_CNT"],10);
        if(cnt > 0){
            returnTitle += " <img src=\"/ysrimg/common/ico_play.gif\" />";
        }
    }
    if (xmlelem["NEW_FLG"] == "Y"){
        returnTitle += " <img src=\"/ysrimg/board/ico_new.gif\" alt=\"new\" class=\"iconN\" />"
    }
    return returnTitle;
}


/*
	. 접미사가  count|cnt 로 끝나는 단어를 골라서 디폴트 값을 '0'을 리턴합니다.
	. ignore case 
*/
function checksuffix(str)
{
	var myRegExp = /[^(cou|c)nt]\b/gi;
	return !myRegExp.test(str);
}

//상단 접근 메소드
function getdefaultval(str)
{
	if(checksuffix(str)) return "0";
	else return "";
}

deleteFlag = false;
var insertCheck = false;

var AjaxBoardManager = {
	/*
	* 리스트를 Ajax를 이용해서 HTML을 생성해서 가져온다. postBody: postData,
	*/
	list : function(element, URL, formName) {
		showAjaxLoadingBox(element);
		new Ajax.Request(URL, {
			method : 'POST',
			parameters:Form.serialize(formName),
			encoding : 'UTF-8',
			onComplete : function(xmlHttp) {
				// 리스트 HTML을 생성
				ListTableCreate(formName, element, xmlHttp.responseText);
				if($('ajaxLoadingBox')) Element.hide('ajaxLoadingBox');
				
				// 히스토리 추가
				if(typeof dhtmlHistory != "undefined") {
					var newLocation = $(formName).page.value;
					var toJson = " { ";
					toJson += "url : '" + URL + "', ";
					toJson += "element : '" + element + "', ";
					toJson += "page : '" + $(formName).page.value + "', ";
					toJson += "formName : '" + formName + "' ";
					toJson += " } ";
					dhtmlHistory.add(newLocation, toJson);
				} else {
					//alert("dhtmlHistory undefined");
				}
			},
			onFailure : function(){
				if($('ajaxLoadingBox')) Element.hide('ajaxLoadingBox');
			}
		});
	},
	/*
    * 열정운영진 리스트를 Ajax를 이용해서 HTML을 생성해서 가져온다. postBody: postData,
    */
    listArdor : function(element, URL, formName) {
        showAjaxLoadingBox(element);
        new Ajax.Request(URL, {
            method : 'POST',
            parameters:Form.serialize(formName),
            encoding : 'UTF-8',
            onComplete : function(xmlHttp) {
                ListArdorCreate(formName, element, xmlHttp.responseXML);
                if($('ajaxLoadingBox')) Element.hide('ajaxLoadingBox');
            },
            onFailure : function(){
                if($('ajaxLoadingBox')) Element.hide('ajaxLoadingBox');
            }
        });
    }
};

function ListArdorCreate(formName, element, listXml) { 
    var root            = listXml.documentElement;
    var xml_view        = document.getElementById(element);
    xml_view.innerHTML  = "";
    var elements_strs   = ["NICKNAME"];  
    var ELEMENTS_STRS   = eval(elements_strs);
    objOption = document.createElement("option");
	objOption.value = "";
	objOption.text = "전체보기";
	xml_view.options.add(objOption);
    if(root.hasChildNodes()) {
        nds = root.childNodes;
        var list_item = listXml.getElementsByTagName("list");
        var xmlelem = new String();
        for(var i=0;i < list_item.length;i++) {
            for(var k=0;k < ELEMENTS_STRS.length;k++){
	            if(list_item[i].getElementsByTagName(ELEMENTS_STRS[k]).length > 0) { 
	                xmlelem[ELEMENTS_STRS[k]] = list_item[i].getElementsByTagName(ELEMENTS_STRS[k])[0].firstChild.nodeValue;
	            } else {
	                xmlelem[ELEMENTS_STRS[k]] = getdefaultval(ELEMENTS_STRS[k]);
	            }
            }
            objOption = document.createElement("option");
            var nickname = xmlelem["NICKNAME"].replaceAll("&lt;", "<").replaceAll("&gt;", ">").replaceAll("&#41;", ")").replaceAll("&#40;", "(").replaceAll("&#39;", "'");
            objOption.value = trim(nickname);
            objOption.text = trim(nickname);
            xml_view.options.add(objOption);
        }
    }
}
/**
* 보드 관련 이벤트 처리부분
*/
var Board = {
    aboutArdor : function(){
        //새창의 크기
		popupWidth = 480;
		popupHeight = 584;
		//스크린의 크기
		screenWidth = screen.availWidth;
	    screenHeight = screen.availHeight;
	        
	    //부모창이 팝업창보다 크기가 클 경우    
	    if(screenWidth > popupWidth && screenHeight >popupHeight){
			//열 창의 포지션	    
	   		StartPopupX = (screenWidth - popupWidth)/2;
		    StartPopupY = (screenHeight - popupHeight)/2;
		    //창 열기
		    window.open('/ardor.do?cmd=about', 'aboutArdor', 'left='+StartPopupX+',top='+StartPopupY+',width='+popupWidth+',height='+popupHeight+', toolbar=no, menubar=no, status=no, scrollbars=no, resizable=no');
	    //부모창이 팝업창보다 크기가 작을 경우
	    }else{

   		    window.open('/ardor.do?cmd=about', 'aboutArdor', 'width='+popupWidth+',height='+popupHeight+'');
	    }
    },
    // 열정운영진 기수별 그룹메뉴보여주기
    showArdor : function(groupId){
        var divArdor = "ardor_" + groupId
        if($(divArdor)) {
            var currentState = $(divArdor).style.display;
            if(currentState == "none"){
                $(divArdor).style.display = "";
            } else {
                $(divArdor).style.display = "none";
            }
        }
    },
    // 열정운영진 개인별 블로그가기
    goArdorBlog : function(groupId, memId){
        location.href="/ardor.do?cmd=list&groupId="+groupId+"&memId="+memId;
    },
	//게시판 유형 변경시 처리
	boardTypeChange : function(url, formName, divElement, type, typeIdx) {
		typeIdx = Number(typeIdx);
		switch(typeIdx) {
			case 1 :
				$('list_type_btn').src = "/ysrimg/board/btn_list_out.gif";
				$('img_type_btn').src = "/ysrimg/board/btn_img_over.gif";   
				break;
			case 2 :
				$('list_type_btn').src = "/ysrimg/board/btn_list_over.gif";
				$('img_type_btn').src = "/ysrimg/board/btn_img_out.gif"; 
				break;
			default:
				break;
		}
		
		$(formName).cmd.value ="ajax_list";
		$(formName).btype.value = type;
		//$(formName).orderBy.value = "";
		AjaxBoardManager.list(divElement, url, formName);
	},
    selectByIngYn : function(url, formName, divElement, ingYn)
    {
        $(formName).cmd.value	=	"ajax_list";
        $(formName).page.value	=	"1";
        $(formName).ingYn.value	=	ingYn;
        document.body.focus();
        AjaxBoardManager.list(divElement, url, formName);
    },
    	
	//페이지 출력수 변경시 처리
    rowLimitChange : function(url, formName, divElement) {
        $(formName).cmd.value ="ajax_list";
        $(formName).page.value = "1";
        document.body.focus();
        AjaxBoardManager.list(divElement, url, formName);
    },
	//정렬 시 호출
	orderBy : function(url, formName, divElement, orderBy, sortIdx) {
	
		sortIdx = Number(sortIdx);
        
        switch(sortIdx) {
            case 1 :
                $('sort_id_date').className = "selected";
                if(cmtOd == 'Y')$('sort_id_cmt').className = "";
                if(viewOd == 'Y')$('sort_id_view').className = "";
                if(recmdOd == 'Y')$('sort_id_recmd').className = "";
                break;
            case 2 :
                if(cmtOd == 'Y')$('sort_id_cmt').className = "";
                if(viewOd == 'Y')$('sort_id_view').className = "selected";
                if(recmdOd == 'Y')$('sort_id_recmd').className = "";
                $('sort_id_date').className = "";
                break;
            case 3 :
                if(viewOd == 'Y')$('sort_id_view').className = "";
                if(cmtOd == 'Y')$('sort_id_cmt').className = "selected";
                if(recmdOd == 'Y')$('sort_id_recmd').className = "";
                $('sort_id_date').className = "";
                break;
            case 4 :
                if(recmdOd == 'Y')$('sort_id_recmd').className = "selected";
                if(cmtOd == 'Y')$('sort_id_cmt').className = "";
                if(viewOd == 'Y')$('sort_id_view').className = "";
                $('sort_id_date').className = "";
                break;
            case 5 :
                break;
            default:
                break;
        }
		
		$(formName).cmd.value ="ajax_list";
		$(formName).page.value = "1";
		$(formName).orderBy.value = orderBy;
		
		AjaxBoardManager.list(divElement, url, formName);
	},
    
	//최신글, 인기글 sorting
	newOrHot : function(url, formName, divElement, orderBy, sortIdx) {
		
		sortIdx = Number(sortIdx);
		
		switch(sortIdx) {
			case 1 :  //최신글
			
				$('list_new_btn').src = "/ysrimg/blog/btn_list_01_over.gif";
				$('list_hot_btn').src = "/ysrimg/blog/btn_list_02_out.gif";   
				break;
			case 3 :  //인기글 
				$('list_new_btn').src = "/ysrimg/blog/btn_list_01_out.gif";
				$('list_hot_btn').src = "/ysrimg/blog/btn_list_02_over.gif"; 
				break;
			default:
				break;
		}
		sortIdx = 5;  //Board.orderBy 실행될때 등록일|덧글수|조회수|추천수에 변화를 주지 않게 하기 위해서 5로 셋팅함..
		Board.orderBy(url, formName, divElement, orderBy, sortIdx);
	},
	//글쓰기 페이지로 이동
	write: function(url, formName, cmd) {
		if(userId == '') {
			Common.loginConfirmDialog(message["board.alert.login.msg"]);
			return;
		}
		$(formName).cmd.value = cmd;
		$(formName).action = url;
		$(formName).method = "post";
		$(formName).submit();
	},
	
	//글보기 페이지로 이동
	view : function(url, formName, seq, cmd, method) {
		$(formName).cmd.value = cmd;
		$(formName).seq.value = seq;
		$(formName).action = url;
		$(formName).method = method;
		$(formName).submit();
	},
	//기수 선택시 처리
    searchByArdorGroup : function(url, formName, divElement)
    {
        $(formName).word.value = "";
        $(formName).ardorMember.value = "";
        $(formName).cmd.value ="ajax_list";
        $(formName).page.value = "1";
        AjaxBoardManager.list(divElement, url, formName);
    },
    // 기수 선택시 닉네임가져오기
    getArdorMember : function(url, formName, divElement)
    {
        $(formName).cmd.value ="ajax_ardor_list";
        AjaxBoardManager.listArdor(divElement, url, formName);
    },
    // 닉네임선택시 처리
    searchByArdorNickname : function(url, formName, divElement){
        $(formName).word.value = "";
        $(formName).cmd.value ="ajax_list";
        $(formName).page.value = "1";
        $(formName).orderBy.value = "";
        AjaxBoardManager.list(divElement, url, formName);
    },
	//검색 요청시 처리
    search : function(url, formName, divElement)
    {
        $(formName).word.value = document.list_form.checkWord.value;
        $(formName).searchCndt.value = document.list_form.search_cndt.value;
        if($(formName).word.value == '')
        {
            alert_module.show('alert', {
                msg : message["board.search.select_item"]
            });             
            return;
        }
        
        
        $(formName).cmd.value ="ajax_list";
        $(formName).page.value = "1";
        $(formName).orderBy.value = "";
        AjaxBoardManager.list(divElement, url, formName);
    },
	//리스트 페이지에서의 페이징숫자를 눌렀을때 처리
    page : function(url, formName, divElement, goPage) {
        $(formName).cmd.value ="ajax_list";
        $(formName).page.value = goPage;
        AjaxBoardManager.list(divElement, url, formName);
    },
    //엘리먼트 숨기기
	hide : function(divElement) {
		if($(divElement)) {
			$(divElement).style.display = 'none';
		}
	},
	
	//엘리먼트 보기게 하기
	show : function(divElement) {
		if($(divElement)) {
			$(divElement).style.display = 'block';
		}
	},
	
	//기수별 Main 화면에서 멤버 선택시 해당 멤버의 Main 화면으로 이동.
	goSelectMem : function() {
		
		var medId = document.getElementById("selectMem").value;
		var groupId = document.getElementById("groupId").value;
		
		ArdorMenu.list(medId,groupId,1);
	},
	backgroundChange : function(background)
	{
		selectByAttribute("bg_list", "title", background);
		$("backgroundUpdateForm").background.value = background;
	},
	popUp: function(url, formName,cmd){
        if (cmd == 'titleUpdate') {
            ysr_modal.show('titleUpdate');
        } else if(cmd == 'backgroundUpdate') {
        	selectByAttribute("bg_list", "title", $("backgroundUpdateForm").background.value);
            ysr_modal.show('backgroundUpdate');
		} else if(cmd == 'profileUpdate') {
            ysr_modal.show('profileUpdate');
        } else if(cmd == 'categoryMove') {
            ysr_modal.show('moveCategory');
        } else if(cmd == 'cateManagerPop') {
            ysr_modal.show('cateManagerPop');
            MyInfo.get_result();
        } else if(cmd == 'catedel') {
            $(formName).cmd.value = cmd;
            var winprops = "resizable=no, location=no, scrollbars=yes";
            goPostPopup2(formName, 'catedel', url, 'catedel', 300, 170, winprops);
        } else if(cmd == 'profilePreview') {
            $(formName).cmd.value = cmd;
            var winprops = "resizable=no, location=no, scrollbars=no";
            goPostPopup2(formName, 'profilePreview', url, 'profilePreview', 460, 295, winprops);
        }
    }   
};

/**
* 열정운영진 관련 스크립트 
*/
var ArdorMenu = {
    ardor: function(formName, url, no, mid, groupId) {
        if (mid == 52)
            location.href = url+"?cmd=intro&mid="+mid;
        else if (mid == 53)
            location.href = url+"?cmd=recruit&mid="+mid+"&groupId="+groupId;
        else if (mid == 57)
            location.href = url+"?cmd=bloglist&isYb=Y&mid="+mid;
        else if (mid == 58)
            location.href = url+"?cmd=list&isYb=N&mid="+mid;
        else if (mid == 55)
            location.href = url+"?cmd=write&mid=53&groupId="+groupId;
        else if (mid == 56)
            location.href = url+"?cmd=list&mid=53&groupId="+groupId;      
        else if (mid == 154)
            location.href = url+"?cmd=bloglist&isYb=Y&mid=154&groupId=7";                              
        else if (mid == 124)
            location.href = url+"?cmd=bloglist&isYb=Y&mid=124&groupId=6";            
        else if (mid == 622)
            location.href = url+"?cmd=bloglist&isYb=Y&mid=622&groupId=5";
        else if (mid == 623)
            location.href = url+"?cmd=bloglist&isYb=Y&mid="+mid+"&groupId=4";
        else if (mid == 624)
            location.href = url+"?cmd=bloglist&isYb=Y&mid="+mid+"&groupId=3";
        else if (mid == 625)
            location.href = url+"?cmd=bloglist&isYb=Y&mid="+mid+"&groupId=2";
        else if (mid == 626)
            location.href = url+"?cmd=bloglist&isYb=Y&mid="+mid+"&groupId=1";
        else
            location.href = url+"?cmd=list&mid="+mid+"&groupId="+groupId;
    },
    index: function() {
        location.href = "/ardor.do?cmd=index";
    },
    intro: function() {         // 열정운영진 소개 
        location.href = "/ardor.do?cmd=intro&mid=52";
    },
    yblist: function() {        //열정운영진 YB 
        //location.href = "/ardor.do?cmd=bloglist&isYb=Y&mid=57";
        //location.href = "/ardor.do?cmd=bloglist&isYb=Y&mid=622";
        //location.href = "/ardor.do?cmd=bloglist&isYb=Y&mid=124";
        location.href = "/ardor.do?cmd=bloglist&isYb=Y&mid=154";
    },
    oblist: function(groupId) {       //열정운영진 OB
        //location.href = "/ardor.do?cmd=list&isYb=N&mid=58";
        if (groupId == 1) mid = 626;
        else if (groupId == 2) mid = 625;
        else if (groupId == 3) mid = 624;
        else if (groupId == 4) mid = 623;
        else if (groupId == 5) mid = 622;
        else if (groupId == 6) mid = 124;
        
        location.href = "/ardor.do?cmd=bloglist&isYb=Y&mid="+mid+"&groupId="+groupId;
        /*if(groupId>1) {
        	location.href = "/ardor.do?cmd=bloglist&isYb=Y&mid="+mid+"&groupId="+groupId;
        }else{
        	location.href = "/ardor.do?cmd=bloglist_be&isYb=Y&mid="+mid+"&groupId="+groupId;        
        }*/
    },    
    
    list: function(memId, groupId, categoryId) {
        if(memId == '0'){     //기수별 Main으로..
        	location.href = "/ardor.do?cmd=bloglist&groupId="+groupId;
        }else{					//개인별 Main으로..
        	location.href = "/ardor.do?cmd=list&groupId="+groupId+"&memId="+memId+"&categoryId="+categoryId;
        }
    },
    report: function() {        //열정리포트  
        location.href = "/ardorreport.do?cmd=list&mid=59";
    },
    recruitInfo: function(groupId) {
        location.href = "/ardor.do?cmd=recruit&mid=53&groupId="+groupId;
    },
    recruit: function(groupId) {
        location.href = "/ardorrecruit.do?cmd=list&mid=53&groupId="+groupId;
    },
    recruitQna: function(groupId) {
        location.href = "/ardorqna.do?cmd=list&mid=53&groupId="+groupId;
    },
    inside: function() {
        location.href = "/ardorinside.do?cmd=list&mid=70";
    }
}



/**
* 프로필, 카테고리, 타이틀 popup 관련..
*/
var MyInfo = {

	update : function(url, formName, cmd){
		var formObj = document.getElementById(formName);
		
		if(formObj.title.value == ''){
			alert_module.show('alert', {
				msg : message["pblog.alert.category"]
			});
			return;
		} else {
			var spanObj = document.getElementById("titleSpan");
			spanObj.innerHTML = formObj.title.value;
			//document.memInfo.title.value = formObj.title.value;
			//formObj.cmd.value = cmd;
			//formObj.action = url;
			//formObj.method = "post";
			//formObj.submit();
			//opener.top.location.reload();
        	url = url + "?cmd="+cmd;

	        //  Ajax로 처리.
	        new Ajax.Request(url, {
	            method : 'POST',
	            parameters:Form.serialize($(formName)),
	            encoding : 'UTF-8',
	            onSuccess : function(xmlHttp) {
	                var resultString = xmlHttp.responseText;
	                var func = new Function("return " + resultString);
	                var obj = func();
	                if(obj.errcode == "0") {
	                	//성공시 처리.       
	                } else {
	                	//실패시 처리.    
	                }
	            }
	        });

			ysr_modal.close();
		}
	},
		
	// 배경 수정하기
	backgroundUpdate : function()
	{
		new Ajax.Request("/ardor.do?cmd=backgroundUpdate", {
			method     : "POST",
			parameters : Form.serialize($("backgroundUpdateForm")),
			encoding   : "UTF-8",
			onSuccess  : function(xmlHttp) {
				if (xmlHttp != null)
				{
					var responseXML = xmlHttp.responseXML;
					var resultCode  = responseXML.getElementsByTagName("resultCode");
					var resultMsg   = responseXML.getElementsByTagName("resultMsg");
					var background  = responseXML.getElementsByTagName("background");
										
					resultCode = (resultCode.length > 0 && resultCode[0].firstChild != null) ? resultCode[0].firstChild.nodeValue : "0";
					resultMsg  = (resultMsg.length  > 0 && resultMsg[0].firstChild  != null) ? resultMsg[0].firstChild.nodeValue  : "";
					background = (background.length > 0 && background[0].firstChild != null) ? background[0].firstChild.nodeValue : "";
					
					if (resultCode == "1")
					{
						if ($("backgroundUpdateForm").oriBackground != null) $("backgroundUpdateForm").oriBackground.value = background;
						if ($("blog_wrap") != null) $("blog_wrap").style.background = background;
					}
					else
					{
						alert(resultMsg);
					}
				}
				else
				{
					alert("ERROR");
				}
			}
		});
		
		ysr_modal.close();
	},
	//배경 수정취소
	backgroundCancel : function()
	{
		$("backgroundUpdateForm").background.value = $("backgroundUpdateForm").oriBackground.value;
		ysr_modal.close();
	},
	
	cateLengthCheck : function(length_limit, formName, contentObj , textname) {
	   
	    var message = document.forms[formName].elements[contentObj].value;
	    
	    message = message.replace(/\r\n$/, "");	
	    ;
	    var length = MyInfo.calculate_msglen(message);
	    
	    $(textname).innerHTML = length;
	    if(length > length_limit) {
	    	alert_module.show('alert', {
				msg : message["pblog.alert.title.header"] + length_limit + message["pblog.alert.title.tail"]
			});
	    	$(contentObj).blur();
	        //alert("<fmt:message bundle='${msg}' key='board.alert.char.limit1' />" + length_limit + "<fmt:message bundle='${msg}' key='board.alert.char.limit2' />");
	        $(contentObj).value = MyInfo.assert_msglen(message, length_limit, formName, contentObj);
	        //Message.alertDialog("<fmt:message bundle='${msg}' key='board.alert.char.limit1' />" + length_limit + "<fmt:message bundle='${msg}' key='board.alert.char.limit2' />");
	    }
	},
	
	calculate_msglen : function(message)
	{
	    
	    var nbytes = 0;
	    var i = 0;
	
	    for (i=0; i<message.length; i++) {
	        var ch = message.charAt(i);
	        if(escape(ch).length > 4) {
	            nbytes += 2;
	        } else if (ch == '\n') {
	            if (message.charAt(i-1) != '\r') {
	                nbytes += 1;
	            }
	        } else if (ch == '<' || ch == '>') {
	            nbytes += 4;
	        } else {
	            nbytes += 1;
	        }
	    }
	
	    return nbytes;
	},
	
	assert_msglen : function(message, maximum, formName, contentObj)
	{
	    var inc = 0;
	    var nbytes = 0;
	    var msg = "";
	    var msglen = message.length;
	    var i = 0;
	
		//alert(message + '\'s length : '+msglen);
	    for (i=0; i<msglen; i++) {
	    	inc = 0;
	        var ch = message.charAt(i);
	        if (escape(ch).length > 4) {
	            inc = 2;
	        } else if (ch == '\n') {
	            if (message.charAt(i-1) != '\r') {
	                inc = 1;
	            }
	        } else if (ch == '<' || ch == '>') {
	            inc = 4;
	        } else {
	            inc = 1;
	        }
	        if ((nbytes + inc) > maximum) {
				//alert(i + ' ? ' + nbytes + ' + ' + inc + ' > ' + maximum + ' '+ msg);
	            break;
	        }
	        nbytes += inc;
	        msg += ch;
	    }
	    //$('textlimit').innerHTML = nbytes;
	
	    return msg;
	},
	
	// 프로필수정하기
    profileUpdate : function(photoForm, profileForm) {     
        var memId = $(profileForm).memId.value;
        var seq = $(profileForm).seq.value;
        var categoryId = $(profileForm).category.value;
		
		if($(photoForm).photoUploadedURL.value != null && $(photoForm).photoUploadedURL.value != '') {
			$(profileForm).myImage.value = $(photoForm).photoUploadedURL.value;
		}
        $(profileForm).profile.value = $(photoForm).profile.value;        
        //  Ajax로 처리.
        new Ajax.Request("/ardor.do?cmd=profileUpdateCommit", {
            method : 'POST',
            parameters:Form.serialize($(profileForm)),
            encoding : 'UTF-8',
            onSuccess : function(xmlHttp) {
                var resultString = xmlHttp.responseText;
                var func = new Function("return " + resultString);
                var obj = func();                
                if(obj.errcode == "0") {
                    //성공시 처리.
                } else { 
                    //실패시 처리.    
                }
            }
        });        
        //Ajax 처리후 obj.errcode로 분기가 안되서 href 코드를 아래에 둠..
        location.href = "/ardor.do?cmd=list&groupId=" + groupId + "&memId=" + memId + "&categoryId="+categoryId;
        ysr_modal.close();
    },
	
	profilePreview : function(photoForm, profileForm) {
		if($(photoForm).photoUploadedURL.value != null && $(photoForm).photoUploadedURL.value != '') {
			$(photoForm).myImage.value = $(photoForm).photoUploadedURL.value;
		}else{
			$(photoForm).myImage.value = $(profileForm).myImage.value;
		}
		Board.popUp("/ardor.do", photoForm, "profilePreview");
	},
	
	pblogPhotoUpload : function(formName, frameName, file_idx, file_path) {	    
	    if(confirm(message["board.confirm.upload.now"])) {
	        //$(formName).action = "/remotecallsvl?call_fun=editor_photoUploadCompleted&file_path="+file_path+"&file_idx=" + file_idx;
	        $(formName).action = "/remotecallsvl";
	        $(formName).method = "post";
	        $(formName).target = frameName;
	        $(formName).call_fun.value = "editor_photoUploadCompleted";
	        $(formName).file_path.value = file_path;
	        $(formName).file_idx.value = file_idx;
	        
	        $(formName).submit();
	        //alert("pblogPhotoUpload");
	    } else {
	        $(formName).reset();
	        return;
	    }
	},
	submit2 : function(formName){
		
		var moveForm = document.moveForm;
		
		var memId = profileForm.memId.value;
		var groupId = profileForm.groupId.value;
		var seq = profileForm.seq.value;

		for(i=0; i<moveForm.categoryList.length; i++){
			if(moveForm.categoryList[i].checked){
				moveForm.category.value = moveForm.categoryList[i].value;
			}
		}
		
		var category = moveForm.category.value;
		
		var url = "/ardor.do?cmd=categoryMoveUpdate";
		
		//  Ajax로 처리.
        new Ajax.Request(url, {
            method : 'POST',
            parameters:Form.serialize($(formName)),
            encoding : 'UTF-8',
            onSuccess : function(xmlHttp) {
                var resultString = xmlHttp.responseText;
                var func = new Function("return " + resultString);
                var obj = func();
                if(obj.errcode == "0") {
                	//성공시 처리.
                } else { 
                	//실패시 처리.  
                }
            }
        });
        
        //Ajax 처리후 obj.errcode로 분기가 안되서 href 코드를 아래에 둠..
		location.href = "/ardor.do?cmd=list&memId=" + memId + "&groupId=" + groupId + "&seq=" + seq + "&category=" + category;  
		ysr_modal.close();
		//document.form.submit();
		//self.close();
	},
    // 카테고리 관리 관련 스크립트 
	//화면 그리기 
    get_result : function(skey, flag){
        var view_table = "";
        // 수정할 경우 
        if(skey != undefined && flag == "1"){
            var updateKey = $(skey).value;//$(skey).innerHTML;
            document.form.listn.value = updateKey;
            skey = updateKey;
        }
        view_table = "<ul>";
        var i=0;
        for(i; i<categoryInfoArrary.length; i++){
            cateInfoDetailArray = categoryInfoArrary[i].split("|");
            var tempDetail = cateInfoDetailArray[0].replaceAll("&#39;", "'").replaceAll("&quot;", '"');
            if(tempDetail == skey) {
                choice_bg = "choice"; 
            } else { 
                choice_bg = "";
            }
            if(tempDetail){
                // 수정모드
                if(tempDetail == skey && flag == '1'){
                    view_table += "<li class='modify'><input type=\"text\" id='catetxt_"+i+"' name=\"catetxt\" maxlength=\"21\" value='"+cateInfoDetailArray[0]+"' onkeyup=\"fnCharChk(this, 20, 'pblog.alert.title.tail');\" onkeydown=\"if(event.keyCode == '13'){return false;}\">";
                    view_table += "<span class=\"right\"><a href=\"javascript:MyInfo.cateupdate('catetxt_"+i+"');\" class=\"first\" style='cursor:hand;'>" + message["board.alert.ok"] + "</a>";
                // 이동모드
                }else{
                    view_table += "<li class='"+choice_bg+"'>"+"<span class=\"category_name\" id='catetxt_"+i+"' value='"+cateInfoDetailArray[0]+"' onclick=\"MyInfo.choice_item('catetxt_"+i+"')\">"+cateInfoDetailArray[0]+"</span>";
                    view_table += "<span class=\"right\"><a href=\"#\" onclick=\"MyInfo.get_result('catetxt_"+i+"', '1');\" class=\"first\">" + message["board.edit"] + "</a>";
                }
                if(categoryInfoArrary.length != 1){
                    view_table += "<a href=\"javascript:void(0)\" onclick=\"MyInfo.row_del('catetxt_"+i+"');\">" + message["board.delete"] + "</a></span></li>";
                }else{
                    view_table += "</span></li>";
                }
            }
        }
        //카테고리 추가버튼 클릭 시 동작
        if(skey=='1'){
            ++i;
            view_table += "<li class=\"modify\"><input type=\"text\" id='catetxt_"+i+"' name='catetxt_"+i+"' maxlength=\"21\" value='' onkeyup=\"fnCharChk(this, 20, 'pblog.alert.title.tail');\" onkeydown=\"if(event.keyCode == '13'){return false;}\"/>";
            view_table += "<span class=\"right\">";
            view_table += "<a href=\"javascript:MyInfo.row_add('catetxt_"+i+"');\" class=\"first\">" + message["board.alert.ok"] + "</a>";
            
            view_table += "<a href=\"javascript:MyInfo.get_result();\">" + message["board.delete"] + "</a>";
            view_table += "</span>";
            view_table += "</li>";
        }
        view_table += "</ul>";
        view_table += "<div class=\"r_btn\">";
        view_table += "<span class=\"btn_move\">";
        view_table += "<a onclick=\"MyInfo.change('up')\"><img src=\"/ysrimg/btns/btn_move_up.gif\" alt=\"위로 이동\" /></a>";
        view_table += "<a onclick=\"MyInfo.change('down')\"><img src=\"/ysrimg/btns/btn_move_down.gif\" alt=\"아래로 이동\" /></a>";
        view_table += "</span>";
        if(categoryInfoArrary.length < 5) {
        	view_table += "<span class=\"btn_add\"><a href=\"javascript:MyInfo.cateadd();\"><img src=\"/ysrimg/btns/btn_category_add.gif\" alt=\"카테고리 추가\" /></a></span>";
        }
        view_table += "</div>";
        $('view').innerHTML = view_table;
    },
	cateadd : function(){
		MyInfo.get_result("1");
	},
	//전체 확인 버튼 
	catesubmit : function(){
		var j = 1
		var memId = $('cateinfo').memId.value;
		var groupId = $('cateinfo').groupId.value;
		var seq = $('cateinfo').seq.value;
		
		for(i=0;i<categoryInfoArrary.length;i++) {
			cateInfoDetailArray = categoryInfoArrary[i].split("|"); 
			$('cateinfo').content.value = cateInfoDetailArray[0];
			$('cateinfo').seq.value = cateInfoDetailArray[1];
			$('cateinfo').deleteFg.value = cateInfoDetailArray[2];
			$('cateinfo').userId.value = cateInfoDetailArray[4];
			$('cateinfo').sortKey.value = i+j;
			$('cateinfo').openFg.value = cateInfoDetailArray[6];

		    var ajaxUrl = "/ardor.do?cmd=cateInfoUpdate";
			new Ajax.Request(ajaxUrl, {
	            method : 'POST',
	            postBody: Form.serialize($('cateinfo')),
	            encoding : 'UTF-8',
	            onComplete : function(xmlHttp) {
	            	if(xmlHttp.responseText!="0"){
						//location.href="/ardor.do?cmd=cateManagerPop&memId="+'${boardForm.memId}'+"&userId="+'${boardForm.userId}'+"&groupId="+'${boardForm.groupId}';
					} else {
						//alert("삭제를  실패하였습니다.");
					}
	            },
	            onFailure : function() {
	            }
	        });
	        location.href = "/ardor.do?cmd=list&memId=" + memId + "&groupId=" + groupId  ;  
			ysr_modal.close();
		}
	},
	change : function(t){
		var key = document.form.listn;
		var temp;
		if(!key.value) return false;
		ln = new Array(); 
	       // 위로 
	    if(t=="up") { 
	        for(i=0;i<categoryInfoArrary.length;i++) {
	        	cateInfoDetailArray = categoryInfoArrary[i].split("|");
	        	var tempDetail = cateInfoDetailArray[0].replaceAll("&#39;", "'").replaceAll("&quot;", '"'); 
	            if(tempDetail == key.value&&i>0) { 
	                temp = categoryInfoArrary[i];
	                categoryInfoArrary[i] = categoryInfoArrary[i-1]; 
	                categoryInfoArrary[i-1] = temp;						
	            } 
	            else ln[i] = categoryInfoArrary[i]; 
	        }
	    }
	    if(t=="down") { 
	        for(i=0;i<categoryInfoArrary.length;i++) {
	        	cateInfoDetailArray = categoryInfoArrary[i].split("|");
	        	var tempDetail = cateInfoDetailArray[0].replaceAll("&#39;", "'").replaceAll("&quot;", '"'); 
	            if(tempDetail == key.value&&i+1<categoryInfoArrary.length) {
	            	temp = categoryInfoArrary[i];
	            	categoryInfoArrary[i] = categoryInfoArrary[i+1];
	            	categoryInfoArrary[i+1] = temp;
	            	i++; 
	            } 
	            else ln[i] = categoryInfoArrary[i]; 
	        }
	    }
	    MyInfo.get_result(key.value); 
	},
	//카테고리 삭제버튼 
	row_del : function(no){
		var catedel = document.cateinfo3;
		var del_key = $(no).value;//$(no).innerHTML;
		var tmpArray = new Array();
		
		for(i=0;i<categoryInfoArrary.length;i++) {
			cateInfoDetailArray = categoryInfoArrary[i].split("|");
			var tempDetail = cateInfoDetailArray[0].replaceAll("&#39;", "'").replaceAll("&quot;", '"');
			if(tempDetail == del_key){
				catedel.seq.value = cateInfoDetailArray[1];
				catedel.userId.value = cateInfoDetailArray[4];
			}else{
				tmpArray.push(categoryInfoArrary[i]);
			}
		}
		categoryInfoArrary = tmpArray;
		
		//팝업창 없이 confirm 창으로 대체..
		//Board.popUp('${ACTION_URL}', 'cateinfo3', 'catedel');
		if(confirm(message["pblog.alert.category.delete"])){

		    var ajaxUrl = "/ardor.do?cmd=allDelete";
			new Ajax.Request(ajaxUrl, {
	            method : 'POST',
	            postBody: Form.serialize($('cateinfo3')),
	            encoding : 'UTF-8',
	            onComplete : function(xmlHttp) {
	            	if(xmlHttp.responseText!="0"){
						MyInfo.get_result();
						//location.href="/ardor.do?cmd=cateManagerPop&memId="+'${boardForm.memId}'+"&userId="+'${boardForm.userId}'+"&groupId="+'${boardForm.groupId}';
					} else {
						alert_module.show('alert', {
							msg : message["board.alert.delete.failed"]
						});
					}
	            },
	            onFailure : function(){
	            }
	        });	
		}else{
			return;
		}
	},
	cateupdate : function(no){
		var ln;
		var key = document.form.listn;
		var tmpArray = new Array();

		if(!MyInfo.check_dup_cateName(no)){
			alert_module.show('alert', {
				msg : message["pblog.alert.category.title.dup"]
			});	
			MyInfo.get_result();
			return;	
		}
		for(i=0;i<categoryInfoArrary.length;i++) {
	    	cateInfoDetailArray = categoryInfoArrary[i].split("|");
	    	var tempDetail = cateInfoDetailArray[0].replaceAll("&#39;", "'").replaceAll("&quot;", '"'); 
	        if(tempDetail == key.value){
	        	$('cateinfo').sortKey.value = cateInfoDetailArray[5];
	        	$('cateinfo').content.value = document.form.catetxt.value;
	        	$('cateinfo').userId.value = cateInfoDetailArray[4];
	        	$('cateinfo').seq.value = cateInfoDetailArray[1]; 
	        	
	        	tmpArray.push(document.form.catetxt.value+"|"+cateInfoDetailArray[1]+"|"+cateInfoDetailArray[2]+"|"+cateInfoDetailArray[3]+"|"+cateInfoDetailArray[4]+"|"+cateInfoDetailArray[5]+"|"+cateInfoDetailArray[6]);
	        }else{
	        	tmpArray.push(categoryInfoArrary[i]);
	        }
	    }
		categoryInfoArrary = tmpArray;

		var ajaxUrl = "/ardor.do?cmd=cateInfoUpdate";
		new Ajax.Request(ajaxUrl, {
            method : 'POST',
            postBody: Form.serialize($('cateinfo')),
            encoding : 'UTF-8',
            onComplete : function(xmlHttp) {
            	if(xmlHttp.responseText!="0"){
					MyInfo.get_result();
					//location.href="/ardor.do?cmd=cateManagerPop&memId="+'${boardForm.memId}'+"&userId="+'${boardForm.userId}'+"&groupId="+'${boardForm.groupId}';
				} else {
					alert_module.show('alert', {
						msg : message["board.alert.delete.failed"]
					});
				}
            },
            onFailure : function(){
            }
        });
	},
	//카테고리명 중복체크 
	check_dup_cateName : function(no){
	    var rlt = true;
		for(i=0;i<categoryInfoArrary.length ;i++) {
			cateInfoDetailArray = categoryInfoArrary[i].split("|");
			var tempDetail = cateInfoDetailArray[0].replaceAll("&#39;", "'").replaceAll("&quot;", '"');
			if(tempDetail == $(no).value){
			    rlt = false;
			}
		}
		return rlt;
	},
	//카테고리 추가/확인 버튼 
	row_add : function(no){
		//문제
		//카테고리추가는 로그인이 renewer로그인이 안되므로 add되지않는다
		if($(no).value == ''){
			alert_module.show('alert', {
				msg : message["pblog.alert.category.title"]
			});
			$(no).focus();
			return;
		}
		if(!MyInfo.check_dup_cateName(no)){
			alert_module.show('alert', {
				msg : message["pblog.alert.category.title.dup"]
			});	
			return;	
		}
		var num =  categoryInfoArrary.length+1;
		
		var date = new Date().toLocaleString(); 
	    categoryInfoArrary.push($(no).value+"|"+num+"|N|"+date+"|" + $('cateinfo2').userId + "|"+num+"|Y");
	    $('cateinfo2').content.value = $(no).value;
		$('cateinfo2').deleteFg.value ='N';
		$('cateinfo2').sortKey.value = num;
		$('cateinfo2').openFg.value = 'Y';
	    
	    var ajaxUrl = "/ardor.do?cmd=cateadd";
		new Ajax.Request(ajaxUrl, {
            method : 'POST',
            postBody: Form.serialize($('cateinfo2')),
            encoding : 'UTF-8',
            onComplete : function(xmlHttp) {
            	if(xmlHttp.responseText!="0"){
					MyInfo.get_result();					
				} else {
					alert_module.show('alert', {
						msg : message["pblog.fail.category.title"]
					});
				}
            },
            onFailure : function(){
            }
        });	    
	},	
	choice_item : function(no) { 
	    var skey = $(no).value;//$(no).innerHTML;
	    document.form.listn.value = skey; 
	    MyInfo.get_result(skey); 
	}
}
