var Browser = new Object();
Browser.isIE = (navigator.userAgent.toLowerCase().indexOf("msie")!=-1);
Browser.isIE_SV1 = (navigator.userAgent.toLowerCase().indexOf("sv1")!=-1);
Browser.isIE_SV2 = (navigator.userAgent.toLowerCase().indexOf("sv2")!=-1);
Browser.isIE_7 = (navigator.userAgent.toLowerCase().indexOf("msie 7")!=-1);
Browser.isFirefox = (navigator.userAgent.toLowerCase().indexOf("firefox")!=-1);
Browser.isSafari = (navigator.userAgent.toLowerCase().indexOf("safari")!=-1);
Browser.isOpera = (navigator.userAgent.toLowerCase().indexOf("opera")!=-1);
Browser.isNetscape = (navigator.userAgent.toLowerCase().indexOf("netscape")!=-1);
Browser.isEtc = (navigator.userAgent.toLowerCase().indexOf("gecko")!=-1 && navigator.userAgent.toLowerCase().indexOf("firefox")==-1 && navigator.userAgent.toLowerCase().indexOf("netscape")==-1 );

var getPreAndNextArticles = function(){};
var gaia={};

gaia.getCookie=function(name){
    name += "=";
    cookie = document.cookie + ";";
    start = cookie.indexOf(name);
    if (start != -1)
    {
        end = cookie.indexOf(";",start);
        return unescape(cookie.substring(start + name.length, end));
    }
    return "";
};

gaia.setCookie=function(name,value,expires){
    var d = new Date(); var day="";
    if(expires)
    {
        var today = new Date();
        var expiry = new Date(today.getTime() + expires * 1000);
        day = "expires="+expiry.toGMTString()+";";
    }
    document.cookie = name+"="+escape(value)+"; path=/;"+day;
};

gaia.popUp = function(url, width, height) {
        var winObj = window.open(url, "PopUp", "scrollbars=no, resiable=yes, width="+width+", height="+height);
        winObj.focus();
};

gaia.daum_paging_rollover = function(obj, img, type) {
    var imgurl = "http://image.daum-img.net/hanmail/2006_ui/";
    var tmp
    if (type == "on") {
        obj.src = imgurl + img + "_over.gif";
    } else {
        obj.src = imgurl + img + ".gif";
    }
};

gaia.confirmDelete = function(){
	var msg = "정말 삭제하시겠습니까?";
	if( confirm( msg ) ){
		return true;
	} else {
		return false;
	}
};

//list search sbjCate
gaia.searchSbjCateList = function(formObj) {
	formObj.action = "list";
	formObj.submit();
};
gaia.setFormValue = function(formObj, name, val) {
	var el = formObj[name];
	if( el ){
		el.value = val;
	}
};

//list
gaia.searchSubmitForm = function(formEl) {
    var errorMessage = null;
    var objFocus = null;
    if (formEl.searchValue.value.length == 0) {
        errorMessage = "내용을 넣어주세요.";
        objFocus = formEl.searchInput;
    }
    if(errorMessage != null) {
        alert(errorMessage);
        objFocus.focus();
        return false;
    }
    return true;
};

//read
gaia.copyURL={
    call:function (articleId){
        if(gaia.copyURL.clipboard(articleId)) {
            alert('게시물 주소가 복사되었습니다. 원하시는 곳에 ctrl+v로 붙여넣으세요.');
        }
    },
    clipboard:function(intext) {
        if (window.clipboardData) {
            window.clipboardData.setData("Text", intext);
                return true;
        }
        else if (window.netscape) {
            try {
                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=intext;
                str.data=copytext;
                trans.setTransferData("text/unicode",str,copytext.length*2);
                var clipid=Components.interfaces.nsIClipboard;
                if (!clip) return false;
                clip.setData(trans,null,clipid.kGlobalClipboard);
                return true;
            } catch(e) {
            }
        }
        return false;
    }
};

gaia.checkLogin = function( loginURL, returnURL ) {
	if( confirm("먼저 로그인 하셔야 합니다.\n로그인 페이지로 이동 하시겠습니까?") ) {
		top.location.href = loginURL + escape( returnURL );
	}
};

