
/** ARK 구성요소의 위치 및 크기를 아래 변수를 통해 조정함. **/
var arkWidth = 550;								// 자동완성 전체 넓이 값을 설정한다(변동폭).
var arkTop = 0;								// 자동완성 상단에서의 위치 값을 설정한다.
var arkLeft = 0;								// 자동완성 왼쪽에서의 위치 값을 설정한다.
var arkImgTop = -50;								// 자동완성 화살표 이미지의 상단에서 위치 값을 설정한다.
var arkImgLeft = 480;							// 자동완성 화살표 이미지의 왼쪽에서 위치 값을 설정한다.
var tooltip01TopPos = 0;						// 자동완성 기능끄기 툴팁의 상단 기준 위치 오차 조정값
var tooltip01LeftPos = 465;					// 자동완성 기능끄기 툴팁의 좌측 기준 위치 오차 조정값
var tooltip02TopPos = 0;						// 자동완성 기능켜기 툴팁의 상단 기준 위치 오차 조정값
var tooltip02LeftPos = -50;						// 자동완성 기능켜기 툴팁의 좌측 기준 위치 오차 조정값

var cp_textarea = document.createElement('textarea');

/*view_cont 폰트 사이즈 변경 시작*/
$(function() {
	
	$(".full_banner").parent().addClass("full_banner_yes");
	
	$('.full_banner .container .close').click(function() {
		//$('.full_banner').stop().animate({'margin-top':-104+'px'}, 150);
		$('.full_banner').stop().animate({'margin-top':-122+'px'}, 150);
		$("body").removeClass("full_banner_yes");
		if($("input:checkbox[name=fct]").attr('checked')){
			var todayDate = new Date();
				todayDate.setDate( todayDate.getDate()+Number(0));
				todayDate.setHours(23,59,59,999);
				document.cookie = "fullbanner=done; path=/; expires=" + todayDate.toGMTString() + ";";
		}
		$(".full_banner .open").show();
	});


	if($.cookie("fullbanner") != "done"){
		$('.full_banner').css('margin-top', '');
	}else{
		$(".full_banner .open").show();
	}

	$('.full_banner .open').click(function() {
		$('.full_banner').stop().animate({'margin-top':0+'px'}, 150);
		$("body").addClass("full_banner-yes");
		$(".full_banner .open").hide();
		$(".full_banner").attr('tabindex', '-1').focus();

		$.removeCookie("fullbanner", {path: '/'});
	});


	$(".view_cont a, .view_cont area").click(function(e){
		e.preventDefault();
		//console.log($(this).attr('href'));
		if($(this).attr('href').indexOf('http://') != -1 || $(this).attr('href').indexOf('https://') != -1){
			window.open($(this).attr('href'));
		}else if($(this).attr('href').indexOf('/policyPhoto/FileDownload.do') != -1){
			window.open($(this).attr('href'));
		}else if($(this).attr('href').indexOf('#') == 0){
			location.href = $(this).attr('href');
		}else if($(this).attr('href').indexOf('/newsNotify') != -1){
			location.href = $(this).attr('href');
		}
	});


	$('.share .share_lst .uc').on('click', function() {
		console.log();
		document.body.appendChild(cp_textarea);
		cp_textarea.value = currUrl;
		cp_textarea.select();
		document.execCommand('copy');
		document.body.removeChild(cp_textarea);
		cp_textarea.value = "";				
	    alert('복사되었습니다.\nCtrl+v를 눌러 붙여넣기하세요.');
		$(this).focus();
	});

		//초기화
	$('.select_opt .restart').click(function(){
		$('#radio_all').attr("checked", true);
		$("input:checkbox[name=chkRepCode]").attr("checked", false);
		$('.select_opt ul').empty();
		
		//$("#repCodeType").val('');
		$("#srchRepCodeType").val('');
	});
	
	$('.tool .tts').click(function(){
		commonTts();
	});


	var ua = window.navigator.userAgent;
	var ie = ua.indexOf('MSIE ') >= 0 || ua.indexOf('Trident/') >= 0;

	//익스플로러 인 경우
	if(ie){
		window.addEventListener("copy",copy_ie);
	//그외
	}else{
		window.addEventListener('copy', function(e){
			document.execCommand('copy');
			e.preventDefault();
			if(cp_textarea.value == ""){
				

				
				//if($(document.getSelection().baseNode).closest('.view-cont').length == 0){

				
				let text = document.getSelection()+'';
				if(text.length <= 50){
					e.clipboardData.setData('text/plain', document.getSelection());
				}else{
					e.clipboardData.setData('text/plain', document.getSelection() + addTxt);
				}

				//e.clipboardData.setData('text/plain', document.getSelection() + addTxt);
			}else{
				e.clipboardData.setData('text/plain', document.getSelection());
			}
		}, false)
	}


});

