개발/WEB PROGRAMMING

[ 공통 ] UTIL성 JAVASCRIPT 코드(실개발자 유용한 꿀팁)

itaekwon class 2020. 3. 26.
728x90
$(document).ready(
		function() {
			$('input[type=text]:enabled:visible:first').focus();
			
			if (typeof page_init == 'function') {
				page_init();
			}

			fvInit("#main");

			$(".fYMD").blur(function() {
				$(this).val($(this).val().getFormatVal("YMD"));
			});
			$(".fYMD").unbind("focus");
			$(".fYMD").focus(function() {
				$(this).val($(this).val().replaceAll("-", ""));
				$(this).select();
			});
			
			$(".tYMD").blur(function() {
				$(this).val($(this).val().getFormatVal("YMD"));
			});
			$(".tYMD").unbind("focus");
			$(".tYMD").focus(function() {
				$(this).val($(this).val().replaceAll("-", ""));
				$(this).select();
			});
			$(".tMONEY").blur(function() {
				$(this).val($(this).val().getFormatVal("MONEY"));
			});
			$(".tMONEY").unbind("focus");
			$(".tMONEY").focus(function() {
				$(this).val($(this).val().replaceAll(",", ""));
				$(this).select();
			});
			$(".tFMONEY").blur(function() {
				$(this).val($(this).val().getFormatVal("MONEY"));
			});
			$(".tFMONEY").unbind("focus");
			$(".tFMONEY").focus(function() {
				$(this).val($(this).val().replaceAll(",", ""));
				$(this).select();
			});

			$(".tYMD").each(function() {
				$(this).val($(this).val().getFormatVal("YMD"));
			});
			$(".tMONEY").each(function() {
				$(this).val($(this).val().getFormatVal("MONEY"));
				$(this).css("text-align", "right");
			});
			$(".tFMONEY").each(function() {
				$(this).val($(this).val().getFormatVal("MONEY"));
				$(this).css("text-align", "right");
			});

			$(".required").each(function() {
				$(this).css("background-color", getItemColor('required'));
			});
			
	        $("input[type=file]").unbind("change");
	        $(document).on("change", "input[type=file]", function() {
	        	if ($(this).attr("data-accept-ext") != undefined && $(this).attr("data-accept-ext") != "") {
	        		var acceptExt = $(this).attr("data-accept-ext");
	        		var fileExt = $(this).val().substring($(this).val().lastIndexOf(".")+1);
	        		
	        		if (fileExt == "" || acceptExt.toLowerCase().indexOf(fileExt.toLowerCase()) == -1) {
	        			alert("첨부하실 수 없는 확장자입니다.\n\n허용확장자[" + acceptExt + "]");
	        		}
	        	}
	        });

			var dateToday = new Date();
			var yrRange = (dateToday.getFullYear()-80) + ":" + (dateToday.getFullYear());
			if($.datepicker != null && $.datepicker != undefined) {
				$( ".showCalIcon:enabled" ).datepicker({
			        showOn : "button"
			            , buttonImage : "/images/icon_calendar.png"
			            , buttonImageOnly : true
		                , changeMonth: true
		                , changeYear : true
						, yearRange : yrRange
			            , dateFormat : "yy-mm-dd"
			            , beforeShow: function() {
			                setTimeout(function(){
			                    $('.ui-datepicker').css('z-index', 99999999999999);
			                }, 0);
			            }
			        });
			}
		});

// form 에 숫자 입력 등 제한처리
function fvInit(formId) {
	$(formId + " :input").filter(".tNUM").keydown(function(e) {
		return numberKeydownCheck(e);
	});
	$(formId + " :input").filter(".tMONEY").keydown(function(e) {
		return numberKeydownCheck(e);
	});
	$(formId + " :input").filter(".tFMONEY").keydown(function(e) {
		return floatKeydownCheck(e);
	});
	$(formId + " :input").filter(".tFLOAT").keydown(function(e) {
		return floatKeydownCheck(e);
	});
	$(formId + " :input").filter(".tENG").keydown(function(e) {
		return engKeydownCheck(e);
	});
	$(formId + " :input").filter(".tENGNUM").keydown(function(e) {
		return engNumKeydownCheck(e);
	});

	// 한글 전환이 필요없는 input 영문 고정
	$(formId + " :input").filter(".tNUM").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tMONEY").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tFMONEY").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tFLOAT").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tEMAIL").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tENG").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tENGNUM").css("ime-mode", "disabled");
	$(formId + " :input").filter(".tYMD").css("ime-mode", "disabled");
}

function formValidate(form) {
	return fv("#" + form.id, "alert");
}

function rfset(reqFields, formId) {
	$(formId + " :input").removeClass("required");
	var arrReqFields = reqFields.split(",");
	for(var i=0; i < arrReqFields.length; i++) {
		$(formId + " :input").find("[name='" + arrReqFields[i].trim() + "']").addClass("required");
	}
}

function all_control_enable(form) {
	if (typeof form == "string") {
		$(form).find(":input:disabled").prop("readonly", true).css("background","#eeeeee");
		$(form).find(":input:disabled").prop("disabled", false);
	} else {
		$("#" + form.id).find(":input:disabled").prop("readonly", true).css("background","#eeeeee");
		$("#" + form.id).find(":input:disabled").prop("disabled", false);
	}
}

function isInReqArr(arrReqFields, chkNm) {
	for(var i=0; i < arrReqFields.length; i++) {
		if (arrReqFields[i].trim() == chkNm) {
			return true;
		}
	}
	return false;
}