gaia.feedback={
    isAgreed : false, //찬성여부
    isDisagreed : false, //반대여부
    isRecommended : false, //추천여부
    divId : null,

    login:function(loginFeedbackUrl){
		alert("로그인을 하신 후 이용해 주시기 바랍니다.");
		/*
		setTimeout(function(){
		//	top.location.href=loginFeedbackUrl;
			top.location.href="http://www.daum.net";
		}, 0);
		*/
		
    },
    call:function(loginUserId, objectUserId, loginFeedbackUrl, callUrl, id, mode){

        gaia.feedback.divId = id;
        
        
        // 모바일에서만 ctcall 이 수집되도록 수정
        var currentUrl = window.location.href.toString();
        if(currentUrl.indexOf('mobile')>0){
        	// ct call을 위한 부분
            var ctEl = document.getElementById(id);
            mizMobile.ctCall(ctEl); // ct call 을 위한 부분
            // end ct call을 위한 부분
        }
        
        
        //로그인체크
        if(loginUserId==''){ gaia.feedback.login(loginFeedbackUrl);return; }

        //본인여부체크
        if(loginUserId==objectUserId){
            alert("자신의 글에는 추천하실 수 없습니다");
            return false;
        }
        if (mode == 'article') {
            if(gaia.feedback.isAgreed){
                alert("이미 평가하셨습니다");
                return;
            }
            if(gaia.feedback.isDisagreed){
                alert("이미 평가하셨습니다");
                return;
            }
            if(gaia.feedback.isRecommended){
//                alert("이미 추천하셨습니다");
            	alert("이미 평가하셨습니다");
                return;
            }
        }
        
        var tmp = callUrl.split("?");
        var url = tmp[0];
        var param = tmp[1];
        var dummy = new Date().getTime();
        new UI.Ajax( { url:url, param:param+"&"+dummy, onComplete:gaia.feedback.callBack} );
    },
    callBack:function(res){
        var result = eval('(' + res.responseText + ')');

        if (result.status == '500'){
            alert("이미 평가하셨습니다.");
            gaia.feedback.isAgreed = true;
            return false;
        }else if(result.status == '600'){
            alert("이미 평가하셨습니다.");
            gaia.feedback.isDisagreed = true;
            return false;
        }else if (result.status == '700'){
//            alert("이미 추천하셨습니다.");
            alert("이미 평가하셨습니다.");
            gaia.feedback.isRecommended = true;
            return false;
        }else if (result.status == '300'){
            alert("오류가 발생했습니다. 다시 한번 시도해 주세요.");
            return false;
        }else if (result.status == '200'){
            if (result.mode == 'recommend')
            {
                document.getElementById(gaia.feedback.divId).innerHTML = result.recommendCount;
                gaia.feedback.isRecommended = true;
            }

            if (result.mode == 'agree')
            {
                document.getElementById(gaia.feedback.divId).innerHTML = result.agreeCount;
                gaia.feedback.isAgreed = true;
            }

            if (result.mode == 'disagree')
            {
                document.getElementById(gaia.feedback.divId).innerHTML = result.disagreeCount;
                gaia.feedback.isDisagreed = true;
            }
        }
    }
};

//write
gaia.updateChar = function(FieldName, mententname, textlimitname){
        var strCount = 0;
        var tempStr, tempStr2;
        for(i = 0;i < document.getElementById(mententname).value.length;i++)
        {
            tempStr = document.getElementById(mententname).value.charAt(i);
            if(escape(tempStr).length > 4) strCount += 2;
                else strCount += 1 ;
        }
        if (strCount > FieldName){
            alert("댓글을 " + FieldName + "byte미만으로 입력해주시기 바랍니다.");
            strCount = 0;
            tempStr2 = "";
            for(i = 0; i < document.getElementById(mententname).value.length; i++)
            {
                tempStr = document.getElementById(mententname).value.charAt(i);
                if(escape(tempStr).length > 4) strCount += 2;
                else strCount += 1 ;
                if (strCount > FieldName)
                {
                    if(escape(tempStr).length > 4) strCount -= 2;
                    else strCount -= 1 ;
                    break;
                }
                else tempStr2 += tempStr;
            }
            document.getElementById(mententname).value = tempStr2;
        }
        document.getElementById(textlimitname).innerHTML = strCount;
};

gaia.add_file = function (){
    var input_add = "<br>URL <input type='text' name='cUrl' >설명<input type='text' name='cTitle'><input type='hidden' name='cMarkingType' value='1'/>"
    document.getElementById("add_area").innerHTML += input_add;
};

gaia.add_relatedContent = function (){
    var input_add = "URL : <input name='url' type='text' value=''><br>" +
                        "title : <input name='title' type='text' value=''><br>" +
                        "imageUrl : <input name='imageUrl' type='text' value=''><br>" +
                        "type : <input name='relatedContentType' type='text' value=''><br>" +
                        "author : <input name='author' type='text' value=''><br>" +
                        "displayOrder : <input name='displayOrder' type='text' value=''><br>" +
                        "-----------------------------------<br>";
    document.getElementById("add_area").innerHTML += input_add;
};

gaia.blogPostion = function(url, isChecked, multi_post_layer ) {
    document.getElementById(multi_post_layer).style.display  = 'block';
    if(isChecked){
            document.getElementById(multi_post_layer).innerHTML =
            '<input type="hidden" id="blogCategoryId" name="blogCategoryId" value="0"><input type="hidden" id="blogArticleOpen" name="blogArticleOpen" value="A"><iframe name="blogpost_prepare" src="'+url+'" width="100%" height="62" border="0" frameborder="0" scrolling="no" marginheight="0" marginwidth="0"></iframe>';
    }else{
            document.getElementById(multi_post_layer).style.display  = 'none';
    }
};