$(window).on('load', function(){
	const acTab = $('.sch_post > .sch_tab > .tab_nav > li.active a').text();
	if(acTab != ''){
		$('title').text(acTab+' | '+ $('title').text());
	}	
});

/*view_cont 폰트 사이즈 변경 끝*/

function fn_poliAudioPopup(url){	
	window.open(url, 'policyAudio2', 'width=520, height=740, resizable=no, scrollbars=yes');
	return false;
}


function fn_repCodeCk(){
	$('.select_opt ul').empty();

	if($('input[name=sch_post_radio]').length > 0){
		var id = $('input[name=sch_post_radio]:checked').attr('id');
		if(id != 'radio_all'){
			$('.select_opt ul').append('<li>'+$("label[for='"+id+"']").text()+'<button><span>삭제</span></button></li>');
		}
	}

	$("input:checkbox[name=chkRepCode]:checked").each(function(){
		$('.select_opt ul').append('<li>'+$("label[for='"+$(this).val()+"']").text()+'<button><span>삭제</span></button></li>');
	});

	fn_liempty_ori();
}


function fn_liempty_ori(){
/* 오작동으로 각 ~List.jsp로 수정해서 옮김	
$('.select_opt ul li button').off('click').on('click', function(){});
	$('.select_opt ul li button').click(function (){
	  var text = $(this).closest('li').text().replace('삭제', '');
	  $('.tab_cont_wrap label').each(function(){
		 if(text == $(this).text()){
			 var id = $(this).attr('for');			 
			 if(id.indexOf('radio_') > -1){
				 $('#radio_all').attr("checked", true);
			 }else{
				 $('#'+id).attr("checked", false);
			 }
		 }
	  });
	  $(this).closest('li').remove();
   });*/
}



//출처 정책정보 선택
function outSiteChk(){
	
	var thisGbn = $('#repCodeType').val();

	var chkedOutSite = $('#repCode').val();
	var arrOutSite = new Array();
	if(chkedOutSite != undefined){	
		arrOutSite = chkedOutSite.split(",");


		$('.tab_nav li').each(function(i){
			if(thisGbn == '' && i == 0){
				$(this).addClass('active');
				$('a', this).attr('title', '선택됨');
				$($('.tab_cont_wrap .cont')[i]).css('display', 'block');
			}else if($('a',this).text() == thisGbn){
				$(this).addClass('active');
				$('a', this).attr('title', '선택됨');
				$($('.tab_cont_wrap .cont')[i]).css('display', 'block');
			}
		});

		var radioCk = false;

		if($('input[name=sch_post_radio]').length > 0){
			var id = $('input[name=sch_post_radio]:checked').attr('id');
			if(id != 'radio_all'){
				$('.select_opt ul').append('<li>'+$("label[for='"+id+"']").text()+'<button><span>삭제</span></button></li>');
				radioCk = true;
			}
		}

		$('#period option').each(function(){
			if($(this).val() == $('#formPeriod').val() && $('#formPeriod').val() == 'direct'){
				$(this).attr('selected', true);
				$('.sch_brief .period').show();
				//$('.custom-select').css('background-color','#f3f3f3');
			}else if($(this).val() == $('#formPeriod').val()){
				$(this).attr('selected', true);
			}
		});
/*오작동으로 각 ~List.jsp로 수정해서 옮김
		for(var loop=0; loop < arrOutSite.length; loop++){
			$checkedObj = $("input:checkbox[name=chkRepCode]");
			$checkedObj.each(function(i){
				if ($(this).val() == arrOutSite[loop]) {
					$(this).attr("checked", true);
					$('.select_opt ul').append('<li>'+$("label[for='"+$(this).val()+"']").text()+'<button><span>삭제</span></button></li>');
				}
			});
		}
*/

		if($('input[name=chkRepCode]:checked').length > 0 || radioCk){
			$('.sch_post .detail_sch').click();
		}

		fn_liempty_ori();
	}
}



