const $is_login = $('#is_login').val();
/// 푸딩 월드에 관련 소켓 
$(document).ready(function(){
	if ($('.modal-dialog').length > 0) {
		// console.log('모달 있음');
		modal_draggable();
	}
	$('.tip_info').tooltip();
	$('.common_a').attr('target','_parent');

	Kakao.init('9a20c447790349975a92df6e50417eab');
})
.on('show.bs.modal', '.modal', function (event) {
	var zIndex = 1050 + (10 * $('.modal:visible').length);
	$(this).css('z-index', zIndex);
	setTimeout(function () {
		$('.modal-backdrop').not('.modal-stack').css('z-index', zIndex - 1).addClass('modal-stack');
	}, 0);
})
//버블링 막기
.on('click','.stop_bubble', function(e){
	e.stopPropagation();
})	
//form 태그 enter submit 방지
.on('keydown', 'form', function (event) {
	if(event.which == 13) event.preventDefault();
})
.on('keyup','input[type="number"]',function () {
	$this = $(this);
	var RegExp = /[\{\}\[\]\/?.,;:|\)*~`!^\-_+┼<>@\#$%&\'\"\\\(\=]/g;	//정규식 구문
	// 특수문자 모두 제거    
	$this.val($this.val().replace(RegExp , ''));
})
// 검색 초기화
.on("click", "#init_search", function (e) {
	e.preventDefault();

	window.location.href = window.location.pathname;
})

// 전체 선택
.on("change", "#check_all", function () {
	$(".card-body .table tbody .list_checkbox").prop("checked", $(this).is(":checked"));
})
.on("change", ".img_file", function () {
	var ext = $(this).val().split('.').pop().toLowerCase();
	console.log(ext);
	// 확장자체크
	var img_ext = $('#img_ext').val();	
	if(ext &&!check_file_ext(ext,img_ext)){
		alert(img_ext+' 만 업로드 할 수 있습니다.');
		$(this).val('');
		return false;
	}
	
})
//푸딩월드 가이드 다운
.on('click','.btn_guide', function(e) {
	window.open('/assets/doc/guide.pdf', '푸딩월드가이드', 'width=700px,height=800px,scrollbars=yes');
})
// 개별 체크박스 체크시 전체 체크박스 체크 변경
.on("change", ".card-body .table tbody .list_checkbox", function () {
	if ($(this).is(":checked")) {
		var $tbody = $(".card-body .table tbody");
		var all_cnt = $tbody.find(".list_checkbox").length;
		var checked_cnt = $tbody.find(".list_checkbox:checked").length;

		if (all_cnt == checked_cnt) $("#check_all").prop("checked", true);
	} else {
		$("#check_all").prop("checked", false);
	}
})
// 3자리 콤마 찍기
.on("keyup", "input.price", function () {
	var price = $(this).val().replace(/,/g, "");
	var regNum = /^[0-9]*$/;

	// 숫자 외의 글자 입력시 ''으로 치환
	if (!regNum.test(price)) price = price.replace(/[^0-9]/g, "");

	// 금액 미입력시 자동으로 0이 입력되는 것 방지
	if (!price) price = "";
	else price = parseInt(price).toLocaleString("en").split(".")[0];

	$(this).val(price);
})
//휴대폰 번호 정규식 체크
.on("keyup", ".phone_number", function ()
	{
		$(this).val($(this).val().replace(/[^0-9]/g, "")
		.replace(/(^02|^0505|^1[0-9]{3}|^0[0-9]{2})([0-9]+)?([0-9]{4})$/, "$1-$2-$3").replace("--", "-"));
})
//드롭다운 내부 클릭시 닫기 방지 
.on('click', '.dropdown-menu', function(e){
	e.stopPropagation();
});
//랜덤 문자열 생성
const generateRandomString = (num) => {
	const characters ='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
	let result1= Math.random().toString(36).substring(0,num);       

	return result1;
}

const swalWithBootstrapButtons = Swal.mixin({
	customClass: {
		confirmButton: 'btn btn-danger mr-2',
		cancelButton: 'btn btn-secondary'
	},
	buttonsStyling: false
});
/**
 * 기존의 serialize, serializeArray와는 다른 Object로 받는 함수
 */
jQuery.fn.serializeObject = function () {
	var obj = null;
	try {
		if (this[0].tagName && this[0].tagName.toUpperCase() == "FORM") {
			var arr = this.serializeArray();
			if (arr) {
				obj = {};
				jQuery.each(arr, function () {
					obj[this.name] = this.value;
				});
			} //if ( arr ) {
		}
	} catch (e) {
		// alert(e.message);
		console.log(e.message);
	} finally {}

	return obj;
};

/**
 * 모달 드래그 기능 추가
 *
 * @return  {[type]}  [return description]
 */
 function modal_draggable() {
	$('.modal-dialog').draggable({
		handle: ".modal-header"
	});
}

function page_reload() {
	location.reload();
}


// daterangepicker를 쓰지만 일자를 하나만 쓰는 경우 초기화
// 날짜 입력 시 해당 요일 선택됨
// 달력 뜨는 위치 입력 받도록 추가
function init_single_daterangepicker(format = 'YYYY-MM-DD', selector = 'input.single_daterange', date = new Date(), drops = "auto") {
	// 하루 선택형 달력 초기화
	var $datepicker = $(selector);

	$datepicker.daterangepicker({
		singleDatePicker: true,
		autoUpdateInput: false,
		locale: {
			format: format,
			daysOfWeek: ["일", "월", "화", "수", "목", "금", "토"],
			monthNames: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
		},
		drops: drops,
		autoApply: true,
		showDropdowns: true,
		start_date: date
	});

	// 날짜 형식 변경
	$datepicker.on("apply.daterangepicker", function (ev, picker) {
		var start_date = picker.startDate.format(format);

		$(this).val(start_date);
	});
}
// 1. 기간 선택형 달력 초기화
// 2. 기간 선택형 달력 날짜 형식 변경
// 날짜 입력 시 해당 요일 선택됨
// 달력 뜨는 위치 입력 받도록 추가
function init_multi_daterangepicker(format = 'YYYY-MM-DD', selector = 'input.daterange', start_date = new Date(), end_date = new Date(), drops = "auto") {
	var $datepicker = $(selector);

	$datepicker.daterangepicker({
		autoUpdateInput: false,
		locale: {
			format: format,
			daysOfWeek: ["일", "월", "화", "수", "목", "금", "토"],
			monthNames: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"]
		},
		drops: drops,
		autoApply: true,
		showDropdowns: true,
		startDate: start_date,
		endDate: end_date
	});

	$datepicker.on("apply.daterangepicker", function (ev, picker) {
		var start_date = picker.startDate.format(format);
		var end_date = picker.endDate.format(format);

		$(this).val(start_date + " ~ " + end_date);
		$(this).trigger('change'); //날짜 선택 시 다른 곳에 날짜 입력 값을 사용하기 위해 추가함
		// 휴일 체크하는 함수가 있을 때 함수 호출
		// 프로젝트 > 일정진척관리 > 공정별 금형 제작 일정 계획/실적에서 사용중
		if (typeof calculate_workday == "function") calculate_workday($(this), picker.startDate.format("YYYY-MM-DD"));
	});
}

/**
 * java, c# 등의 언어로 되어있는 프로그램에서 utf-8 문자열을 javascript에서 제대로 변환 못하는 경우
"유니 코드 문제" DOMString s는 16 비트로 인코딩 된 문자열이므로 유니 코드 문자열에서 window.btoa를 호출하는 대부분의 브라우저에서 문자가 8 비트 바이트 범위 (0x00)를 초과하면 Character Out *Of Range exception가 발생합니다 ~ 0xFF). 이 문제를 해결하는 방법에는 두 가지가 있습니다.

첫 번째는 전체 문자열을 이스케이프 처리하고 (UTF-8의 경우 encodeURIComponent 참조) 인코딩합니다.
두 번째는 UTF-16 DOMString 을 UTF-8 문자 배열로 변환 한 다음 인코딩하는 것입니다.
이전 솔루션에 대한 참고 사항 : MDN 기사는 원래 Character Out Of Range 예외 문제를 해결하기 위해 unescape 및 escape을 사용하도록 제안했지만 이후에는 더 이상 사용되지 않습니다. 여기에있는 다른 답변은 decodeURIComponent 및 encodeURIComponent을 사용 하여이 문제를 해결할 것을 제안했지만 신뢰할 수없고 예측할 수없는 것으로 판명되었습니다. 이 답변에 대한 최신 업데이트는 최신 JavaScript 함수를 사용하여 속도를 향상시키고 코드를 현대화합니다.
 * @param {string} str
 */
function b64_encode_unicode(str) {
	// first we use encodeURIComponent to get percent-encoded UTF-8,
	// then we convert the percent encodings into raw bytes which
	// can be fed into btoa.
	return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,
		function toSolidBytes(match, p1) {
			return String.fromCharCode('0x' + p1);
		}));
}

/**
 * java, c# 등의 언어로 되어있는 프로그램에서 utf-8 문자열을 javascript에서 제대로 변환 못하는 경우
"유니 코드 문제" DOMString s는 16 비트로 인코딩 된 문자열이므로 유니 코드 문자열에서 window.btoa를 호출하는 대부분의 브라우저에서 문자가 8 비트 바이트 범위 (0x00)를 초과하면 Character Out *Of Range exception가 발생합니다 ~ 0xFF). 이 문제를 해결하는 방법에는 두 가지가 있습니다.

첫 번째는 전체 문자열을 이스케이프 처리하고 (UTF-8의 경우 encodeURIComponent 참조) 인코딩합니다.
두 번째는 UTF-16 DOMString 을 UTF-8 문자 배열로 변환 한 다음 인코딩하는 것입니다.
이전 솔루션에 대한 참고 사항 : MDN 기사는 원래 Character Out Of Range 예외 문제를 해결하기 위해 unescape 및 escape을 사용하도록 제안했지만 이후에는 더 이상 사용되지 않습니다. 여기에있는 다른 답변은 decodeURIComponent 및 encodeURIComponent을 사용 하여이 문제를 해결할 것을 제안했지만 신뢰할 수없고 예측할 수없는 것으로 판명되었습니다. 이 답변에 대한 최신 업데이트는 최신 JavaScript 함수를 사용하여 속도를 향상시키고 코드를 현대화합니다.
 * @param {string} str
 */
function b64_decode_unicode(str) {
	// Going backwards: from bytestream, to percent-encoding, to original string.
	return decodeURIComponent(atob(str).split('').map(function (c) {
		return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
	}).join(''));
}

/**
 * a tag로 미리 되어 있지 않은 경우 파일을 다운로드 하기 위해
 *
 * @param {string} file_url
 */
function download_file_by_url(file_url) {
	var link = document.createElement('a');
	link.setAttribute('download', '');
	document.body.appendChild(link);
	link.href = file_url;
	link.click();
	link.remove();
}

/**
 * 숫자 3자리마다 콤마 찍기
 * @param  {int} number
 * @return {string}
 */
// function comma(number) {
// 	return number ? parseInt(number).toLocaleString("en").split(".")[0] : "";
// }
function comma(str) {
	str = String(str);
	return str.replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
}

function uncomma(str) {
	str = String(str);
	return str.replace(/[^\d]+/g, '');
}

/**
 * 이미지 미리보기
 *
 * @param   {[type]}  input  [input description]
 * @param   {[type]}  ele    [ele description]
 *
 * @return  {[type]}         [return description]
 */
function setImageFromFile(input, ele) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            ele.attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);
    }
}

/**
 * 좌측으로 내용물이 밀리지 않는 스크롤바 (사용할 때 style 또는 less에 height나 max-height 지정해줘야 함)
 *
 * @param   {string}  selector  selector string
 *
 * @return  {void}
 */
function init_scrollbar(selector = '') {
	$(selector).mCustomScrollbar("destroy");
	var option = {
		theme: "minimal-dark",
		mouseWheelPixels: 120,
		advanced: {
			autoScrollOnFocus: false
		}
	}
	$(selector + ".scroll-y").mCustomScrollbar(option);

	option.axis = "x";
	option.advanced["autoExpandHorizontalScroll"] = true;
	option.advanced["updateOnSelectorChange"] = true;
	$(selector + ".scroll-x").mCustomScrollbar(option);
}

/**
 * 숫자 앞에 원하는 자릿수 만큼 0을 붙여줌
 * @param   {number}  n
 * @param   {number}  digits
 *
 * @return  {[string]}
 */

function leadingZeros(n, digits) {
	var zero = '';
	n = n.toString();

	if (n.length < digits) {
		for (var i = 0; i < digits - n.length; i++)
			zero += '0';
	}
	return zero + n;
}

/**
 * window.location.search에서 같은 key가 있으면 value를 바꿔서, 없으면 key, value를 넣어서 search 형식으로 반환
 * 
 * @param {string} search: window.location.search
 * @param {array} key_values
 * @return {string}
 */
function set_search_params(search, key_values) {
	var array = [];
	for (var matchs of [...search.matchAll(/([^?^&]*)=([^&]*)/g)]) {
		var matched = false;
		for (var key_value of key_values) {
			if (matchs[1] == key_value[0]) {
				matched = true;
			}
		}
		if (!matched) {
			array.push(matchs[1] + "=" + matchs[2]);
		}
	}
	for (var key_value of key_values) {
		if ('' != key_value[1]) {
			array.push(key_value[0] + "=" + key_value[1]);
		}
	}
	return (0 < array.length) ? "?" + array.join('&') : "";
}

/**
 * window.location.search에 중 해당 key의 value를 반환
 * 
 * @param {string} search 
 * @param {string} key 
 * @return {string}
 */
function get_search_value_by_key(search, key) {
	// for (var matchs of [...search.matchAll(/([^?^&]*)=([^&]*)/g)]) {
	// 	if (matchs[1] == key) {
	// 		return matchs[2];
	// 	}
	// }

	var matchs = search.match(key + '=([^&]*)');
	if (matchs && 1 < matchs.length) {
		return matchs[1];
	}
	return "";
}

/**
 * 데이터테이블 init
 *
 * @param   {[type]}  $ele        [$ele description]
 * @param   {[type]}  options     [options description]
 * @param   {[type]}  page_reset  [page_reset description]
 *
 * @return  {[type]}              [return description]
 */
function datatables_init($ele, options, page_reset = true) {
	var settings = $.extend({
		pageLength: 10,
		scrollY: 800,
		scrollX: "100%",
		language: {
			"sEmptyTable": "데이터가 없습니다.",
			"sInfo": "시작 번호 _START_ - 끝 번호 _END_ / 총 _TOTAL_",
			"sInfoEmpty": "0 - 0 / 0",
			// "sInfoFiltered":   "(총 _MAX_ 개)",
			"sInfoFiltered": "",
			"sInfoThousands": ",",
			"sLengthMenu": "페이지당 줄 수 _MENU_",
			"sLoadingRecords": "읽는중...",
			// "sProcessing":     "처리중...",
			// "sProcessing":     '<img src="/public/image/gear.gif" />',
			"sProcessing": '<div class="datatable_loader">Loading...</div>',
			"sSearch": "검색:",
			"sZeroRecords": "검색 결과가 없습니다.",
			"oPaginate": {
				"sFirst": "처음",
				"sLast": "마지막",
				"sNext": "다음 >",
				"sPrevious": "< 이전"
			},
			"oAria": {
				"sSortAscending": ": 오름차순 정렬",
				"sSortDescending": ": 내림차순 정렬"
			},
			search: '<i class="fas search_ico fa-search"></i>',
			searchPlaceholder: "검색 "
		},
		destroy: true,
		stateSave: true,
		searching: false,
		bLengthChange: false,
		processing: true,
		serverSide: true,
		fixedHeader: true,
		scrollCollapse: true,
		autoWidth: false,
		order: [],
		// columnDefs: [{
		// 	orderable: false
		// }],
	}, options);
	// $ele.DataTable(settings);
	if (page_reset) {
		$ele.DataTable(settings).search('').page('first').draw('page');
	} else {
		$ele.DataTable(settings);
	}
}



/**
 * url의 모든 인자값을 가져온다.
 *
 * @return  {[type]}  [return description]
 */
function get_url_query() {
	var url = document.location.href;
	var qs = url.substring(url.indexOf('?') + 1).split('&');
	for (var i = 0, result = {}; i < qs.length; i++) {
		qs[i] = qs[i].split('=');
		result[qs[i][0]] = decodeURIComponent(qs[i][1]);
	}
	return result;
}

/**
 * 이름(닉네임) 정규식 체크
 *
 */
 function name_check(value) {
	var regName = /^(?=.*[A-Za-z가-힣])[A-Za-z0-9가-힣]{2,16}$/;
	if (regName.test(value) === true) {
		return true;
	}else{
		return false;
	}
}


/**
 * 소셜주소 정규식 체크(영어는 무조건 들어가야 하며 숫자는 필수가 아니며 최소 4자리 이상 16자리 이하)
 *
 */
 function social_check(value) {
	var regAddress = /(?=.*[A-Za-z])[A-Za-z0-9]{3,16}$/;
	if (regAddress.test(value) === true) {
		return true;
	}else{
		return false;
	}
}
/**
 * 숫자만 입력되었을 때 true를 반환한다
 *
 */
 function number_check(value) {
	var regAddress = /^[0-9]+$/;
	if (regAddress.test(value) === true) {
		return true;
	}else{
		return false;
	}
}
/**
 * 비밀번호 정규식 체크(최소 8 자, 최소 하나의 문자 및 하나의 숫자)
 *
 */
 function pw_check(value) {
	var regPw = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d$@$!%*#?&]{8,}$/;
	if (regPw.test(value) === true) {
		return true;
	}else{
		return false;
	}
}
/**
 * 비밀번호 정규식 체크(숫자만 들어갔을 때)
 *
 */
 function pw_check2(value) {
	var regPw = /[0-9]{8,}$/;
	if (regPw.test(value) === true) {
		return true;
	}else{
		return false;
	}
}
/**
 * 이메일 정규식 체크(이메일 글자 앞 중간 뒤에 영문+숫자 포함하여 특수문자 중 점( . ) 하이픈( - ) 언더바( _ ) 만 사용 가능하도록)
 *
 * @param   {[type]}  value  [value description]
 *
 * @return  {[type]}         [return description]
 */
function email_check(value) {

	var regEmail = /^([\w\.\_\-])*[a-zA-Z0-9]+([\w\.\_\-])*([a-zA-Z0-9])+([\w\.\_\-])+@([a-zA-Z0-9]+\.)+[a-zA-Z0-9]{2,64}$/;
	if (regEmail.test(value) === true) {
		return true;
	}else{
		return false;
	}
}
/**
 * 지갑주소 정규식 체크(이더리움과 동일)
 *
 * @param   {[type]}  value  [value description]
 *
 * @return  {[type]}         [return description]
 */
 function wallet_check(value) {

	var regWallet = /^0x[a-fA-F0-9]{40}$/g;
	if (regWallet.test(value) === true) {
		return true;
	}else{
		return false;
	}
}
/**
 * 현재시간을 가져온다.
 *
 * @param   {string}  format    datetime | date | time
 *
 * @return  {string}            [return description]
 */
function get_real_time(format = 'datetime') {
	var now = new Date();

	real_time = now.getFullYear() + "-";
	real_time += ("0" + (now.getMonth() + 1)).slice(-2) + "-"; //월은 0부터 시작하므로 +1을 해줘야 한다.
	real_time += ("0" + now.getDate()).slice(-2);
	real_time += " ";
	real_time += ("0" + now.getHours()).slice(-2) + ":";
	real_time += ("0" + now.getMinutes()).slice(-2) + ":";
	real_time += ("0" + now.getSeconds()).slice(-2);

	if (format == 'date') real_time = real_time.split(' ')[0];
	if (format == 'time') real_time = real_time.split(' ')[1];
	else real_time = real_time;

	return real_time;
}


function post_form(url, parm, target){ 
	var f = document.createElement('form'); 
	var objs, value; 
	for(var key in parm){ 
		value = parm[key]; 
		objs = document.createElement('input'); 
		objs.setAttribute('type', 'hidden'); 
		objs.setAttribute('name', key); 
		objs.setAttribute('value', value); 
		f.appendChild(objs); 
	} 
	if(target) 
	f.setAttribute('target', target); 

	f.setAttribute('method', 'post'); 
	f.setAttribute('action', url); 
	document.body.appendChild(f); 
	f.submit(); 
}

/**
 * 파일확장자
 *
 * @param   string  file_name  [file_name description]
 *
 * @return  string             [return description]
 */
function get_file_extension_from_file_name(file_name) {
	try {
		return file_name.split('.').pop();
	} catch (e) {
		return '';
	}
}

/**
 * 확장자 체크
 *
 * @param   string  file_ext    [file_ext description]
 * @param   string  ext_string  [ext_string description]
 *
 * @return  boolean              [return description]
 */
function check_file_ext(file_ext,ext_string) {

	if($.inArray(file_ext, ext_string.split(',')) == -1) {
		return false;
	}
	return true;	
}

/**
 * 저장 진행바
 *
 * @return  {[type]}  [return description]
 */
function open_progress_modal() {
	//upload Progress
	var $modal_progress = $('#modal_progress');
	$(".progress-bar",$modal_progress).css("width", "0%");
	$modal_progress.modal();
	
	var xhr = $.ajaxSettings.xhr();
	if (xhr.upload) {
		xhr.upload.addEventListener('progress', function (event) {
			var percent = 0;
			var position = event.loaded || event.position;
			var total = event.total;
			if (event.lengthComputable) {
				percent = Math.ceil(position / total * 100);
			}
			//update progressbar
			$(".progress-bar",$modal_progress).css("width", +percent + "%");
			$(".status",$modal_progress).text(percent + "%");
		}, true);
	}
	return xhr;
}

/**
 * byte 용량을 환산하여 반환
 * 용량의 크기에 따라 MB, KB, byte 단위로 환산함
 * @param fileSize  byte 값
 * @param fixed     환산된 용량의 소수점 자릿수
 * @returns {String}
 */
 function byte(fileSize, fixed) {
    var str

    //MB 단위 이상일때 MB 단위로 환산
    if (fileSize >= 1024 * 1024) {
        fileSize = fileSize / (1024 * 1024);
        fileSize = (fixed === undefined) ? fileSize : fileSize.toFixed(fixed);
        str = comma(fileSize) + ' MB';
    }
    //KB 단위 이상일때 KB 단위로 환산
    else if (fileSize >= 1024) {
        fileSize = fileSize / 1024;
        fileSize = (fixed === undefined) ? fileSize : fileSize.toFixed(fixed);
        str = comma(fileSize) + ' KB';
    }
    //KB 단위보다 작을때 byte 단위로 환산
    else {
        fileSize = (fixed === undefined) ? fileSize : fileSize.toFixed(fixed);
        str = comma(fileSize) + ' byte';
    }
    return str;
}

// Closure
(function () {
	/**
	 * Decimal adjustment of a number.
	 *
	 * @param {String}  type  The type of adjustment.
	 * @param {Number}  value The number.
	 * @param {Integer} exp   The exponent (the 10 logarithm of the adjustment base).
	 * @returns {Number} The adjusted value.
	 */
	function decimalAdjust(type, value, exp) {
		// If the exp is undefined or zero...
		if (typeof exp === 'undefined' || +exp === 0) {
			return Math[type](value);
		}
		value = +value;
		exp = +exp;
		// If the value is not a number or the exp is not an integer...
		if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) {
			return NaN;
		}
		// Shift
		value = value.toString().split('e');
		value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp)));
		// Shift back
		value = value.toString().split('e');
		return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp));
	}

	// Decimal round
	if (!Math.round10) {
		Math.round10 = function (value, exp) {
			return decimalAdjust('round', value, exp);
		};
	}
	// Decimal floor
	if (!Math.floor10) {
		Math.floor10 = function (value, exp) {
			return decimalAdjust('floor', value, exp);
		};
	}
	// Decimal ceil
	if (!Math.ceil10) {
		Math.ceil10 = function (value, exp) {
			return decimalAdjust('ceil', value, exp);
		};
	}
})();

// 메뉴 내의 button click 처리는 위의 코드로 되지 않아 button 내의 onclick으로 처리
function logout() {
	
	// swalWithBootstrapButtons.fire({
	// 	title: '로그아웃 하시겠습니까?',
	// 	icon: 'warning',
	// 	showCancelButton: true,
	// 	confirmButtonText: '로그아웃',
	// 	cancelButtonText: '취소'
	// }).then((result) => {
	// 	if (result.isConfirmed) {
			$.ajax({
				type: "POST",
				url: "/api/web/logout",
				dataType: "json",
				success: function (data) {
					//카카오 연결끊기
					if (Kakao.Auth.getAccessToken()) {
						Kakao.API.request({
							url: "/v1/user/unlink",
							success: function (response) {
								// console.log(response);								
								location.href='/';
								
							},
							fail: function (error) {
								console.log(error);
							},
						});
					}
					localStorage.removeItem('members');
					window.location.href='/';
				},
				complete: function () {}
			});
	}
	// })

// }

// 사용자권한 텍스트 변환
function convert_user_auth(auth) {
	var user_auth = {
		'0' : '최고관리자',
		'1' : '일반사용자',
		'2' : '강사',
		'4' : '부스관리자'
	};

	var user_auth_text_class = {
		'0' : 'text-danger',
		'1' : 'text-dark',
		'2' : 'text-success',
		'4' : 'text-warning'
	};

	var return_value = {
		text : user_auth[auth],
		text_class : user_auth_text_class[auth]
	};

	return return_value;
}

//시간 @분전 체크
function timeForToday(value) {
    const today = new Date();
    const timeValue = new Date(value);

    const betweenTime = Math.floor((today.getTime() - timeValue.getTime()) / 1000 / 60);
    if (betweenTime < 1) return '방금전';
    if (betweenTime < 60) {
        return `${betweenTime}분전`;
    }

    const betweenTimeHour = Math.floor(betweenTime / 60);
    if (betweenTimeHour < 24) {
        return `${betweenTimeHour}시간전`;
    }

    const betweenTimeDay = Math.floor(betweenTime / 60 / 24);
    if (betweenTimeDay < 365) {
        return `${betweenTimeDay}일전`;
    }

    return `${Math.floor(betweenTimeDay / 365)}년전`;
}
//문자열에서 숫자, 마이너스 기호, 소숫점을 제외한 모든 문자를 제거한다.
function get_number(str){
	var regex = /[^0-9-.]/g;				// 숫자가 아닌 문자열을 선택하는 정규식
	var result = str.replace(regex, "");	// 원래 문자열에서 숫자가 아닌 모든 문자열을 빈 문자로 변경
	return result;
}
// function logout_sns(id,auth){
	
// 	$.ajax({
// 		url: "/api/web/logout_sns",
// 		dataType : 'json',
// 		type : 'POST',
// 		data : {
// 			id :id,
// 			auth : auth
// 		},
// 		success: function(data){
// 			console.log(data);										
// 		},
// 		error: function (request, error, textStatus){
// 			console.log(error);
// 		}, complete: function() {}
// 	})
// }

function check_browser(){
	const agent = window.navigator.userAgent.toLowerCase();
		let browserName;
		switch (true) {
			case agent.indexOf("edge") > -1: 
				browserName = "MS Edge"; // MS 엣지
				break;
			case agent.indexOf("edg/") > -1: 
				browserName = "Edge (chromium based)"; // 크롬 기반 엣지
				break;
			case agent.indexOf("opr") > -1 && !!window.opr: 
				browserName = "Opera"; // 오페라
				break;
			case agent.indexOf("chrome") > -1 && !!window.chrome: 
				browserName = "Chrome"; // 크롬
				break;
			case agent.indexOf("trident") > -1: 
				browserName = "MS IE"; // 익스플로러
				break;
			case agent.indexOf("firefox") > -1: 
				browserName = "Mozilla Firefox"; // 파이어 폭스
				break;
			case agent.indexOf("safari") > -1: 
				browserName = "Safari"; // 사파리
				break;
			default: 
				browserName = "other"; // 기타
		}
       	return browserName;
}

function mobile(){
	return  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}

function set_tab(tab){
	sessionStorage.setItem('SocialTab',tab);
}
function checkLogin(url){
	$is_login == '1' ? location.href=url : $modal_sign.init_modal();
}

//이벤트가 반복적으로 함수를 활성화하는 것을 방지
function debounce(func, delay) {
	let timeout;
	return function() {
	  const context = this;
	  const args = arguments;
	  clearTimeout(timeout);
	  timeout = setTimeout(() => func.apply(context, args), delay);
	};
}
function throttle(func, delay) {
	let wait = false;
  
	return (...args) => {
	  if (wait) {
		  return;
	  }
  
	  func(...args);
	  wait = true;
	  setTimeout(() => {
		wait = false;
	  }, delay);
	}
  }