gaia.file={
    fileObjName : "file0",

    createFileObj:function() {
        var num = String(parseInt(gaia.file.fileObjName.substring(4, gaia.file.fileObjName.length)) + 1);
        var str = "";
        var fileName = "file" + num;
        var newDiv = document.createElement("DIV");
        newDiv.id = "filelist" + num;
        newDiv.style.paddingBottom = '4px';
        document.getElementById("filesDiv").appendChild(newDiv);
        str = "<input type='file' name='file"+num+"' id='file"+num+"' size='32'>";
        str += " <a href='javascript:gaia.file.removeFileObj("+num+")'><img src='http://icon.daum-img.net/gaia/bt_delete.gif' width='37' height='20' border=0 alt='ì­ì ' /></a>";
        document.getElementById("filelist"+num).innerHTML = str;

        fileObjName = fileName;
    },

    removeFileObj:function(num) {
        document.getElementById("filelist"+num).innerHTML = "";
        document.getElementById("filelist"+num).style.display = 'none';
    },

    removeFileObj2:function(){
        var v = document.getElementById('fileid').checked;
        if(v == true){
            document.getElementById('filelist0').style.display = "";
        }else{
            document.getElementById('filelist0').style.display = "none";
        }
        removeFileObj();
    }
};

gaia.snsPosting = {

	isOpend : false, // 공개여부

	connectionCheck	:function(input, bbsId, connectionisEnabled, serviceName){
		if(input.checked) {
	        var url = "/gaia/do/profile/getProfileInfo";
	        var param = "bbsId=" + bbsId;
			new UI.Ajax( { url:url, param:param, onComplete:gaia.snsPosting.callBack} );

			if (connectionisEnabled != "true" && gaia.snsPosting.isOpend)
				gaia.popUp("http://profile.daum.net/api/popup/JoinProfile.daum?service_name="+serviceName+"&callback=SNSProfileCallBack",300,300);
		}
	},

    callBack:function(res){
        var result = eval('(' + res.responseText + ')');
        if (result.isOpened == 'false')
            alert("SNS 동시 등록을 하려면 Daum 프로필을 공개로 설정 해주세요.");
        else
        	gaia.snsPosting.isOpend = true;
    }
};

gaia.commentReply = {
    displayFrom:function(id,type){
        document.getElementById("id").value =id;
        var replyWrap = document.getElementById('rct_'+id);
        var replyForm = document.getElementById('updateCmtArea');
        replyWrap.appendChild(replyForm);
        replyForm.style.display = "block";
        replyWrap.parentNode.style.display = "";
        gaia.commentListResize();
    },

    hiddenForm:function(id,type){
        var replyForm = document.getElementById('updateCmtArea');
        replyForm.style.display = "none";
        gaia.commentListResize();
    },

    submit:function(id) {
        var errorMessage = null;
        var objFocus = null;
        var cmtText = document.getElementById("recomment");
        if (cmtText.value.length == 0) {
            errorMessage = "내용을 넣어주세요.";
            alert(errorMessage);
            cmtText.focus();
        }
        else{
            document.updateCommentForm.action = "commentReply";
            if (gaia.commentWrite.checkBadKeyword(document.updateCommentForm, cmtText.value))
            	document.updateCommentForm.submit();
            else
            	cmtText.focus();
        }
        
    }
};

gaia.commentWrite = {

    user_login_info : 0, // 0:미로그인 1:로그인 2:본인확인필요
    
    submitForm: function() {
        var errorMessage = null;
        var objFocus = null;
        var cmtText = document.getElementById("comment");
        var cmtSubject = document.getElementById("subject");
        
        if (cmtSubject && cmtSubject.value.length == 0) {
            errorMessage = "제목을 넣어주세요.";
            objFocus = cmtSubject;
        }
        else if (cmtText.value.length == 0) {
            errorMessage = "내용을 넣어주세요.";
            objFocus = cmtText;
        }

        if( errorMessage!= null) {
            alert(errorMessage);
            objFocus.focus();
            return false;
        } else {
        	var cmtAll = cmtText.value;
        	if (cmtSubject) {
	        	cmtAll = cmtSubject.value + cmtText.value;
	        }
        	return gaia.commentWrite.checkBadKeyword(document.writeCommentForm, cmtAll);
        }
    },

    checkLogin : function(loginURL,id) {
        if(gaia.commentWrite.user_login_info==0) {
            if(confirm("먼저 로그인 하셔야 합니다.\n로그인 페이지로 이동 하시겠습니까?")){
                top.location = loginURL + escape (parent.document.location.href+'#commentFrame');
            }
            else{
        		document.getElementById(id).blur();
            }
       } 	
    },

    checkLogin2 : function(isBlockedServiceCheck, blockedSvcRedirectURL, identityCheck, loginLimit, id) {
        topUrl = escape (parent.document.location.href);

        if(isBlockedServiceCheck == "true"){
            top.location = blockedSvcRedirectURL;
        }
        if(identityCheck == "false") {
            if(confirm("정통부 지침에 따라 본인확인을 하셔야 댓글을 작성하실 수 있습니다.\n본인확인 페이지로 이동 하시겠습니까?")){
                top.location = loginLimit+topUrl;
            }else {
            	document.getElementById(id).value = "";
            	document.getElementById(id).blur();
            }	
        }
    },
	
	// 댓글 내용 중 금칙어 체크
	checkBadKeyword : function( form, cmtText ){
		var obj = null;
		var url = "/gaia/do/forbiddenKeyword";
		var param = "bbsId=" + form.bbsId.value + "&content=" + encodeURIComponent( cmtText );
		var succeed = false;

		var ajax = new gaia.Ajax({
			url: url,
			method: "POST",
			async: false,
			paramString: param,
			onsuccess: function( r ){
				var obj = eval( '('+ r.responseText+')' );
				if ( obj.badStatus == 400 ){
					succeed = true;
				} else {
					// 금칙어
					alert('금칙어가 있습니다.'); 
					succeed = false;
				} 
			}
		}).request();
		return succeed;
	}
}