// form validation check
function fv(formId, alertGbn) {
	var validationResult = true;
	var errMsg = "";
	var chkRadioNameList = "";
	if (formId.substring(0,1) != "#") {
		formId = "#" + formId;
	}
	if (alertGbn == undefined) {
		alertGbn = "alert";
	}
	var reqFields = ($(formId + " :input[name*='req_fields']").length > 0 ? $(formId + " :input[name*='req_fields']").val() : "");
	var arrReqFields = reqFields.split(",");
	$(formId + " :input").each(
			function() {
				var title = ($(this).attr("data-field-name") == undefined || $(this).attr("data-field-name") == "" ? $(this).prop("name")
						: $(this).attr("data-field-name"));

				if (($(this).hasClass("required") || $(this).hasClass("fvRequired") || isInReqArr(arrReqFields, $(this).prop("name")))
						&& ($(this).attr("disabled") == undefined || $(this).attr("disabled") == false)) {
					if (($(this).prop("type") == "text"
							|| (isInReqArr(arrReqFields, $(this).prop("name")) && ($(this).prop("type") == "hidden"))
							|| $(this).prop("type") == "password"
							|| $(this).prop("type") == "email"
							|| $(this).prop("type") == "textarea" || $(this)
							.prop("type") == "file")
							&& $(this).val().trim() == "") {
						if (alertGbn == "alert") {
							$(this).focus();
							alert(title + "을(를) 입력하여 주십시오.");
							validationResult = false;
							return false;
						} else if (alertGbn == "allerr") {
							errMsg += title + "을(를) 입력하여 주십시오." + "\n";
						}
					} else if ($(this).get(0).tagName == "SELECT"
							&& $(this).val() == "") {
						if (alertGbn == "alert") {
							$(this).focus();
							alert(title + "을(를) 선택하여 주십시오.");
							validationResult = false;
							return false;
						} else if (alertGbn == "allerr") {
							errMsg += title + "을(를) 선택하여 주십시오." + "\n";
						}
					} else if (($(this).prop("type") == "radio" || $(this)
							.prop("type") == "checkbox")
							&& $("input[name='" + $(this).prop("name")
									+ "']:checked").length == 0) {
						if (alertGbn == "alert") {
							$(this).focus();
							alert(title + "을(를) 선택하여 주십시오.");
							validationResult = false;
							return false;
						} else if (alertGbn == "allerr") {
							if (chkRadioNameList.indexOf($(this).prop("name")
									+ ",") < 0) {
								errMsg += title + "을(를) 선택하여 주십시오" + "\n";
								chkRadioNameList += $(this).prop("name") + ",";
							}
						}
					}
				}
				if ($(this).val() != "" && $(this).prop("type") == "file" && $(this).attr("data-accept-ext") != undefined && $(this).attr("data-accept-ext") != "") {
					var acceptExt = $(this).attr("data-accept-ext");
	        		var fileExt = $(this).val().substring($(this).val().lastIndexOf(".")+1);
	        		
	        		if (fileExt == "" || acceptExt.toLowerCase().indexOf(fileExt.toLowerCase()) == -1) {
						if (alertGbn == "alert") {
							$(this).focus();
							alert(title + "에 첨부된 파일은 첨부하실 수 없는 확장자입니다.\n\n허용확장자[" + acceptExt + "]\n");
							if ($.browser.msie) { 
								// ie 일때 input[type=file] init. 
								$("#filename").replaceWith( $("#filename").clone(true) ); 
							} else { 
								// other browser 일때 input[type=file] init. 
								$("#filename").val("");
							}

							validationResult = false;
							return false;
						} else if (alertGbn == "allerr") {
							errMsg += title + "에 첨부된 파일은 첨부하실 수 없는 확장자입니다.\n\n허용확장자[" + acceptExt + "]\n";
						}
	        		}
				}
				if ($(this).hasClass("tYMD") && $(this).val() != ""
						&& $(this).val().isYmd() == false) {
					if (alertGbn == "alert") {
						$(this).focus();
						alert(title + " 입력값이 날짜 형식에 맞지 않습니다.\n");
						validationResult = false;
						return false;
					} else if (alertGbn == "allerr") {
						errMsg += title + " 입력값이 날짜 형식에 맞지 않습니다.\n";
					}
				}
				if (($($(this).hasClass("tMONEY") || this).hasClass("tNUM"))
						&& $(this).val() != ""
						&& $(this).val().replace(/,/g, '').isNum() == false) {
					if (alertGbn == "alert") {
						$(this).focus();
						alert(title + " 입력값은 숫자로만 입력하여 주십시오.");
						validationResult = false;
						return false;
					} else if (alertGbn == "allerr") {
						errMsg += title + " 입력값은 숫자로만 입력하여 주십시오.\n";
					}
				}
				if (($(this).hasClass("tFMONEY") || $(this).hasClass("tFLOAT"))
						&& $(this).val() != ""
						&& $(this).val().replace(/,/g, '').isFloat() == false) {
					if (alertGbn == "alert") {
						$(this).focus();
						alert(title + " 입력값은 실수로만 입력하여 주십시오.");
						validationResult = false;
						return false;
					} else if (alertGbn == "allerr") {
						errMsg += title + " 입력값은 실수로만 입력하여 주십시오.\n";
					}
				}
				if ($(this).hasClass("tENG") && $(this).val() != ""
						&& $(this).val().isEng() == false) {
					if (alertGbn == "alert") {
						$(this).focus();
						alert(title + " 입력값은 영문으로만 입력하여 주십시오.");
						validationResult = false;
						return false;
					} else if (alertGbn == "allerr") {
						errMsg += title + " 입력값은 영문으로만 입력하여 주십시오.\n";
					}
				}
				if ($(this).hasClass("tENGNUM") && $(this).val() != ""
						&& $(this).val().isEngNum() == false) {
					if (alertGbn == "alert") {
						$(this).focus();
						alert(title + " 입력값은 영문/숫자로만 입력하여 주십시오.");
						validationResult = false;
						return false;
					} else if (alertGbn == "allerr") {
						errMsg += title + " 입력값은 영문/숫자로만 입력하여 주십시오.\n";
					}
				}
				if ($(this).hasClass("tEMAIL") && $(this).val() != ""
						&& $(this).val().isEmail() == false) {
					if (alertGbn == "alert") {
						$(this).focus();
						alert(title + " 입력값이 이메일 형식에 맞지 않습니다." + "\n");
						validationResult = false;
						return false;
					} else if (alertGbn == "allerr") {
						errMsg += title + " 입력값이 이메일 형식에 맞지 않습니다." + "\n";
					}
				}
				if ($(this).attr("data-minlen") != undefined) {
					if (parseInt($(this).attr("data-minlen")) > $(this).val().length && $(this).val() != "") {
						alert(title + " 의 값을 최소 " + $(this).attr("data-minlen") + "글자 이상으로 입력하여 주십시오." + "\n");
						validationResult = false;
						return false;
					}
				}
				if ($(this).attr("data-chkfunc") != undefined) {
					if (eval($(this).attr("data-chkfunc")) == false) {
						validationResult = false;
						return false;
					}
				}
			});
	if (alertGbn == "alert") {
		return validationResult;
	} else if (alertGbn == "allerr") {
		return errMsg;
	} else {
		return "";
	}
}

/*******************************************************************************
 * ajax를 통해 서버 처리 후 특정 레이어에 replace ex) ajaxReplace("xx.do","a=1&b=2","divId",
 * function suc() {}, function err() {}, function comp() {}); 1. callUrl ajax
 * call 처리할 서버 주소 2. 전달 매개변수 3. html내용을 변경할 layerId, 4. 성공시 처리가 필요한 추가 function
 * (생략가능) 5. 실패시 처리가 필요한 추가 function (생략가능) 6. 전체 완료시 처리가 필요한 추가 function (생략가능)
 ******************************************************************************/
