
//JS버전
var today = new Date();
const js_version = itp_fn_date_format(today);

requirejs.config({
	baseUrl: ITP_CONTEXTPATH,
	paths: {
		'jquery': 'js/jquery.min',
		'jquery-ui': 'js/jquery-ui.min',
		'jquery.number': 'js/jquery.number',
		'jquery.sortable': 'js/jquery.ui.sortable',
		'jquery.grid.addons': 'plugins/grid.addons',
		'jquery.bootstrap': 'bootstrap/dist/js/bootstrap.min',
		'jquery.bootstrap.treeview': 'bootstrap/dist/js/bootstrap-treeview',
		'jquery.bootstrap.fileUpload': 'bootstrap-fileUpload/dist/bootstrap-FileUpload',
		'jquery.bootstrap.datepicker': 'bootstrap-datepicker/js/bootstrap-datepicker',
	    'jquery.bootstrap.datepicker.locale': 'bootstrap-datepicker/locales/bootstrap-datepicker.' + ITP_LANGUAGE + '.min',
		'jquery.jqGrid': 'js/jquery.jqGrid',
		'jquery.jqGrid.grouping': 'js/grid.grouping',
		'jquery.jqGrid.inlinedit': 'js/grid.inlinedit',
		'jquery.jqGrid.formedit': 'js/grid.formedit',
		'jquery.jqGrid.celledit': 'js/grid.celledit',
		'jquery.jqGrid.treegrid': 'js/grid.treegrid',
		'jquery.jqGrid.fmatter': 'js/jquery.fmatter',
		'jquery.jqGrid.locale': 'js/i18n/grid.locale-' + ITP_LANGUAGE,
		'smarteditor2': 'se2/js/service/HuskyEZCreator',
		'message.locale': 'js/app/locales/locale-' + ITP_LANGUAGE + '.js?version='+js_version,
		'crypto': 'js/crypto' //Crypto 암호화 js
	},
	shim: {
		'jquery.bootstrap': {
			deps: [
				'jquery',
				'jquery-ui'
			]
		},
		'jquery.bootstrap.treeview': {
			deps: ['jquery.bootstrap']
		},
		'jquery.bootstrap.fileUpload': {
			deps: ['jquery.bootstrap']
		},
		'jquery.bootstrap.datepicker.locale': {
			deps: [
				'jquery.bootstrap',
				'jquery.bootstrap.datepicker'
			]
		},
		'jquery.jqGrid.locale': {
			deps: [
				'jquery.jqGrid',
				'jquery.jqGrid.grouping',
				'jquery.jqGrid.inlinedit',
				'jquery.jqGrid.formedit',
				'jquery.jqGrid.celledit',
				'jquery.jqGrid.treegrid',
				'jquery.jqGrid.fmatter'
			]
		}
	}
});

