You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

543 lines
17 KiB
JavaScript

2 years ago
//-------------------------------------------------
// ajaxSetup 세팅
//-------------------------------------------------
var errorForm = null;
var openAjaxCount = 0;
var closeAjaxCount = 0;
var openBlockUI = 0;
$.ajaxSetup({
cache: false,
dataType: 'json',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ajaxError(handleAjaxError);
$(document).ajaxComplete(function(event, xhr,settings){
if(!settings.hideLoading) closeAjaxLoading();
errorForm = null;
});
$(document).ajaxSend(function (event, xhr, settings) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'));
resetAjaxFormErrorMessage();
/*
if(!settings.hideLoading) {
if(typeof settings.bindForm == "undefined") openAjaxLoading(null);
else openAjaxLoading(settings.bindForm);
}
*/
});
$(document).ajaxSuccess(function(event, xhr, settings) {
// if(!settings.hideLoading) closeAjaxLoading();
errorForm = null;
});
// Ajax 에러 헨들러
function handleAjaxError(event, xhr, status, err) {
if (xhr.status === 401) {
// 로그아웃 된 상태
window.location.reload();
} else if (xhr.status === 419) {
alert('페이지가 만료되었습니다. 페이지를 다시 새로고침 합니다.');
window.location.reload();
} else if (xhr.status === 422) {
// Validaton 실패
var data = JSON.parse(xhr.responseText);
showAjaxFormErrorMessage(data);
}
else {
console.log(err);
if(err !== 'abort') alert(xhr.responseText);
}
closeAjaxLoading();
errorForm = null;
}
function showAjaxFormErrorMessage(data) {
var fistElement = null;
var message = "";
for (var i in data.errors) {
var name = i;
var element = null;
if (errorForm == null) {
element = $("[name=" + name + "]:not(:disabled)");
errorForm = element.closest("form");
} else {
element = errorForm.find("[name=" + name + "]:not(:disabled)");
}
if (element.length === 0) {
alert(message);
return;
}
// var row = element.closest(".form-group", errorForm);
// if(row.length === 0) row = element.closest("div.row", errorForm);
errorForm.find("[type=submit]").prop("disabled", false);
var dialog = element.closest(".modal-dialog");
if (dialog.length > 0) {
dialog.find(".modal-footer").find("[type=submit]").prop("disabled", false);
}
element.addClass("is-invalid");
message = $.isArray(data.errors[i]) ? data.errors[i][0] : data.errors[i];
//element.tooltip('enable');
element.addClass('has-tooltip');
element.attr('data-toggle', 'tooltip');
element.attr('data-title', message);
if (fistElement === null) {
fistElement = element;
}
}
if (fistElement !== null) {
fistElement.focus();
}
}
function resetAjaxFormErrorMessage() {
if (errorForm != null) {
errorForm.find(".is-invalid").removeClass("is-invalid");
errorForm.find(".has-tooltip").removeClass('has-tooltip');
//errorForm.find('[data-toggle="tooltip"]').tooltip('disable');
}
}
function openAjaxLoading(form) {
if (openAjaxCount > 0) return;
//console.log("openAjaxCount : "+openAjaxCount);
if (openAjaxCount === closeAjaxCount) {
openAjaxCount++;
if (form != null) {
//form.off("upload.progress");
form.bind("upload.progress", function (e, data) {
//console.log($("#blockUITitle"));
//Object {total: 38336387, upload: 38336387, percent: 100}
$(".blockUITitle:last-child").text(Math.floor(data.percent) + "% 업르드중... 잠시만 기다리세요...");
if (data.percent >= 100) {
form.off("upload.progress");
}
});
}
$.blockUI({
message: '<span class="text-white"><i class="fal fa-compass fa-4x fa-spin"></i><div class="blockUITitle">Please wait.</div></span>',
css: {border: '0', background: 'none'},
baseZ: 9000
});
// 에러가 날경우 닫지 못하는 문제로 15초가 넘으면 닫도록 처리함
// 오래 걸리는 작업때문에 주석 > 푸시등
/*
openBlockUI = setTimeout(function(){
closeAjaxLoading();
alert("[에러!!] 요청한 내용을 처리하지 못했습니다.")
}, 5000);
*/
}
}
function closeAjaxLoading() {
if (openAjaxCount === 0 || closeAjaxCount > 0) return;
closeAjaxCount++;
if (openAjaxCount === closeAjaxCount) {
clearTimeout(openBlockUI);
$.unblockUI();
openAjaxCount = 0;
closeAjaxCount = 0;
}
}
//-------------------------------------------------
var extExecutes = "php,php3,php4,phps,phtm,phtml,htm,html,sh,ph,inc,cgi,pl,tpl,exe,com,bat,dll,cpl,asp,aspx,vbs,java,jsp";
var extImages = "gif,jpg,jpeg,png,bmp";
$(document).ready(function() {
var checkMessage = function (result, msg, obj) {
if (!result) {
if (msg != undefined) alert(msg);
if (obj != undefined) obj.focus();
return false;
} else {
return true;
}
}
// 양쪽 공백 제거
$.fn.trim = function () {
var pattern = /(^\s*)|(\s*$)/g;
return this.val().replace(pattern, "");
}
// 공백 검사
$.fn.checkNull = function () {
var pattern = /^\s+|\s+$/g;
return (this.val() == null || this.val().replace(pattern, '') == '');
}
// 입력값이 비어 있는지 체크
$.fn.checkEmpty = function (msg) {
return checkMessage(!this.checkNull(), msg, this);
}
// 숫자인지 검사
$.fn.checkNumber = function (msg) {
var pattern = /^[0-9]+$/;
return checkMessage(pattern.test(this.val()), msg, this);
}
// 영문자인지 검사
$.fn.checkEnglish = function (msg) {
if (this.checkNull()) return false;
var pattern = /(^[a-zA-Z]+$)/;
return checkMessage(pattern.test(this.val()), msg, this);
}
// 한글인지 검사(자음, 모음만 있는 한글은 불가)
$.fn.checkKorean = function (msg) {
if (this.checkNull()) return false;
var pattern = /([^가-힣\x20])/i;
return checkMessage(!pattern.test(this.val()), msg, this);
}
// 영문자와 숫자 검사
$.fn.checkEngNumber = function (msg) {
if (this.checkNull()) return false;
var pattern = /(^[a-zA-Z0-9]+$)/;
return checkMessage(pattern.test(this.val()), msg, this);
}
// 최소입력숫자 제한
$.fn.checkCount = function (cnt, msg) {
if (this.checkNull()) return false;
if (!this.checkNumber()) return false;
if (this.val() < cnt) {
return checkMessage(false, msg, this);
} else {
return true;
}
}
// 입력길이 체크
$.fn.checkLength = function (len, ctype, msg) {
var str = this.val();
var str_len = 0;
for (var i = 0; i < str.length; i++) {
if (str.charCodeAt(i) > 255) {
str_len += 2;
} else {
str_len++;
}
}
if (ctype == 'max') {
return checkMessage((str_len <= len), msg, this);
} else if (ctype == 'min') {
return checkMessage((str_len >= len), msg, this);
} else {
return false;
}
}
$.fn.disableNumber = function () {
this.val(this.val().replace(/[^0-9]/g, ""));
};
$.fn.setComma = function (options) {
var opts = $.extend({}, {delimiter: ','}, options);
return this.each(function () {
$this = $(this);
var o = $.meta ? $.extend({}, opts, $this.data()) : opts;
var str = $this.html();
$this.html($this.html().toString().replace(new RegExp("(^\\d{" + ($this.html().toString().length % 3 || -1) + "})(?=\\d{3})"), "$1" + o.delimiter).replace(/(\d{3})(?=\d)/g, "$1" + o.delimiter));
});
};
$.fn.checkEmail = function (msg) {
var pattern = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return checkMessage(pattern.test(this.val()), msg, this);
}
// 전화번호 형식 검사
$.fn.checkPhone = function (check, msg) {
if (this.checkNull() || check == undefined) {
checkMessage(false, msg, this);
return false;
}
var str = this.val();
var pattern1, pattern2;
var result = false;
if (check == "phone") { //유선전화번호
pattern1 = /^(0[2-8][0-5]?)-?([1-9]{1}[0-9]{2,3})-?([0-9]{4})$/;
pattern2 = /^(1544|1566|1577|1588|1644|1688)-?([0-9]{4})$/;
result = (pattern1.test(str) || pattern2.test(str));
} else if (check == "mobile") { //휴대전화번호
pattern1 = /^(01[01346-9])-?([1-9]{1}[0-9]{2,3})-?([0-9]{4})$/;
result = pattern1.test(str);
} else { //유선전화,휴대전화 모두..
pattern1 = /^(0[2-8][0-5]?|01[01346-9])-?([1-9]{1}[0-9]{2,3})-?([0-9]{4})$/;
pattern2 = /^(1544|1566|1577|1588|1644|1688)-?([0-9]{4})$/;
result = (pattern1.test(str) || pattern2.test(str));
}
return checkMessage(result, msg, this);
}
//전화번호인지 검사
$.fn.checkPhoneNumber = function(msg) {
var pattern = /^[-0-9]*$/;
return checkMessage(pattern.test(this.val()), msg, this);
}
$.fn.autoHyphen = function() {
this.val(convertHyphen(this.val()));
}
// 파일확장자 검사
$.fn.checkExtension = function (check, msg) {
if (this.checkNull() || check == undefined) return true;
var str = this.val();
var exts = '';
var ext = str.substring(str.lastIndexOf(".") + 1).toLowerCase();
var result = false;
if (check == "image") { //이미지
exts = extImages;
} else if (check == "movie") { //동영상
exts = "asx,asf,wmv,wma,mpg,mpeg,mov,avi,flv,mp4";
} else if (check == "execute") { //실행파일
exts = extExecutes;
} else {
exts = check.toLowerCase();
}
result = (exts.indexOf(ext) != -1);
return checkMessage(result, msg, this);
}
$(".number").keyup(function () {
$(this).disableNumber();
});
$(".hyphen").keyup(function() {
$(this).autoHyphen();
});
var controls = {
leftArrow: '<i class="fal fa-angle-left" style="font-size: 1.25rem"></i>',
rightArrow: '<i class="fal fa-angle-right" style="font-size: 1.25rem"></i>',
}
$.fn.datepicker.dates['ko'] = {
days: ['일요일', '월요일', '화요일', '수요일', '목요일', '금요일', '토요일'],
daysShort: ['일', '월', '화', '수', '목', '금', '토'],
daysMin: ['일', '월', '화', '수', '목', '금', '토'],
months: ['1월','2월','3월','4월','5월','6월', '7월','8월','9월','10월','11월','12월'],
monthsShort: ['1월','2월','3월','4월','5월','6월', '7월','8월','9월','10월','11월','12월'],
titleFormat: "yyyy년 MM",
today: '이번달',
clear: '초기화',
};
$('.datepicker').datepicker({
orientation: "bottom left",
todayHighlight: true,
templates: controls,
format: "yyyy-mm-dd",
autoclose: true,
language: 'ko',
}).attr("autocomplete","off");
$('.datepicker-right').datepicker({
orientation: "bottom right",
todayHighlight: true,
templates: controls,
format: "yyyy-mm-dd",
autoclose: true,
language: 'ko',
}).attr("autocomplete","off");
// 동적으로 툴팁이 추가되었을때
$('body').tooltip ({
placement: 'top',
container: 'body',
boundary: 'window',
selector: '.has-tooltip',
});
$('.datetimepicker').datetimepicker({
hideSeconds: true,
allowInputToggle: true,
format: "HH:mm",
icons: {
time: "fal fa-clock-o",
date: "fal fa-calendar",
up: "fal fa-arrow-up",
down: "fal fa-arrow-down",
}
});
$(".input-mask").inputmask();
$('[data-toggle="tooltip"]').tooltip();
autosize($(".autosize"));
$(".custom-file-input").on("change", function() {
var fileName = $(this).val().split("\\").pop();
$(this).siblings(".custom-file-label").addClass("selected").html(fileName);
});
});
// 달력 생성
function createCalendar(selector, eventSources, options, datepickerCallback) {
var calendar = new FullCalendar.Calendar($(selector)[0], $.extend({}, {
plugins: ['dayGrid', 'list', 'timeGrid', 'interaction', 'bootstrap'],
themeSystem: 'bootstrap',
timeZone: 'UTC',
dateAlignment: "month", //week, month
locale: 'ko',
eventTimeFormat: {
hour: 'numeric',
minute: '2-digit',
meridiem: 'short'
},
navLinks: false,
header: {
left: '',
center: 'title',
right: 'today prev,next'
},
footer: {
// left: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek',
left: '',
center: '',
right: ''
},
editable: false,
eventLimit: false, // allow "more" link when too many events
eventSources : eventSources,
viewSkeletonRender: function()
{
$(selector).find('.fc-toolbar .btn-default').addClass('btn-sm');
$(selector).find('.fc-header-toolbar h2').addClass('fs-md');
$(selector).find('#calendar').addClass('fc-reset-order')
},
}, options));
calendar.render();
$(selector).find('.fc-toolbar h2').datepicker({
orientation: "bottom left",
todayHighlight: true,
templates: {
leftArrow: '<i class="fal fa-angle-left" style="font-size: 1.25rem"></i>',
rightArrow: '<i class="fal fa-angle-right" style="font-size: 1.25rem"></i>'
},
format: "yyyy-mm",
viewMode: "months",
minViewMode: "months",
language: (_LANG === 'ko')?'kr':_LANG
}).on('changeDate', function(e){
// console.log(e.date);
if(datepickerCallback != null) {
datepickerCallback(moment(e.date).format("YYYY-MM-DD"));
}
else {
$(this).datepicker('hide');
calendar.gotoDate( moment(e.date).format("YYYY-MM-DD") );
}
});
$(selector).find('.fc-toolbar h2').click(function () {
$(this).datepicker('show');
});
return calendar;
}
function getFileSize(bytes) {
var kb = bytes / 1024;
var mb = kb / 1024;
var gb = mb / 1024;
var str = "";
if (bytes >= 1024 * 1024 * 1024) {
str = gb.toFixed(2) + "GB";
} else if (bytes >= 1024 * 1024) {
str = mb.toFixed(2) + "MB";
} else if (bytes >= 1024) {
str = parseInt(kb) + "KB";
} else if (bytes <= 0) {
str = bytes;
} else {
str = parseInt(bytes) + "B";
}
return str;
}
function alertModal(messsage) {
$('#alert-modal-body').html(messsage);
$('#alertModal').modal('show');
}
function convertHyphen(str) {
if (!str) {
return "";
}
str = str.replace(/[^0-9]/g, "");
str = str.replace(/(^02|^0505|^1[0-9]{3}|^0[0-9]{2})([0-9]+)?([0-9]{4})$/,"$1-$2-$3");
str = str.replace("--", "-");
return str;
}
function isIE() {
var agent = navigator.userAgent.toLowerCase();
return (navigator.appName == 'Netscape' && agent.indexOf('trident') != -1) || (agent.indexOf("msie") != -1);
}
function sendEditorImage(editor, file) {
var formData = new FormData();
formData.append('image', file);
$.ajax({
url: '/cms/board/image/upload',
data: formData,
type: 'POST',
dataType : "json",
cache: false,
contentType: false,
processData: false,
success: function(result) {
if (result.code == 'success') {
var data = result.data;
$(editor).summernote('insertImage', data.url, function($image) {
$image.attr({
'src': data.url,
'alt': data.origin,
'class': 'editorImage'
});
});
} else {
alert(result.message);
}
}
});
}