
/*
 * NLIB 공통 JavaScript 
 */

//---------------------------------------------------------------------------------------------------------------
// 레이어 팝업 관련 함수 
//---------------------------------------------------------------------------------------------------------------

function fn_layerPopWithClass(url, addClasses) {
	// 클릭 시, 로딩되도록 처리 (2021.10.20)
	$("#NLIB_LAYER_POPUP").removeClass();
    $("#NLIB_LAYER_POPUP").addClass(addClasses);
    $("#NLIB_LAYER_POPUP").load(url);

    var classes = addClasses.split(" ");
    
    $("div[name='NLIB_LAYER_POPUP']." + classes[0]).fadeIn();
	
    $('html,body').addClass('no-scroll');
}

// XXXXXXXXXXX : alreadySignUpPopup.jsp > fn_showLayerPop
function fn_showLayerPop() {
	$("#NLIB_LAYER_POPUP").show();
}

function fn_layerPopFormSubmit(formName, display) {
	var dataList = $("#" + formName).serialize();
	var url = $("#" + formName).attr('action');
	
	if(display) $("#NLIB_LAYER_POPUP").show();
	else $("#NLIB_LAYER_POPUP").hide();
	
    $.ajax({
        type: "post",
        url: url,
        data: dataList
    }).done(function(response){
    	$("#NLIB_LAYER_POPUP").empty().append(response);
    });
}

function fn_closeLayerPopup() {
	$("#NLIB_LAYER_POPUP").html("");
	$("#NLIB_LAYER_POPUP").fadeOut();
	$("#NLIB_LAYER_POPUP").removeClass();
	$('html,body').removeClass('no-scroll');
}

function fn_layerPopWithHtml(cHtml, addClasses) {
	$("#NLIB_LAYER_POPUP").removeClass();
    $("#NLIB_LAYER_POPUP").addClass(addClasses);
    $("#NLIB_LAYER_POPUP").html(cHtml);
    $("#NLIB_LAYER_POPUP").show();

    var classes = addClasses.split(" ");
    
    $("div[name='NLIB_LAYER_POPUP']." + classes[0]).fadeIn();
}

//---------------------------------------------------------------------------------------------------------------
// 알림 관련 함수 
//---------------------------------------------------------------------------------------------------------------

function gfn_myAlert(newAlertNum) {
	
	if(newAlertNum == "undefined" || newAlertNum == null || newAlertNum < 1) {
		return;
	}
	
	var alertShowed = gfn_getCookie("_NLIB_ALERT_DONE");
	if(!fn_isEmpty(alertShowed) && alertShowed == "Y") return;
		
    var notiHtml = 
        '<div class="row Title">' + 
        '    <p>지방문화원 소장자료</p>' + 
        '    <h3>알림</h3>' + 
        '</div>' + 
        '<div class="inner">' + 
        '    <div class="row Text">' + 
        '        <p>아직 확인하지 않은<br>새로운 알림이 <span>' + newAlertNum + '</span>건 있습니다.</p>' + 
        '    </div>' + 
        '    <div class="row btn-box">' + 
        '        <button type="button" class="btn btn-color" onclick="gfn_closeMyAlert()">확인</button>' + 
        '        <button type="submit" class="btn btn-green" onclick="location.href = \'/cmm/listNotifications.do\'; ">알림 목록으로</button>' + 
        '    </div>' + 
        '    <button type="button" class="notice-close" onclick="fn_closeLayerPopup()"></button>' + 
        '</div>' + 
        '<div class="Bg"></div>';
    fn_layerPopWithHtml(notiHtml, "pop-notice");
}

function gfn_closeMyAlert() {
	gfn_setCookie("_NLIB_ALERT_DONE", "Y");
	fn_closeLayerPopup();
}

function gfn_setCookie(cookieName, cookieValue, cookieExpire, cookiePath, cookieDomain, cookieSecure){
    var cookieText = escape(cookieName) + '=' + escape(cookieValue);
    cookieText += (cookieExpire ? '; EXPIRES='+cookieExpire.toGMTString() : '');
    cookieText += (cookiePath ? '; PATH='+cookiePath : '');
    cookieText += (cookieDomain ? '; DOMAIN='+cookieDomain : '');
    cookieText += (cookieSecure ? '; SECURE' : '');
    document.cookie=cookieText;
}
 
function gfn_getCookie(cookieName){
    var cookieValue=null;
    if(document.cookie){
        var array=document.cookie.split((escape(cookieName)+'='));
        if(array.length >= 2){
            var arraySub=array[1].split(';');
            cookieValue=unescape(arraySub[0]);
        }
    }
    return cookieValue;
}
 

