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

requirejs.config({
	baseUrl: ITP_CONTEXTPATH,
	waitSeconds: 0,
	paths: {
		'jquery': 'js/jquery.min',
		'jquery-ui': 'js/jquery-ui.min',
		'jquery.bootstrap': 'bootstrap/dist/js/bootstrap.min',
		'jquery.bootstrap.fileUpload': 'bootstrap-fileUpload/dist/bootstrap-FileUpload.js?version='+js_version,
		'jquery.bootstrap.datepicker': 'bootstrap-datepicker/js/bootstrap-datepicker',
		'jquery.bootstrap.datepicker.locale': 'bootstrap-datepicker/locales/bootstrap-datepicker.' + ITP_LANGUAGE + '.min',
		'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.fileUpload': {
			deps: ['jquery.bootstrap']
		},
		'jquery.bootstrap.datepicker.locale': {
			deps: [
				'jquery.bootstrap',
				'jquery.bootstrap.datepicker'
			]
		},
	}
});

require([
	'jquery',
	'jquery.bootstrap',
	'jquery.bootstrap.datepicker.locale',
	'message.locale'
], function($) {
	history.pushState(null, null, location.href);

	CommonObj.init();

	$('#ITP_MOBILE_BTN_HOME').on('click', function() {
		$(location).attr('href', MOBILE_CONTEXTPATH + '/app/main.html');
	});

	$('#ITP_MOBILE_BTN_MENU').on('click', function() {
		$('#ITP_MENU').toggle();
	});

	$('#ITP_MOBILE_BTN_SETTING').on('click', function() {
		fn_make_slide_menu.loadPage('SETTING01010', MOBILE_CONTEXTPATH + '/app/setting/SETTING01010.html', null)
		$('#ITP_MENU').toggle();
	});

	$('.ITP_BTN_NAV_CLOSE').on('click', function() {
		$('#ITP_MENU').toggle();
	});

	// 로그아웃 버튼
	$('#ITP_MOBILE_BTN_LOGOUT').click(function() {
		CommonObj.isApp ? location.replace('app:logout') : fnLogout();
	});

	if(VIEW_PAGE !== 'LOGIN' && VIEW_PAGE !== 'PAY') {
		var data = JSON.parse(sessionStorage.getItem('itp_login_info'));
		if(CommonObj.isApp) {
			if(data && data.connKey) {
				console.log("data 1 : ");
				itp_fn_session_data(data.connKey);
			} else {
				console.log("data 2 : ");
				location.replace('app:connKey');
			}
		} else {
			itp_fn_session_data(data.connKey);
		}
	}

});

var itp_fn_session_data = function(connKey) {
	CONN_KEY = connKey; //로그인 했을때 넣었던 키를 가져옴

	var callbackFn = function(result) {
		console.log(result);
		CODE_LIST = result.codeList;
		AUTH_MENU_LIST = result.authMenuList;
		ACT_LIST = result.actList;
		LOGIN_USER_INFO = result.userInfo;

		// 사용자 정보 만들기
		fn_make_user_info.init();

		// 왼쪽 메뉴 만들기
		fn_make_slide_menu.init();

		mobMainObj.init();
	};
	fn_ajax_call('/api/session/data-app', null, callbackFn, 'GET');
};

var itp_fn_logined_check = function(user_nm_update, fn) {
	var now, expiration, data = false;
	data = sessionStorage.getItem('itp_login_info');
	if(data) {
		data = JSON.parse(data);
		now = new Date();
		expiration = new Date(data.timestamp);
		expiration.setMinutes(expiration.getMinutes() + 60);

		if (now.getTime() > expiration.getTime()) {
			data = false;
			fnSessionOut();
		} else {
			sessionStorage.setItem('itp_login_info', JSON.stringify({
				timestamp: new Date(),
				connKey: data.connKey		//Jwt키를 가져와서 세션 스토리지에 저장
			}));
			if(user_nm_update && user_nm_update == true) {
				if (fn !== undefined || typeof fn !== 'undefined') {
					fn();
				}
			}
		}
	} else {
		// 로그인 페이지로 이동
		if($(location).attr('pathname').indexOf('login.html') < 0)
			$(location).attr('href', MOBILE_CONTEXTPATH + '/app/login.html');
	}
};

