$(document).on("ready", function() {
	accessibility();
	gnb();
	sidebar();
	topMove();
	// 숏폼(.short), 오디오(.autio) 썸네일 배경 변경
	$('.thumb.custom').each(function(){
		var imgsrc = $(this).find('img').attr('src');
		$(this).css('background', 'url('+imgsrc+')');
	});

	// 영상 표시 아이콘

	$('span.text span:contains(재생버튼을 누르시면 동영상이 재생됩니다.)').each(function(){
		$(this).html($(this).text().replace('재생버튼을 누르시면 동영상이 재생됩니다.', ''));
	});

	$("a[href*='mediaNewsView.do']").find('.thumb').not('.play').addClass('play');
	$("a[href*='cateId=good_flash']").find('.thumb').not('.play').addClass('play');
	$(".photo_list.short").find('.thumb').not('.play').addClass('play');

	$("a[href*='https://www.korea.kr/video/index.html']").find('.thumb').not('.play').addClass('play');

	$(".article.box .as_tab .media").find('.play').removeClass('play');



	//$(".multimedia .wrap .meslide").find('.thumb.custom.short').not('.play').addClass('play');

	$('.thumb.play').each(function(){
		if ($(this).parent().parent().find('.share').length > 0 ){
			$(this).prepend('<span class="ico_play pos"><i>영상</i></span>');
		} else {
			$(this).prepend('<span class="ico_play"><i>영상</i></span>');
		}
	});

	/*
	$(".area_contents .as_side").each(function(){
		if ($(this).find('.banner_choice').length == 0){
			sidebar();
		}
	});
	*/

	// 이미지 확대
	//$('.travel_places_img img').wrap('<span class="zoomImg"></span>');
	//$('.travel_img img').wrap('<span class="zoomImg"></span>');
	$('.view_cont > p img').wrap('<span class="zoomImg"></span>');
	$('.cardnews_slider .slider_wrap .slider_for .slides > li img').wrap('<span class="zoomImg"></span>');

	$('.zoomImg, .view_cont .imageWrap figure:not(.left, .right) .imageSpan, .photoview_slider .slider_wrap .slider_for .slides > li .thumb').zoom({
		on:'click',
		magnify:1.8,
		callback: function(){
			$(this).on('click',function(){
				$(this).toggleClass('hover');
			});
		}
	});

	//관련사이트
	$('.rel_btn').on('click',function(){
		const t = $(this);
		if(t.parent().hasClass('active')){
			t.attr("title","관련사이트 열기");
		}else{
			t.attr("title","관련사이트 닫기");
		}
		t.parent().toggleClass("active");
	});

	//영역외 클릭
	$(document).on('click',function(e){
		if(!$(e.target).parents().hasClass('related_link')){
			$('.related_link').removeClass('active').find('button').attr('title','관련사이트 열기');
		}
	});

});

$(window).on("load", function() {
	fullBanner();

});

$(window).on("load scroll", function() {
	fixed();
});

