/*
 * Common Java Script by gagamel
 *
 * Copyright (c) 2010 gagamel
 * Dual licensed under the MIT (MIT-LICENSE.txt)
 * and GPL (GPL-LICENSE.txt) licenses.
 *
 * $Date: 2019-08-06 $
 */

/**
 * 로그인메뉴목록을 sessionStorage에 담는다.
 */
let cfnSetLoginMenuList = function(loginMenuList) {
	sessionStorage.setItem('loginMenuList', JSON.stringify(loginMenuList));
}

/**
 * sessionStorage에 담긴 메뉴정보를 가져온다.
 */
let cfnGetMenuInfo = function(menuId) {
	let loginMenuList = JSON.parse(sessionStorage.loginMenuList);
	
	let menu = '';

	loginMenuList.forEach(function(item) {
		if (menuId == item.menuId) {
			menu = item;
			return false;
		}
	});

	return menu;
}

/**
 * LNB메뉴 그리기
 */
let cfnDrawLnbMenu = function(gnbMenuId) {
	let loginMenuList = JSON.parse(sessionStorage.loginMenuList);
	
	let lnbTag = '<li>\n';
	
	$.each(loginMenuList, function(idx1, item1) {
		if (gnbMenuId == item1.pmenuId) {
			if (item1.leafLvl == 0) {
				//lnbTag += '	<a class="dep2" attr="data-url=' + item1.menuUrl + '">\n';
				lnbTag += '	<a class="dep2" href="javascript:void(0);" onclick="fnClickLnb(\'' + item1.menuId + '\');">\n';
			} else {
				lnbTag += '	<a class="dep2">\n';
			}
			
			/* lnbTag += '		<i class="fa fa-shopping-cart"></i>\n';
			lnbTag += '		<span class="nav-label"> ' + item1.menuNm + '</span>\n';
			lnbTag += '		<i class="mnArrow fa fa-angle-down"></i>\n'; */
			lnbTag += item1.menuNm + '\n';
			lnbTag += '	</a>\n';
			
			if (item1.leafLvl > 0) {
				lnbTag += '	<ul class="dep3">\n';
				
				$.each(loginMenuList, function(idx2, item2) {
					if (item1.menuId == item2.pmenuId) {
						lnbTag += '		<li>\n';
						//lnbTag += '			<a href="javascript:void(0);" attr="data-url=' + item2.menuUrl + '"><span>' + item2.menuNm + '</span></a>\n';
						lnbTag += '			<a href="javascript:void(0);" onclick="fnClickLnb(\'' + item2.menuId + '\');"><span>' + item2.menuNm + '</span></a>\n';
						lnbTag += '		</li>\n';
					}
				});
				
				lnbTag += '	</ul>\n';
			}
		}
	});
	
	lnbTag += '</li>\n';
	
	$('#lnb').html(lnbTag);
}

/**
 * @type   : function
 * @access : public
 * @desc   : Combobox 구성
 * <pre>
 *     cfnCreateCombo("/renderer/company/brand/list", oTarget, "[선택]");
 * </pre>
 * @param  : actionUrl - URL. 필수
 *           oTarget - target 오브젝트. 필수
 *           defaultTxt - default 텍스트([선택]/[전체]). option
 *           chooseCd - 선택된 코드 값. option
 *           isCodeDisp - 코드표시(true/false). option
 * @return : None
 * @since  : 2019/06/07
 * @author : gagamel
 */
var cfnCreateCombo = function(actionUrl, oTarget, defaultTxt, chooseCd, isCodeDisp) {
	if (gagajf.isNull(isCodeDisp)) isCodeDisp = true;

	$.getJSON(actionUrl
		, function(result, status) {
			if (status == 'success') {
				$('option', oTarget).remove();

				if (!gagajf.isNull(defaultTxt)) {
					$(oTarget).append('<option value="">' + defaultTxt + '</option>');
				}

				$.each(result, function(idx, data) {
					var tag = '<option value="' + data.cd + '"';

					if (!gagajf.isNull(chooseCd) && chooseCd == data.cd) {
						tag += ' selected';
					}

					if (isCodeDisp) {
						tag += '>[' + data.cd + '] ' + data.cdNm + '</option>';
					} else {
						tag += '>' + data.cdNm + '</option>';
					}

					$(oTarget).append(tag);
				});
			}
		});
}


