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 search sbjCate
gaia.searchSbjCateList = function(formObj) {
	formObj.action = "list";
	formObj.submit();
};

//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){
    	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 + "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";
        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;
        } else {
			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() {

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