var fn_make_user_info = {
	init : function() {
		this.set();
	},
	view: function() {
		$('#ITP_LOGIN_USER_NM').text(this.get('userNm'));
		$('#ITP_LOGIN_USER_ID').text(this.get('userId'));
		$('.name_info .fnBrnadNm').text(this.get('brandNm'));
		if(this.get('storeNm') !== '') {
			$('.name_info .fnStoreNm').text(this.get('storeNm'));
		} else {
			$('.name_info .fnLblDash').hide();
			$('.name_info .fnLblStoreNm').hide();
		}
	},
	isEmpty: function() {
		return sessionStorage.getItem('itp_manage_user_info') === null;
	},
	set: function() {
		if(this.isEmpty()) {
			sessionStorage.setItem('itp_manage_user_info', JSON.stringify(LOGIN_USER_INFO));
		} else {
			if(typeof(LOGIN_USER_INFO) == "string") {
				var sessionUserInfo = this.get();
				$.each(JSON.parse(LOGIN_USER_INFO), function(key, value) {
					sessionUserInfo[key] = value;
				});
				sessionStorage.setItem('itp_manage_user_info', JSON.stringify(sessionUserInfo));
			}
		}
		this.view();
	},
	get: function(key) {
		var sessionUserInfo = JSON.parse(sessionStorage.getItem('itp_manage_user_info'));
		return (key === undefined || key === null) ? sessionUserInfo : sessionUserInfo[key];
	}
};

var fn_make_slide_menu = {
	init: function() {
		$('#ITP_SIDEBAR .panel-group').empty();
		this.make();
	},
	make: function() {
		var selector = '#ITP_SIDEBAR .panel-group > .panel-default:last';
		$.each(AUTH_MENU_LIST, function(key, value) {
			if(value.level === 2) { // LEVEL2
				$('#ITP_SIDEBAR .panel-group').append($('#ITP_AJAX_MAIN_SIDE_LEVEL2_ROWCOPY').val());
				$(selector).find('.fnMenuNm').text(value.menuNm);
				$(selector).find('.accordion-toggle').attr('href', '#ITP_NAV_'+value.menuNo);
				$(selector).find('.panel-collapse').attr('id', 'ITP_NAV_'+value.menuNo);
				$(selector).find('.fnLevelBottomList').empty();
			} else if(value.level === 3) { // LEVEL3
				$(selector).find('.fnLevelBottomList').append($('#ITP_AJAX_MAIN_SIDE_LEVEL3_ROWCOPY').val());
				$(selector + ' .fnLevelBottomList .itp_svg_in:last').find('.fnMenuNm').text(value.menuNm);
				$(selector + ' .fnLevelBottomList .itp_svg_in:last').find('.itp_nav_link').attr('data-itp-nav-id', value.menuId);
				$(selector + ' .fnLevelBottomList .itp_svg_in:last').find('.itp_nav_link').attr('data-conn-url', value.connUrl);
				$(selector + ' .fnLevelBottomList .itp_svg_in:last').find('.itp_nav_link').attr('data-open-cd', value.openCd);
				$(selector + ' .fnLevelBottomList .itp_svg_in:last').find('.itp_nav_link').attr('id', value.menuId + '_PAGE_NO');
			}
		});

		this.action();
	},
	action: function() {
		var _this = this;
		$('#ITP_SIDEBAR .accordion-toggle').off('click').on('click', function(e) {
			$(this).find('i.indicator').toggleClass('glyphicon-chevron-down');
		});
		$('#ITP_SIDEBAR .itp_nav_link').off('click').on('click', function() {
			const id = $(this).attr('data-itp-nav-id');
			const connUrl = $(this).attr('data-conn-url');
			const openCd = $(this).attr('data-open-cd');
			console.log('connUrl ===> ' + connUrl);

			if(openCd === 'C') {
				const href = MOBILE_CONTEXTPATH + connUrl;
				_this.loadPage(id, href);
				$('#ITP_MENU').toggle();
			}
		});
		$('#ITP_SIDEBAR .panel-group > .panel-default:first').find('.accordion-toggle').trigger('click');
	},
	loadPage: function(id, href, param) {
		//로그인체크
		itp_fn_logined_check();

		$.ajax({
			contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
			url: href,
			data: param,
			type: 'POST',
			dataType: 'html',
			async: false,
			timeout: 10000,
			beforeSend: function() {
			},
			complete: function() {
			},
			success: function(html) {
				$('#ITP_CONTAINER div.itp_mobile_contents').empty().append(html);
				//JS파일적용
				const js = "<script src=\"../js/app/"+id.substring(0, id.length - 5).toLowerCase()+"/ITP_"+id+".js?version="+js_version+"\"></script>";
				$('#ITP_CONTAINER #ITP_MOBILE_'+id+' #ITP_MOBILE_JS').append(js);
			},
			error: function(xhr, status, error) {
				if (xhr.status == 401) location.href = MOBILE_CONTEXTPATH + '/app/';
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failPage);
			},
			fail: function() {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failPage);
			}
		});
	}
};