function ajaxReplace(callUrl, jsonData, layerId, successFunc, errFunc,
		completeFunc) {
	$("#ly-loading").show();
	
	if (getType(jsonData) == "object") {
		jsonData.jdcid = (new Date()).getTime();
	} else if (getType(jsonData) == "string") {
		jsonData += "&jdcid=" + (new Date()).getTime() + "&ajax_yn=Y";
	}

	/*$(layerId)
			.html(
					"<div style='text-align:center;'><img src='/counsel/class/images/ajax-loading.gif'></div>");*/
	$.ajax({
		url : callUrl,
		data : jsonData,
		contentType : "application/x-www-form-urlencoded; charset=UTF-8",
		type : 'POST',

		success : function(data) { 
			$(layerId).html(data);
			appendHtmlAfterWork(layerId);
			if (successFunc) {
				successFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			if (errFunc) {
				errFunc();
			}
		},
		complete : function(data) {
			$("#ly-loading").hide();
			if (completeFunc) {
				completeFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}

function ajaxAppend(callUrl, jsonData, layerId, successFunc, errFunc,
		completeFunc) {

	if (getType(jsonData) == "object") {
		jsonData.jdcid = (new Date()).getTime();
		jsonData.ajax_yn = "Y";
	} else if (getType(jsonData) == "string") {
		jsonData += "&jdcid=" + (new Date()).getTime() + "&ajax_yn=Y";
	}
	$.ajax({
		url : callUrl,
		data : jsonData,
		contentType : "application/x-www-form-urlencoded; charset=UTF-8",
		type : 'POST',

		success : function(data) { 
			$(layerId).append(data);
			appendHtmlAfterWork(layerId);
			if (successFunc) {
				successFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			if (errFunc) {
				errFunc();
			}
		},
		complete : function(data) {
			if (completeFunc) {
				completeFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}


function ajaxTemplateAppend(callUrl, jsonData, layerId, successFunc, errFunc,
		completeFunc,transData) {

	if (getType(jsonData) == "object") {
		jsonData.jdcid = (new Date()).getTime();
		jsonData.ajax_yn = "Y";
	} else if (getType(jsonData) == "string") {
		jsonData += "&jdcid=" + (new Date()).getTime() + "&ajax_yn=Y";
	}
	
	$.ajax({
		url : callUrl,
		data : jsonData,
		contentType : "application/x-www-form-urlencoded; charset=UTF-8",
		type : 'POST',

		success : function(data) {

			data = data.replaceAll("#tpl_marker#",transData);

			$(layerId).append(data);
			appendHtmlAfterWork(layerId);
			if (successFunc) {
				successFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			if (errFunc) {
				errFunc();
			}
		},
		complete : function(data) {
			if (completeFunc) {
				completeFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}

function ajaxReplaceSync(callUrl, jsonData, layerId, successFunc, errFunc,
		completeFunc) {

	if (getType(jsonData) == "object") {
		jsonData.jdcid = (new Date()).getTime();
		jsonData.ajax_yn = "Y";
	} else if (getType(jsonData) == "string") {
		jsonData += "&jdcid=" + (new Date()).getTime() + "&ajax_yn=Y";
	}

	/*$(layerId)
			.html(
					"<div style='text-align:center;'><img src='/counsel/class/images/ajax-loading.gif'></div>");*/

	$.ajax({
		url : callUrl,
		data : jsonData,
		async : false,
		contentType : "application/x-www-form-urlencoded; charset=UTF-8",
		type : 'POST',

		success : function(data) { 
			$(layerId).html(data);
			appendHtmlAfterWork(layerId);
			if (successFunc) {
				successFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			if (errFunc) {
				errFunc();
			}
		},
		complete : function(data) {
			if (completeFunc) {
				completeFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}

function ajaxReplaceEucKr(callUrl, jsonData, layerId, successFunc, errFunc,
		completeFunc) {

	if (getType(jsonData) == "object") {
		jsonData.jdcid = (new Date()).getTime();
		jsonData.ajax_yn = "Y";
	} else if (getType(jsonData) == "string") {
		jsonData += "&jdcid=" + (new Date()).getTime() + "&ajax_yn=Y";
	}

	/*$(layerId)
			.html(
					"<div style='text-align:center;'><img src='/counsel/class/images/ajax-loading.gif'></div>");*/

	$.ajax({
		url : callUrl,
		data : jsonData,
		contentType : "application/x-www-form-urlencoded; charset=EUC-KR",
		type : 'POST',

		success : function(data) { 
			$(layerId).html(data);
			appendHtmlAfterWork(layerId);
			if (successFunc) {
				successFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			if (errFunc) {
				errFunc();
			}
		},
		complete : function(data) {
			if (completeFunc) {
				completeFunc();
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}

//ajax으로 파일 업로드시 사용 
function ajaxFileUpload(callurl, jsonData, successFunc, errFunc, completeFunc) {
	console.log("ajaxFileUpload start!");
	$("#ly-loading").show();
	$.ajax({
      url : callurl,
      contentType : "application/json",
      data: jsonData,
      method: 'POST',
      processData: false,
      contentType: false,
      
      success : function(data) {
      	if (successFunc) {
          	console.log("ajaxFileUpload success");
      		successFunc(data);    
      	}
      },
      error: function(data){
      	if (errFunc) {
          	console.log("ajaxFileUpload err");
      		errFunc(data);    
      	}
      },
      complete : function(data) {
    	  console.log("ajaxFileUpload end");
          if (completeFunc) {
          	completeFunc(data);    
          }
          
          resetFileForm();
          $("#ly-loading").hide();
      }
	});
}

function appendHtmlAfterWork(layerId) {
	appendHtmlAfterWorkObj($(layerId));
}

function appendHtmlAfterWorkObj(jqueryObj) {
	jqueryObj.find(".tYMD").blur(function() {
		$(this).val($(this).val().getFormatVal("YMD"));
	});
	jqueryObj.find(".tYMD").focus(function() {
		$(this).val($(this).val().replaceAll("-", ""));
		$(this).select();
	});
	$(".required").css("background-color", getItemColor('required'));
	
	var dateToday = new Date();
	var yrRange = (dateToday.getFullYear()-80) + ":" + (dateToday.getFullYear());
	jqueryObj.find( ".showCalIcon:enabled" ).datepicker({
        showOn : "button"
            , buttonImage : "/images/icon_calendar.png"
            , buttonImageOnly : true
            , changeMonth: true
            , changeYear : true
            , yearRange:yrRange
            , dateFormat : "yy-mm-dd"
            , beforeShow: function() {
                setTimeout(function(){
                    $('.ui-datepicker').css('z-index', 99999999999999);
                }, 0);
            }
        });
}

function ajaxJson(callurl, jsonData, successFunc, errFunc, completeFunc) {
	toggleLoading(true);
	if (callurl.indexOf("rtn_json") < 0 ) {
		callurl += (callurl.indexOf("?") >= 0 ? "&" : "?") + "rtn_json=Y";
	}
	$.ajax({
		url : callurl,
		data : jsonData,
		async : true,
		dataType : "json",
		contentType : "application/x-www-form-urlencoded; charset=UTF-8",
		type : 'POST',

		success : function(data) {
			if (successFunc) {
				successFunc(data);
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			console.log("error ajaxJson:" + data);
			if (errFunc) {
				errFunc(data);
			}
		},
		complete : function(data) {
			toggleLoading(false);
			if (completeFunc) {
				completeFunc(data);
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}

function ajaxJsonSync(callurl, jsonData, successFunc, errFunc, completeFunc) {
	if (callurl.indexOf("rtn_json") < 0 ) {
		callurl += (callurl.indexOf("?") >= 0 ? "&" : "?") + "rtn_json=Y";
	}
	$.ajax({
		url : callurl,
		data : jsonData,
		async : false,
		dataType : "json",
		contentType : "application/x-www-form-urlencoded; charset=UTF-8",
		type : 'POST',

		success : function(data) {
			if (successFunc) {
				successFunc(data);
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		},
		error : function(data) {
			console.log("error ajaxJson:" + data);
			if (errFunc) {
				errFunc(data);
			}
		},
		complete : function(data) {
			if (completeFunc) {
				completeFunc(data);
			}
			if (typeof sessionTimeRefresh != "undefined") {
				sessionTimeRefresh();
			}
		}
	});
}

// form 자료 ajax submit 처리
function ajaxSubmitForm(submitUrl, formId, successFunc, errFunc) {
	if ($(formId).find("input[name=rtn_json]").length == 0) {
		$(formId).append("<input type='hidden' name='rtn_json' value='Y'/>");
	} else {
		$(formId).find("input[name=rtn_json]").val("Y");
	}
	$("#ly-loading").show();
	
	$(formId).ajaxForm({
		url : submitUrl,
		type : "POST",
		dataType : "json",
		beforeSubmit : function(data, frm, opt) {
			return true;
		},
		success : function(responseJson, statusText) {
			if(responseJson.userErrMsg != undefined) {
				alert(responseJson.userErrMsg);
			} else if(responseJson.errMsg != undefined) {
				alert("자료처리중 오류가 발생하였습니다.");
			} else {
				if (successFunc) {
					// console.log(responseJson);
					successFunc(responseJson);
				}
			}
			$(formId).ajaxFormUnbind();
		},
		error : function(data) {
			console.log("error:" + JSON.stringify(data));
			if (errFunc) {
				errFunc();
			}
			$(formId).ajaxFormUnbind();
		},
	    complete : function(responseJson){
	    	$(formId).find("input[name=rtn_json]").val("N");
	    	formatMask(formId);
			$("#ly-loading").hide();
        }
	});
	$(formId).submit();
}

// 아래 data의 내용이 json 으로 해석되지 않는것만 제외하고는 위의 ajaxJson과 모두 동일함
function ajaxSendMail(callurl, jsonData, successFunc, errFunc, completeFunc) {
	$.ajax({
		url : callurl,
		data : jsonData,
		type : 'POST',
		processData: false,
	    contentType: false,

		success : function(data) {
			if (successFunc) {
				successFunc(data);
			}
		},
		error : function(data) {
			if (errFunc) {
				errFunc(data);
			}
		},
		complete : function(data) {
			if (completeFunc) {
				completeFunc(data);
			}
		}
	});
}
 
// 화면(Table)의 내용을 excel파일로 다운로드
function screenToExcel(id, titleNm, fileNm) {
	if (fileNm == undefined || fileNm == "") {
		fileNm = titleNm + ".xls";
	}
	$(id).table2excel({
		exclude : ".noExl",
		exclude_links : true,
		name : titleNm,
		filename : fileNm
	});
}

// keydown inputchk
function numberKeydownCheck(e) {
	var key = e.charCode || e.keyCode || 0;
	// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers
	// ONLY
	// home, end, period, and numpad decimal
	return (key == 8 || key == 9 || key == 13 || key == 35 || key == 36
			|| key == 46 || (key >= 35 && key <= 40)
			|| (key >= 48 && key <= 57 && e.shiftKey == false) || (key >= 96 && key <= 105));
}

function floatKeydownCheck(e) {
	var key = e.charCode || e.keyCode || 0;
	// allow backspace, tab, delete, enter, arrows, numbers and keypad numbers
	// ONLY
	// home, end, period, and numpad decimal
	return (key == 8 || key == 9 || key == 13 || key == 35 || key == 36
			|| key == 46 || (key >= 35 && key <= 40)
			|| key == 110
			|| (key >= 48 && key <= 57 && e.shiftKey == false)
			|| (key >= 96 && key <= 105) || (key >= 189 && key <= 190));
}

function engNumKeydownCheck(e) {
	var keyCd = e.charCode || e.keyCode || 0;
	var regEx = /[0-9A-Za-z]/g;
	var key = String.fromCharCode(e.which);
	if (keyCd == 8 || keyCd == 9 || keyCd == 35 || keyCd == 36 || keyCd == 37
			|| keyCd == 39 || keyCd == 46 || (keyCd >= 96 && keyCd <= 105)
			|| regEx.test(key)) {
		return true;
	} else {
		return false;
	}
}

function engKeydownCheck(e) {
	var keyCd = e.charCode || e.keyCode || 0;
	var englishAlphabet = /[A-Za-z]/g;
	var key = String.fromCharCode(e.which);
	if (keyCd == 8 || keyCd == 9 || keyCd == 35 || keyCd == 36 || keyCd == 37
			|| keyCd == 39 || keyCd == 46 || englishAlphabet.test(key)) {
		return true;
	} else {
		return false;
	}
}

jQuery.fn.center = function() {
	this.css("position", "absolute");
	this.css("top", Math.max(0,
			(($(window).height() - $(this).outerHeight()) / 2)
					+ $(window).scrollTop())
			+ "px");
	this.css("left", Math.max(0,
			(($(window).width() - $(this).outerWidth()) / 2)
					+ $(window).scrollLeft())
			+ "px");
	return this;
}

// 브라우저 컨트롤 관련 함수
var frameControl = new Object(
		{
			// 브라우저 체크(FF3, FF2, FF, IE, Saf, Chr, Op)

			// 팝업 리사이징
			resize : function() {
				var winSize = this.alertSize();
				var sizeWidth = winSize[0];
				var sizeHeight = winSize[1];

				var Dwidth = 0, Dheight = 0;

				if (browser() == "IE") {
					Dwidth = document.body.scrollWidth;
					Dheight = document.body.scrollHeight;
				} else {
					Dwidth = document.compatMode == "CSS1Compat" ? document.documentElement.scrollWidth
							: document.body.scrollWidth;
					Dheight = document.compatMode == "CSS1Compat" ? document.documentElement.scrollHeight
							: document.body.scrollHeight;
				}

				var width = Dwidth - sizeWidth;
				var height = Dheight - sizeHeight;
				self.resizeBy(width, height);
			},

			// 윈도우 사이즈 체크
			alertSize : function() {
				var myWidth = 0, myHeight = 0;
				if (typeof (window.innerWidth) == 'number') {
					// Non-IE
					myWidth = window.innerWidth;
					myHeight = window.innerHeight;
				} else if (document.documentElement
						&& (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
					// IE 6+ in 'standards compliant mode'
					myWidth = document.documentElement.clientWidth;
					myHeight = document.documentElement.clientHeight;
				} else if (document.body
						&& (document.body.clientWidth || document.body.clientHeight)) {
					// IE 4 compatible
					myWidth = document.body.clientWidth;
					myHeight = document.body.clientHeight;
				}
				return [ myWidth, myHeight ];
			}
		});

var browser = function() {
	// Return cached result if avalible, else get result then cache it.
	if (browser.prototype._cachedResult)
		return browser.prototype._cachedResult;

	// Opera 8.0+ (UA detection to detect Blink/v8-powered Opera)
	var isOpera = (!!window.opr && !!opr.addons) || !!window.opera
			|| navigator.userAgent.indexOf(' OPR/') >= 0;

	// Firefox 1.0+
	var isFirefox = typeof InstallTrigger !== 'undefined';

	// At least Safari 3+: "[object HTMLElementConstructor]"
	var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf(
			'Constructor') > 0;

	// Chrome 1+
	var isChrome = !!window.chrome && !isOpera;

	// At least IE6
	var isIE = /* @cc_on!@ */false || !!document.documentMode;

	// Edge 20+
	var isEdge = !isIE && !!window.StyleMedia;

	return browser.prototype._cachedResult = isOpera ? 'Opera'
			: isFirefox ? 'Firefox' : isSafari ? 'Safari' : isChrome ? 'Chrome'
					: isIE ? 'IE' : isEdge ? 'Edge' : "Don't know";
};

if (!String.prototype.endsWith) {
	String.prototype.endsWith = function(searchString, position) {
		var subjectString = this.toString();
		if (typeof position !== 'number' || !isFinite(position)
				|| Math.floor(position) !== position
				|| position > subjectString.length) {
			position = subjectString.length;
		}
		position -= searchString.length;
		var lastIndex = subjectString.indexOf(searchString, position);
		return lastIndex !== -1 && lastIndex === position;
	};
}

function getType(p) {
	if (Array.isArray(p))
		return 'array';
	else if (typeof p == 'string')
		return 'string';
	else if (p != null && typeof p == 'object')
		return 'object';
	else
		return 'other';
}

function getIType(elim) {
	var itype = "";
	if (elim.className.indexOf("tENGNUM") >= 0) {
		itype = "ENGNUM";
	} else if (elim.className.indexOf("tMONEY") >= 0) {
		itype = "MONEY";
	} else if (elim.className.indexOf("tNUM") >= 0) {
		itype = "NUM";
	} else if (elim.className.indexOf("tFMONEY") >= 0) {
		itype = "FMONEY";
	} else if (elim.className.indexOf("tFLOAT") >= 0) {
		itype = "FLOAT";
	} else if (elim.className.indexOf("tEMAIL") >= 0) {
		itype = "EMAIL";
	} else if (elim.className.indexOf("tYMD") >= 0) {
		itype = "YMD";
	}
	return itype;
}

function removeMask(frm) {
	$(frm).find(".tYMD").each(function() {
		$(this).val($(this).val().replace(/-/g, ""));
	});
	$(frm).find(".tMONEY").each(function() {
		$(this).val($(this).val().replace(/,/g, ""));
	});
	$(frm).find(".tFMONEY").each(function() {
		$(this).val($(this).val().replace(/,/g, ""));
	});
}

function formatMask(frm) {
	$(frm).find(".tYMD").each(function() {
		$(this).val($(this).val().getFormatVal("YMD"));
	});
	$(frm).find(".tMONEY").each(function() {
		$(this).val($(this).val().getFormatVal("MONEY"));
		$(this).css("text-align", "right");
	});
	$(frm).find(".tFMONEY").each(function() {
		$(this).val($(this).val().getFormatVal("MONEY"));
		$(this).css("text-align", "right");
	});
}

function formatMaskElm(ctrl) {
	var itype = getIType(ctrl);
	switch (itype) {
	case "MONEY":
	case "FMONEY":
		ctrl.value = ctrl.value.getFormatVal("MONEY");
		ctrl.style.textAlign = "right";
		break;
	case "NUM":
	case "FLOAT":
		ctrl.style.textAlign = "right";
		break;
	case "YMD":
		ctrl.value = ctrl.value.getFormatVal("YMD");
	}
}

function isObject(object_key) {
	try {
		document.all[object_key].value;
		return true;
	} catch (e) {
		return false;
	}
}

function isEmpty(input) {
	if (input.value == null || input.value.replace(/ /gi, "") == "") {
		return true;
	}
	return false;
}

function changeObjectProperty(input, status, bool) {
	var col_property = input.className;
	if (status == "readonly") {
		input.readOnly = true;
		if (col_property.indexOf('required') >= 0) {
			input.className = col_property.replaceAll("required", "");
		}
		input.disabled = false;
		input.style.backgroundColor = getItemColor('readonly');
		if (bool == undefined || bool == true) {
			input.value = "";
		}
	} else if (status == "enabled") {
		input.readOnly = false;
		if (col_property.indexOf('required') >= 0) {
			input.className = col_property.replaceAll("required", "");
		}
		input.disabled = false;
		input.style.backgroundColor = '#ffffff';
	} else if (status == "required") {
		input.readOnly = false;
		if (col_property.indexOf('required') < 0) {
			input.className += " required";
		}
		input.disabled = false;
		input.style.backgroundColor = getItemColor('required');
	} else if (status == "requiredOnly") {
		input.readOnly = true;
		if (col_property.indexOf('required') < 0) {
			input.className += " required";
		}
		input.disabled = false;
		input.style.backgroundColor = getItemColor('required');
	} else if (status == "disabled") {
		input.disabled = true;
		input.style.backgroundColor = getItemColor('readonly');
	}
}

function getItemColor(status) {
	if (status == 'required') {
		return "#f7efbe";
	}
	if (status == 'readonly') {
		return "#f6f6f6";
	}
}

function f_parseInt(input) {
	return input.value == '' ? 0 : parseInt(input.value.replace(/,/g, ""));
}

function f_parseFloat(input) {
	return input.value == '' ? 0 : parseFloat(input.value.replace(/,/g, ""));
}

function getRadioValue(input) {
	try {
		if (input.length > 1) {
			for (var inx = 0; inx < input.length; inx++) {
				if (input[inx].checked)
					return input[inx].value;
			}
		} else {
			if (input.checked)
				return input.value;
		}
		return "";
	} catch (e) {
		return "";
	}
}

function getSelectedText(selectObj) {
	for (var i = 0; i < selectObj.options.length; i++) {
		if (selectObj.options[i].value != '' && selectObj.options[i].selected) {
			return selectObj.options[i].text;
		}
	}
	return "";
}

function setCookie(name, value, expiredays) {
	var today = new Date();
	today.setDate(today.getDate() + expiredays);
	document.cookie = name + "=" + escape(value) + "; path=/; expires="
			+ today.toGMTString() + ";";
}

function getCookie(name) {
	var nameOfCookie = name + "=";
	var x = 0

	while (x <= document.cookie.length) {
		var y = (x + nameOfCookie.length);
		if (document.cookie.substring(x, y) == nameOfCookie) {
			if ((endOfCookie = document.cookie.indexOf(";", y)) == -1)
				endOfCookie = document.cookie.length;
			return unescape(document.cookie.substring(y, endOfCookie));
		}
		x = document.cookie.indexOf(" ", x) + 1;
		if (x == 0)
			break;
	}
	return "";
}

function deleteCookie(name) {
	var exp = new Date();
	exp.setTime(exp.getTime() - 1);
	var cval = getCookie(name);
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

// FORM 생성
function create_form(form_nm, pageUrl) {
	var form = document.createElement('form');
	form.setAttribute('id', form_nm);
	form.setAttribute('name', form_nm);
	form.setAttribute('action', pageUrl);
	form.setAttribute('target', form_nm);
	form.setAttribute('method', 'post');
	form.style.display = "none";
	return form;
}

// INPUT 생성
function create_input(form, input_type, input_name, input_value) {
	var input;
	input = document.createElement('input');
	input.setAttribute('type', input_type);
	input.setAttribute('name', input_name);
	input.setAttribute('value', input_value);
	form.appendChild(input);
}

// MODAL 그리기
function makeModalHeader(mTitle) {
	var cHtml = "<div class='modal-dialog'>"
			+ "<div class='modal-content'>"
			+ "<div class='modal-header'>"
			+ "<button type='button' class='close' data-dismiss='modal' aria-hidden='true'></button>"
			+ "<h4 class='modal-title'>" + mTitle + "</h4>" + "</div>"
			+ "<div class='modal-body'>";
	return cHtml;
}

function makeModalFooter() {
	return "</div></div></div>";
}

function chkChkShift(frm, chkNm, chk) {

    var firstChk = -1;
    var lastChk = -1;
    var nowChk = -1;
    if (event.shiftKey == 1) {
        for (var i = 0; i < frm.elements.length; i++){
            if (frm.elements[i].name == chkNm && frm.elements[i].checked && firstChk == -1) {
                firstChk = i;
            }
            if (frm.elements[i].name == chkNm && frm.elements[i] == chk) {
                nowChk = i;
            }
        }
    }

    if (firstChk < nowChk) {
        lastChk = nowChk;
    } else {
        lastChk = firstChk;
        firstChk = nowChk;
    }
    for (var i = firstChk; i < lastChk; i++){
        if (frm.elements[i].name == chkNm && frm.elements[i].type == 'checkbox') {
            frm.elements[i].checked = true;
        }
    }
}

function populatedropdown(dayfield, monthfield, yearfield, $hasData) {
	
	var monthtext=['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sept','Oct','Nov','Dec'];
	
	var today=new Date();
	
	var dayfield=document.getElementById(dayfield);
	var monthfield=document.getElementById(monthfield);
	var yearfield=document.getElementById(yearfield);
	
	for (var i=0; i<31; i++) {
		dayfield.options[i]=new Option(i+1, i+1);
	}
	
	if(!$hasData) dayfield.options[today.getDate() - 1]=new Option(today.getDate(), today.getDate(), true, true); //select today's day
	
	for (var m=0; m<12; m++) {
		monthfield.options[m]=new Option(monthtext[m], m+1);
	}
	
	if(!$hasData) monthfield.options[today.getMonth()]=new Option(monthtext[today.getMonth()], today.getMonth() + 1, true, true); 
		
	var thisyear=today.getFullYear();
	
	var y = 0;
	
	while(thisyear > 1899) {
		yearfield.options[y]=new Option(thisyear, thisyear);
		thisyear-=1;
		y++;
	}
	
	if(!$hasData) yearfield.options[0]=new Option(today.getFullYear(), today.getFullYear(), true, true); 
	
}

function isValidDate(val) {
	return val.isYmd();
}
 
function getDigit($val) {
	
	return Number($val) < 10?"0"+$val:$val;
	
}

function onSelected($elementId, $value) {
	
	document.getElementById($elementId)
	var i = 0;
	while(i < document.getElementById($elementId).options.length) {
		if(Number($value) == Number(document.getElementById($elementId).options[i].value)) {
			document.getElementById($elementId).options[i].selected = true;
			break;
		}
		++i;
	}
	
}


chkChange = function(obj) {
	obj.checked = (!obj.checked);
}

function selSes(svcUrl, addParam, rtnFunc) {
	var jsonData = "url=" + svcUrl + addParam; 
	
	jQuery.ajax({
      url :'/session/mkSso.do'
       , data: jsonData
       , type: 'POST'
      , dataType: 'json'
      , success:function(data){
        rtnFunc(data);
      }
   , error : function(error) {
      alert("해당 페이지를 열지 못하였습니다.");
      }
   });
}

/**
 * RMS Renewal Function Start
 */

/**
 * 탭 활성화 Function
 * @param tabId
 * @param bFlag
 * @returns
 */
function openTab(tabId, bFlag) {
	toggleLoading(true);
	
	$(".footerNav ul li").removeClass("active");
	$(tabId).addClass("active");
	
	var objMenu = findArrayObj(arrMenu, "TAB", tabId);
	
	makeContentHeader(objMenu.menuName, "closeTab(\'" + tabId + "\')");
	
	var contentsId = objMenu.contentsId;
	$(".objMenu").css("display", "none");
	$(contentsId).css("display", "block");
	
	toggleLoading(false);
}

/**
 * Menu Tab 닫기 Function
 * @param tabId
 * @param mainHome
 * @returns
 */
function closeTab(tabId, mainHome) {
	/*savePage();*/
	
	// 닫은 탭 데이터 삭제
	$(tabId + " a").text("");
	$(tabId).css("display", "");
	
	var nIdx = findArrayIndex(arrMenu, "TAB", tabId);
	var rMenuContent = arrMenu[nIdx].contentsId;
	$(rMenuContent).remove();
	
	if (nIdx > -1) arrMenu.splice(nIdx, 1);
	
	if(arrMenu.length > 0) {
		for(var i = 0 ; i < arrMenu.length; i++) {
			var objMenu = arrMenu[i];
			var oldTabId = objMenu.tabId;
			var newTabId = "#tab" + (i+1);
			
			if(newTabId != oldTabId) {
				var menuName = $(oldTabId + " a").text();
				$(oldTabId + " a").text("");
				$(oldTabId).css("display", "");
				
				$(newTabId + " a").text(menuName);
				$(newTabId).show();
				objMenu.tabId = newTabId;
			}
		}
		openTab(newTabId, false);
	} else {
		closeAllTab(mainHome);
	}
}

/**
 * 전체 Menu Tab 닫기 Function
 * @param mainHome
 * @returns
 */
function closeAllTab(mainHome) {
	$(".footerNav ul li").css("display", "");
	$(".footerNav ul li a").text("");
	
	$(".objMenu").remove();
	menuIdx = 0;
	arrMenu.splice(0,arrMenu.length);
	
	callMenu('/situation/list', mainHome);
}

/**
 * 메뉴에 해당하는 Contents Header 명 변경 Function
 * @param menuName
 * @param closeFnc
 * @returns
 */
function makeContentHeader(menuName, closeFnc) {
	$(".contents .header h2").text(menuName);
	$(".contents .header .location strong").text(menuName);
	$(".contents .header .location .closeBtn").attr("onclick", closeFnc);
}

/**
 * TargetId에 Iframe Append Function
 * @param contents
 * @returns
 */
function makeContentFrame(targetId, contents) {
	$(targetId).append('<iframe class="objMenu" name="'+contents+'" id="'+contents+'"></iframe>');
}

/**
 * 배열에서 원하는 값을 찾는 Function
 * @param arrObj
 * @param sTarget
 * @param sFind
 * @returns
 */
function findArrayObj(arrObj, sTarget, sFind) {
	var objResult;
	if(arrObj.length > 0) {
		$.each(arrObj, function(i, obj){
			switch(sTarget) {
			case "URL" :
				if(obj.targetUrl === sFind) objResult = obj;
				else if(obj.tabUrl === sFind) objResult = obj;
				break;
			case "TAB" :
				if(obj.tabId === sFind) objResult = obj;
				break;
			}
	    }); 
	}
	return objResult;
}

/**
 * 배열에서 원하는 값의 Index 찾는 Function
 * @param arrObj
 * @param sTarget
 * @param sFind
 * @returns
 */
function findArrayIndex(arrObj, sTarget, sFind) {
	var nIdx;
	if(arrObj.length > 0) {
		$.each(arrObj, function(i, obj){
			switch(sTarget) {
			case "URL" :
				if(obj.targetUrl === sFind) nIdx = i;
				break;
			case "TAB" :
				if(obj.tabId === sFind) nIdx = i;
				break;
			}
	    }); 
	}
	return nIdx;
}

/**
 * Form에 해당하는 Input Tag 삭제
 * @param formId
 * @returns
 */
function clearHiddenForm(formId) {
	$(formId + " input").remove();
}

/**
 * Form에 필요한 Hidden Tag 생성 function
 * @param name
 * @param id
 * @param value
 * @param formId
 * @returns
 */
function appendHiddenForm(name, id, value, formId) {
	$("<input>").attr({ 
        name: name, 
        id: id, 
        type: "hidden", 
        value: value
    }).appendTo(formId);
}

/**
 * Excel Download 호출 Function
 * @param url
 * @param param
 * @returns
 */
function excelProc(url, param) {
	toggleLoading(true);

	document.excelForm.action = url;
	
    $.fileDownload($("#excelForm").prop('action'), {
        //preparingMessageHtml: "We are preparing your report, please wait...",
        //failMessageHtml: "There was a problem generating your report, please try again.",
        httpMethod: "POST",
        data: param,
        successCallback: function (url) {
        	toggleLoading(false);
        },
        failCallback: function (responseHtml, url) {
        	alert("Excel Download Fail!");
        	toggleLoading(false);
        }
    });
}

/**
 * Loading Image Toggle Function
 * @param bShow
 * @returns
 */
function toggleLoading(bShow) {
	if(bShow) {
		$("#ly-loading").show();
	} else {
		$("#ly-loading").hide();
	}
}

/**
 * Excel Upload 버튼 호출 Function
 * @param obj
 * @param url
 * @returns
 */
function goExcelUploadProc(obj, url) {
	$("#uploadFile").change(function() {
		var form = $('#uploadForm')[0];
        var formData = new FormData(form);
        formData.append("fileObj", $("#uploadFile")[0].files[0]);
        ajaxFileUpload(url, formData, obj.uploadSuccess, obj.uploadFail);
	});
	$("#uploadFile").click();
}

/**
 * Upload Form에 있는 file Reset
 * @returns
 */
function resetFileForm() {
	$('#uploadForm input').remove();
    $('#uploadForm').append('<input type="file" name="uploadFile" id="uploadFile" style="display:none;"/>');
}

/**
 * serialize parameter 합치기
 * @param param1
 * @param param2
 * @returns
 */
function addParam(param1, param2) {
	if(getType(param1) == "object") {
		param1 = $.param(param1);
	}
	
	if(getType(param2) == "object") {
		param2 = $.param(param2);
	}
	
	var param = param1 + "&" + param2;
	return param;
}

var arrTargetObj = [];	// Popup을 호출 한 Object
var nPopupCount = 0;	// Popup 수량

/**
 * Layer Popup Open Function
 * @param obj
 * @param title
 * @param url
 * @param method
 * @param width
 * @param height
 * @param left
 * @param top
 * @returns
 */
function openLayerPopup(obj, title, url, method, width, height, left, top) {
	// 이미 열려있는 Popup 닫기
	arrTargetObj.push(obj);

	if (nPopupCount != 0) nPopupCount++;
	
	console.log("nPopupCount2 : " + nPopupCount);

	if(nPopupCount == 1) {
		closeLayerPopup();
		++nPopupCount;
	}
	
	if (nPopupCount == 0) nPopupCount++;
	
	createLayerPopup(nPopupCount);
	
	if(width != null && width != "" && width != undefined) {
		$("#popupWrap" + nPopupCount).width(width);
	}
	if(height != null && height != "" && height != undefined) {
		$("#popupWrap" + nPopupCount).height(height);
	}
	
	var offsetLeft = 0;
	var offsetTop = 0;
	if(left != null && left != "" && left != undefined) {
		offsetLeft = left;
	} else {
		offsetLeft = "calc(50vw)";
	}
	
	if(top != null && top != "" && top != undefined) {
		offsetTop = top;
	} else {
		offsetTop = "calc(50vh)";
	}
	$("#popupWrap" + nPopupCount).offset( { left: offsetLeft, top:offsetTop } );
	
	var contentH = $("#popupWrap" + nPopupCount).height();
	$("#popContent" + nPopupCount).height('calc(' + contentH + 'px - 6em)');
	
	$("#popTit" + nPopupCount + " > span").text(title);
	$("#popLayer" + nPopupCount).css('display', 'table');
	
	document.popupForm.action = url;
	document.popupForm.method = method;
	document.popupForm.target = "popContent" + nPopupCount;
	document.popupForm.submit();
}

/**
 * Layer Popup Close
 * @param sFuncName
 * @param args
 * @returns
 */
function closeLayerPopup(sFuncName, args) {
	if(arrTargetObj.length > 0) {
		var targetObj = arrTargetObj.pop();
		// 닫힐 때 Function 호출
		if(sFuncName != "" && sFuncName != null && sFuncName != undefined) {
			targetObj[sFuncName](args);
		}
	}
	
	$("#popLayer"+ nPopupCount).remove();
	nPopupCount--;
}

/**
 * Layer Popup 생성 Function
 * @param id
 * @returns
 */
function createLayerPopup(id) {
	var popup	= '<div class="popLayer" id="popLayer'+id+'">'
				+ '	<div class="popInner">'
				+ '		<div class="popupWrap widL" id="popupWrap'+id+'">'
				+ '			<div id="popTit'+id+'" class="popTit"><span>메일 발송</span></div>'
				+ '			<div class="popCont">'
				+ '				<iframe name="popContent'+id+'" id="popContent'+id+'" class="popContent"></iframe>'
				+ '			</div>'
				+ '			<button class="btnClose" onclick="closeLayerPopup()">닫기</button>'
				+ '		</div>'
				+ '	</div>'
				+ '</div>';
	$('body').append(popup);
}

/**
 * Form Data Serialize 후 Json String 형태로 바꾸는 Function
 * @param formId
 * @param hiddenName
 * @param sColumnName
 * @param sValue
 * @returns
 */
function serializeJsonString(formId, hiddenName, sColumnName, sValue) {
	var jsonObj = $(formId).serializeObject();
	
	if(sColumnName != null && sColumnName != undefined && sColumnName != "") {
		var arrObj = [];
		$.each(jsonObj[hiddenName], function(i, obj){
			var bIsColumn = obj.hasOwnProperty(sColumnName);
			
			if(bIsColumn) {
				if(sValue != null && sValue != undefined && sValue != "") {
					if(obj[sColumnName] === sValue) {
						arrObj.push(obj);
					}
				} else {
					arrObj.push(obj);
				}
			}
	    });
		jsonObj[hiddenName] = arrObj;
	}
	
	var jsonStr = JSON.stringify(jsonObj);
	
	return jsonStr;
}

/**
 * Form Data Serialize 후 Json Object 형태로 바꾸는 Function
 * @param formId
 * @param hiddenName
 * @param sColumnName
 * @param sValue
 * @returns
 */
function serializeJsonObject(formId, hiddenName, sColumnName, sValue) {
	var jsonObj = $(formId).serializeObject();
	
	if(sColumnName != null && sColumnName != undefined && sColumnName != "") {
		var arrObj = [];
		$.each(jsonObj[hiddenName], function(i, obj){
			var bIsColumn = obj.hasOwnProperty(sColumnName);
			
			if(bIsColumn) {
				if(sValue != null && sValue != undefined && sValue != "") {
					if(obj[sColumnName] === sValue) {
						arrObj.push(obj);
					}
				} else {
					arrObj.push(obj);
				}
			}
	    });
		jsonObj[hiddenName] = arrObj;
	}
	
	return jsonObj;
}

/**
 * @alias 페이징 처리 함수
 * @param nowPage 현재 페이지 번호
 * @param pageSize 리스트 글 갯수
 * @param blockPage 페이지 갯수
 * @param callback 콜백 함수
 */
function generatePagingHTML(nowPage, pageSize, totalCount, blockPage, goToFoward, tranId){
	if(totalCount != 0){
		var totalPage  = Math.ceil(totalCount/pageSize);
		
		btImgFirst="/images/common/btn/bt_fst.gif"; 
		btImgPrev="/images/common/btn/bt_prev.gif";
		btImgNext="/images/common/btn/bt_next.gif";
		btImgLast="/images/common/btn/bt_end.gif";
		
		var paggingStr = "";
		var intTemp = -1;
		var intLoop = -1;
		
		nowPage = parseInt(nowPage);
					
		if( nowPage != 1 ){
			if( btImgFirst == "" ){
				paggingStr += " <li class=\"fst\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", 1)'>◀</a></li>\n";
			}else{
				paggingStr += " <li class=\"fst\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", 1)'><img src='" + btImgFirst + "' alt=\"처음리스트\" ></a></li>\n";
			}
			if( btImgFirst == "" ){
				paggingStr += " <li class=\"prev\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", " + (nowPage-1) + ")'><</a></li>\n";
			}else{
				paggingStr += " <li class=\"prev\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", " + (nowPage-1) + ")'><img src='" + btImgPrev + "' alt=\"이전리스트 10개\" ></a></li>\n";
			}
		}else{
			if( btImgFirst == "" ){
				paggingStr += " ◀\n";
			}else{
				paggingStr += " <li class=\"fst\"><a><img src='" + btImgFirst + "' alt=\"처음리스트\" ></a></li>\n";
			}
			if( btImgFirst == "" ){
				paggingStr += " <";
			}else{
				paggingStr += " <li class=\"prev\"><a><img src='" + btImgPrev + "' alt=\"이전리스트 10개\" ></a></li>\n";
			}
		}
		
		intTemp = Math.floor((nowPage - 1) / (blockPage*1.0)) * blockPage + 1;
		intLoop = 1;

		while( !( (intLoop > blockPage) || (intTemp > totalPage) ) ){
			if( intTemp == nowPage ){
				paggingStr += " <li class='on'><a  href='javascript:"+goToFoward+"(\"" + tranId + "\", " + intTemp + ")'>" + intTemp + "</a></li>\n";
			}else{
				paggingStr += " <li><a  href='javascript:"+goToFoward+"(\"" + tranId + "\", " + intTemp + ")'>" + intTemp + "</a></li>\n";
			}
			intTemp = intTemp + 1;
			intLoop = intLoop + 1;
		}
		if( nowPage != totalPage){
			if( btImgNext == "" ){
				paggingStr += " <li class=\"next\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", " + (nowPage+1) + ")'>></a></li>\n";
			}else{
				paggingStr += " <li class=\"next\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", " + (nowPage+1) + ")'><img src='" + btImgNext + "' alt=\"다음리스트 10개\" ></a></li>\n";
			}
			if( btImgLast == "" ){
				paggingStr += " <li class=\"end\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", " + totalPage + ")'>▶</a></li>\n";
			}else{
				paggingStr += " <li class=\"end\"><a href='javascript:"+goToFoward+"(\"" + tranId + "\", " + totalPage + ")'><img src='" + btImgLast + "' alt=\"마지막리스트\" ></a></li>\n";
			}
		}else{
			if( btImgNext == "" ){
				paggingStr += " >";
			}else{
				paggingStr += " <li class=\"next\"><a><img src='" + btImgNext + "' alt=\"다음리스트 10개\" ></a></li>\n";
			}
			if( btImgLast == "" ){
				paggingStr += " ▶\n";
			}else{
				paggingStr += " <li class=\"end\"><a><img src='" + btImgLast + "' alt=\"마지막리스트\" ></a></li>\n";
			}
		}
		$(".pagingNav").html(paggingStr);
	}else{
		$(".pagingNav").html("");
	}
}

/**
 * file Max Size Check Function
 * @param el
 * @param targetId
 * @param fileId
 * @param maxSize
 * @returns
 */
function checkFile(el, targetId, fileId, maxSize){
	// files 로 해당 파일 정보 얻기.
	var file = el.files;

	// file[0].size 는 파일 용량 정보입니다.
	if(file[0].size > 1024 * 1024 * maxSize){
		// 용량 초과시 경고후 해당 파일의 용량도 보여줌
		alert(maxSize + 'MB 이하 파일만 등록할 수 있습니다.\n\n' + '현재파일 용량 : ' + (Math.round(file[0].size / 1024 / 1024 * 100) / 100) + 'MB');
		$("#" + fileId).remove();
		$("#" + targetId).append('<input type="file" name="'+fileId+'" id="'+fileId+'" onchange="checkFile(this)">') ;
	}
	// 체크를 통과했다면 종료.
	else return;
}

/**
 * RMS Renewal Function End
 */
728x90

댓글