/** * Protect window.console method calls, e.g. console is not defined on IE * unless dev tools are open, and IE doesn't define console.debug * IE9 이전 버전에서 console 오류 발생을 방지하기 위하여 아래의 처리로직 추가.(IE8등 하위버전 호환을 위하여) * @since 2014.04.29 김철현 */ (function() { // union of Chrome, FF, IE, and Safari console methods var methods = [ 'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn' ]; var console = (window.console = window.console || {}); var noop = function () {}; for (var i=0; i < methods.length; i++) { if ( !(methods[i] in console) ) { // define undefined methods console[methods[i]] = noop; } } })(); /** * jQuery Datepicker Default Setting * 그리드외의 일반 폼에서도 사용하므로 공통 속성을 설정하도록 한다. */ $.datepicker.setDefaults( { dateFormat: "yy-mm-dd" , changeMonth: true , changeYear: true //20년전부터 10년 후까지 , yearRange: ''+((new Date).getFullYear()-20)+ ':'+((new Date).getFullYear()+10) } ); /* * 년도 조회 조건 초기값 */ var _COMMON_DEFAULT_YEAR = 2010; /* * 초기 년도 부터 지정년도까지의 년도를 Return 하는 함수 * param: lastYear [Optional] - 없을 경우 올해년도 -1 년 * return: Array * write: 김철현 * since: 2011.05.01 */ function commonGetYear(lastYear) { var returnArray = []; if (!lastYear) { lastYear = new Date().getFullYear(); } for(var i=_COMMON_DEFAULT_YEAR; i<=parseInt(lastYear, 10); i++) { returnArray.push([i.toString()]); } return returnArray; } /** * jQuery.ajax 통신 중 Error 발생 시 호출 될 콜백함수 * @param jqXHR XMLHttpRequest object * @param textStatus a string describing the type of error * @param errorThrown */ function common_callbackAjaxLoadError(jqXHR, textStatus, errorThrown) { var message; var statusErrorMap = { '400' : "Server understood the request but request content was invalid.", '401' : "Unauthorised access.", '403' : "Forbidden resouce can't be accessed", '500' : "Internal Server Error.", '503' : "Service Unavailable" }; //메세지 구성 if (jqXHR.status) { message =statusErrorMap[jqXHR.status]; if(!message){ message="Unknow Error \n." + errorThrown; } }else if(textStatus=='parsererror'){ message="Error.\nParsing JSON Request failed."; }else if(textStatus=='timeout'){ message="Request Time out."; }else if(textStatus=='abort'){ message="Request was aborted by the server"; }else { message="Unknow Error \n." + errorThrown; } // alert(message); } /** * 목록 버튼 클릭 시 이동할 페이지 URL을 구하는 함수. * @param pHiddenFrame hidden frame Object * @param pHisKey 현재 페이지의 location.pathname 값. * @return String 이동할 페이지 URL(ContextRoot 부터의 주소임.) */ function common_getReturnPage(pHiddenFrame, pHisKey){ //아래 에러가 발생하면 개발자가 로직 확인 후 발생하지 않도록 조치하여야 함. if (pHiddenFrame.commonMoveUrlInfo[pHisKey] == undefined) { console.debug("이전 페이지 URL 정보가 존재하지 않습니다. 정보가 없어도 괜찮은 상황인지 확인 바랍니다."); return ""; } return pHiddenFrame.commonMoveUrlInfo[pHisKey]; } /** * 목록 버튼 클릭 시 이동할 페이지 URL을 구하는 함수. * @param pHiddenFrame hidden frame Object * @param pSourcePageUrl 상세 페이지의 ContextRoot 부터의 Url * @param pReturnPageUrl 이동할 페이지(목록)의 ContextRoot 부터의 Url */ function common_setReturnPage(pHiddenFrame, pSourcePageUrl, pReturnPageUrl){ var hostUrl = location.protocol + "//" + location.hostname; //포트가 없을수도 있으므로.. if(location.port != ""){ hostUrl += ":" + location.port; } // http:// 부터 contextroot 전까지 제거한다. pSourcePageUrl = pSourcePageUrl.replace(hostUrl, ""); pReturnPageUrl = pReturnPageUrl.replace(hostUrl, ""); //전역 개체에 관련 정보 셋팅한다. pHiddenFrame.commonMoveUrlInfo[pSourcePageUrl] = pReturnPageUrl; } /**************************************************************************************************************************************************************** * 이전 공통 함수 등록 ****************************************************************************************************************************************************************/ /*** * * System Global Function * common jsp의 함수는 함수 앞에 common을 붙임. * 함수는 [ 동사(소문자로 시작)+명사(대문자로 시작)]으로 명명. ex}common_calendar() * 전역변수는[ common_변수명 ] 으로 명명. ex)common_trStatus * 함수내에 선언된 것은 prefix 없이 쓴다. * ***/ var common_divLength = 3; //한글 한자를 1byte로 환산하는 기준 (한글1자 = 3byet) /** * 달력을 표시하는 함수(달력을 호출하여 선택된 일자를 EMEdit Object에 담는다. * * @param obj 달력에서 선택된 일자를 보여줄 Object * @return * * @since 2004. 05. 25(전수일) * @2009.03.27 안가희 Emedit 에서도 값을 받을수 있도록 추가. */ function common_calendar(obj) { var result = common_popUpCalendar(); if (result == "") { return; } obj.value = result; } /** * 달력을 PopUp으로 호출한다. * * @param * @return 달력을 PopUp창으로 반환 * * @since 2004. 05. 25(전수일) * modify firefox, chrome에서 너무 작게 열려서 사이즈 조정 (2013.11.07 신명진) */ function common_popUpCalendar() { var s_pos = "dialogWidth:230px;dialogHeight:205px;scroll:no;status:no;center:yes;resizable:yes;"; var s_url = "/common/util/common_calendar.jsp"; var result = window.showModalDialog(s_url, window , s_pos); if (result == "" || result == null) result = ""; return result; } //--------------------------파일 업로드 다운로드 관련----------------------------------------------------- /** * 파라미터로 넘어온 FORM OBJECT 에 HIDDEN ELEMENT 를 설정한다. * * @param documentObject Document Object * @param formObject Form Object * @param objectName Object Name * @param objectValue Object Value * @return null * * @since 2004. 12. 23(전수일). */ function common_setHiddenElement(documentObject, formObject, objectName, objectValue){ if(documentObject.getElementById(objectName)){ documentObject.getElementById(objectName).value = objectValue; }else{ var hiddenElement = documentObject.createElement("input"); hiddenElement.type = 'hidden'; hiddenElement.id = objectName; hiddenElement.name = objectName; hiddenElement.value = objectValue; formObject.appendChild(hiddenElement); } } //--------------------------파일 업로드 다운로드 관련----------------------------------------------------- /** * 첨부파일 DownLoad * * @param orgFileName : 첨부한 파일명 * @param sysFileName : 첨부한 파일을 시스템 규칙에 의하여 바꾼 파일명 * @return * * @since 2005. 08. 01(김철현). * @see common#common_setHiddenElement(documentObject, formObject, objectName, objectValue) */ function common_fileDownload(orgFileName, sysFileName){ var commonForm = document.forms[0]; var commonDocument = document; if (document.all.executeFileFrame == undefined || document.all.executeFileFrame == null){ var iframe = document.createElement("iframe"); //var iframe = document.createElement(""); iframe.setAttribute("id", "executeFileFrame"); iframe.setAttribute("name", "executeFileFrame"); iframe.setAttribute("width", "0"); iframe.setAttribute("height", "0"); iframe.setAttribute("marginwidth", "0"); iframe.setAttribute("marginheight", "0"); iframe.setAttribute("scrolling", "0"); iframe.setAttribute("frameborder", "0"); document.body.appendChild(iframe); } common_setHiddenElement(commonDocument, commonForm, "append_file_nm", encodeURI(orgFileName)); common_setHiddenElement(commonDocument, commonForm, "append_sys_code", sysFileName); commonForm.method = "post"; commonForm.action = "/ncs/CommonFileDownload/downloadFile"; commonForm.target = "executeFileFrame"; commonForm.submit(); } /** * 현재일자를 가져오는 함수 * * @param * @return 현재일자를 반환 * * @since 2005. 08. 01(김철현). */ function common_getDate() { var currDate = new Date(); var yy = currDate.getFullYear(); var tmpMon = currDate.getMonth(); var mon = (tmpMon < 9) ? "0" + (tmpMon + 1) : tmpMon + 1 ; var tmpDay = currDate.getDate(); var day = (tmpDay < 10) ? "0" + tmpDay : tmpDay ; return yy.toString() + mon.toString() + day.toString() ; } /** * 현재일자에서 일정한 일자수만큼 계산해서 반환 * * @param int * @return string * * @since 2006. 11. 21(이석원) */ function common_getDateDiff( num ) { var date = new Date(); var year = date.getFullYear(); var nmonth = date.getMonth(); var day = date.getDate(); var nextDay = date.getDate() + num; date = new Date( year , nmonth , nextDay ); var tmpYy = date.getFullYear(); var yy = (tmpYy > 99) ? tmpYy : 1900 + tmpYy; var tmpMon = date.getMonth(); var mon = (tmpMon < 9) ? "0" + (tmpMon + 1) : tmpMon + 1 ; var tmpDay = date.getDate(); var day = (tmpDay < 10) ? "0" + tmpDay : tmpDay ; return yy.toString() + mon.toString() + day.toString() ; } /** * 현재월에서 일정한 월수만큼 계산해서 반환 * * @param int * @return string * * @since 2006. 12. 11(이석원) */ function common_getMonthDiff( num ){ var date = new Date(); var year = date.getFullYear(); var nmonth = date.getMonth() + num; var day = date.getDate(); date = new Date(year, nmonth, day); var tmpYy = date.getFullYear(); var yy = (tmpYy > 99) ? tmpYy : 1900 + tmpYy; var tmpMon = date.getMonth(); var mon = (tmpMon < 9) ? "0" + (tmpMon + 1) : tmpMon + 1 ; var tmpDay = date.getDate(); var dd = (tmpDay < 10) ? "0" + (tmpDay) : tmpDay ; //2월엔 윤달 계산 후 28, 29일이 되도록(2007. 09. 10 김재열) if(mon == 2 && dd > 28){ if (((yy % 4 == 0) && (yy % 100 != 0)) || (yy % 400 == 0)){ dd = 29; }else { dd = 28; } } return yy.toString() + mon.toString() + dd.toString(); } /** * 날짜의 표기를 바꾸는 함수 * * @param sdate : 기준일자 (string : yyyymmdd) * @param stype : 변환형식 (1:yyyy/mm/dd, 2:yyyy-mm-dd, 3:dd/mm/yyyy, 4:mm/dd/yyyy) * @return 날짜의 표기를 변환하여 변환된 형식으로 날짜를 반환 * * @since 2005. 08. 01(김철현) */ function common_DateMask(sdate,stype, format) { var yy = sdate.substring(0,4); var mm = sdate.substring(4,6); var dd = sdate.substring(6,8); switch (stype) { case 2 : return yy + "-" + mm + "-" + dd; break; case 3 : return dd + "/" + mm + "/" + yy; break; case 4 : return mm + "/" + dd + "/" + yy; break; default : return yy + "/" + mm + "/" + dd; break; } } /** * 좌우 양쪽의 공백제거 * * @param text * @return String text 에서 좌우공백을 제외한 String * * @since 2005. 01. 11(전수일). */ function common_trim(text) { return common_trimRight(common_trimLeft(text)); } /** * 왼쪽공백제거 * * @param text * @return String text 에서 왼쪽공백을 제외한 String * * @since 2005. 01. 11(전수일). */ function common_trimLeft(text) { if (text == "") { return text; } var len = text.length; var st = 0; while ((st < len) && (text.charAt(st) <= ' ')) { st++; } return (st > 0) ? text.substring(st, len) : text; } /** * 오른쪽공백제거 * * @param text * @return String text 에서 오른쪽공백을 제외한 String * * @since 2005. 01. 11(전수일). */ function common_trimRight(text) { if (text == "") { return text; } var len = text.length; var st = 0; while ((st < len) && (text.charAt(len - 1) <= ' ')) { len--; } return (len < text.length) ? text.substring(st, len) : text; } /** * 날짜[년월] 체크 * * @param date Object * @return boolean * * @since 2005. 01. 11(전수일). */ function common_isDateMonth(date) { if (date == null || common_rtnMsg(date, " ", "").length != 6) { return false; } var year = eval(date.substring(0, 4)); var month = eval(date.substring(4, 6)); if (month < 1 || month > 12) { return false; } return true; } /** * 오직 숫자로만 이루어져 있는지 체크 한다. * * @param num Numeric * @return boolean * * @since 2005. 01. 11(전수일). */ function common_isNumber(num, isFloat) { num = common_trimRight(num); //num이 number 인 경우에는 아래 match 함수에서 에러가 발생하므로 //string으로 변환하여야 한다. if (typeof num != "string") { num = num.toString(); } if (isFloat == true){ //numStr = /^-?(\d+\.?\d*)$|(\d*\.?\d+)$/; //num.match(/^\b[0-9]+(\.[0-9]+)?\b$/) if (num.match(/^-?\b[0-9]+(\.[0-9]+)?\b$/)) { return true; } } else { if (num.match(/^\b\d+\b$/)) { return true; } } return false; } /** * CheckBox 에서 특정값을 가진 option 을 선택하기(기존 검색 조건의 복구를 위해 사용) * @CheckBoxObj Target comboBox name * @optoionValue 선택할 값 * @return null */ function common_checkValueByRadio(radioObj,value){ for (var i=0; i < radioObj.length; i++) { if(radioObj[i].value==value){ radioObj[i].checked = true ; } } } /** * 특정 문자집단을 치환하는 함수 * @param argMsg :바꾸고자 하는 원래의 문자열 * @param replaceChar : 바꾸고자 하는 특정문자 * @param replaceMsg : 특정문자를 치환하고자 하는 String * @return String * * @since 2007. 01. 23(김인숙) */ //-------------------------------------------------------------------------------------------------- //특정문자를 원하는 문자로 대치하는 함수 //-------------------------------------------------------------------------------------------------- function common_rtnMsg(str, oldVal, newVal) { if (str.length < 1) { return ""; }else{ for (var i = 0; i < str.length; i++) { str = str.replace(oldVal,newVal); } return str; } } /* * Copyright (C) 2006 Baron Schwartz * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, version 2.1. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * $Revision: 1.3 $ */ //Abbreviations: LODP = Left Of Decimal Point, RODP = Right Of Decimal Point Number.formatFunctions = {count:0}; //Constants useful for controlling the format of numbers in special cases. Number.prototype.NaN = 'NaN'; Number.prototype.posInfinity = 'Infinity'; Number.prototype.negInfinity = '-Infinity'; Number.prototype.numberFormat = function(format, context) { if (isNaN(this) ) { return Number.prototype.NaNstring; } else if (this == +Infinity ) { return Number.prototype.posInfinity; } else if ( this == -Infinity) { return Number.prototype.negInfinity; } else if (Number.formatFunctions[format] == null) { Number.createNewFormat(format); } return this[Number.formatFunctions[format]](context); } Number.createNewFormat = function(format) { var funcName = "format" + Number.formatFunctions.count++; Number.formatFunctions[format] = funcName; var code = "Number.prototype." + funcName + " = function(context){\n"; // Decide whether the function is a terminal or a pos/neg/zero function var formats = format.split(";"); switch (formats.length) { case 1: code += Number.createTerminalFormat(format); break; case 2: code += "return (this < 0) ? this.numberFormat(\"" + String.escape(formats[1]) + "\", 1) : this.numberFormat(\"" + String.escape(formats[0]) + "\", 2);"; break; case 3: code += "return (this < 0) ? this.numberFormat(\"" + String.escape(formats[1]) + "\", 1) : ((this == 0) ? this.numberFormat(\"" + String.escape(formats[2]) + "\", 2) : this.numberFormat(\"" + String.escape(formats[0]) + "\", 3));"; break; default: code += "throw 'Too many semicolons in format string';"; break; } eval(code + "}"); } Number.createTerminalFormat = function(format) { // If there is no work to do, just return the literal value if (format.length > 0 && format.search(/[0#?]/) == -1) { return "return '" + String.escape(format) + "';\n"; } // Negative values are always displayed without a minus sign when section separators are used. var code = "var val = (context == null) ? new Number(this) : Math.abs(this);\n"; var thousands = false; var lodp = format; var rodp = ""; var ldigits = 0; var rdigits = 0; var scidigits = 0; var scishowsign = false; var sciletter = ""; // Look for (and remove) scientific notation instructions, which can be anywhere m = format.match(/\..*(e)([+-]?)(0+)/i); if (m) { sciletter = m[1]; scishowsign = (m[2] == "+"); scidigits = m[3].length; format = format.replace(/(e)([+-]?)(0+)/i, ""); } // Split around the decimal point var m = format.match(/^([^.]*)\.(.*)$/); if (m) { lodp = m[1].replace(/\./g, ""); rodp = m[2].replace(/\./g, ""); } // Look for % if (format.indexOf('%') >= 0) { code += "val *= 100;\n"; } // Look for comma-scaling to the left of the decimal point m = lodp.match(/(,+)(?:$|[^0#?,])/); if (m) { code += "val /= " + Math.pow(1000, m[1].length) + "\n;"; } // Look for comma-separators if (lodp.search(/[0#?],[0#?]/) >= 0) { thousands = true; } // Nuke any extraneous commas if ((m) || thousands) { lodp = lodp.replace(/,/g, ""); } // Figure out how many digits to the l/r of the decimal place m = lodp.match(/0[0#?]*/); if (m) { ldigits = m[0].length; } m = rodp.match(/[0#?]*/); if (m) { rdigits = m[0].length; } // Scientific notation takes precedence over rounding etc if (scidigits > 0) { code += "var sci = Number.toScientific(val," + ldigits + ", " + rdigits + ", " + scidigits + ", " + scishowsign + ");\n" + "var arr = [sci.l, sci.r];\n"; } else { // If there is no decimal point, round to nearest integer, AWAY from zero if (format.indexOf('.') < 0) { code += "val = (val > 0) ? Math.ceil(val) : Math.floor(val);\n"; } // Numbers are rounded to the correct number of digits to the right of the decimal code += "var arr = val.round(" + rdigits + ").toFixed(" + rdigits + ").split('.');\n"; // There are at least "ldigits" digits to the left of the decimal, so add zeros if needed. code += "arr[0] = (val < 0 ? '-' : '') + String.leftPad((val < 0 ? arr[0].substring(1) : arr[0]), " + ldigits + ", '0');\n"; } // Add thousands separators if (thousands) { code += "arr[0] = Number.addSeparators(arr[0]);\n"; } // Insert the digits into the formatting string. On the LHS, extra digits are copied // into the result. On the RHS, rounding has chopped them off. code += "arr[0] = Number.injectIntoFormat(arr[0].reverse(), '" + String.escape(lodp.reverse()) + "', true).reverse();\n"; if (rdigits > 0) { code += "arr[1] = Number.injectIntoFormat(arr[1], '" + String.escape(rodp) + "', false);\n"; } if (scidigits > 0) { code += "arr[1] = arr[1].replace(/(\\d{" + rdigits + "})/, '$1" + sciletter + "' + sci.s);\n"; } return code + "return arr.join('.');\n"; } Number.toScientific = function(val, ldigits, rdigits, scidigits, showsign) { var result = {l:"", r:"", s:""}; var ex = ""; // Make ldigits + rdigits significant figures var before = Math.abs(val).toFixed(ldigits + rdigits + 1).trim('0'); // Move the decimal point to the right of all digits we want to keep, // and round the resulting value off var after = Math.round(new Number(before.replace(".", "").replace( new RegExp("(\\d{" + (ldigits + rdigits) + "})(.*)"), "$1.$2"))).toFixed(0); // Place the decimal point in the new string if (after.length >= ldigits) { after = after.substring(0, ldigits) + "." + after.substring(ldigits); } else { after += '.'; } // Find how much the decimal point moved. This is #places to LODP in the original // number, minus the #places in the new number. There are no left-padded zeroes in // the new number, so the calculation for it is simpler than for the old number. result.s = (before.indexOf(".") - before.search(/[1-9]/)) - after.indexOf("."); // The exponent is off by 1 when it gets moved to the left. if (result.s < 0) { result.s++; } // Split the value around the decimal point and pad the parts appropriately. result.l = (val < 0 ? '-' : '') + String.leftPad(after.substring(0, after.indexOf(".")), ldigits, "0"); result.r = after.substring(after.indexOf(".") + 1); if (result.s < 0) { ex = "-"; } else if (showsign) { ex = "+"; } result.s = ex + String.leftPad(Math.abs(result.s).toFixed(0), scidigits, "0"); return result; } Number.prototype.round = function(decimals) { if (decimals > 0) { var m = this.toFixed(decimals + 1).match( new RegExp("(-?\\d*)\.(\\d{" + decimals + "})(\\d)\\d*$")); if (m && m.length) { return new Number(m[1] + "." + String.leftPad(Math.round(m[2] + "." + m[3]), decimals, "0")); } } return this; } Number.injectIntoFormat = function(val, format, stuffExtras) { var i = 0; var j = 0; var result = ""; var revneg = val.charAt(val.length - 1) == '-'; if ( revneg ) { val = val.substring(0, val.length - 1); } while (i < format.length && j < val.length && format.substring(i).search(/[0#?]/) >= 0) { if (format.charAt(i).match(/[0#?]/)) { // It's a formatting character; copy the corresponding character // in the value to the result if (val.charAt(j) != '-') { result += val.charAt(j); } else { result += "0"; } j++; } else { result += format.charAt(i); } ++i; } if ( revneg && j == val.length ) { result += '-'; } if (j < val.length) { if (stuffExtras) { result += val.substring(j); } if ( revneg ) { result += '-'; } } if (i < format.length) { result += format.substring(i); } return result.replace(/#/g, "").replace(/\?/g, " "); } Number.addSeparators = function(val) { return val.reverse().replace(/(\d{3})/g, "$1,").reverse().replace(/^(-)?,/, "$1"); } String.prototype.reverse = function() { var res = ""; for (var i = this.length; i > 0; --i) { res += this.charAt(i - 1); } return res; } String.prototype.trim = function(ch) { if (!ch) ch = ' '; return this.replace(new RegExp("^" + ch + "+|" + ch + "+$", "g"), ""); } String.leftPad = function (val, size, ch) { var result = new String(val); if (ch == null) { ch = " "; } while (result.length < size) { result = ch + result; } return result; } String.escape = function(string) { return string.replace(/('|\\)/g, "\\$1"); } $.fn.digits = function(){ return this.each(function(){ $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); }) }; /** * 언어 변경 * @since 2014. 01. 21(김재열) 20190911 ctxCheckPath -> ctxUnCheckPath */ function common_setLang(langCode){ document.location.href = "/ncs/CommonLocaleController/setLocale?langCode="+langCode; } /** * jqGrid resize 를 위한 함수 * @param leftSize : 좌측 메뉴 사이즈 * @return 없음 * @since 2014. 02. 21(김재열). * @modify : 2014. 02. 24(신명진) * splitter가 있는 경우 화면이 나뉘어 있으므로 별도로 사이즈 처리, 왼쪽 그리드 id에 'L'을 넣어줘야하는 제약이 있음 * @modify : 2014.03.06(장우석) chart 와 jqgrid 가 같이 있는 화면의 리사이즈 처리. 그리드의 width 를 60%로 주어서 제어함.(jsp 에서 chart width를 40%, 그리드 width 를 60% 로 주었음) * 전체 화면에 적용가능하지 않다면 인접한 개체를 찾는 셀렉터가 있다고 하니 추후에 셀렉터를 사용하여 수정할 것 * @modify : 2014.07.22(김철현) grid heigh도 resize가 되도록 수정 * @modify : 2014.10.19(이광희) MySplitter 가 있어도 전체를 써야하는 그리드가 있으므로 splitter가 있는 경우는 L과 R을 붙이도록 수정 */ function common_resize(leftSize){ //높이를 구하는데 필요한 변수 셋팅. var gridCount = $("div[id*='gbox_']").length; //그리드의 개수(그리드 개수만큼 분배하기 위함) //메뉴높이,footer 등 기본 높이값 셋팅 var defaultHeight = 220 + 115 + $("div#footer").height(); var bindHeight = ($('.TopMenuOpen').css('display')=='none')?defaultHeight:(defaultHeight-110); //버튼,입력폼,tip 등의 화면 기본컨트롤 높이 저장, var clientHeight = $(window).height(); //좌측메뉴가 길어서 document 길이가 화면보다 길어진 경우에는 footer가 안보이므로 그리드 높이에 footer높이가 반영되도록 한다. //단 각 페이지가 처음 로딩시에는 좌측 메뉴가 동적으로 그려지고 common_resize 호출 시점보다 늦은 관계로 반영이 안될 수도 있다. if ($("div#sidebar").height() > clientHeight) { bindHeight -= $("div#footer").height(); } var gridHeight = 0; //그리드가 존재할 경우 수행 if (gridCount > 0) { //그리드외에 화면을 구성하는 요소의 높이를 구한다. $('div.box, div.tip_wrapper, textarea, div#body_head, div.bind_contents, div.bind_h2, div.bind_btn_h1, div.title, div.bind_h2_result').each(function(){ bindHeight += $(this).height(); }); //그리드 하나당 높이를 구한다. gridHeight = parseInt((clientHeight - bindHeight) / gridCount, 10); } if(!leftSize) leftSize = 0; $("div[id*='gbox_']").each(function(){ var gridId = this.id.substring(5); if($("td[id*='chart']").length > 0){ $("#"+gridId).setGridWidth(($("#page_contents").width()+leftSize) * 0.6); } else if($("#"+gridId).parents("td[resize]").length > 0){ var w = $("#"+gridId).parents("td[resize]")[0].width; if(w.indexOf("%") > -1){ w = $("#page_contents").width()*($("#"+gridId).parents("td[resize]")[0].width.replace("%","")/100); } $("#"+gridId).setGridWidth(parseInt(w, 10)+(leftSize/$("td[resize]").length), false); } else{ $("#"+gridId).setGridWidth(($("#page_contents").width())+leftSize); } //위에서 구한 gridHeight 와 원본 높이를 비교하여 처리한다. if (gridHeight > $("#"+gridId).jqGrid("getGridParam", "_orgHeight")) { $("#"+gridId).setGridHeight(gridHeight-($($("#"+gridId).jqGrid("getGridParam", "pager")).height())); } else { $("#"+gridId).setGridHeight($("#"+gridId).jqGrid("getGridParam", "_orgHeight")); } common_groupHeaderResize(gridId); }); } /** * jqGrid GroupHeader resize 를 위한 함수 * @param gridId : 그리드 Id * @return 없음 * @since 2014. 04. 24(김철현). */ function common_groupHeaderResize(gridId) { var groupHeaders = $("#" + gridId).jqGrid("getGridParam", "groupHeader"); if (groupHeaders != null) { $("#" + gridId).jqGrid("destroyGroupHeader").jqGrid("setGroupHeaders", groupHeaders); } } /** * jquery datepicker(달력) 공통 옵션 세팅 * @return 공통 옵션 세팅 값 * @since 2014. 02. 25(김재열). */ function common_setDatepicker(){ var obj = new Object(); obj.dateFormat = "yy-mm-dd"; obj.showButtonPanel = true; obj.changeMonth = true; obj.changeYear = true; return obj; } /** * jquery datepicker(달력) 공통 옵션 세팅 * @since 2014. 02. 25(김재열). */ function common_datepicker(obj){ obj.datepicker({ dateFormat: "yy-mm-dd", showButtonPanel: true, //하단 닫기 영역 changeMonth: true, //selectbox changeYear: true, //selectbox showOn: 'both', //input과 image 동시 사용 buttonImage: '/common/images/icon/calendar.png', onClose: function(dateText, inst){ //splitter show $(".splitter-bar.splitter-bar-vertical.ui-state-default").show(); }, beforeShow:function(input, inst){ //splitter hide $(".splitter-bar.splitter-bar-vertical.ui-state-default").hide(); } }); $(".ui-datepicker-trigger").attr("style", "cursor: pointer; padding-left:2px"); //달력 아이콘(icon) 위치 } /** * jquery ui monthpicker plugin(월달력) 공통 옵션 세팅 * @since 2014. 03. 06(신명진). */ function common_monthpicker(obj){ obj.monthpicker({ pattern: "yyyy-mm", showOn:"both", buttonImage: '/common/images/icon/calendar.png', }).bind('monthpicker-show', function(e){ //splitter hide $(".splitter-bar.splitter-bar-vertical.ui-state-default").hide(); }).bind("monthpicker-hide", function(e){ //splitter show $(".splitter-bar.splitter-bar-vertical.ui-state-default").show(); }); $("div[id^='monthpicker']").each(function(idx){ $("div[id^='monthpicker']")[idx].style.width = "150px"; }); } /** * 날짜 체크 * * @param date Object * @return boolean * * @since 2005. 01. 11(전수일) * 파라미터에 공백을 제거하기 위해 common_rtnMsg으로 공백 처리 추가(2007. 10. 18 김도형) * 숫자인 데이터만 가능 하도록 추가(2008. 09. 22 오용욱) */ function common_isDate(date) { if (date == null || common_rtnMsg(date, " ", "").length != 8 || !common_isNumber(date)) { return false; } var year = eval(date.substring(0, 4)); var month = eval(date.substring(4, 6)); var day = eval(date.substring(6, 8)); if (month < 1 || month > 12) { return false; } var totalDays; switch (eval(month)){ case 1 : totalDays = 31; break; case 2 : if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) totalDays = 29; else totalDays = 28; break; case 3 : totalDays = 31; break; case 4 : totalDays = 30; break; case 5 : totalDays = 31; break; case 6 : totalDays = 30; break; case 7 : totalDays = 31; break; case 8 : totalDays = 31; break; case 9 : totalDays = 30; break; case 10 : totalDays = 31; break; case 11 : totalDays = 30; break; case 12 : totalDays = 31; break; } if (day > totalDays) { return false; } return true; } /** * 날짜 체크(MMDD형식) * * @param date Object * @return boolean * * @since 2015. 08. 04(지창용) * 월일형식으로 체크하는 기능 추가. */ function common_isDateMMDD(date) { date = date.split("-").join(""); if (date == null || common_rtnMsg(date, " ", "").length != 4 || !common_isNumber(date)) { return false; } var month = eval(date.substring(0, 2)); var day = eval(date.substring(2, 5)); if (month < 1 || month > 12) { return false; } var totalDays; switch (eval(month)){ case 1 : totalDays = 31; break; case 2 : totalDays = 28; break; case 3 : totalDays = 31; break; case 4 : totalDays = 30; break; case 5 : totalDays = 31; break; case 6 : totalDays = 30; break; case 7 : totalDays = 31; break; case 8 : totalDays = 31; break; case 9 : totalDays = 30; break; case 10 : totalDays = 31; break; case 11 : totalDays = 30; break; case 12 : totalDays = 31; break; } if (day > totalDays) { return false; } return true; } /** * 특정차량검색 박스 input 시 검색어 자동완성 함수 * ts 대상input태그 */ function common_specificVehicleSearchAuto(ts, ulId){ if($(ts).val() == ""){ $("#"+ulId).children().remove(); return; } $.ajax({ type: "POST", dataType: "json", url: "/ncs/KncapCommon/selectPredictiveList.json", data: {"PREDICT_SEARCH":$(ts).val()}, success: function(result, textStatus, jqXHR){ if (common_confirmServerMessage(result)){ return; } var ul = $("#"+ulId); ul.children().remove(); var item = result.predictList; if(item.length <= 0) { var li = document.createElement("li"); var strong = document.createElement("strong"); strong.innerHTML = "No Result"; li.appendChild(strong); ul.append(li); } else { for(var i=0; i -1){ if(type == "combo"){ msg = "Maker"; }else{ msg = "Car Segment"; } if($("#"+parentSelId).val() == "" || $("#"+brandSelId).val() == ""){ alert($.validator.format('Select a maker and brand', msg)); return; } var arrId = $("#"+brandSelId).val().split("_"); idx = arrId[1]; year = arrId[2]; } else{ idx = type; year = selYear; } if(year < '2013'){ url = "KncapEvalOldResultDetial/initList.jsp?_menu_code_=KNCAP_EVAL_OLD_RESULT_LS&DETAIL_IDX="+idx+"&DETAIL_YEAR="+year; }else{ if(year>='2017'){ url = "KncapEvalResultDetail/initList2017.jsp?_menu_code_=KNCAP_EVAL_RESULT_LS&DETAIL_IDX="+idx+"&DETAIL_YEAR="+year; }else{ url = "KncapEvalResultDetail/initList.jsp?_menu_code_=KNCAP_EVAL_RESULT_LS&DETAIL_IDX="+idx+"&DETAIL_YEAR="+year; } } location.href = "/app/"+url; } /** * 숫자 체크 */ function checkRoundNumeric(_obj) { var str = ""; if(typeof(_obj) != "undefined") { var pattern = /^[0-9.]+$/; str = _obj.value; if(str.length > 0 && !pattern.test(str)) { alert("숫자로 입력해주세요"); _obj.value = ""; return str; } else if (str.length > 9) { alert("유효하지 않은 숫자입니다."); _obj.value = ""; return str; } } return str; } function check100Numeric(_obj) { var str = ""; if(typeof(_obj) != "undefined") { var pattern = /^[0-9.]+$/; str = _obj.value; if(str.length > 0 && !pattern.test(str)) { alert("숫자로 입력해주세요"); _obj.value = ""; return str; } else if (str.length > 9) { alert("유효하지 않은 숫자입니다."); _obj.value = ""; return str; } else if (parseInt(str, 10) > 100) { alert("너무 큰 범위입니다."); _obj.value = ""; return str; } } return str; } function checkIntegerNumeric(_obj) { var str = ""; if(typeof(_obj) != "undefined") { var pattern = /^[0-9]+$/; str = _obj.value; if(str.length > 0 && !pattern.test(str)) { alert("숫자로 입력해주세요"); _obj.value = ""; return str; } else if (str.length > 9) { alert("유효하지 않은 숫자입니다."); _obj.value = ""; return str; } } return str; } function rtnParseFloat(value) { var str = 0; if (value != undefined || value != "") { var pattern = /^[0-9.]+$/; if(value.length > 0 && pattern.test(value)) { str = parseFloat(value, 10);; } } return str; } function common_getDateCount( date1 , date2 ){ var date01 = new Date( eval( date1.substring( 0 , 4 ) ) , eval( date1.substring( 4 , 6 ) ) - 1 , eval( date1.substring( 6 , 8 ) ) ); var date02 = new Date( eval( date2.substring( 0 , 4 ) ) , eval( date2.substring( 4 , 6 ) ) - 1 , eval( date2.substring( 6 , 8 ) ) ); var date_count = (date02.getTime() - date01.getTime()) / (24*60*60*1000) + 1; return date_count; } /** * 두 날짜사이의 달수를 카운트로 반환 * * @param yyyymm1 , yyyymm2 * @return int * * @since 2008. 05. 08(황용연) */ function common_getMonthCount( yyyymm1 , yyyymm2 ){ var date1 = new Date( eval( yyyymm1.substring( 0 , 4 ) ) , eval( yyyymm1.substring( 4 , 6 ) ) - 1 , 01); var date2 = new Date( eval( yyyymm2.substring( 0 , 4 ) ) , eval( yyyymm2.substring( 4 , 6 ) ) - 1 , 10);//같은 01로 줄경우 한달이 30일 일 경우 한달 차이를 인식 못하므로 날짜의 차이를 더 둠 var diffDate = new Date(date2.getTime() - date1.getTime()); var month_count = (diffDate.getFullYear()-1970)*12 + diffDate.getMonth(); return month_count; } /** * jQGrid 데이터 엑셀로 Export 처리 * * @param gridObj : 그리드 Object * @param excelFileName : Export 할 엑셀 파일명 * @param excelTitle : 엑셀 타이틀 * @return * * @since 2019.08.20 */ function common_excelExport(gridObj, pFileName, excelTitle, accessType){ var allJQGridData = gridObj.jqGrid("getGridParam", "data"); var excelFileName = pFileName.replace(//g, ""); excelFileName = pFileName.replace(/ /g, ""); if (allJQGridData.length <= 0) { return; } var jqgridRowIDs = gridObj.getDataIDs(); var headerData = gridObj.getRowData(jqgridRowIDs[0]); var columnNames = new Array(); var columnHeaders = new Array(); var allColumnNames = gridObj.jqGrid("getGridParam", "colModel"); $("#excelExportForm").children().remove(); for (var headerValue in headerData) { var isColumnHidden = gridObj.jqGrid("getColProp", headerValue).hidden; var idxImg = headerValue.indexOf("IMG") + headerValue.indexOf("IMAGE"); if (!isColumnHidden && headerValue != null && idxImg <= -2) { columnNames.push(headerValue); $(gridObj[0].p.colModel).each(function(i){ if (this.name === headerValue) { columnHeaders.push(this.label); } }); } } var excelData = ""; for (var k = 0; k < columnNames.length; k++) { excelData += columnHeaders[k] + "▥"; } excelData = common_removeLastChar(excelData) + "▤"; var postElement = ""; var colName, cellValue = "", data; for(var i=0; i -1) { cellValue = $(cellValue).text(); } cellValue = cellValue.replace(/'/g, "'"); excelData += cellValue + "▥"; } } excelData = common_removeLastChar(excelData) + "▤"; } postElement = ""; postElement += ""; postElement += ""; $("#excelExportForm").append(postElement); if (accessType == "W" || accessType == "A") { $("#excelExportForm")[0].target = "_self"; } else { $("#excelExportForm")[0].target = "_blank"; } $("#excelExportForm")[0].action = "/ncs/CommonExcelExport/excelExport.excel"; $("#excelExportForm")[0].submit(); } /** * 문자열 자르기 * * @param str : 자를 문자열 * @return str : 끝에서 한자리 잘린 문자열 * * @since 2019.08.20 */ function common_removeLastChar(str) { // Remove the last character from a string return str.substring(0, str.length - 1); } /** * 버튼체크 * * @param str : 자를 문자열 * @return str : 끝에서 한자리 잘린 문자열 * * @since 2019.08.21 */ function common_radioCheck(objId, value){ $(":radio[name='" + objId + "'][value='" + value+ "']").prop("checked", true); $(":radio[name='" + objId + "'][value!='" + value+ "']").prop("checked", false); } function common_checkboxCheck(objId, value, selVal, unselVal) { var obj = $("#" + objId); obj.val(value); if(value == selVal) { obj.prop("checked", true); } else { obj.prop("checked", false); } } function common_checkboxRevalue(objId, selVal, unselVal) { var objOrg = $("#chk" + objId); var obj = $("#" + objId); if (objOrg.is(':checked')) { obj.val(selVal); } else { obj.val(unselVal); } } /** * 문자열 길이 제한 */ function checkCharLength(_obj, maxlength) { var str = ""; if(typeof(_obj) != "undefined") { str = _obj.value; if(str.length > maxlength) { alert("글자수 " + maxlength + " 이하로 입력해주세요."); _obj.value = ""; return str; } } return str; }