function gnb () {
	var lnbCrt1 = $('.gnb > ul > li:nth-child(' + (lnbDep1) + ')');
	var lnbCrt2 = $('.gnb > ul > li:nth-child(' + (lnbDep1) + ') .menu_item > ul > li:nth-child(' + (lnbDep2) + ')');
	lnbCrt1.addClass('on');
	lnbCrt2.addClass('on');

	const dep1 = $('.gnb > ul > li');
	const dep1_cnt = dep1.length;
	$('.gnb').addClass('menu_cnt_' + dep1_cnt);
	
	$('.gnb > ul > li').on('click mouseenter focusin', function(){
		$('.header').addClass('menu_on');
		$(this).closest(".gnb").addClass('on');
		/* $('.gnb > ul > li').removeClass('on');
		$(this).addClass('on'); */
	});
	/* dep1.find(' > a').on('click',function(){
		return false;
	}); */
	$('.gnb').on('mouseleave', function(){
		$('.header').removeClass('menu_on');
		$(this).closest('.gnb').removeClass('on');
		/* $(this).find('> li').removeClass('on');*/
		lnbCrt1.addClass('on');
		lnbCrt2.addClass('on'); 
	});

	//포커스 아웃 시 메뉴 닫기
	window.addEventListener("keyup", (e) => {
		if(!e.target.closest(".gnb")){
			$('.header').removeClass('menu_on');
			$('.gnb').removeClass('on');
		}
	})

	//2차메뉴 위치
	$('.gnb > ul > li').each(function(index){
		const percent = (100 / dep1_cnt);
		$(this).find('.submenu > div > .menu_item').css({left:(percent * index) + '%'})
	});
	//2차메뉴 높이가 가장큰 값으로 전부 높이 맞추기
	const h_array = $('.gnb .nav > li .menu_item').map(function(){
		return $(this).height();
	}).get();
	const max_height = Math.max.apply(Math, h_array);
	$('.gnb .nav > li .menu_item').height(max_height);
	$('.gnb_bg').height(max_height + 80);

	$('body.main .gnb > ul > li:last-child div > ul > li:last-child').on('keydown', function(e){
		if(!e.shiftKey && e.keyCode == 9) $('.gnb > ul > li').removeClass('on');
		$('.gnb > ul').removeClass('on');
		lnbCrt1.addClass('on');
		lnbCrt2.addClass('on');
	});

	$('.gnb ul li div > ul > li').on('mouseenter focusin', function(){
		//$(this).closest('ul').find('li').removeClass('on');
		$(this).parent().find('li.on').removeClass('on');

		$(this).addClass('on');
	}).on('mouseleave focusout', function(e){
		$(this).removeClass('on');
	});
	$('.gnb > ul > li > a').on('keydown',function(e){
		if(e.shiftKey && e.keyCode == 9) {
			$this = $(this);
			$this.parent().removeClass('on');
			lnbCrt1.addClass('on');
			lnbCrt2.addClass('on');
			$i = $this.parent().index();
		  if($i){
			$li = $('.gnb > ul > li').eq($i-1);
			$li.addClass('on');
			$li.find('li').last().focus();
		  }
		}
	});

	//site map
	$('#header .util .sitemap-open').on('click', function(){
		$(this).next('.sitemap_layer').stop().fadeIn();
	});
	$('#header .sitemap_layer .btn-close').on('click focusout', function() {
		$(this).parent().parent().stop().fadeOut();
		$('#header .sitemap-open').focus();
	});

	//sch detail
	$('#header .util .sch-open').on('click', function(){
		$('#header .util .sch_layer').stop().fadeIn();
	});

	$('#header .util .sch-open-dtl').on('click', function(){
		$('#header .util .sch_layer').stop().fadeIn();
		$('.dtl_sch_open').addClass('active').next().stop().fadeIn();
		$('.dtl_sch_open').find('span').text('닫기');
	});

	$('#header .sch_layer .btn-close').on('click focusout', function() {
		$(this).parent().parent().fadeOut();
		$('.dtl_sch_wrap').stop().fadeOut();
		$('.dtl_sch_open').removeClass('active');
		$('.dtl_sch_open').find('span').text('열기');
		$('.sch-open-dtl').focus();
	});

	$('#header .sch_layer #hsch_topSearchKeyword').on('input', function() {
		if($('#header .sch_layer #hsch_topSearchKeyword').val() ==''){
			$('#header .sch_layer .clear_input').css('display', 'none');
		}else{
			$('#header .sch_layer .clear_input').css('display', 'block');
		}
	});

	$('#header .sch_layer .clear_input').on('click', function() {
		$(this).css('display', 'none');
		$('#header .sch_layer .sch input').focus();
	});

	$('.dtl_sch_open').on('click', function(){
		if($(this).hasClass('active')){
			$(this).removeClass('active').next().stop().fadeOut();
			$(this).find('span').text('열기');
		}else{
			$(this).addClass('active').next().stop().fadeIn();
			$(this).find('span').text('닫기');
		}
    });

	$('.dtl_sch_close').on('click focusout', function(){
		$(this).parent('.dtl_sch_wrap').fadeOut();
		$('.dtl_sch_open').focus();
		$('.dtl_sch_open').removeClass('active');
		$('.dtl_sch_open').find('span').text('열기');
    });

	$('.dtl_sch_post .sbtn').on('click', function(){
		if($(this).hasClass('close')){
			$(this).removeClass('close');
			$(this).parent().parent().removeClass('active');
			$(this).find('span i').text('펼치기');
			$(this).parent().next('ul').hide();
		}else{
			$(this).addClass('close');
			$(this).parent().parent().addClass('active');
			$(this).find('span i').text('접기');
			$(this).parent().next('ul').show();
		}
    });

};