gaia.commentListResize = function() {
	gaia.iframeHeightResize("commentFrame");
}
gaia.iframeHeightResize = function( id ){
	var parentSearchNode = parent.document.getElementById(id);
    if(parentSearchNode) {
        var oBody = document.body;
	    	oBody.style.top='0';
	    	oBody.style.position="absolute";
        var height, width;
        if (navigator.userAgent.indexOf("MSIE") == -1) {
            height=oBody.clientHeight;
        } else {
            height=oBody.clientHeight;
        }
        parentSearchNode.height=height;
    	oBody.style.position="";
    }
}

gaia.resizePopup = function(size) {
    var h=0;
    var popHeight = document.getElementById("popWrap").offsetHeight+34;

    if (Browser.isIE_SV1)       { h = 14; }
    else if(Browser.isIE_7)     { h = 18; }
    else if(Browser.isEtc)      { h = 22; }
    else if(Browser.isFirefox)  { h = 32; }
    else if(Browser.isNetscape) { h = -2; }
    else if(Browser.isOpera)    { h = 26; }
    else                        { h = 0; }
        window.resizeTo(size,popHeight+h);
}

gaia.refreshClose =  function () {

        opener.gaia.commentWrite.user_login_info = 1;  // 0:미로그인 1:로그인
        
        //window.opener.location.reload();
        window.close();
}

gaia.convert2ParticipantArticle = function() {
    document.convert2ParticipantArticleForm.submit();;
};

gaia.chkCclCode = function (){
		var cc=dd=s='';
		if(UI.$('cclComUseY').checked) cc = '';
		else if(UI.$('cclComUseN').checked)	cc = '-nc'

		if(UI.$('cclChgY').checked) dd = '';
		else if(UI.$('cclChgN').checked) dd = '-nd'
		else if(UI.$('cclChgP').checked) dd = '-sa'
		
		if(UI.$('ccl').checked) s = 'by' + cc + dd;
		else	s = 'na';
		var f = document.forms['tx_editor_form'];
		f.cclCode.value = s;
}

gaia.setCCLOption = function (curObj){
	var cclComUseN = document.getElementById('imgCclComUseN');
	var cclChgN = document.getElementById('imgCclChgN');
	var cclChgP = document.getElementById('imgCclChgP');

    var id = curObj.id
	switch(id){
		case "cclComUseN":
			cclComUseN.style.display = "block";
			break;
		case "cclComUseY":
			cclComUseN.style.display = "none";
			break;
		case "cclChgY":
			cclChgN.style.display = "none";
			cclChgP.style.display = "none";
			break;
		case "cclChgN":
			cclChgP.style.display = "none";
			cclChgN.style.display = "block";
			break;
		case "cclChgP":
			cclChgN.style.display = "none";
			cclChgP.style.display = "block";
			break;
		default:
			cclComUseN.style.display = "block";
			cclChgN.style.display = "block";
			break;
	}
}

//jes
if(typeof(UI)=="undefined") var UI={};
Object.extend=function(a, b){
  for (var property in b) a[property] = b[property];
  return a;
};

UI.$=function(s) { return document.getElementById(s) };
UI.toogle=function(id) { UI.$(id).style.display=(UI.getStyle(UI.$(id),'display')=='none') ? 'block':'none' };
UI.getStyle=function(el, style) {
	//prototype.js 
	var value = el.style[style];
	if(!value)
	{
		if(document.defaultView && document.defaultView.getComputedStyle) 
		{
			var css = document.defaultView.getComputedStyle(el, null);
			value = css ? css[style] : null;
		} 
		else if (el.currentStyle) value = el.currentStyle[style];
	}
	return value == 'auto' ? null : value;
};