//---------------------------------------------------------------------------------------------------------------
// 문자열 처리 관련 함수 
//---------------------------------------------------------------------------------------------------------------

function fn_isEmpty(value) {
	if(value == null) return true;
	if(typeof value == "undefined") return true;
	if(typeof value == "string" && value == "") return true;
	if(value == "null") return true;
	if(Array.isArray(value) && value.length < 1) return true;
	
	return false;
}

function fn_unescapeHtml(escapedStr) {
    var doc = new DOMParser().parseFromString(escapedStr, "text/html");
    return doc.documentElement.textContent;
}

function fn_lengthBytes(s) {
	if(s != undefined && s != "") {
		for(b=i=0;c=s.charCodeAt(i++);b+=c>>11?3:c>>7?2:1);
		return b;
	} else {
		return 0;
	}
}

function fn_extractContentText(html) {
    return new DOMParser().parseFromString(html, "text/html").documentElement.textContent;
}

function gfn_removeQuotes(str) {
	if(fn_isEmpty(str)) return "";
	 
	return str.replace(/"/gi, '').replace(/'/gi, "");
}

//---------------------------------------------------------------------------------------------------------------
// RIS 처리 관련 함수 
//---------------------------------------------------------------------------------------------------------------

function risShow(risId){
	var tag = document.createElement("div");

	tag.class="popup pop-user-set pop-export";
	tag.id = "export-data";
	tag.style="style='display: none;'";
	
	document.body.prepend(tag);

	document.getElementById("export-data").className="popup pop-user-set pop-export";

	var html="";
	html+='<form name="risDownloadForm" id="risDownloadForm" method="post"><input type="hidden" id="risId" name="risId"></form>';
	html+='<div class="pop-serge">';
	html+='<div class="row Title">';                                                                                          
	html+='    <h3>서지정보 내보내기<span>(Export)</span></h3>';                                                                      
	html+='</div>';                                                                                                           
	html+='<div class="inner">';                                                                                              
	html+='    <div class="row Text">';                                                                                       
	html+='        <div class="con-1">';                                                                                      
	html+='            <p>서지정보 내보내기 안내</p>';                                                                                  
	html+='            <div class="text-box">';                                                                               
	html+='                <p>소장자료관은 콘텐츠 생산자 및 연구자들을 위해 서지정보 내보내기 기능을 제공하고 있습니다.</p>';                                        
	html+='                <p><span>서지정보 내용</span><br>형식, 제목, 저자, 시리즈, 언어, URL, 태그</p>';                                      
	html+='                <p><span>제공 포맷</span><br>RIS : Search Information System (*.ris)</p>';                             
	html+='                <p><span>RIS 지원 서지관리 프로그램</span><br>EndNote, Mendeley, Zotero) 외</p>';                             
	html+='            </div>';                                                                                               
	html+='        </div>';                                                                                                   
	html+='        <div class="con-2">';                                                                                      
	html+='            <p>서지관리 프로그램 안내</p>';                                                                                 
	html+='            <div class="text-box">';                                                                               
	html+='                <p>서지관리 프로그램은 문헌 및 온라인 콘텐츠 등 자료를 관리하고 공유하는데 사용됩니다.</p>';                                           
	html+='                <p>-  해당 프로그램은 소속기관 또는 개인 가입이 필요할 수 있으며, 소장자료관은 링크만 제공하고 직접 서비스를 제공하지 않습니다.</p>';                  
	html+='                <p><span>Zotero (www.zotero.com) / 한글 메뉴 지원 (o), 300MB 용량 무료 (초과 유료)</span></p>';                  
	html+='                <p><span>EndNote (www.endnote.com) / 한글 메뉴 지원 (x) , 2G 용량 무료 (초과유료)</span></p>';                   
	html+='                <p><span>Mendeley (www.mendeley.com) / 한글 메뉴 지원 (x), 2G 용량 무료 (초과유료)</span></p>';                  
	html+='            </div>';                                                                                               
	html+='        </div>';                                                                                                   
	html+='    </div>';                                                                                                       
	html+='    <div class="row btn-box">';                                                                                    
	html+='        <button type="button" class="btn btn-color" id="risExport" onclick="risDownload(\''+risId+'\');">내보내기</button>';                                                
	html+='        <button type="submit" class="btn btn-gray" onclick="risClose();">닫기</button>';                                                   
	html+='    </div>';                                                                                                       
	html+='    <button type="button" class="serge-close" onclick="risClose();"></button>';                                                          
	html+='</div>';                                                                                                           
	html+='<div class="Bg"></div>';                                                                                           
	html+='</div>';
	
	$("#export-data").append(html);
}

function risDownload(risId){
	$("#risId").val(risId);
	
	document.risDownloadForm.action="/ris/risDownload.do";
	document.risDownloadForm.submit();
}

function risClose(){
	$("#export-data").remove();
}

function forgetPassword(form)
{
	$("#"+form).attr("action", "/member/initPasswordFormPopup.do"); 
    fn_layerPopFormSubmit(form,true);
}

function fn_changeInterestBtn(masterId,onOff){
	if(onOff == "on")
	{
		$.ajax({
	        type: "POST",
	        url: "/interest/insertInterest.ajax",
	        async: false,
	        data: {"masterId" : masterId}
	    }).done(function(result){
	    	alert(result);
	    	if(result == "로그인 후 이용하실 수 있습니다.")
    		{
	    		return false;
    		}
	    	$(".favorit").removeAttr("onclick");
   		    $(".favorit").attr("onclick","fn_changeInterestBtn('" + masterId + "','off')");
	    });
	}
	if(onOff == "off")
	{
		var masterIdArray = [];
		masterIdArray.push(masterId);
		$.ajax({
		       url : "/interest/deleteInterests.ajax",
		       type : "POST",
		       async: false,
		       data : {"masterIdList" : masterIdArray},
		       success : function(result){
		           alert(result);
		           if(result == "로그인 후 이용하실 수 있습니다.")
		    		{
			    		return false;
		    		}
		           $(".favorit").removeAttr("onclick");
		   		   $(".favorit").attr("onclick","fn_changeInterestBtn('" + masterId + "','on')");
		       },error : function(){
		       }
		   });
	}
}

function fn_changeInterest(masterId,onOff){
	var html="";
	
	if(onOff == "on")
	{
		$.ajax({
	        type: "POST",
	        url: "/interest/insertInterest.ajax",
	        async: false,
	        data: {"masterId" : masterId}
	    }).done(function(result){
	    	alert(result);
	    	if(result == "로그인 후 이용하실 수 있습니다.")
    		{
	    		return false;
    		}
	    	if(result == "관심자료에 추가되었습니다.")
			{
	    		$("#favorites_"+masterId).removeAttr("onclick");
	    		$("#favorites_"+masterId).attr("onclick","fn_changeInterest('" + masterId + "','off')");
	    		$("#favorites_"+masterId).attr("title","관심자료에서 삭제합니다.");
	    		html += "<img src=\"/images/icon/icon-cart-Favorites-on.png\" class=\"off\" alt=\"즐겨찾기 아이콘\">"
	    		html += "<img src=\"/images/icon/icon-cart-Favorites.png\" class=\"on\" alt=\"즐겨찾기 아이콘\">";
	    		$("#favorites_"+masterId).html(html);
			}
	    });
	}
	if(onOff == "off")
	{
		var masterIdArray = [];
		masterIdArray.push(masterId);
		$.ajax({
		       url : "/interest/deleteInterests.ajax",
		       type : "POST",
		       async: false,
		       data : {"masterIdList" : masterIdArray},
		       success : function(){
		           alert("선택하신 관심자료가 삭제되었습니다.");
		           $("#favorites_"+masterId).removeAttr("onclick");
		   		   $("#favorites_"+masterId).attr("onclick","fn_changeInterest('" + masterId + "','on')");
		   	       $("#favorites_"+masterId).attr("title","관심자료로 등록합니다.");
		   	 	   html += "<img src=\"/images/icon/icon-cart-Favorites.png\" class=\"off\" alt=\"즐겨찾기 아이콘\">"
		   		   html += "<img src=\"/images/icon/icon-cart-Favorites-on.png\" class=\"on\" alt=\"즐겨찾기 아이콘\">";
		   	 	   $("#favorites_"+masterId).html(html);
		       },error : function(){
		       }
		   });
	}
	
}

function pageLoad(fnName,pageIndex, totRecordCount, startPage, endPage, lastPage)
{
	$("#paging *").remove();
	
	var html="";
	if(totRecordCount != 0)
	{
		
		if(pageIndex != 1 ){
			html+="<li class=\"btn btn-first\"><a href=\"#\" onclick=\"" + fnName + "(1); return false;\" title=\"처음으로\">처음으로</a></li> "
			html+="<li class=\"btn btn-prev\"><a href=\"#\" onclick=\"" + fnName + "("+ (pageIndex*1 -1) +"); return false;\" title=\"이전\">이전</a></li>";
		}else{
			html+="<li class=\"btn btn-first\"><a href=\"#\" title=\"처음으로\">처음으로</a></li> "
			html+="<li class=\"btn btn-prev\"><a href=\"#\" title=\"이전\">이전</a></li>";
		}
		
		for(startPage; startPage <= endPage; startPage++ )
		{
			if(startPage != pageIndex)
			{
				html+= "<li><a href=\"#\" onclick=\"" + fnName + "("+ startPage +"); return false;\" title=\""+startPage+"페이지\">" + startPage + "</a></li>"
			}else{
				html+= "<li class=\"on\"><a href=\"#\" title=\"현재위치 페이지\">"+ startPage +"</a></li>"
			}
		}
		
		if(pageIndex != lastPage){
			html+="<li class=\"btn btn-next\"><a href=\"#\" onclick=\"" + fnName + "("+ (pageIndex*1 +1) +"); return false;\" title=\"다음\">다음</a></li>"
			html+="<li class=\"btn btn-last\"><a href=\"#\" onclick=\"" + fnName + "("+ lastPage +"); return false;\" title=\"맨끝으로\">맨끝으로</a></li>";
		}else{
			html+="<li class=\"btn btn-next\"><a href=\"#\" title=\"다음\">다음</a></li>"
			html+="<li class=\"btn btn-last\"><a href=\"#\" title=\"맨끝으로\">맨끝으로</a></li>";
		}
	}else{
		html+="<li class=\"btn btn-first\"><a href=\"#\" title=\"처음으로\">처음으로</a></li> "
		html+="<li class=\"btn btn-prev\"><a href=\"#\" title=\"이전\">이전</a></li>"
		html+="<li class=\"on\"><a href=\"#\" title=\"현재위치 페이지\">"+ startPage +"</a></li>"
		html+="<li class=\"btn btn-next\"><a href=\"#\" title=\"다음\">다음</a></li>"
		html+="<li class=\"btn btn-last\"><a href=\"#\" title=\"맨끝으로\">맨끝으로</a></li>";
	}
	
	
	$("#paging").html(html);
}

function gfn_formatDateStr(yyyymmdd, defVal) {
	if(fn_isEmpty(yyyymmdd)) return defVal;
	if(yyyymmdd.length == 8) {
		return yyyymmdd.substr(0, 4) + "-" + yyyymmdd.substr(4,2) + "-" + yyyymmdd.substr(6);
	} else if(yyyymmdd.length == 6) {
		return yyyymmdd.substr(0, 4) + "-" + yyyymmdd.substr(4,2);
	} else if(yyyymmdd.length == 4) {
		return yyyymmdd;
	} 
		
	return defVal;
}

// 원문보기 
var DOC_VIEW_URL = "https://port.nculture.org/npdfView.do?npdf=N";
var VIDEO_VIEW_URL = "https://port.nculture.org/nvodView.do?nvod=N";
var IMAGE_VIEW_URL = "https://port.nculture.org/nImageView.do?nImage=N";

function gfn_showDocPdf(interfaceId,masterId,typeDivCd,dtlsTypeDivCd) {
	var url="";
	
	if(typeDivCd == "IT_PHOTO" && (dtlsTypeDivCd == "C199" || dtlsTypeDivCd == "C01"))
	{
		url = IMAGE_VIEW_URL;
	}else if((typeDivCd == "IT_VIDEO") && (dtlsTypeDivCd == "C290" || dtlsTypeDivCd == "C02" || dtlsTypeDivCd == "C03"))
	{
		url = VIDEO_VIEW_URL;
	}else{
		url = DOC_VIEW_URL;
	}
	
	//로그 
	$.ajax({
        type: "post",
        url: "/search/InsertDataInquiryLog.ajax",
        data: {"masterId" : masterId}
    }).done(function(response){
    });
	
	var openNewWindow = window.open(url + interfaceId, "_blank");
}

function snsShare(snsType, url) {
	var url,name,specs,changedUrl,title;
	if(document.title.indexOf("|") > -1){
		title = encodeURIComponent($.trim(document.title.split("|")[1]));
	}else{
		title = encodeURIComponent($.trim(document.title));
	}
	if(url != ''){
		changedUrl = encodeURIComponent(url);
	}
	
	if(snsType == '1'){
		url = 'https://www.facebook.com/sharer/sharer.php?u=' +changedUrl+'&amp;t='+title;
		name = 'facebooksharedialog';
		specs = "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600";
	}else if(snsType == '2'){
		url = 'https://twitter.com/intent/tweet?text=[%EA%B3%B5%EC%9C%A0]%20' + title+'&url='+changedUrl;
		name = 'twittersharedialog';
		specs = "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600";
	}else if(snsType == '3'){
		url = 'http://blog.naver.com/openapi/share?url=' +changedUrl+'&amp;title='+title;
		name = 'naversharedialog';
		specs = "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=600,width=600";
	}else if(snsType == '4'){
		url = 'https://story.kakao.com/s/share?url='+changedUrl;
		name = 'kakaostorysharedialog';
		specs = "menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=400,width=600";
	}
	window.open(url, name, specs);
}

$( document ).on('click' , 'button.share', function (e) {
	//e.preventDefault(); 
	var tUrl = $(this).attr('data-cUrl');
	$('#div_pop-sharing img').attr('data-cUrl',tUrl); // url 모두 맵핑
	if(tUrl != null && tUrl != ''){
		/*if(tUrl.indexOf(location.host) == -1){
			tUrl = location.protocol + '//' + location.host + tUrl;
		}*/
		getShortUrlData(tUrl);
	}
});

$( document )
.on('click', '#div_pop-sharing img.sns-pop', function(e) {
	e.preventDefault();
	snsShare($(this).attr('data-sType'),$(this).attr('data-cUrl'));
})
.on('click', '#div_pop-sharing button.btn-close-pop', function(e) {
	e.preventDefault();
	$(this).find('img').attr('data-cUrl','');
})
.on('click', '#div_pop-sharing button.btn-white', function(e) {
	e.preventDefault();
	$('#p_link-copy').select(); //복사할 텍스트를 선택
	document.execCommand("copy") //클립보드 복사 실행
	alert('단축 URL이 복사되었습니다.')
});

function getShortUrlData(url) {
	$.ajax({
	method: 'GET',
	url: '/search/shorturl-data.do',
	data: {url: url},
	dataType: 'json',
	cache: false
	})
	.done(function( data ) {
		var urlData = data
		if(urlData != null && urlData != ""){
			$('#p_link-copy').val(urlData);
			qrcodeMake(urlData);
		} else {
			qrcodeMake(url);
		}
	});
}

//QR코드
function qrcodeMake(url) {
	$("#qrcode").empty();
	var qrcode = new QRCode(document.getElementById("qrcode"), {
		colorDark : "#000000",
		colorLight : "#ffffff",
		correctLevel : QRCode.CorrectLevel.H
	});
	qrcode.makeCode(url);
}


function gfn_openNewWindow(rul) {
	var win = window.open(rul, "_blank");
}

function gfn_gotoUrl(url) {
	location.href = url;
}

function gfn_getDetail(masterId, host) {
	
	if(fn_isEmpty(host)) host = "";
	else host = "https://" + host + ".nculture.org";
	
    var form = document.createElement("form");
    form.style.display = "none";
    $(form).attr("action", host + "/search/searchItemDetail.do");
    $(form).attr("method", "post");
    $(form).attr("target", "_blank");
    
    var element = document.createElement("input");
    $(element).attr("name", "masterId");
    $(element).attr("value", masterId);
    
    form.appendChild(element);
    document.body.appendChild(form);
    form.submit();
    
    document.body.removeChild(form);
    
    return;	
}

function gfn_rentItem(mngOrgCd, masterId) {
	
	if(fn_isEmpty(masterId)) {
		alert("자료ID 정보가 없습니다.");
		return;
	}

    var form = document.createElement("form");
    form.style.display = "none";
    $(form).attr("action", "/rent/confirmRent.do");
    $(form).attr("method", "get");
    $(form).attr("target", "_blank");
    
    var element1 = document.createElement("input");
    $(element1).attr("name", "mngOrgCd");
    $(element1).attr("value", mngOrgCd);

    var element2 = document.createElement("input");
    $(element2).attr("name", "selItems");
    $(element2).attr("value", masterId);

    form.appendChild(element1);
    form.appendChild(element2);
    
    document.body.appendChild(form);
    form.submit();
    
    document.body.removeChild(form);
    
    return;	
}

function gfn_reserveReadItem(mngOrgCd, masterId) {
	
	if(fn_isEmpty(masterId)) {
		alert("자료ID 정보가 없습니다.");
		return;
	}

    var form = document.createElement("form");
    form.style.display = "none";
    $(form).attr("action", "/read/confirmRead.do");
    $(form).attr("method", "get");
    $(form).attr("target", "_blank");
    
    var element1 = document.createElement("input");
    $(element1).attr("name", "mngOrgCd");
    $(element1).attr("value", mngOrgCd);

    var element2 = document.createElement("input");
    $(element2).attr("name", "selItems");
    $(element2).attr("value", masterId);

    form.appendChild(element1);
    form.appendChild(element2);
    
    document.body.appendChild(form);
    form.submit();
    
    document.body.removeChild(form);
    
    return;	
}