function topMove () {

	$('.go_top').on('click', function() {
		$('html, body').animate({scrollTop : 0}, 100);
		$('body').focus();
	});
	$(window).on('scroll', function() {
		if($(window).scrollTop() > 430){
			$('.go_top').addClass('active');
		}else{
			$('.go_top').removeClass('active');
		}
	});

};

function fullBanner () {

	$('.full_banner .container .close').on('click', function() {
		$('.full_banner').stop().animate({'margin-top':-122+'px'}, 150); //122
		$('body').removeClass('full_banner_yes');
		$('.full_banner .open').show();
	});

	$('.full_banner .open').on('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();
	});

};

function fixed () {

	if($('body:not(.main)').hasClass("full_banner_yes")){
		if($(window).scrollTop()>338){
			$('body:not(.main) .header').addClass('fixed');
			$('body:not(.main) main.sub').css('margin-top','161px');
			$('body:not(.main) .layer_popup').css('top','110px');
		}else{
			$('body:not(.main) .header').removeClass('fixed');
			$('body:not(.main) main.sub').removeAttr('style');
			$('body:not(.main) .layer_popup').removeAttr('style');
		}
	}else{
		if($(window).scrollTop()>338){
			$('body:not(.main) .header').addClass('fixed');
			$('body:not(.main) main.sub').css('margin-top','161px');
		}else{
			$('body:not(.main) .header').removeClass('fixed');
			$('body:not(.main) main.sub').removeAttr('style');
		}
	}

};


function accessibility () {

	//통합검색창 하위검색조건 열기
	$('.sch_layer .dtl_sch_post input').on('click', function(){
		const data = $(this).data('target');
		$(this).closest('li').find('.period_free_date').removeClass('active');
		$('.' + data).addClass('active');
	});


	$('img[usemap]').rwdImageMaps(); //이미지맵
	$('a[target="_blank"]').attr('title','새창으로 열림');
	$('[class*="xi-"], [class*="xe-"]').attr('aria-hidden','true'); //아이콘폰트 스크린리더가 읽지 못하도록 하는 속성
	//$('#lnb').attr('tabindex', '-1');
	$('#nav').attr('tabindex', '-1');
	$('#main').attr('tabindex', '-1');
	$('body').attr('tabindex', '-1');
	$('.tabs_common li.active button, .tabs_common li.active a, .sort-post ul.sort li.active button, .tabs_text li.active a').attr('title','선택됨');
	$('.as_side .policy_home .menu ul li.on a').attr('title','선택됨');
	$('.sch_post.expert .tab_nav li.active > a').attr('title','선택됨');
	$('.sch_post.photo .tab_nav li.active > a').attr('title','선택됨');
	$('.area_contents .as_side .focus_menu .keywords li.on a').attr('title','선택됨');
	$('.area_contents .as_side .audio_menu .keywords li.on a').attr('title','선택됨');

	$('.tts').on('click', function() {
		if($(this).hasClass('active')){
			$(this).removeClass('active');
			$(this).find('span').text('시작');
		}else{
			$(this).addClass('active');
			$(this).find('span').text('멈추기');
		}
	});

	var nowZoom = 1.25;
	var maxZoom = 2;
	var mimZoom = 0.5;
	$('.tool .plus').on('click', function() {
		console.log(nowZoom);
		if(nowZoom < maxZoom){
			nowZoom += 0.0625;
			$('.editor_note, .article_body .view_cont').css('font-size', + nowZoom + 'rem');
		}
	});
	$('.tool .minus').on('click', function() {
		console.log(nowZoom);
		if(nowZoom > mimZoom){
			nowZoom -= 0.0625;
			$('.editor_note, .article_body .view_cont').css('font-size', + nowZoom + 'rem');
		}
	});

	$('.font_size .size_lst ul li button').on('click', function() {
		$(this).attr('title','선택됨').parent().addClass('active').siblings().removeClass('active').children('a').attr('title','');
		var font_size = 20;
		if($(this).hasClass("ftsize1")) font_size = 18;
		else if($(this).hasClass("ftsize2")) font_size = 20;
		else if($(this).hasClass("ftsize3")) font_size = 23;
		else if($(this).hasClass("ftsize4")) font_size = 24;
		else if($(this).hasClass("ftsize5")) font_size = 25;
		$('.article_body .view_cont').css("font-size",font_size+"px");
	});

	$('.font_size .open').on('click', function() {
		if($(this).find('span').text() == '글자크기 설정 열기' ){
			$(this).next('.size_lst').stop().fadeIn(150);
			$(this).find('span').text('글자크기 설정 닫기');
		}else{
			$(this).find('span').text('글자크기 설정 열기');
			$(this).next('.size_lst').stop().fadeOut(150);
		}
	});

	$('.font_size .size_lst .close').on('click focusout', function() {
		$(this).parent('.font_size .size_lst').stop().fadeOut(150);
		$('.font_size .open span').text('글자크기 설정 열기');
		$('.font_size .open').focus();
	});

	if($('.font_size').length > 0){
		$(document).on('click', function(e) {
			if(!$('.font_size').is(e.target) && $('.font_size').has(e.target).length === 0){
				$('.font_size .open span').text('글자크기 설정 열기');
				$('.font_size .size_lst').stop().fadeOut(150);
			}
		});
	}

	/* 2023.08.24 삭제
	$('table').each(function(){
		var tableTitle = $(this).attr('summary');
		if ($(this).find('caption').length > 0){
			$(this).find('caption').append(tableTitle);
		} else {
			$(this).prepend('<caption>' + tableTitle + '</caption>');
		}
		$(this).removeAttr('summary');
	});
	*/

	$('.imageWrap').each(function(){
		if ($(this).find('.captions b, .captions strong').text().length <= 1){
			$(this).find('.captions').remove();
		}
	});

};