/**
 * @type   : function
 * @access : public
 * @desc   : MultiCombobox 구성
 * <pre>
 *     cfnCreateCombo("/renderer/company/brand/list", oTarget, "[선택]");
 * </pre>
 * @param  : actionUrl 	- URL. 필수
 *           oTarget 	- target 오브젝트. 필수
 *           defaultTxt - default 텍스트([선택]/[전체]). option
 *           chooseValArr 	- 선택된 코드 값. option arr
 *           isCodeDisp - 코드표시(true/false). option
 *           isAllYn    - 전체선택 존재여부. option
 *           searchParams - . option
 *           formId -  target 오브젝트의 formId. option
 *
 * @return : None
 * @since  : 2019/06/07
 * @author : gagamel
 */
var cfnCreateMultiCombo = function(actionUrl, oTarget, defaultTxt, chooseValArr, isCodeDisp, isAllYn, searchParams, formId){

	var opt = {};
		opt.actionUrl 	 = actionUrl;		//컨트롤러 URL
		opt.oTarget 	 = oTarget;			//타겟DIV
		opt.defaultTxt 	 = defaultTxt;		//디폴트 텍스트 기본 = 선택
		opt.chooseValArr = chooseValArr;	//기존 체크될 데이터
		opt.isCodeDisp   = isCodeDisp;		//[코드] 값 표현여부
		opt.isAllYn 	 = isAllYn;			//전체선택버튼 존재여부 Y:N
		opt.params		 = searchParams;	//조회시 파라미터 (json타입)
		opt.formId		 = formId;			//화면 formId

	var html = "";
	var isChecked = "";

	if(opt.actionUrl){
		$.getJSON(opt.actionUrl
				, opt.params
				, function(result, status) {
					if (status == 'success') {
						opt.dataArr = result;

						html += '<div class="multiCheckBox" style="width:230px">';
						html += '	<button type="button" class="sltBtn" style="overflow-x: hidden; padding-right:5px;">'+opt.defaultTxt+'</button>';
						html += '	<ul style="display: none; box-shadow: 3px 3px 3px; overflow-y:scroll;">';
						if(opt.isAllYn){
							html += '		<li><label class="chkBox"><input type="checkbox" name="전체선택" id="'+opt.oTarget+'" onclick="uifnAllCheck(\''+opt.oTarget+'\')">전체선택</label></li>';
						}
						for(var i in opt.dataArr){
							for(var idx in chooseValArr){
								if(opt.dataArr[i] == chooseValArr[idx]){
									isChecked = "checked";
								}else{
									isChecked = "";
								}
							}
							if(opt.isCodeDisp){
								html += '		<li><label class="chkBox"><input type="checkbox" name="'+opt.oTarget+'" value="'+opt.dataArr[i].cd+'" '+isChecked+'>['+opt.dataArr[i].cd+']'+opt.dataArr[i].cdNm+'</label></li>';
							}else{
								html += '		<li><label class="chkBox"><input type="checkbox" name="'+opt.oTarget+'" value="'+opt.dataArr[i].cd+'" '+isChecked+'>'+opt.dataArr[i].cdNm+'</label></li>';
							}
						}
						html += '	</ul>';
						html += '</div>';

						if (opt.formId) {
							$("#"+opt.formId).find("#"+opt.oTarget).html(html);
						}else{
							$("#"+opt.oTarget).html(html);
						}


						//높이조절 10개 이상시 스크롤생성
						var height = ((opt.dataArr.length + (opt.isAllYn?1:0)) * 28) > 308 ? 308 : ((opt.dataArr.length + (opt.isAllYn?1:0)) * 28);
						$("#"+opt.oTarget).find("ul").height(height);
					}
				});
	}
}

/**
 * @type   : function
 * @access : public
 * @desc   : Checkbox 구성
 * <pre>
 *     cfnCreateCheckbox("/renderer/company/brand/list", $('#div0'), "brandMngIdx", callBackFun);
 * </pre>
 * @param  : actionUrl - URL. 필수
 *           oTarget - target 오브젝트. 필수
 *           checkboxNm - 체크박스명. 필수
 * @return : None
 * @since  : 2019/06/14
 * @author : gagamel
 */