function fn_periodOption(){
		$('#period option').each(function(){
		if($(this).val() == $('#formPeriod').val() && $('#formPeriod').val() == 'direct'){
			$(this).attr('selected', true);
			$('.sch_brief .period').show();
			//$('.custom-select').css('background-color','#f3f3f3');
		}else if($(this).val() == $('#formPeriod').val()){
			$(this).attr('selected', true);
		}
	});
}


/**
 * 기사추천하기
 * 1. AJAX - 기사추천하기
 * @param  : newsId     - 뉴스 ID
 * @return : 기사추천수카운트
 */
function commonNewsRecommend(newsId){	
	$.ajax({
		type:"POST",
		url: "/common/recommend.do",
		dataType: "xml",
		data: {
			  newsId:newsId
		},
		success: function( data ) {
			var result = "";
			$(data).find('item').each(function() {
				result = $.trim($(this).find('value').text());
			});

			$(".as_sns .like .count, .view_opt .like .count").html(result);
			$(".as_sns .like, .view_opt .like").addClass('active');	
			
			return;
		}
	});
}

function commonTts(){
	if(window.speechSynthesis.speaking){
		window.speechSynthesis.cancel(); // 현재 읽고있다면 초기화	
	}else{
		if (typeof SpeechSynthesisUtterance === "undefined" || typeof window.speechSynthesis === "undefined") {
			alert("해당 브라우저는 음성읽기 기능이 지원되지 않습니다.");
			return
		}
		
		window.speechSynthesis.cancel(); // 현재 읽고있다면 초기화
		
		//const prop = opt_prop || {};
		var newText = '';
		var $el = document.querySelector('.container .editor_note'); 
		if($el != undefined){
			newText = $el.innerHTML.replace(/<[^>]*>?/g, ''); 			
		}
		$el = document.querySelector('.container .view_cont');
		var text = $el.innerHTML;
		var pcnt = text.indexOf('<div class="text" id="photoText">');
		if(pcnt == -1)pcnt=0;
		text = text.substr(pcnt, text.length); 
		
		var hcnt = text.indexOf('<div class="hidden"/>');
		if(hcnt == -1)hcnt=0;
		text = text.substr(hcnt, text.length); 
		
		text = text.replace('재생버튼을 누르시면 동영상이 재생됩니다', ''); 
		text = text.replaceAll('&nbsp;', ' '); 
		text = text.replaceAll('&lt;', ''); 
		text = text.replaceAll('&gt;', ''); 
		text = text.replace(/<figure(.*?)<(\/?)figure>/gi, ''); 

		newText += text.replace(/<[^>]*>?/g, ''); 
		newText = newText.replace(/\([^)]+\)/g, ''); 

		//console.log(newText);
		
		var voices = window.speechSynthesis.getVoices(); 
		const speechMsg = new SpeechSynthesisUtterance();
		speechMsg.rate = 1; // 속도: 0.1 ~ 10      
		speechMsg.pitch = 1; // 음높이: 0 ~ 2
		speechMsg.lang = "ko-KR";
		speechMsg.text = newText;
		speechMsg.onend = (event) =>{$('.tool .tts').removeClass('active')};
		//speechMsg.voice = voices.filter(function(voice) { return voice.name == 'Google 한국의'; })[0]; 

		ttsClickCount();	

		window.speechSynthesis.speak(speechMsg);
	}
}



function ttsClickCount(){
		var tblKey = "TTS";
		var newsId = "WEB";
		var type = 'TTS';

	    
	    var dataStr = 'tblKey=' + tblKey + '&newsId=' + newsId + '&snsGubun=' + type;

	    $.ajax({
	             type: 'get'
	           , url: '/common/snsShare.do'
	           , data: dataStr
	           , dataType: 'xml'
	           , timeout : 5000
	           , success: function(data) {
	             }
	           , error : function() {

	           }
	           , complete : function() {
	       		  
	           }
	       });        
	}
	