function sidebar () {

	var top_last_scroll = 0;
	var diff_scroll = 0;
	function onScrollDirection() {
		var function_direction = function () {
			var top_scroll = $(document).scrollTop();
			window.diff_scroll = top_scroll - window.top_last_scroll;
			window.top_last_scroll = top_scroll;
			$(window).trigger('onScrollAdjustEndLine');
		};
		$(window).scroll(function_direction);
		$(window).resize(function_direction);
		setTimeout(function () {
			window.diff_scroll = -1;
			$(window).trigger('onScrollAdjustEndLine');
		}, 200);
	}
	function onScrollAdjustEndLine(query_start, query_end, query_in) {
		$(window).on('onScrollAdjustEndLine', function () {
			var obj_start = $(query_start);
			var obj_end = $(query_end);
			var obj_in = $(query_in);
			if (obj_start && obj_end && obj_in) {
				var top_in = obj_in.offset().top;
				var top_win = $(document).scrollTop();
				var top_start = obj_start.offset().top;
				var top_end = obj_end.offset().top;
				var left_start = obj_start.offset().left - $(window).scrollLeft();
				var width_start = obj_start.width();
				var height_win = $(window).innerHeight();
				var height_end = obj_end.height();
				var height_in = obj_in.height();
				var bot_win = top_win + height_win;
				var bot_end = top_end + height_end;
				var bot_in = top_in + height_in;
				var gap_max = top_end + height_end - top_start - height_in;

				var hight_header = $('.header.fixed').outerHeight(true) + 25;
				var hight_area_page = $('.area_page').outerHeight(true) + 15;
				var hight_area_audio = $('.area_audio_player').outerHeight(true) + 15;

				obj_start.css({ height: height_in + 'px' });
				if (window.diff_scroll == 0) {
					if (obj_in.css('position') == 'fixed') {
						obj_in.css({ left: left_start + 'px' });
					}
				}
				if (height_in >= bot_end - top_start) {
					obj_in.css({ position: 'relative', top: '0px', left: '0px', width: '' });
				} else if (height_win > top_end + height_end - top_start) {
					obj_in.css({ position: 'relative', top: '0px', left: '0px', width: '' });
				} else if (height_win - hight_header - hight_area_page - hight_area_audio > height_in) {

					if (top_start >= top_win) {
						obj_in.css({ position: 'relative', top: '0px', left: '0px', width: '' });
					} else if (top_start + gap_max <= top_win) {
						obj_in.css({ position: 'relative', top: gap_max + 'px', left: '0px', width: ''});
					} else {
						obj_in.css({ position: 'fixed', top: hight_header + 'px', left: left_start + 'px', width: width_start + 'px' });
					}

				} else {
					if (window.diff_scroll < 0) {
						if (top_start >= top_win) {
							obj_in.css({ position: 'relative', top: '0px', left: '0px', width: '' });
						} else if (top_in >= top_win) {
							obj_in.css({ position: 'fixed', top: hight_header + 'px', left: left_start + 'px', width: width_start + 'px' });
						} else if (obj_in.attr('data-direction') == 'down' && obj_in.css('position') == 'fixed') {
							obj_in.css({ position: 'relative', top: top_in - top_start - diff_scroll + 'px', left: '0px', width: '' });
						}
						obj_in.attr('data-direction', 'up');
					}
					if (window.diff_scroll > 0) {
						if (bot_end <= bot_win) {
							obj_in.css({ position: 'relative', top: gap_max + 'px', left: '0px', width: '' });
						} else if (bot_in <= bot_win) {
							obj_in.css({ position: 'fixed', top: height_win - height_in /*- hight_area_page*/ - hight_area_audio + 'px', left: left_start + 'px', width: width_start + 'px' });
						} else if (obj_in.attr('data-direction') == 'up' && obj_in.css('position') == 'fixed') {
							obj_in.css({ position: 'relative', top: top_in - top_start - diff_scroll + 'px', left: '0px', width: '' });
						}
						obj_in.attr('data-direction', 'down');
					}
				}
			}
		});
	}

	function onScrollWork () {
		var thisTarget = $('main.sub');
		if (thisTarget.find('.article_top').length > 0){
			$('.as_sns').css({ top: $('.article_top').outerHeight() + 40 +  'px'});
		} else {
			$('.as_sns').removeAttr('style');
		}

		if (thisTarget.find('.as_sns').length > 0){
			onScrollAdjustEndLine('.as_sns .scroll_start', '.area_contents', '.as_sns .scroll_in');
			//$('main.sub.list .area_contents .as_sns').css('margin-left','-81px');
			if (thisTarget.find('.livere_box').length > 0){
				$('.as_sns .comment').parent('li').show();
			} else {
				$('.as_sns .comment').parent('li').hide();
			}
		}else{
			$('main.sub.list .area_contents .as_sns').css('margin-left','0');
		}
		if (thisTarget.find('.as_side').length > 0){
			onScrollAdjustEndLine('.as_side .scroll_start', '.area_contents', '.as_side .scroll_in');
		}else{
			$('main.sub .area_contents .article_wrap, main.sub .area_contents .article_wrap .container').css('width','100%');
		}

		//좌측 공유, 좋아요, 댓글 버튼 높이
		if($('main.view .as_sns').length){ // 상세페이지
			const v_top = $('.variety').position().top + ($('.variety').outerHeight(true) - $('.variety').innerHeight()) + $('.view_title').outerHeight(true);
			$('.as_sns').css({top:v_top});
		}
		if($('main.list .as_sns').length){ // 리스트 페이지
			const q_top = $('.breadcrumbs').outerHeight(true) + $('.view_title').outerHeight(true);
			$('.as_sns').css({top:q_top});
			console.log(q_top);
		}
	}

	$('.as_side').contents().wrapAll('<div class="scroll_start"><div class="scroll_in"></div></div>');
	$('.as_sns').contents().wrapAll('<div class="scroll_start"><div class="scroll_in"></div></div>');
	onScrollDirection();

	onScrollWork();
	$(window).on("load resize", function() {
		onScrollDirection();
	});

	$(window).on("load", function() {
		onScrollWork();
	});

	$('.livere_comment button').on('click', function(){
		onScrollDirection();
    });

	$('.as_side .article button, .as_side .article a').on('mousedown', function(e){
		e.preventDefault();
	}).on('focusin', function(){
		$('html, body').animate({scrollTop : $(this).offset().top - 300}, 100);
	});


	/*
	$(window).on("scroll load resize", function() {
		var winScroll = $(window).scrollTop();
		var asideScroll = $('.as_side .scroll-in').attr('data-direction');
		if( asideScroll === 'up'){
			console.log('up');
			$('.as_side .scroll-in').css('padding-top','');
			if( winScroll < 390){
				$('.as_side .scroll-in').css('padding-top','');
			}
		}else if( asideScroll === 'down'){
			console.log('down');
			$('.as_side .scroll-in').css('padding-top','');
		}
	});
	*/

	//전자책 상단 탭메뉴 접근성
	$('.category_lst li').each(function(){
		const t = $(this);

		if(t.hasClass('active')){
			t.find('a').attr('title','선택됨');
		}
	});
};