require([
	'jquery',
	'jquery.bootstrap',
	'jquery.bootstrap.datepicker.locale',
	'jquery.jqGrid.locale',
	'message.locale'
], function($) {
	$.jgrid.styleUI.Bootstrap.base.rowTable = 'table table-bordered table-striped';
	$.jgrid.defaults.styleUI = 'Bootstrap';
	$.jgrid.defaults.datatype = 'json';
	$.jgrid.defaults.mtype = 'POST';
	$.jgrid.defaults.width = 782;
	$.jgrid.defaults.height = '100%';
	$.jgrid.defaults.autowidth = true;
	$.jgrid.defaults.shrinkToFit = true;
	$.jgrid.defaults.viewrecords = true;
	$.jgrid.defaults.altRows = true;
	$.jgrid.defaults.loadonce = false;
	$.jgrid.defaults.resizable = true;
	$.jgrid.defaults.multiSort = false;
	$.jgrid.defaults.cellEdit = false;
	$.jgrid.defaults.multiselect = true;
	$.jgrid.defaults.multiboxonly = true;
	$.jgrid.defaults.outoencode = true;
	$.jgrid.defaults.cellsubmit = 'clientArray';
	$.jgrid.defaults.page = 1;
	$.jgrid.defaults.rowNum = 20;
	$.jgrid.defaults.rownumWidth = 50;
	//$.jgrid.defaults.multiselectWidth = 30;
	$.jgrid.defaults.jsonReader = {
		root: 'gridRows',
		page: 'gridPage',
		total: 'gridTotal',
		records: 'gridRecords',
		repeatitems: false,
		cell: 'cell'
	};
	$.jgrid.defaults.ajaxGridOptions = {
		contentType: 'application/json'
	};
	$.jgrid.defaults.treeGridModel = 'adjacency';
	$.jgrid.defaults.ExpandColClick = true;
	$.jgrid.defaults.tree_root_level = 0;
	$.jgrid.defaults.treeReader = {
		level_field: 'level',
		leaf_field: 'leaf'
	};

	history.pushState(null, null, location.href);
    window.onpopstate = function () {
    	itp_fn_modal_alert(ITP_MSG_LOCALE.message.page.noBack);
        history.go(1);
    };

	$('[data-toggle="tooltip"]').tooltip();
	$('.modal.itp_modal .modal-content').draggable();

	$.fn.clearForm = function() {
		return this.each(function() {
		    var type = this.type, tag = this.tagName.toLowerCase();

		    if (tag == 'form')
		      return $(':input',this).clearForm();
		    if (type == 'text' || type == 'password' || tag == 'textarea'|| type == 'hidden')
		      this.value = '';
		    else if (type == 'checkbox' || type == 'radio')
		      this.checked = false;
		    else if (tag == 'select')
		      this.selectedIndex = -1;
		});
	};

	$.fn.serializeObject = function() {
		var result = {};
		var extend = function(i, element) {
			var node = result[element.name];
			if ('undefined' !== typeof node && node !== null) {
				if ($.isArray(node)) {
					node.push($.trim(element.value));
				} else {
					result[element.name] = [node, $.trim(element.value)];
				}
			} else {
				result[element.name] = $.trim(element.value);
			}
		}
		$.each(this.serializeArray(), extend);
		return result;
	};

	$.fn.extend({
		treed: function(o) {
			var openedClass = 'glyphicon-minus text-primary';
			var closedClass = 'glyphicon-plus text-primary';

			if (typeof o != 'undefined') {
				if (typeof o.openedClass != 'undefined') {
					openedClass = o.openedClass;
				}
				if (typeof o.closedClass != 'undefined') {
					closedClass = o.closedClass;
				}
			};

			var tree = $(this);
			tree.addClass('tree');
			tree.find('li').has('ul').each(function() {
				var branch = $(this);
				branch.find('.list-group-item').first().prepend('<i class="indicator glyphicon ' + closedClass + '"></i>');
				branch.addClass('branch');
				branch.on('click', function(e) {
					if (this == e.target) {
						var icon = $(this).find('.list-group-item').first().children('i:first');
						icon.toggleClass(openedClass + ' ' + closedClass);
						$(this).children('ul').children().toggle();
					}
				});
				branch.children('ul').children().toggle();
				//branch.children('ul').children().show();
			});

			tree.find('.branch .indicator').each(function() {
				$(this).on('click', function() {
					$(this).closest('li').click();
					return false;
				});
			});
		}
	});
	
	var popNo = itp_fn_get_url_param('popNo');
	var preview = itp_fn_get_url_param('preview');
	
	$('#ITP_POPUP_CHK_TODAY').on('change', function() {
		//alert($('#ITP_POPUP_CHK_TODAY').is(':checked'));	
		if(!preview || preview != 'Y') {
			if($('#ITP_POPUP_CHK_TODAY').is(':checked')) { // 오늘 하루 그만 보기
				itp_fn_set_cookie(popNo, "Y", 1);   
			} else {
				itp_fn_set_cookie(popNo, "N", 1);
			}	
		}	 
	});
	
	var data = JSON.parse(sessionStorage.getItem('itp_login_info'));
	if(data && data.connKey) {
		CONN_KEY = data.connKey; //로그인 했을때 넣었던 키를 가져옴	
	}
	
	// 팝업번호
	// console.log(itp_fn_get_url_param('popNo'));
	const key = {popNo: popNo, viewCd: 'R'};
	var param = $.param(key);
	itp_fn_POPUP_info(param);		
});