var cfnCreateCheckbox = function(actionUrl, oTarget, checkboxNm, callBackFun) {
	$.getJSON(actionUrl
		, function(result, status) {
			if (status == 'success') {
				$(oTarget).html('');
				$.each(result, function(idx, data) {
					$(oTarget).append('<label class="chkBox"><input type="checkbox" name="' + checkboxNm + '" value="' + data.cd + '"/>' + data.cdNm + '</label>');
				});

				if (typeof(callBackFun) != 'undefined')
					callBackFun.call();
			}
		});
}

/**
 * @type   : function
 * @access : public
 * @desc   : 다중 select의 선택된 값을 표시
 * <pre>
 *     cfnShowMultiSelectedValue($('#detailForm select[name=roleDiv]'), "M,S,D");
 * </pre>
 * @param  : objToShow - 표시할 다중 select 객체
 * @param  : values - 다중 선택된 값(콤마(,)로 연결). 예) M,S,D
 * @since  : 2019/06/04
 * @author : gagamel
 */
var cfnShowMultiSelectedValue = function(objToShow, values) {
	// 기존 선택된 옵션 값 초기화
	$.each($('option', objToShow), function() {
		$(this).prop('selected', false);
	});

	var mSelect = $(objToShow).parent()

	$.each($(mSelect).find('.mSelected > li'), function() {
		if (!$(this).hasClass('off') && !$(this).hasClass('srchFld')) {
			$(this).addClass('off');
		}
	});

	$.each($(mSelect).find('.mSelecting > ul > li'), function() {
		if ($(this).hasClass('off')) {
			$(this).removeClass('off');
		}
	});
	// 기존 선택된 옵션 값 초기화

	$.each($('option', objToShow), function(idx1) {
		var obj = $(this);
		
		if (gagajf.isNull(values)) return;
		
		$.each(values.split(','), function(idx2, item2) {
			if ($(obj).val() == item2) {
				$(obj).prop('selected', true);
				$(mSelect).find('.mSelected > li').eq(idx1).removeClass('off');
				$(mSelect).find('.mSelecting > ul > li').eq(idx1).addClass('off');
			}
		});
	});
}

/**
 * @type   : function
 * @access : public
 * @desc   : Tab의 idx 번째를 show
 * <pre>
 *     cfnShowTab($('.nav-tabs > li').eq(2));
 * </pre>
 * @param  : objToShow - 보여줄 객체
 * @param  : idx - index
 * @since  : 2019/03/31
 * @author : gagamel
 */
var cfnShowTab = function(objToShow) {
	//$(objToShow).removeClass('on');
	$(objToShow).siblings().removeClass('on');
	$(objToShow).addClass('on');
	$(objToShow).find('a').trigger('click');
}

/**
 * Global Ajax Error Handler
 */
/*$(document).ajaxError(function(event, jqxhr, settings, thrownError) {
	if (jqxhr.status !== 200) { // 404("Not Found"), 500("Internal Server Error") and ...
		// 에러 처리 함수가 등록 안되어 있는 경우
		if (settings && typeof settings.error !== 'function') {
			// $(Element).load() 호출 시 에러가 발생할 경우 '/error'로 이동
			if (settings.dataType == 'html') {
				window.location.replace("/error");
			} else {
				alert('요청이 진행되지 못했습니다\n죄송합니다, 에러가 발생했습니다.');
			}
		}

	}
});*/

/**
 * @type   : function
 * @access : public
 * @desc   : 기간(from ~ to)로 날짜 구성
 * <pre>
 *     cfnCreateCalendar('#sellTerms', 'startDt', 'endDt', true, '판매');
 * </pre>
 * @param  : tgtId - 만들어진 tag를 표시할 Target ID
 * @param  : dtFromId - 시작일자 ID
 * @param  : dtToId - 종료일자 ID
 * @param  : isRequired - 검색조건 필수여부. 옵션
 * @param  : validName - 유효성검증 시 사용되는 명칭. isRequired 값이 true일 때만 사용. 옵션
 * @since  : 2019/09/09
 * @author : gagamel
 */
