// 문서 바로보기를 위한 url 설정
var originHost = "https://www.copyright.or.kr";

var fullPath = window.location.pathname;

var pathArr = fullPath.split("/");	
var path = "";
for(var a = 0; a < (pathArr.length-1); a++){
    path = path + pathArr[a] + "/";
}


$(function() {
	// csrf 토큰을 헤더에 담아서 사용
	$.ajaxSetup({
		headers:
		{ 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') }
	});
	
    $('.fbHooking').click( CommonUtil.goFacebook );
    $('.twtHooking').click( CommonUtil.GoTwitter );
    $('.topExp').click( CommonUtil.topExp );
    $('.btn-copy-ucilink').click( Uci.copyUcicode );
    $('.brd_doc_preview').click(CommonUtil.brdDocViewer);

    $('.brd_doc_preview2').click(CommonUtil.brdDocViewer);

    $('.open_doc_preview').click(CommonUtil.openDocViewer);
    /*$('.attachment').click(CommonUtil.checkDownload);*/

    $('.btn-board').click(CommonUtil.brdDocViewer);

    Search.getKeyword();
});

var Uci = {
    copyUcicode : function() {
        try {
            var $this =$(this);
            var ucicode = $this.find('.ucicode').val();
            var copyText = 'http://uci.or.kr/'+ ucicode;

            var ie = (document.all) ? true : false;
            if(ie) {
                window.clipboardData.setData('Text', copyText);
                alert('복사되었습니다. Ctrl+V로 붙여 넣기 하세요.');
            } else {
                prompt("UCICODE 입니다. Ctrl+C를 눌러 클립보드로 복사하세요", copyText );
            }

            return false;
        } catch(e) {
            alert("[js/common/common_util.js's Uci.copyUcicode]" + e.description);
        }
    }
};

var CommonUtil = {
    init : function() {	},

    /**
     * 페이스북
     * @return
     */
    goFacebook : function( text ) {
        try {

            var urls = document.URL;
            var url = encodeURIComponent(urls);

            window.open("http://www.facebook.com/sharer.php?t="+text+"&u="+url
                ,'','toolbar=0, location=0, directories=1, status=1, menubar=1, scrollbars=yes, resizable=1,width=626,height=436');

        } catch ( e ) {
            alert("[js/common/common_util.js's CommonUtil.goFacebook]" + e.description);
        }
    },

    /**
     * 트위터
     * @return
     */
    GoTwitter : function( ) {
        try {
            var urls = document.URL;
            var url = encodeURIComponent(urls);

            window.open('http://twitter.com/home?status=' + url
                ,'','toolbar=0, location=0, directories=1, status=1, menubar=1, scrollbars=yes, resizable=1,width=926,height=436');

        } catch ( e ) {
            alert("[js/common/common_util.js's CommonUtil.GoTwitter]" + e.description);
        }
    },

    /**
     * 프린터
     * @return
     */
    topExp : function( ) {
        try {
            window.print();
            return false;
        } catch ( e ) {
            alert("[js/common/common_util.js's CommonUtil.topExp]" + e.description);
        }
    },

    /**
     * 첨부문서 미리보기	 *
     */
    brdDocViewer : function() {
        //CommonUtil.playLoadingBar();
        var $this = $(this);
        //var brdno = $this.attr("data-brdno");
        var brdctsno = $this.attr("data-brdctsno");
        var brdctsfileno = $this.attr("data-brdctsfileno");

        var docViewer = window.open("문서 바로보기", "docViewer" ,'toolbar=0, location=0, directories=1, status=1, menubar=1, scrollbars=yes, resizable=1,width=938,height=951');
        var $docForm = $("#docForm");
        $docForm.attr("target", "docViewer");
        $docForm.find("input[name=fid]").val(brdctsno + "" + brdctsfileno);
        $docForm.find("input[name=filePath]").val(originHost + path + "download.do?brdctsno=" + brdctsno + "&brdctsfileno=" + brdctsfileno);
        $docForm.find("input[name=convertType]").val(0);
        $docForm.find("input[name=fileType]").val("URL");
        $docForm.find("input[name=sync]").val(0);
        $docForm.submit();

        /*
        $.ajax(
            {
                type: "GET",
                url: "/common/docviewer/brd/preview.do",
                async: true,
                dataType: "json",
                data : {
                    "brdno" : brdno,
                    "brdctsno" : brdctsno,
                    "brdctsfileno" : brdctsfileno
                },
                error: function(data){
                    $.unblockUI();
                    alert("문서변환을 실패 하였습니다. 관리자에게 문의하세요.");
                },
                success:function(data) {
                    $.unblockUI();
                    var query = "fn="+ data.fileNameEnc +"&rs=/result/copyright/file_board/"+brdno+"/"+ brdctsno +"/"+ brdctsfileno;
                    window.open('/plugins/skin_v02_2016_4.2.0/doc.html?' + query
                            ,'','toolbar=0, location=0, directories=1, status=1, menubar=1, scrollbars=yes, resizable=1,width=938,height=951');
                }
            }
        );
        */
    },

    /**
     * 첨부문서 미리보기	 *
     */
    openDocViewer : function() {
        var $this = $(this);

        var toSeq = $this.attr("data-toSeq");
        var seq = $this.attr("data-seq");
        var filePath = $this.attr("data-url");
        filePath = filePath.replace(/ /gi, ''); // 빈 칸 제거

        filePath = originHost + path + filePath;

        var docViewer = window.open("문서 바로보기", "docViewer" ,'toolbar=0, location=0, directories=1, status=1, menubar=1, scrollbars=yes, resizable=1,width=938,height=951');
        var $docForm = $("#docForm");
        $docForm.attr("target", "docViewer");
        $docForm.find("input[name=fid]").val(toSeq + "" + seq);
        $docForm.find("input[name=filePath]").val(filePath);
        $docForm.find("input[name=convertType]").val(0);
        $docForm.find("input[name=fileType]").val("URL");
        $docForm.find("input[name=sync]").val(0);
        $docForm.submit();
        /*
                CommonUtil.playLoadingBar();
                var $this = $(this);
                var toSeq = $this.attr("data-seq");
                var fileNm = $this.attr("data-fileNm");

                $.ajax(
                    {
                        type: "GET",
                        url: "/common/docviewer/opendoc/preview.do",
                        async: true,
                        dataType: "json",
                        data : {
                            "toSeq" : toSeq,
                            "fileNm" : fileNm
                        },
                        error: function(data){
                            $.unblockUI();
                            alert("문서변환을 실패 하였습니다. 관리자에게 문의하세요.");
                        },
                        success:function(data) {
                            $.unblockUI();
                            var query = "fn="+ fileNm +"&rs=/result/copyright/open_document/data/" + toSeq;
                            window.open('/plugins/skin_v02_2016_4.2.0/doc.html?' + query
                                    ,'','toolbar=0, location=0, directories=1, status=1, menubar=1, scrollbars=yes, resizable=1,width=938,height=951');
                        }
                    }
                );	*/
    },
    /*playLoadingBar : function() {
        $.blockUI({
            title : '문서변환 중입니다.',
            message : "<p style='font-size: 2em;margin: 20px 5px;font-weight: bold;color: rgb(105, 105, 105);'>문서변환 중...</p><img style='width: 300px;' src='/images/common/progress-bar.gif'></img>",
            css : {
                width : '400px',
                height : '100px',
                top : '500px',
                left: '45%',
                cursor : false
            }
        });
    },*/
    /**
     * 정보만족도 평가 *
     */
    saveInfoSatisfaction : function() {
        if($("input[name='point']:checked").length == 0){
            alert("만족도 점수선택 후 평가하여 주세요.");
            $("#point5").focus();
            return false;
        }
        $.ajax(
            {
                type: "POST",
                url: "/common/satisfaction/save.do",
                dataType: "text",
                data : $("#satisfactionForm").serialize(),
                error: function(data){
                    alert("만족도조사 평가에 실패하였습니다. 관리자에게 문의하세요.");
                },
                success:function(result) {
                    var json = eval("(" + result + ")");
                    alert(json.resultMessage);
                    $(".satisfaction_wrap").remove();
                    $(".info-satisfaction-success-area").show();
                }
            }
        );
    }

    /*,
    checkDownload: function() {
        if(confirm("파일을 다운로드 하시겠습니까?")){
            return false;
        } else {
            return false;
        }
    }*/
};

var Search = {
    /**
     * 검색 키워드 불러오기
     */
    getKeyword : function() {
        try {
            var target		= "popword";
            var range		= "W";
            var collection  = "_ALL_";
            var charset  = "UTF-8";
            var datatype   = "xml";
            var defaultmsg = '<a href=\"#wisenutQuery\" >인기검색어 수집기간입니다.</a>';
            $.ajax({
                type: "POST",
                url: "/search/keyword.do",
                dataType: "xml",
                data: { "target" : target, "range" : range, "collection" : collection , "datatype" : datatype, "charset" : charset },
                success: function(xml) {
                    var str = "";
                    var index = 0;
                    $(xml).find("Query").each(function(){
                        if(index < 4) {
                            if($(this).attr("id") != 1 ) {
                                str += ', ';
                            }
                            str += "<a href=\"#wisenutQuery\" onclick=\"javascript:doKeyword('" + $(this).text() + "');\">" + $(this).text() + "</a>";
                        }
                        index++;
                    });
                    if(str == "") {
                        str += defaultmsg;
                    }
                    var $html = str;
                    $('.favorite-word em').after(str);
                },
                error : function(a,b,c) {
                    $('.favorite-word em').after(defaultmsg);
                }
            });
        } catch (e) {
            alert("[/js/common/.js's Search.getKeyword] " + e.description);
        }
    }
};

//인기검색어
function doKeyword(query) {
    var searchForm = document.frmSearch;
    searchForm.wisenutPageStartNo.value = "0";
    searchForm.wisenutQuery.value = query;
    searchForm.submit();
}