UI.Ajax = function(options) {
    this.options={
        method:'GET',
        param:'',
        onComplete:null,
        onError:null,
        asynchronous: true,
        contentType: 'application/x-www-form-urlencoded',
        encoding:'UTF-8'
    }
    Object.extend(this.options, options);
    if(this.options.url) this.send();
};
UI.Ajax.prototype={
    getReq:function(){
        var req=null;
        try { req = new XMLHttpRequest(); }
        catch(e)
        {
            try { req = new ActiveXObject("Msxml2.XMLHTTP"); }
            catch(e)
            {
                try { req = new ActiveXObject("Microsoft.XMLHTTP"); }
                catch(e) { }
            }
        }
        return req;
    },
    send:function(){
        this.req = this.getReq();
        var op=this.options;
        var url=op.url;
        var param=op.param;
        var method=op.method.toUpperCase();
        if(method=='GET' && param) url=url+"?"+param;
        this.req.open(method, url, op.asynchronous);
        this.req.setRequestHeader('Content-Type', op.contentType+';charset='+op.encoding);

        var self = this;
        this.req.onreadystatechange = function() { self.onStateChange.call(self) }
        this.req.send(method=='POST'?param:null);
    },
    onStateChange: function() {
        if(this.req.readyState==4)
        {
            if(this.req.status=="200") this.options.onComplete(this.req);
            else
            {
                if(this.options.onError) this.options.onError(this.req);
                else alert("서버에러입니다! 잠시후에 다시 시도하세요! "+this.req.status);
            }
        }
    }
};

// from jigu
gaia.extend=function(a, b){
	for (var property in b) a[property] = b[property];
	return a;
};

gaia.Ajax = function(_options){
	this.options = {
		url: '',
		method: 'get',
		async: true,
		paramString: '',
		encoding: 'utf-8',
		onsuccess: function(){},
		onfailure: function(){},
		onloading: function(){},
		headers: {}
	}
	
	gaia.extend(this.options, _options || {});
	this.init();
}
gaia.Ajax.prototype = {
	init: function(){
		if(window.XMLHttpRequest){
			this.XHR = new XMLHttpRequest();
		}else if(window.ActiveXObject){	
			try{
				this.XHR = new ActiveXObject("Msxml2.XMLHTTP");			
			}catch(e){
				try{
					this.XHR = new ActiveXObject("Microsoft.XMLHTTP");				
				}catch(e){				
					this.XHR = null;
				}
			}
		}		
		if(!this.XHR){return false;};
	},
	request: function(url1, options){
		this.setOptions(options);
		var url = url1 || this.options.url;
		if(this.options.paramString.length > 0 && this.options.method=='get'){
			url = url+((url.indexOf('?')>0) ? '&':'?')+this.options.paramString;
		}
		this.open(url);
	},
	open: function(url){
		var self = this;
		if(this.options.async){this.XHR.onreadystatechange = function(){ self.stateHandle.call( self ); };}
		this.XHR.open(this.options.method, url, this.options.async);
		var headers = this.options.headers;
		for(var v in headers){
			this.XHR.setRequestHeader(v,headers[v]);
		}
		this.XHR.send(this.options.paramString);
		if(!this.options.async) this.stateHandle();
	},
	abort: function(){
		if(this.XHR){
			this.XHR.abort();
			this.callTimeout();
		}
	},
	stateHandle: function(e){
		switch(this.XHR.readyState){
			case 4:
				window.clearTimeout(this.options.timer);
				this.options.timer = null;
				if(this.XHR.status == 200 || this.XHR.status == 304){
					this.callSuccess();
				}else if(this.XHR.status >= 400){
					this.callFailure(this.XHR.status);
				}
				break;
				
			case 1:
				this.callLoading();
				break;			
		}			
	},
	callSuccess: function(){
		this.options.onsuccess(this.XHR);		
	},
	callFailure: function(){
		this.options.onfailure(this.XHR);		
	},
	callLoading: function(){
		this.options.onloading(this.XHR);		
	},
	setOptions: function(options){
		gaia.extend(this.options, options || {});
		this.options.method = this.options.method.toLowerCase();
		// header 정의
		this.setHeader('charset',this.options.encoding);
		if(this.options.method=='post'){
			this.setHeader('Content-Type', 'application/x-www-form-urlencoded');
		}
	},
	setHeader: function(key, value){
		if(typeof key === 'object'){
			// header를 셋팅하고 이것을 open시에 첨가한다.
			gaia.extend(this.options.headers, key || {}, true);
		} else {
			this.options.headers[key] = value;
		}
		return this;
	}
};;


/* ---------------------------------------------------------------------------- */

gaia.scrollTop = function(){
	window.scrollTo( 0, 0 );
	return false;
};