function fn_make_select(options, code, select_id, all_show_yn, all_name) { //셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();

	$.each(options, function(key, value) {
		if (value.codeCd == code) {
			if(all_show_yn == undefined || all_show_yn == true) {
				if(all_name == undefined || all_name == '') {
					$('<option/>', {'value': '', 'text': value.codeNm}).prependTo($select_id);
				} else {
					$('<option/>', {'value': '', 'text': all_name}).prependTo($select_id);
				}
			}
			$.each(value.codeDtlList, function(k, val) {
				$('<option/>', {
					'value': val.codeDtlCd,
					'text': val.codeDtlNm
				}).appendTo($select_id);
			});
			return false;
		}
	});
};

function fn_make_select_upper_menu(options, select_id, all_show_yn, all_name) { //셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();
	if(all_show_yn == true) {
		$('<option/>', {'value': '', 'text': all_name}).prependTo($select_id);
	}
	$.each(options, function(key, value) {
		if (value.level == 3) {
			$('<option/>', {
				'value': value.menuNo,
				'text': value.menuNm
			}).appendTo($select_id);
		}
	});
};

function fn_make_select_brand(options, select_id, all_show_yn, all_name) { //브랜드 셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();
	if(all_show_yn == true) {
		$('<option/>', {'value': '', 'text': all_name}).prependTo($select_id);
	}
	$.each(options, function(key, value) {
		$('<option/>', {
			'value': value.brandId,	// 브랜드코드
			'text': value.brandNm	// 브랜드명
		}).appendTo($select_id);
	});
};

function fn_make_select_item_class(options, select_id, all_show_yn, all_name) { //브랜드 셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();
	if(all_show_yn == true) {
		$('<option/>', {'value': '', 'text': all_name}).prependTo($select_id);
	}
	$.each(options, function(key, value) {
		$('<option/>', {
			'value': value.itemClass,	// 브랜드코드
			'text': value.itemClassNm	// 브랜드명
		}).appendTo($select_id);
	});
};

function fn_make_select_store(options, select_id, all_show_yn, all_name, all_value) { //매장 셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();
	if(all_show_yn == true) {
		$('<option/>', {'value': !all_value || all_value == undefined ? '' : all_value, 'text': all_name}).prependTo($select_id);
	}
	$.each(options, function(key, value) {
		$('<option/>', {
			'value': value.storeId,	// 매장번호
			'text': value.storeNm	// 매장명
		}).appendTo($select_id);
	});
}

function fn_make_select_whs(options, select_id, all_show_yn, all_name) { //창고 셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();
	if(all_show_yn == true) {
		$('<option/>', {'value': '', 'text': all_name}).prependTo($select_id);
	}
	$.each(options, function(key, value) {
		$('<option/>', {
			'value': value.whsId,	// 창고아이디
			'text': value.whsNm		// 창고명
		}).appendTo($select_id);
	});
};