function cfnCreateCalendar(tgtId, dtFromId, dtToId, isRequired, validName, empty, hideList) {
	var tag = '';
	tag += '<span class="nowrap">\n';
	tag += '	<input name="' + dtFromId + '" id="' + dtFromId + '" type="text" class="w80 schDate" maxlength="10"' + ((typeof(isRequired) != "undefined" && isRequired) ? " required=\"required\"" : "") + ' data-valid-name="' + validName + '시작일시" data-valid-type="calendar"/>\n';
	tag += '	~\n';
	tag += '	<input name="' + dtToId + '" id="' + dtToId + '" type="text" class="w80 schDate" maxlength="10"' + ((typeof(isRequired) != "undefined" && isRequired) ? " required=\"required\"" : "") + ' data-valid-name="' + validName + '종료일시" data-valid-type="calendar"/>\n';
	tag += '</span>\n';
	if(typeof empty!='undefined'){
		tag += '<button type="button" class="btn btn-default btn-sm btnCel3m" onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'\');">기간X</button>\n';
	}
	tag += '<button type="button" class="btn btn-default btn-sm btnToday" 		onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'t\');">오늘</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnYesterday" 	onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'y\');">어제</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnRecentWeek" 	onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'7d\');">최근한주</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnThisWeek" 	onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'tw\');">이번주</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnYesterWeek" 	onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'pw\');">지난주</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnRecentMonth" onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'1m\');">최근한달</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnThisMonth" 	onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'tm\');">이번달</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnYesterMonth" onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'pm\');">지난달</button>\n';
	tag += '<button type="button" class="btn btn-default btn-sm btnRecent3Month" onclick="gagajf.setDate(\'' + tgtId+'\', \'' + dtFromId + '\', \'' + dtToId + '\', \'3m\');">최근3개월</button>\n';
	$(tgtId).html(tag);

	if(hideList && hideList.length > 0){
		for(var i in hideList){
			$(tgtId+" ."+hideList[i]).hide();
		}
	}

	$(tgtId + ' .schDate').datepicker({
		changeMonth: true,
		changeYear: true,
		firstDay: 0,
		defaultDate: $(tgtId + '.schDate').val(),
		onSelect: function(){
			var fromVal = Number($(tgtId+" #"+dtFromId).val().replace(/-/gi, ''));
			var toVal = Number($(tgtId+" #"+dtToId).val().replace(/-/gi, ''));
			if($(this).val()==""){
				return;
			}
			if($(this).attr("id")==dtFromId){
				if($(tgtId+" #"+dtToId).val()!=""){
					if(fromVal>toVal){
						mcxDialog.alert('시작일자가 종료일자보다 큽니다.');
						$(tgtId+" #"+dtFromId).val('');
						$(tgtId+" #"+dtFromId).focus();
					}
				}
			}else{
				 if($(tgtId+" #"+dtFromId).val()!=""){
					if(fromVal>toVal){
						mcxDialog.alert('종료일자가 시작일자보다 작습니다.');
						$(tgtId+" #"+dtToId).val('');
						$(tgtId+" #"+dtToId).focus();
					}
				}
			}
		}
	});

	$(tgtId+" #"+dtFromId).off("blur");
	$(tgtId+" #"+dtFromId).on("blur", function(){
		var fromVal = Number($(tgtId+" #"+dtFromId).val().replace(/-/gi, ''));
		var toVal = Number($(tgtId+" #"+dtToId).val().replace(/-/gi, ''));
		if($(this).val()==""){
			return;
		}else if($(tgtId+" #"+dtToId).val()!=""){
			if(fromVal>toVal){
				mcxDialog.alert('시작일자가 종료일자보다 큽니다.');
				$(tgtId+" #"+dtFromId).val('');
				$(tgtId+" #"+dtFromId).focus();
			}
			$(this).change();
		}
	});
	$(tgtId+" #"+dtToId).off("blur");
	$(tgtId+" #"+dtToId).on("blur", function(){
		var fromVal = Number($(tgtId+" #"+dtFromId).val().replace(/-/gi, ''));
		var toVal = Number($(tgtId+" #"+dtToId).val().replace(/-/gi, ''));
		if($(this).val()==""){
			return;
		}else if($(tgtId+" #"+dtFromId).val()!=""){
			if(fromVal>toVal){
				mcxDialog.alert('종료일자가 시작일자보다 작습니다.');
				$(tgtId+" #"+dtToId).val('');
				$(tgtId+" #"+dtToId).focus();
			}
			$(this).change();
		}
	});
}