//요즘 동시 등록
gaia.YozmIn = function(){
	var isYozmUser = false;
	var userId = null, daumId = null;	
	var conn = null;
	return {
		init: function( _userId, _daumId ){
			conn = new daum.Ajax();
			if( !!_userId && !!_daumId ){
				daum.Event.addEvent( window, "load", daum.Function.bind( this.checkJoined, this ) );
				userId = _userId;
				daumId = _daumId;
			} else {
				// 비 로그인 
			}			
		},
		checkJoined: function(){
			var self = this;
			conn.request('/gaia/do/api/yozm/joined?urlname='+daumId, {onsuccess:function(r){self.joinedCallback(r);}});
		},
		joinedCallback: function( r ){
			var cJoined = daum.Ajax.jsonToObject(r.responseText);
			if( cJoined.result == 1 ){	// 가입자
				isYozmUser = true;
				// 미즈넷에서만 쓰임
				/*
				var pattern = /\/(magazine|magazine_mom)\//;
				if( pattern.test( miznet.doc.loc ) == false ){
					daum.$('sendToYozm').checked = true;
				}
				*/
			}
		},
		preMultiPost: function( checked ){
			if( !!checked && !isYozmUser ){	//  미가입자일 때에만 
				daum.$('yozmJoinWrap').style.display = 'block';
			} else {
				daum.$('yozmJoinWrap').style.display = 'none';
			}
		},
		checkNickName: function(){
			var self = this;
			var nick = encodeURI(daum.$('nickname_yozm').value);
			conn.request('http://bbs.music.daum.net/gaia/do/api/yozm/validateNickname?name='+nick, {onsuccess:function(r){self.nicknameCallback(r);}});
		},
		nicknameCallback: function( r ){
			var rt = daum.Ajax.jsonToObject(r.responseText);
			if( !!rt.message ){
				if( rt.message == 'OK' ) rt.message = '사용가능한 닉네임입니다.';
				daum.$('yozmAlertMsg').innerHTML = rt.message;
			}
		},
		goJoin: function(){
			var self = this;
			var nick = encodeURI(daum.$('nickname_yozm').value);		
			conn.request('http://bbs.music.daum.net/gaia/do/api/yozm/join?viewerid='+userId+'&urlname='+daumId+'&nickname='+nick, {method:'get',onsuccess:function(r){self.goJoinCallback(r);}});
		},
		goJoinCallback: function( r ){
			var rt = daum.Ajax.jsonToObject(r.responseText);
			if( !!rt.message ){
				daum.$('yozmAlertMsg').innerHTML = rt.message;
			} else {
				isYozmUser = true;
				daum.$('yozmAlertMsg').innerHTML = '가입되었습니다.';
			}
		},
		isUser: function(){
			return isYozmUser;
		}		
	};
}();

// Daum지식 동시등록
gaia.qnaPosting = function(){
	
	var method = {
		displayGuideLayer : function( objChk, guideEl ){
			if( objChk.checked == true ){
				daum.hide( guideEl );				
			} else {
				daum.show( guideEl );				
			}
		}
	};
	
	return method;
}();

// 본문 img 크기 자동조절
gaia.resizeContentImg = function( container, maxW ){
	var imgList = container.getElementsByTagName("img");
	var maxWidth = maxW || 540;
	
	// image load event
	for( var i=imgList.length-1; i>=0; i-- ){
		var img = imgList[i];
		var tempImg = new Image();
		tempImg.src = img.src;

		daum.addEvent( tempImg, "load", function(ev){
			var imgCache = img;
			return function(ev){
				if( imgCache.width > maxWidth || imgCache.clientWidth > maxWidth  ){
					imgCache.width = maxWidth;
				}
			};
		}());
	}
	// document load event ( 확인사살 )
	daum.addEvent( window, "load", function(ev){
		for( var i=imgList.length-1; i>=0; i-- ){
			var img = imgList[i];
			if( img.width > maxWidth || img.clientWidth > maxWidth  ){
				img.width = maxWidth;
			}
		};
	});
};

// 포토 갤러리에서 분류 변경시 템플리 교체
gaia.photoCategoryTemplate = function(){
	var objCate = [];
	var template = [];
	var selectedValue = null;
	var msgReplace = "분류를 변경하면 현재 작성중인 내용이 모두 사라집니다.\n변경을 원하신다면 내용을 복사한 뒤 계속 진행해 주시기 바랍니다.\n\n지금 분류를 변경 하시겠습니까?",
		msgDiffLength = "죄송합니다.\n분류와 템플릿의 개수가 일치하지 않습니다",
		msgDefaultText = "분류 선택후 사진을 등록해 주세요";
	
	var eventFunc = function(ev){
		var trg = daum.getElement(ev);
		var num = trg.value;
		if( selectedValue == null ){
			Editor.modify( ({content:template[num-1], attachments:[]}) );
			selectedValue = num;
		} else {
    		if( confirm( msgReplace ) ){
    			Editor.modify( ({content:template[num-1], attachments:[]}) );
				selectedValue = num;
    		} else {
    			for( var i=objCate.length-1; i>=0; --i ){
    				if( objCate[i].value == selectedValue ){
    					objCate[i].checked = true;
    					break;
    				}
                }
				
			}
		}
	};

	var method = {
		init: function( _temp, type ){
			objCate = document.forms.tx_editor_form.objCate1;
			if( type == "edit" ){
				for( var i=objCate.length-1; i>=0; --i ){
	            	if( objCate[i].checked == true ){
	            		selectedValue = objCate[i].value;
	            		break;
	            	}
	            }				
			} else {
				Editor.modify( ({content:msgDefaultText, attachments:[]}) );
			}
			template = _temp;
			
			if( _temp.length != objCate.length ){
				alert(msgDiffLength);
				return false;
			}
			
			for( var i=objCate.length-1; i>=0; --i ){
            	daum.addEvent( objCate[i], "click", eventFunc );
            }
		}
	};
	return method;
}();