function fn_make_select_location(options, select_id, all_show_yn, all_name) { //위치 셀렉트 박스 만들기
	$select_id = $('#' + select_id);
	$select_id.empty();
	if(all_show_yn == true) {
		$('<option/>', {'value': '', 'text': all_name}).prependTo($select_id);
	}
	$.each(options, function(key, value) {
		$('<option/>', {
			'value': value.location,	// 로케이션
			'text': value.locationNm	// 로케이션명
		}).appendTo($select_id);
	});
};

function fnHashed(code) { //유니코드로 들어오는 해쉬키를 스트링으로 변환
	return decodeURIComponent(JSON.parse('"' + code.replace(/\"/g, '\\"') + '"'));
}

function fnLogout() { //로그아웃
	var callbackFn = function(result) {
		sessionStorage.removeItem('itp_login_info'); //Jwt 키 제거
		sessionStorage.removeItem('itp_manage_user_info'); //로그인 사용자 정보 제거
		$(location).attr('href', CommonObj.isApp ? 'app:logout' : MOBILE_CONTEXTPATH + '/app/login.html');
	};
	fn_ajax_call('/api/member/sign-out', null, callbackFn, 'PATCH');
}

function fnSessionOut() { //1시간 동안 아무것도 안할때 또는 강제 만료시킬때 사용
	var callbackFn = function(result) {
		sessionStorage.removeItem('itp_login_info'); //Jwt 키 제거
		sessionStorage.removeItem('itp_manage_user_info'); //로그인 사용자 정보 제거
		$(location).attr('href', CommonObj.isApp ? 'app:logout' : MOBILE_CONTEXTPATH + '/app/login.html');
	};
	fn_ajax_call('/api/session/expire', null, callbackFn, 'PATCH');
}

// 2021.07.07 송호성 추가
function fn_call_popup(type, popnm, container,  popFn, args, returnType) {
	console.log('[ITP_CALL_POPUP] type = ' + type + ', popnm = ' + popnm);
	var contextPath = returnType === 'S' ? ITP_CONTEXTPATH : MOBILE_CONTEXTPATH;
	$.ajax({
		contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
		url: contextPath + '/app/popup/'+type+'/'+popnm+'.html',
		type: 'POST',
		dataType: 'html',
		async: false,
		timeout: 10000,
		beforeSend: function() {
			//$('#ITP_OVERLAY').show();
		},
		complete: function() {
			//$('#ITP_OVERLAY').hide();
		},
		success: function(html) {
			var append = function() {
				var deferred = $.Deferred();
				try {
					$(container).empty();
					$(container).append(html);
					deferred.resolve();
				} catch(err) {
					deferred.reject(err);
				}
				return deferred.promise();
			};
			append().done(function() {
				const js = '<script src="'+contextPath+'/js/app/popup/'+type+'/ITP_'+popnm+'.js?version='+js_version+'"></script>';
				$('#ITP_ASIDE #ITP_'+popnm+' #ITP_POPUP_JS').empty();
				$('#ITP_ASIDE #ITP_'+popnm+' #ITP_POPUP_JS').append(js);

				eval('itp_fn_' + popnm)(popFn, args, returnType);
				$('.modal.itp_modal .modal-content').draggable();
			});
		},
		error: function(xhr, status, error) {
			if (xhr.status == 401) location.href = contextPath + '/';
			itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failData);
		},
		fail: function() {
			itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failData);
		}
	});

};

//AJAX 양식 (이렇게 사용하시면 됩니다.)
function fn_ajax_call(href, param, fn, type, errFn) {
	$.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();
			var data = JSON.parse(sessionStorage.getItem('itp_login_info'));
			xhr.setRequestHeader('X-AUTH-TOKEN', (data) ? data.connKey : null); //Jwt 토큰을 헤더에 담아서 보낸다.
			// 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', MOBILE_CONTEXTPATH + '/app/login.html');
				}
			} else {
				itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failProcess);
			}
			if (errFn !== undefined || typeof errFn !== 'undefined') errFn();
		},
		fail: function() {
			itp_fn_modal_alert_ajax(ITP_MSG_LOCALE.message.ajax.failProcess);
			if (errFn !== undefined || typeof errFn !== 'undefined') errFn();
		}
	});
};