/**
 * @type   : function
 * @access : public
 * @desc   : 기간으로 조회시 날짜지정
 * <pre>
 *     cfnChangeCalendar('diff','obj1','obj2','dateFormat');
 * </pre>
 * @param  : diff - 날짜간격(3m : 최근 3개월 , 1m : 최근 한달, 1d : 오늘, -1d : 어제, 7d : 최근 한 주, tw : 이번주, lw : 지난주, tm : 이번달, lm : 지난달)
 * @param  : obj1 - 시작날짜 오브젝트
 * @param  : obj2 - 종료날짜 오브젝트
 * @param  : dateFormat - 날짜형식
 * @since  : 2019/07/02
 * @author : yhkim
 */
function cfnChangeCalendar(diff, obj1, obj2, dateFormat) {
	var sdt = new Date();
	var edt = new Date();

	var smonth = sdt.getMonth();
	var sday = sdt.getDate();

	var emonth = edt.getMonth();

	var weekday = sdt.getDay();

	if (diff == '3m') {
		sdt.setMonth(smonth - 3);
	} else if (diff == '1m') {
		sdt.setMonth(smonth - 1);
	} else if (diff == '7d') {
		sdt.setDate(sday - 7);
	} else if (diff == '1d') {
		sdt.setDate(sday);
	} else if (diff == '-1d') {
		sdt.setDate(sday - 1);
		edt.setDate(sday - 1);
	} else if (diff == 'tw') {
		sdt.setDate(sday - weekday);
		edt.setDate(edt.getDate() - weekday + 6);
	} else if (diff == 'lw') {
		sdt.setDate(sday - weekday - 7);
		edt.setDate(edt.getDate() - weekday - 1);
	} else if (diff == 'tm') {
		sdt.setDate(1);
		edt.setMonth(emonth + 1);
		edt.setDate(0);
	} else if (diff == 'lm') {
		sdt.setMonth(smonth - 1);
		sdt.setDate(1);
		edt.setMonth(emonth);
		edt.setDate(0);
	} else {
		$('#sdate').val('');
		$('#edate').val('');
		return;
	}

	var syear = sdt.getFullYear();
	smonth = sdt.getMonth()+1;
	smonth = ((smonth < 10) ? "0" + smonth : smonth);
	sday = sdt.getDate();
	sday = ((sday < 10) ? "0" + sday : sday);

	var delimiter = "-";
	if (dateFormat == "yymmdd") delimiter = "";

	obj1.val(syear + delimiter + smonth + delimiter + sday);

	var eyear = edt.getFullYear();
	emonth = edt.getMonth()+1;
	emonth = ((emonth < 10) ? "0" + emonth : emonth);
	var eday = edt.getDate();
	eday = ((eday < 10) ? "0" + eday : eday);

	obj2.val(eyear + delimiter + emonth + delimiter + eday);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 입력 필드의 문자열 길이를 체크한다.
 * <pre>
 *     cfnGetTextLength($('#msgContents'), 90, $('#dpLoc'));
 * </pre>
 * @param  : obj - 입력필드 오브젝트
 * @param  : maxLen - 최대길이(bytes 수)
 * @param  : dpLoc - optional. 현재의 길이를 표시할 곳
 * @return : None
 * @since  : 2019/07/22
 * @author : gagamel
 */
var cfnGetTextLength = function(obj, maxLen, dpLoc) {
	var valLen = $(obj).val().length;
	var cByte = 0;
	var sliceLen = 0;

	for (i = 0; i < valLen; i++) {
		var aChar = $(obj).val().charAt(i);
		if (escape(aChar).length == 6) {
			cByte += 3; //한글이면 3를 더한다
		} else if (aChar == '\n') {
			cByte += 2; //엔터면 2을 더한다
		} else {
			cByte++; //한글아니면 1을 더한다
		}

		if (cByte <= maxLen) {
			sliceLen = i + 1;
		}
	}

	// 사용자가 입력한 값이 제한 값을 초과하는지를 검사한다.
	if (parseInt(cByte) > parseInt(maxLen)) {
		mcxDialog.alert('허용된 글자수가 초과되었습니다.\n초과된 부분은 자동으로 삭제됩니다.');
		//var orgStr = $(obj).val();
		var slicedStr = $(obj).val().substr(0, sliceLen);
		$(obj).val(slicedStr);
		var cByte = 0;
		for (i = 0; i < $(obj).val().length; i++) {
			var aChar = $(obj).val().charAt(i);
			if (escape(aChar).length == 6) {
				cByte += 3; //한글이면 3를 더한다
			} else if (aChar == '\n') {
				cByte += 2; //엔터면 2을 더한다
			} else {
				cByte++; //한글아니면 1을 더한다
			}
		}
	}

	$(dpLoc).text(cByte.addComma());
}


/**
 * @type   : function
 * @access : public
 * @desc   : 셀렉트박스 년도 설정
 * <pre>
 *     cfnDateYearSetting('usacYear', 5);
 * </pre>
 * @param  : elTarget - 셀렉트박스id
 * @param  : targetYear - +- 설정 년도
 * @since  : 2019/10/17
 * @author : rladbwnd5
 */
var cfnDateYearSetting = function(elemetId,targetYear) {
	var currentYear = (new Date()).getFullYear();
	var optionHtml = "";

	optionHtml += '<option value="">[전체]</option>';
	for (var year = currentYear-targetYear; year <= currentYear+targetYear; year++) {
		optionHtml += '<option value="'+year+'">'+year+'년'+'</option>\n';
	}
	$('#'+elemetId).append(optionHtml);
};



/**
 * @type   : function
 * @access : public
 * @desc   : JQuery를 이용한 비동기 submit 처리
 *           파라미터의 명칭은 쿼리문과 동일하게 작성해야 한다.
 * <pre>
 *     var params = new Object();
 *     params.cmd = "getCodeDetailComboList";
 *     params.GROUP_CD = "G900";
 *     params.CODE = "0202";
 *
 *     cfnAjaxSubmit("/renderer.do", "json", jfCallback, params);
 *
 *     or
 *
 *     cfnAjaxSubmit("/renderer.do", "json", jfCallback);
 * </pre>
 * @param  : actionUrl - action url. 필수
 *           type - 처리결과 형식(text, html, xml, json). 필수
 *           callback - type이 text, xml, json 일 때는 콜백함수명
 *                      type이 html일 때는 target명. 필수
 *           params - 파라미터 오브젝트. 옵션
 * @return : None
 * @since  : 2014/10/14
 * @author : gagamel
 */
var cfnAjaxSubmit = function(actionUrl, type, callback, params) {
	if (!params) params = new Object();
	$.post(actionUrl
		, $.param(params)
		, function(result) {
			if (type == "html") {
				if (!gagajf.isNull(callback))
					$(document.getElementById(callback)).html(result);
					$('.schDate').datepicker({
						changeMonth: true,
						changeYear: true,
						defaultDate: $('.schDate').val()
					});
			} else {
				// Callback 함수 호출
				if (typeof(callback) == "function")
					callback.call(this, result);
			}
		}
		, type);
}

/**
 * @type   : function
 * @access : public
 * @desc   : Form 객체를 가지고 JQuery를 이용한 비동기 Submit 처리
 * <pre>
 *     cfnAjaxSubmitForm($('#formId'), "/base/rest/adminuser/create", "json", jfCreateAdminUserResult);
 * </pre>
 * 위와같이 사용했을 경우 true를 리턴한다.
 * @param  : formId - document form ID
 *           actionUrl - The URL to submit
 *           type - The data's type(text, html, xml, json, jsonp)
 *           callback - This attribute is optional.
 *               If type is 'html' then it is target's name when the result success.
 *               Otherwise it is function which calls when the result success.
 *           isDisabledEvent - This attribute is optional.
 *               If isDisabledEvent is true then you can not click all event.
 *               Otherwise you can click event.
 * @author : gagamel
 * @since  : 2017/09/14
 */
var cfnAjaxSubmitForm = function(formId, actionUrl, type, callback, isDisabledEvent) {
	var progressbarId;

	if (type == "jsonp") {
		$.ajax({
			type : "POST",
			url : actionUrl,
			data : $(formId).serialize(),
			dataType : type,
			jsonp : "callback",
			beforeSend : function(jqXHR, settings) {
				if (isDisabledEvent) {
					// Button disabled & progressBar show
					progressbarId = "progressbar";
					createProgressbar('body', progressbarId);
				} else {
					if (type == "html") {
						// ProgressBar show
						progressbarId = getUUID();
						$('#' + progressbarId).remove();
						createProgressbar('#' + callback, progressbarId);
					}
				}
			},
			complete : function() {
				// ProgressBar remove
				$('#' + progressbarId).remove();
			},
			success : function(result) {
				if (typeof(callback) == "function")
					callback.call(this, result);
			},
			error : function() {
				alert("오류로 인해 처리되지 않았습니다.");
			}
		});
	} else {
		$.ajax({
			type : "POST",
			url : actionUrl,
			data : $(formId).serialize(),
			dataType : type,
			beforeSend : function(jqXHR, settings) {
				if (isDisabledEvent) {
					// Button disabled & progressBar show
					progressbarId = "progressbar";
					createProgressbar('body', progressbarId);
				} else {
					if (type == "html") {
						// ProgressBar show
						progressbarId = getUUID();
						$('#' + progressbarId).remove();
						createProgressbar('#' + callback, progressbarId);
					}
				}
			},
			complete : function() {
				// ProgressBar remove
				$('#' + progressbarId).remove();
			},
			success : function(result) {
				if (type == "html") {
					if (!gagajf.isNull(callback))
						$(document.getElementById(callback)).html(result);
				} else {
					// Callback 함수 호출
					if (typeof(callback) == "function")
						callback.call(this, result);
				}
			},
			error : function() {
				alert("오류로 인해 처리되지 않았습니다.");
			}
		});
	}
}

/**
 * @type   : function
 * @access : public
 * @desc   : 그리드 No 처리
 * <pre>
 *     cfnGridNumner('searchForm', params.node.rowIndex, 'A');
 * </pre>
 * @param  : formId - 화면 from id
 * @param  : idx - row idx
 * @param  : sortFlag - A : asc, D: desc
 * @since  : 2019/12/10
 * @author : eskim
 */
var cfnGridNumner = function (formId, idx, sortFlag){
	var result = idx;
	var startRow = 0;
	var pageNo = $('#'+formId).find('#pageNo').val().removeComma();
	var pageSize = $('#'+formId).find('#pageSize').val().removeComma();
	var totRowCnt = $('#'+formId).find('#gridRowTotalCount').text().removeComma();

	if (typeof(sortFlag) == 'undefined' || sortFlag == "A"){
		startRow = (Number(pageNo) - 1) * Number(pageSize);
		result = (startRow + idx + 1)
	}else{
		startRow = (Number(pageNo) - 1) * Number(pageSize);
		result = Number(totRowCnt) - (idx + startRow) ;
	}

	return result; //.addComma();
}

/**
 * @type   : function
 * @access : public
 * @desc   : 샘플파일 다운로드
 * <pre>
 *     cfnDownloadSampleFile('SF001');
 * </pre>
 * @param  : sampleFileId - 샘플파일ID
 * @since  : 2019/12/26
 * @author : rladbwnd5
 */
function cfnDownloadSampleFile(sampleFileId) {
	$.get('/common/sample/file/' + sampleFileId
		, function(result) {
			if (gagajf.isNull(result)) {
				mcxDialog.alert('다운로드 받을 파일이 존재하지 않습니다.');
				return;
			}


			var str = '<a id="aFileDownload" href="#" style="display: none;"></a>';
			if ($('#aFileDownload').length == 0) {
				$('body').append(str);
			}

			$('#aFileDownload').attr({
				href : _sampleUrl + '/' + result
//				href : '/src/main/webapp/files/data/csv/' + result
			}).get(0).click();

		});
}

/**
 * @type   : function
 * @access : public
 * @desc   : SNS 로그인 Init
 * <pre>
 *     cfnSnsLoginInit();
 * </pre>
 * @param  : -
 * @since  : 2020/02/24
 * @author : Daehyoung
 */
var callback;

function cfnSnsLoginInit(callback, snsType) {

	callback = snsCallback;
	// 네이버 로그인 init
	var redirect_uri = "http://locd.admin.pastelmall.com/common/oAuthignin?snsType=NA";
    var naverInstance = new naver_id_login("OMmbCMu7ac7GgYWgjlhv", redirect_uri);
    var state = naverInstance.getUniqState();

    naverInstance.setButton("white", 4,40);
    naverInstance.setState(state);
    naverInstance.setPopup();
    naverInstance.init_naver_id_login();

    if(snsType == 'NA'){
    	naverLogin.getLoginStatus(function (status) {
    		if (status) {
    			/* (5) 필수적으로 받아야하는 프로필 정보가 있다면 callback처리 시점에 체크 */
    			console.log("### INFO naverLogin : ", naverLogin);
    			var email = naverLogin.user.getEmail();
    			if( email == undefined || email == null) {
    				alert("이메일은 필수정보입니다. 정보제공을 동의해주세요.");
    				/* (5-1) 사용자 정보 재동의를 위하여 다시 네아로 동의페이지로 이동함 */
    				naverLogin.reprompt();
    				return;
    			}
    			snsCallback(naverLogin.user);
    		} else {
    			console.log("로그인에 실패하였습니다.");
    		}
    	});
    }

    // 카카오 로그인 init
    if(typeof initCheck == "undefined"){
    	Kakao.init('f435c12d89ddb9cc6337f4cf0a05fd30');
		initCheck = true;
	}

}

/**
 * @type   : function
 * @access : public
 * @desc   : 네이버 로그인
 * <pre>
 *     cfnSnsLogin();
 * </pre>
 * @param  : -
 * @since  : 2020/02/24
 * @author : Daehyoung
 */
function cfnNaverLogin(callback, snsType) {

}
/**
 * @type   : function
 * @access : public
 * @desc   : 카카오 로그인
 * <pre>
 *     cfnKakaoLogin();
 * </pre>
 * @param  : -
 * @since  : 2020/02/24
 * @author : Daehyoung
 */
function cfnKakaoLogin() {
	Kakao.Auth.loginForm({
		success: function(authObj) {
			var kakaoToken = authObj.access_token;
			Kakao.API.request({
				url: '/v2/user/me',
				success: function(res) {
					var param = {};
					param.email 			= res.kaccount_email;
					param.id 				= res.id;
					param.image 		= res.properties.profile_image;
					param.nickname 	= res.properties.nickname;
					snsCallback(param);
				},
				fail: function(error) {
					alert(JSON.stringify(error));
				}
			});
		},
		fail: function(err) {
			alert(JSON.stringify(err));
		}
	});
}
/**
 * @type   : function
 * @access : public
 * @desc   : 구글 로그인
 * <pre>
 *     cfnSnsLogin();
 * </pre>
 * @param  : -
 * @since  : 2020/02/24
 * @author : Daehyoung
 */
function cfnGoogleLogin(googleUser) {
	var profile = googleUser.getBasicProfile();
	var param = {};
	param.email 			= profile.getEmail();
	param.id 				= profile.getId();
	param.image 		= profile.getImageUrl();
	param.nickname	= profile.getName();
	snsCallback(param);
}

/**
 * @type   : function
 * @access : public
 * @desc   : 휴대폰 번호 자동 하이픈
 * <pre>
 *     cfnCellPhonnHypen(this);
 * </pre>
 * @param  : obj - 입력필드 오브젝트
 * @return : None
 * @since  : 2019/03/13
 * @author : jsshin
 */
function cfnCellPhonnHypen(obj) {
	//$(obj).val( $(obj).val().replace(/[^0-9]/g, '').replace(/(^0[0-9]{2})([0-9]+)?([0-9]{4})/, '$1-$2-$3').replace('--', '-') );
	$(obj).val( $(obj).val().replace(/[^0-9]/g, "").replace(/(^02|^050[0-9]{1}|^1[0-9]{3}|^0[0-9]{2})([0-9]+)?([0-9]{4})$/,"$1-$2-$3").replace("--", "-") );
}


var fnCalendarDateValidation = function(tgtId, dtFromId, dtToId) {
	var fromVal = Number($(tgtId+" #"+dtFromId).val().replace(/-/gi, ''));
	var toVal = Number($(tgtId+" #"+dtToId).val().replace(/-/gi, ''));
	var result = true;
	if(fromVal > toVal) {
		mcxDialog.alertC('시작일자가 종료일자보다 큽니다.',{
			sureBtnText: "확인",
			sureBtnClick: function() {
				$(tgtId+" #"+dtFromId).focus();
			}
		});
		result = false;
	}
	return result;
};