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 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";
    }
};

//list
gaia.searchSubmitForm = function(formEl) {
    var errorMessage = null;
    var objFocus = null;
    if (formEl.searchInput.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.feedback={
    isAgreed : false, //찬성여부
    isDisagreed : false, //반대여부
    isRecommended : false, //추천여부
    divId : null,

    login:function(loginFeedbackUrl){
        //top.location.href=loginFeedbackUrl;
    	alert("로그인을 하신 후 이용해 주시기 바랍니다.");
    },
    call:function(loginUserId, objectUserId, loginFeedbackUrl, callUrl, id, mode){

        gaia.feedback.divId = id;

        //로그인체크
        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("이미 추천하셨습니다");
                return;
            }
        }

        var tmp = callUrl.split("?");
        var url = tmp[0];
        var param = tmp[1];
        new UI.Ajax( { url:url, param:param, 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("이미 추천하셨습니다.");
            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 + "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.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.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";
        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";
            document.updateCommentForm.submit();
        }
    }
};

gaia.commentWrite = {

    user_login_info : 0, // 0:미로그인 1:로그인 2:본인확인필요

    submitForm: function(formEl) {
        var errorMessage = null;
        var objFocus = null;
        var cmtText = document.getElementById("comment");
        var cmtSubject = document.getElementById("subject");

        if (cmtText.value.length == 0) {
            errorMessage = "내용을 넣어주세요.";
            objFocus = cmtText;
        }

        if( errorMessage!= null) {
            alert(errorMessage);
            objFocus.focus();
            return false;
        }
        return true;
    },

    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).blur();
            }
        }
    }
}

gaia.commentListResize = function() {

    if(parent.document.getElementById("commentFrame")) {
        var oBody = document.body;
        oBody.style.top='0';
        var height, width;
        if (navigator.userAgent.indexOf("MSIE") == -1) {
            height=oBody.scrollHeight;
        } else {
            height=oBody.scrollHeight+oBody.offsetHeight-oBody.clientHeight;
        }
        parent.document.getElementById("commentFrame").height=height+10;


    }
}

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.claimFormSubmit = function(formEl) {

    document.claimReportForm.submit();
};
// 지식S형 때문에 삭제 alert 추가.
gaia.del = function(url, allowPost) {
	var message = ( allowPost == "Y") ? "해당 글을 삭제하시겠습니까? \nDaum지식에 등록된 게시글은 삭제되지 않습니다." : "해당 글을 삭제하시겠습니까?"
	if(confirm(message)){
		document.location.href = url;
	}
}
//jes
if(typeof(UI)=="undefined") var UI={};
Object.extend=function(a, b){
  for (var property in b) a[property] = b[property];
  return a;
};

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;
        if(location.href.toLowerCase().indexOf("recipeid") > -1) {
        	url = "http://board.miznet.daum.net/gaia/do/cook/recipe/mizr/" + url;
        }
        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);
            }
        }
    }
};
//  지식S형 연동
var cia_ui = {
	display : function(data) {
		var div = data.serviceid + "_" + data.sectionid + "_" + data.itemid;
		var display_div = document.getElementById(div);
		display_div.innerHTML = this.makeHTML(data);
	},
	makeHTML : function(data) {
		var html = "";
		html += "<div class='top'>위의 질문은 <strong>Daum지식</strong>에도 등록되었습니다.";

		if( data.answerCount !=0 || data.commentCount != 0 ){
			html += " <span class='bar'>|</span> 답변 <a href='"+ data.link + "' target='daumKnowledge'  class='cnt'>"
				    + data.answerCount + "</a> &nbsp;댓글 <a href='"+ data.link + "' target='daumKnowledge'  class='cnt'>"
				    + data.commentCount + "</a></div>" ;
			if (data.answerCount > 0) {
				var len = 120;
				if( document.getElementById("qnaPosted_conLength") ){
					len = parseInt(document.getElementById("qnaPosted_conLength").value,10);
				}
				var txt = data.detail.answers[0].content.substring(0, len) + '...';
				var inp = document.createElement('input');
				inp.value = txt;

				html += "<div class='imgSection'></div><div class='answer clearfix'><a href='"+ data.link +"' target='_blank'>"+ txt+ "</a></div>";
			}
		}else{
			html += " <a href='"+ data.link + "' target='_blank' class='goQna'>질문바로가기</a></div>";
		}

		return html;
	}
}

function ciaCallback(data) {
	cia_ui.display(data);
}