var itp_fn_POPUP_info = function(param) {
	fn_ajax_call('/api/pop/info-pop', param, itp_fn_POPUP_info_callback, 'GET');
};

var itp_fn_POPUP_info_callback = function(result) {
	// console.log(result);
	// C:내용입력, I:이미지
	$('head title').html(result.popNm); // 타이틀
		
	if(result.popTypeCd == 'C') {
		$('#ITP_POPUP .fnPopupPreview').html(result.popDesc.replace(/(\n|\r\n)/g, '<br>'));
		$('#ITP_POPUP .fnPopupPreview').css('padding', '6px 18px');	
	} else if(result.popTypeCd == 'I') {
		$('#ITP_POPUP .fnPopupPreview').html('<img alt="'+result.popNm+'" src="'+result.fileUrl+'">');
	}	
};

function fn_ajax_call(href, param, fn, type) {
	$.ajax({
		contentType: 'application/json',
		url: DOMAIN + href,
		data: param,
		type: type,
		async: false,
		timeout: 10000,
		xhrFields: {
			withCredentials: true //Cross Domain 처리
		},
		beforeSend: function(xhr) {
			$('#ITP_OVERLAY').show();
			xhr.setRequestHeader('X-AUTH-TOKEN', CONN_KEY); //Jwt 토큰을 헤더에 담아서 보낸다.
		},
		complete: function() {
			$('#ITP_OVERLAY').hide();
		},
		success: function(result) {
			if (result.code !== undefined) { //성공시에도 메세지가 있으면 얼럿 예)저장되었습니다.
				itp_fn_modal_alert_ajax(result.message);
			}
			if (fn !== undefined || typeof fn !== 'undefined') fn(result);
		},
		error: function(xhr, status, error) {
			if (xhr.responseJSON !== undefined) { //실패시 서버에서 내려주는 메세지 얼럿
				itp_fn_modal_alert_ajax(xhr.responseJSON.message);
				if (xhr.status == 401) { //401에러가 떨어지면 로그인페이지로 이동
					sessionStorage.removeItem('itp_login_info'); //Jwt 키 제거
					$(location).attr('href', ITP_CONTEXTPATH + '/login.html');
				}
			} else {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failProcess);
			}
		},
		fail: function() {
			itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failProcess);
		}
	});
};

function itp_fn_get_url_param(name) {
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results == null) {
       return null;
    } else {
       return results[1] || 0;
    }
};

function itp_fn_date_format(date, type) {
    let month = date.getMonth() + 1;
    let day = date.getDate();
    let hour = date.getHours();
    let minute = date.getMinutes();
    let second = date.getSeconds();

    month = month >= 10 ? month : '0' + month;
    day = day >= 10 ? day : '0' + day;
    hour = hour >= 10 ? hour : '0' + hour;
    minute = minute >= 10 ? minute : '0' + minute;
    second = second >= 10 ? second : '0' + second;

	if(type && type == 1) {
		return date.getFullYear() + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	} else {
		return date.getFullYear() + month + day + hour + minute + second;
	}
};

// 쿠키 가져오기
var itp_fn_get_cookie = function (cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
}

// 24시간 기준 쿠키 설정하기  
var itp_fn_set_cookie = function (cname, cvalue, exdays) {
    var todayDate = new Date();
    todayDate.setTime(todayDate.getTime() + (exdays*24*60*60*1000));    
    var expires = "expires=" + todayDate.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}