function itp_fn_modal_alert(msg) {
	$('#ITP_MODAL_ALERT_CANCEL').hide();
	$('#ITP_MODAL_ALERT').modal('show');
	$('#ITP_MODAL_ALERT').find('.itp_alert_txt').html(msg);
	$('#ITP_MODAL_ALERT_CONFIRM').off('click');
	$('#ITP_MODAL_ALERT_CONFIRM').on('click', function() {
		$('#ITP_MODAL_ALERT').modal('hide');
	});
};

function itp_fn_modal_alert_ajax(msg) {
	$('#ITP_MODAL_ALERT_AJAX').modal('show');
	$('#ITP_MODAL_ALERT_AJAX').find('.itp_alert_txt').html(msg);
	$('#ITP_MODAL_ALERT_AJAX_CONFIRM').off('click');
	$('#ITP_MODAL_ALERT_AJAX_CONFIRM').on('click', function() {
		$('#ITP_MODAL_ALERT_AJAX').modal('hide');
	});
};

function itp_fn_modal_duplicate(label, input) {
	let msg = ITP_MSG_LOCALE.message.form.duplicate;
	msg = msg.replace('{0}', label);
	$('#ITP_MODAL_ALERT_CANCEL').hide();
	$('#ITP_MODAL_ALERT').modal('show');
	$('#ITP_MODAL_ALERT').find('.itp_alert_txt').html(msg);
	$('#ITP_MODAL_ALERT_CONFIRM').off('click');
	$('#ITP_MODAL_ALERT_CONFIRM').on('click', function() {
		$('#ITP_MODAL_ALERT').modal('hide');
		if (input != null) {
			$(input).focus();
		}
	});
};

function itp_fn_modal_confirm(msg, fn, args) {
	$('#ITP_MODAL_ALERT_CANCEL').show();
	$('#ITP_MODAL_ALERT').modal('show');
	$('#ITP_MODAL_ALERT').find('.itp_alert_txt').html(msg);
	if (fn !== undefined || typeof fn !== 'undefined') {
		$('#ITP_MODAL_ALERT_CONFIRM').off('click');
		$('#ITP_MODAL_ALERT_CONFIRM').on('click', function() {
			fn.callBack(args);
			$('#ITP_MODAL_ALERT').modal('hide');
		});
	}
}

function itp_fn_modal_empty(msg) {
	$('#ITP_MODAL_NOT_INPUT').hide();
	$('#ITP_MODAL_NOT_INPUT').modal('show');
	$('#ITP_MODAL_NOT_INPUT').find('.fnNotInput').html(msg);
	$('#ITP_MODAL_NOT_INPUT_CONFIRM').off('click');
	$('#ITP_MODAL_NOT_INPUT_CONFIRM').on('click', function() {
		$('#ITP_MODAL_NOT_INPUT').modal('hide');
	});
};

let itp_fn_form_validate = function(form, element, arry, msg, type) {
	var error = function(txt) {
		if (type != 'ONLYCHK') {
			if (msg == undefined || typeof msg == 'undefined') {
				msg = txt;
			}

			$(element).closest('.itp_ip').addClass('has-error');
			var error_msg = $('<span class="help-block">' + msg + '</span>');
			if($(element).parent('.input-group').length) {
				error_msg.insertAfter($(element).parent());
			} else {
				error_msg.insertAfter($(element));
			}
		}
	};

	if ($.inArray('empty', arry) > -1) {
		if ($(element).val() == '' || $(element).val() < 1) {
			error(ITP_MSG_LOCALE.message.form.mandatory);
			return false;
		}
	}

	if ($.inArray('emptyNum', arry) > -1) {
		if ($(element).val() == '' || $(element).val() < 0) {
			error(ITP_MSG_LOCALE.message.form.mandatory);
			return false;
		}
	}

	if ($.inArray('number', arry) > -1) {
		const regExp = /^[0-9]+$/;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.onlynumber);
			return false;
		}
	}

	if ($.inArray('float', arry) > -1) {
		if($(element).val() == '') return true;
		const regExp = /^\d+.?\d?\d?\d?$/;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.onlynumber);
			return false;
		}
	}

	if ($.inArray('tel', arry) > -1) {
		const regExp = /^\d{2,3}-\d{3,4}-\d{4}$/;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.wrongtelnumber);
			return false;
		}
	}

	if ($.inArray('email', arry) > -1) {
		const regExp = /^[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*@[0-9a-zA-Z]([-_\.]?[0-9a-zA-Z])*\.[a-zA-Z]{2,3}$/i;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.wrongemail);
			return false;
		}
	}

	if ($.inArray('id', arry) > -1) {
		const regExp = /^[a-z]+[a-z0-9]{4,11}$/g;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.wronguserid);
			return false;
		}
	}

	if ($.inArray('id2', arry) > -1) {
		const regExp = /^[A-Za-z0-9+]*$/;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.wronguserid2);
			return false;
		}
	}

	if ($.inArray('password', arry) > -1) {
		const regExp = /^(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])(?=.*[0-9]).{8,16}$/;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.wrongpassword);
			return false;
		}
	}

	if ($.inArray('url', arry) > -1) {
		const regExp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/;
		if (!regExp.test($(element).val())) {
			error(ITP_MSG_LOCALE.message.form.wronglink);
			return false;
		}
	}

	return true;
};