// print
gaia.print = function( bbsId, articleId ){
	var url = ["/gaia/do/miznet/print/read?bbsId=", bbsId, "&articleId=", articleId].join("");
	var width = 620,
		height = 840;
	var winObj = window.open(url, "PrintPopUp", "scrollbars=yes, resiable=yes, width="+width+", height="+height);
};

// Coca
var Coca = function(){

	var win = window,
		doc = document,
		indexOfMs = navigator.appName.indexOf("Microsoft");

	var getSWF = function(movieName){
		return (indexOfMs != -1)?win[movieName]:doc[movieName];
	};

	var method = {

		//function은 수정 금지

		//function : upload 시작
		upload: function(){
			getSWF("coca").browse();
		},
		//function : activate 시작(현재는 모든 업로드 서버 -php, 업로드팜- 들이 바로 activation 하기 때문에 호출할 필요가 없다. 
		activate: function(){
			getSWF("coca").activate();
		},
		//function : remove 파일 삭제 key 는 attach type url을 집어 넣는다.
		remove: function(key){
			return getSWF("coca").remove(key);//return remain count
		},
		//upload enable
		enableCoca: function(key){
			return getSWF("coca").enableCoca();
		},
		//upload disable
		disableCoca: function(key){
			return getSWF("coca").disableCoca();
		},

		//callback은 서비스에서 알아서 오버라이드
		//ctx 는 한 페이지 안에 여러 플래시 업로더 인스턴스가 있을 때 구분하기 위한 용도, ctx를 따로 주지 않는 경우 빈 문자열을 반환한다. 

		//플래시 인스턴스에 mouse_over
		on_mouse_over: function(ctx)
		{
			console.log(ctx+"_mouseover");
		},
		//플래시 인스턴스에 mouse_out
		on_mouse_out: function(ctx)
		{
			console.log(ctx+"_mouseout");
		},
		//callback : 에러 발생 시 호출
		on_error: function(msg, ctx){
			console.log(ctx+"_error:"+msg);
		},
		//callback : 파일 브라우저 창에서 취소 할 때 호출
		on_browse_cancel: function(hasError, ctx){
			console.log(ctx+"_browse_cancel");
		},
		//callback : 파일 브라우저에서 파일 선택 후 확인 시 호출
		on_upload_start: function(ctx, count){
			console.log(ctx+"_upload_start:"+count);
		},
		//callback : 파일 업로드가 시작 될 때 호출 - 파일을 3개 선택했으면 3번 호출
		on_upload_open: function(name, size, type, ctx){
			console.log(ctx+"_upload_open:"+name);
		},
		//callback : 전체 선택 파일의 업로드 량 변화 시 호출 - 퍼센트
		on_upload_progress: function(percent, ctx){
			console.log(ctx+"_upload_progress:"+percent);
		},
		//callback : 파일 업로드가 끝나고, result가 오기까지 기다리기 시작
		on_upload_wating_complete: function(name, type, ctx){
			console.log(ctx+"_upload_wating_complete:"+name);
		},
		//callback : 파일 업로드가 끝났을 때 호출 - result 는 이전 카페 php 모듈의 리턴값과 동일, 파일 3개를 올렸으면 3번 호
		on_upload_complete: function(result, ctx){
			console.log(ctx+"_upload_complete:\n"+result);
			var data = result.split("||");
			daum.$("cocaPreviewThumb").innerHTML = '<img src="'+data[1]+'" width="164" height="110" alt="" />';
			daum.$("titleImageUrl").value = data[1];
		},
		//callback : 모든 업로드가 끝났을 때 호출
		on_upload_finish: function(ctx){
			console.log(ctx+"_upload_finish");
		},
		//callback : 파일 액티베이트가  끝났을 때 호출 - 현재 파일서버들은 자동 액티베이트 방식이기 때문에 호출되지 않는다.
		on_activate_complete: function(result, ctx){
			console.log(ctx+"_activate_complete:\n"+result);
		},
		//callback : 파일 액티베이트가  모두 끝났을 때 호출 - 현재 파일서버들은 자동 액티베이트 방식이기 때문에 호출되지 않는다.
		on_activate_finish: function(ctx){
			console.log(ctx+"_activate_finish");
		},
		//callback : 설정해놓은 파일 사이즈보다  큰 파일을 선택했을 경우
		on_over_filesize: function(filename, maxsize, ctx){
			console.log(ctx+"_oversize:"+filename+","+maxsize);
		},
		//callback : 설정해놓은 파일 개수보다  많이  파일을 선택했을 경우
		on_over_filecount: function(overcount, maxcount, ctx){
			console.log(ctx+"_overcount:"+overcount+","+maxcount);
		},
		//callback : 설정해놓은 전체 파일 사이즈 파일를 넘게 선택했을 경우
		on_over_filequota: function(overquota, maxquota, ctx){
			console.log(ctx+"_overquota:"+overquota+","+maxquota);
		},
		//callback : 용량이나 개수 제한이 업로드 도중 넘을 경우 해당 파일은 SKIP, extension_quota_flag는 특정 파일에 쿼타를 줄 경우 해당 파일의 그룹명(다음 에디터에 커플링)
		on_upload_skip: function(name, size, type, ctx, extension_quota_flag){
			console.log(ctx+"_upload_skip:"+name);
		},
		//callback : 100% progress 이후, complete 대기 중
		on_upload_wating_complete: function(name, extension, ctx){
			console.log(ctx+"_wait_complete:"+name);
		},
		on_upload_restrict_complete: function(result, ctx){
			console.log(ctx+"_restrict_complete:"+result);
		}
	};

	return method;
}();