window.speechSynthesis.cancel(); // 현재 읽고있다면 초기화


   //위클리 공감 ebook 열기
	function openEbook(dir) {
		window.open("https://gonggam.korea.kr/fcatalog/ecatalog5.jsp?Dir="+dir);
	}

	//위클리 공감, 카툰 공감 ebook 열기
	function openEbookWeekly(dir, newsId, fileId, gbn) {
		updateNewsDataHitCnt(newsId);
		window.open("https://gonggam.korea.kr/fcatalog/ecatalog5.jsp?Dir="+dir+"&fileId="+fileId+"&gbn="+gbn);
	}

	function updateNewsDataHitCnt(newsId){

		$.ajax({
			type:"POST",
			url: "/common/updateNewsDataHitCnt.do",
			dataType: "xml",
			data: {
				  newsId:newsId
			},
			success: function( data ) {
				return;
			}
		});

	}

	//부처 간행물 ebook 열기
	function openEbookDept1(dir, newsId) {
		ebookPanViewCntUpdate(newsId);
		window.open("https://gonggam.korea.kr/fcatalog/ecatalog.jsp?Dir="+dir);
	}

	//부처 간행물 ebook 열기
	function openEbookDept2(dir, newsId) {
		ebookPanViewCntUpdate(newsId);
		window.open(dir);
	}

	function ebookPanViewCntUpdate(newsId){

		$.ajax({
			type:"POST",
			url: "/common/ebookPanViewCntUpdate.do",
			dataType: "xml",
			data: {
				  newsId:newsId
			},
			success: function( data ) {
				return;
			}
		});

	}
		
   /**
    * 전화번호 체크
    * @param  : str - 문자열, num - 구분
    * @return : boolean
    */
   function checkTelNumber(str, num){	// 전화  형식 체크
	   var ch1 = /^[0-9]{2,4}$/;		// 앞자리
	   var ch2 = /^[0-9]{3,4}$/;		// 중간자리
	   var ch3 = /^[0-9]{3,4}$/;		// 끝자리
	   var ch0 = /^[0-9]{2,4}-[0-9]{3,4}-[0-9]{3,4}$/;	// 전체
       var result = true;
       if($.trim(str) == null || $.trim(str) == "") {
    	   return false;
       }
       if (num==1) {
    	   result = ch1.test(str);	// 앞자리
       } else if (num==2) {
    	   result = ch2.test(str);	// 중간자리
       } else if (num==3) {
    	   result = ch3.test(str);	// 끝자리
       } else {
    	   result = ch0.test(str);	// 전체
       }

       return result;
   }

   /**
    * 컨텐츠 인쇄 팝업
    */
   function viewPrint() {
	   var url = location.href;
	   if(url.indexOf("pressReleaseView") > -1 && $("#content").length > 0 || $("#content_press").length > 0){
		   $("#content_press").contents().find("#print-btn").click();
	   }else{
		   window.open('/common/searchPrint.do','printPop', 'width=760, height=600, top=0, left=0, scrollbars=yes, resizable=no, status=yes');
	   }
   }

   /**
    * 영상자료 컨텐츠 인쇄 팝업
    */
   function viewArchivePrint(newsId) {
	   var URL = "/common/archivePrint.do?newsId=" + newsId;
	   window.open(URL,'printPop', 'width=760, height=600, top=0, left=0, scrollbars=yes, resizable=no, status=yes');
   }

   /**
    * 전문자료 인쇄 팝업
    */
   function viewExpPrint() {
	   window.open('/common/expPrint.do','printPop', 'width=760, height=600, top=0, left=0, scrollbars=yes, resizable=no, status=yes');
   }

   /**
    * 연설문 인쇄 팝업
    */
   function viewSpeechPrint() {
	   window.open('/common/speechPrint.do','printPop', 'width=760, height=600, top=0, left=0, scrollbars=yes, resizable=no, status=yes');
   }

   /**
    * 뉴스레터 인쇄 팝업
    */
   function viewNewsLetterPrint() {
	   window.open('/common/newsLetterPrint.do','printPop', 'width=810, height=600, top=0, left=0, scrollbars=yes, resizable=no, status=yes');
   }

	const addTxt = "\n\n[출처] 대한민국 정책브리핑(www.korea.kr)";

	function copy_ie2(){
		if(window.clipboardData){
			var txt = window.clipboardData.getData('Text');
			var result = window.clipboardData.setData('Text',txt + addTxt);
		}
	}

	function copy_ie(){
		if(window.event){
			window.event.returnValue = true;
			window.setTimeout('copy_ie2()',25);
		}
	}
	
	function showNotifyMsg(){
	  alert("9.4(월) 오픈 예정입니다.");
	}