let itp_fn_form_clear_validate = function(modal, form) {
	$(form).find('.itp_ip').removeClass('has-error');
	$(form).find('.help-block').remove();

	if (modal != null) {
		$(modal).on('hidden.bs.modal', function() {
			$(form).find('.itp_ip').removeClass('has-error');
			$(form).find('.help-block').remove();
		});
	}
};

let itp_fn_form_event = {
	onKeyup: function(formId) {
		$(formId).find('input[data-key-up]').on('keyup', function() {
			let value = '';
			let arry = $(this).data('key-up').split(',');
			if ($.inArray('number', arry) > -1) {
				value = $(this).val().replace(/[^0-9]/g, "");
			}
			if ($.inArray('comma', arry) > -1) {
				value = $(this).val().replace(/[^0-9]/g, "")
					.replace(/\B(?=(\d{3})+(?!\d))/g, ",");
			}
			if ($.inArray('regNo', arry) > -1) {
				value = $(this).val().replace(/[^0-9]/g, "")
					.replace(/(^[0-9]{3}|^0[0-9]{2})([0-9]+)?([0-9]{5})$/,"$1-$2-$3")
			}
			if ($.inArray('corpNo', arry) > -1) {
				if($(this).val().length > 13) return;
				value = $(this).val().replace(/[^0-9]/g, "")
					.replace(/(^[0-9]{6})([0-9]+)?([0-9]{7})$/,"######-#######")
			}
			if ($.inArray('tel', arry) > -1) {
				value = ($(this).val().startsWith('0')) ? $(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("--", "-") : '';
			}
			$(this).val(value);
		});
	},
	removeChar: function(formId) {
		$(formId).find('input[data-key-up]').each(function() {
			$(this).val($(this).val().replace(/[^0-9]/g, ""));
		});
	},
	isValid: function(formId, type) {
		var isValid = false;
		$(formId).find('input, select, checkbox, textarea').each(function(k) {
			if($(this).data('check-required')) {
				var arry = $(this).data('check-required').split(',');
				var alertMsg = $(this).data('alert-required');
				isValid = itp_fn_form_validate(formId, '#' + $(this).attr('id'), arry, undefined, alertMsg);
				if(!isValid) {
					if(alertMsg && alertMsg.length > 0) {
						itp_fn_modal_empty($(this).data('alert-msg'));
					}
					return false;
				}
			}
		});
		return isValid;
	}
};

let itp_fn_payment = {
	call: function(param, fn) {
		this.popup(param, fn);
	},
	popup: function(param, fn) {
		// 결제 팝업 결과
		var popFn = function(rowDataPop) {
			if(fn) fn(rowDataPop);
		};
		// 결제 팝업
		// 결제타입코드 : 10(선불(충전)), 20(후불(결제)), 30(후불(선결제))
		var args = {
			'payTpCd': param.loanDvsn,
			'brandId': param.brandId,
			'storeId': param.storeId
		};
		fn_call_popup('biz', 'BIZPOP_PO_PAYMENT', '#ITP_ASIDE', popFn, args, 'M');
	}
};

let itp_fn_call_app = {
	barcode: function() {
		location.replace('app:barcode');
	},
	payment: function(param) {
		location.replace('app:payment:' + param);
	},
	backPress: function() {
		location.replace('app:pageBack');
	}
};

let CommonObj = {
	listSize: 10,
	jsonParam: function(formId) {
		const param = $(formId).serializeObject();
		param.gridSize = this.listSize;
		return JSON.stringify(param);
	},
	init: function() {

		$('.modal.itp_modal .modal-content').draggable();

		$.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;
		// 			});
		// 		});
		// 	}
		// });

	},
	moreView: function(id, isScroll, fn) {
		if(isScroll) {
			$(id).off('scroll').on('scroll', function () {
				if($(this).scrollTop() + $(this).innerHeight() + 1 >= $(this)[0].scrollHeight) {
					fn();
				}
			});
		} else {
			$(id).off('scroll');
		}
	},
	getParameter: function(name) {
		var rtnval = '';
		var nowAddress = unescape(location.href);
		var parameters = (nowAddress.slice(nowAddress.indexOf('?') + 1,
			nowAddress.length)).split('&');
		for (var i = 0; i < parameters.length; i++) {
			var varName = parameters[i].split('=')[0];
			if (varName.toUpperCase() === name.toUpperCase()) {
				rtnval = parameters[i].split('=')[1];
				break;
			}
		}
		return rtnval;
	},
	comma: {
		set: function(str) {
			return String(str).replace(/(\d)(?=(?:\d{3})+(?!\d))/g, '$1,');
		},
		remove: function(str) {
			return String(str).replace(/[^\d]+/g, '');
		}
	},
	currency: {
		add: function(val, curr) {
			return CommonObj.comma.set(val).concat((curr === undefined) ? '원' : curr);
		},
		remove: function(val) {
			return val.replace(/[^0-9]/g, '');
		}
	},
	onlyNumber: function(str) {
		return (str) ? str.replace(/[^0-9]/g, '') : str;
	},
	nullToString: function(value) {
		return (value == null || value.length === 0) ? '' : value;
	},
	isPayPossible: function() {
		return (fn_make_user_info.get('apprYn') === 'Y');
	},
	btnPay: function(id) {
		return this.isPayPossible() ? $(id).show() : $(id).hide();
	},
	schWhsDvsn: function(isEmpty) {
		return (fn_make_user_info.get('authTpCd') === '50') ? 'W02' : isEmpty ? '' : 'W01';
	},
	appInfo: {
		object: function() {
			return JSON.parse(sessionStorage.getItem('itp_manage_app_info'));
		},
		set: function(strInfo) {
			sessionStorage.setItem('itp_manage_app_info', strInfo);
		},
		get: function(key) {
			return (key === undefined || key === null) ? '' : CommonObj.isApp ? this.appInfo.object()[key] : '';
		}
	},
	isApp: (/oqpo_android|oqpo_ios/).test(navigator.userAgent.toLowerCase())
};

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 if(type && type == 2) {
		return date.getFullYear() + '.' + month + '.' + day;
	} else if(type && type == 3) {
		return date.getFullYear() + '' + month + '' + day;
	} else if(type && type == 4) {
		return date.getFullYear() + '-' + month + '-' + day;
	} else {
		return date.getFullYear() + month + day + hour + minute + second;
	}
}

function itp_fn_date_add(type, iAdd) {
	var date = new Date();
	if(type === 'Y') date.setFullYear(date.getFullYear() + iAdd);
	else if(type === 'M') date.setMonth(date.getMonth() + iAdd);
	else if(type === 'D') date.setDate(date.getDate() + iAdd);
	return itp_fn_date_format(date, 2);
}

function itp_fn_fire_window_resize() {
	var evt = document.createEvent('HTMLEvents');
	evt.initEvent('resize', true, false);
	window.dispatchEvent(evt);
};

const ITP_DATE_LANGUAGE = (function() {
	let lang = ITP_LANGUAGE;
	if (lang == 'en') {lang = ITP_LANGUAGE + '-GB';}
	var agrs = {language: lang};
	return agrs;
}());