gaia.mobileCommentReply = {
    displayForm:function(id,type){
        document.getElementById("id").value =id;
        var replyWrap = document.getElementById('rct_'+id);
        var replyForm = document.getElementById('updateCmtArea');
        if(replyForm.parentNode.className != "area_comment") {
        	replyForm.parentNode.style.display = "none";
        }
        replyWrap.appendChild(replyForm);
        // animate 효과 제거 (모바일에서 너무 느림)
        // daum.Fx.animate(replyWrap, {height:'159px', padding:'14px 0 15px'}, {duration:0.3, callback:function(){gaia.commentListResize();}});
        replyForm.style.display = "block";
        replyWrap.style.display = "";
        gaia.commentListResize();
        
    },

    hiddenForm:function(id,type){
        var replyForm = document.getElementById('updateCmtArea');
        replyForm.parentNode.style.display = "none";
        //replyForm.parentNode.style.height = "0px";
        //replyForm.parentNode.style.padding = "0";
        replyForm.style.display = "none";
        gaia.commentListResize();
    },

    submit:function(id) {
        var errorMessage = null;
        var objFocus = null;
        var cmtText = document.getElementById("recomment");
        if (cmtText.value.length == 0) {
            errorMessage = "내용을 넣어주세요.";
            alert(errorMessage);
            cmtText.focus();
        }
        else{
            document.updateCommentForm.action = "commentReply";
            if (gaia.commentWrite.checkBadKeyword(document.updateCommentForm, cmtText.value))
            	document.updateCommentForm.submit();
            else
            	cmtText.focus();
        }
        
    }
};

//write
/*   모바일에서는 onkeydown, onkeyup, onkeypress event가 통하지 않는다. 
gaia.mobileUpdateChar = function(FieldName, mententname, textlimitname){
    var strCount = 0;
    var tempStr, tempStr2;
    for(i = 0;i < document.getElementById(mententname).value.length;i++)
    {
        tempStr = document.getElementById(mententname).value.charAt(i);
        if(escape(tempStr).length > 4) strCount += 2;
            else strCount += 1 ;
    }
    if (strCount > FieldName){
        alert("최대 " + FieldName + "bytes까지 가능합니다. 초과된 내용은 자동으로 삭제됩니다.");
        strCount = 0;
        tempStr2 = "";
        for(i = 0; i < document.getElementById(mententname).value.length; i++)
        {
            tempStr = document.getElementById(mententname).value.charAt(i);
            if(escape(tempStr).length > 4) strCount += 2;
            else strCount += 1 ;
            if (strCount > FieldName)
            {
                if(escape(tempStr).length > 4) strCount -= 2;
                else strCount -= 1 ;
                break;
            }
            else tempStr2 += tempStr;
        }
        document.getElementById(mententname).value = tempStr2;
    }
    document.getElementById(textlimitname).innerHTML = strCount;
};
*/

gaia.mobileUpdateChar = {
	
	timer:null,
	
	focus:function(FieldName, mententname, textlimitname) {
		
	    this.timer= window.setInterval(function(){
	    	
	    	var strCount = 0;
		    var tempStr, tempStr2;
		    
		    for(i = 0;i < document.getElementById(mententname).value.length;i++)
		    {
		        tempStr = document.getElementById(mententname).value.charAt(i);
		        if(escape(tempStr).length > 4) strCount += 2;
		            else strCount += 1 ;
		    }
		    
		    if (strCount > FieldName){
		        alert("최대 " + FieldName + "bytes까지 가능합니다. 초과된 내용은 자동으로 삭제됩니다.");
		        strCount = 0;
		        tempStr2 = "";
		        for(i = 0; i < document.getElementById(mententname).value.length; i++)
		        {
		            tempStr = document.getElementById(mententname).value.charAt(i);
		            if(escape(tempStr).length > 4) strCount += 2;
		            else strCount += 1 ;
		            if (strCount > FieldName)
		            {
		                if(escape(tempStr).length > 4) strCount -= 2;
		                else strCount -= 1 ;
		                break;
		            }
		            else tempStr2 += tempStr;
		        }
		        document.getElementById(mententname).value = tempStr2;
		    }
		    document.getElementById(textlimitname).innerHTML = strCount;
		    
	    }, 200);
	},
	
	blur:function() {
		window.clearInterval(this.timer);
		this.timer= null;
	}		
}


gaia.mobileCheckLogin = function(url, type) {
	if(type == "loginCheck") {
		if(confirm("먼저 로그인 하셔야 합니다.\n로그인 페이지로 이동 하시겠습니까?"))
			parent.location.href = url;	
	} else {
		parent.location.href = url;
	}
};
    
    
    
    
