var DateUtil = {
    /*============================
     * 현재날짜로부터 월 단위로 계산된 날짜(yyyymmdd) 반환
     *  -addMonth가 0 이면 현재월
     *  -음의 숫자면 전월 (ex: -1 전월, -2 전전월, -3 ...)
     *  -양의 숫자면 차월 (ex: 1 차월, 2 차차월, 3 ...)
     ============================*/
    getDate : function(){
        var result = new Object();
        switch (arguments.length) {
            case 1:
                result = calcDate(arguments[0]);
                break;
            case 2:
                result = calcDate(arguments[0], arguments[1]);
                break;
            default:
                result = calcDate();
                break;
        }
        return result;

        //날짜 계산
        function calcDate(addMonth, stdDay){
            if(addMonth!=undefined)
                addMonth = addMonth + 1;
            addMonth = addMonth==undefined?1:addMonth;


            /*
             * 필수값 설정
             *  -날짜 설정
             *  -ago OR after 여부 설정
             */
            var date  = new Date();
            var yyyy  = date.getFullYear();
            var mm = ( date.getMonth() + (addMonth) );
            var dd = date.getDate();
            if(stdDay!=undefined){
                stdDay = stdDay.replace(/[^0-9]/gi,'');
                yyyy = stdDay.substring(0,4);
                mm = stdDay.substring(4,6);
                dd = stdDay.substring(6,8);

                if(addMonth==13)
                    yyyy = Number(yyyy)+1;
            }

            var isAfter = false;
            if((addMonth*1)>0)
                isAfter = true;

            /*
             * 유효성 처리
             *  -해(year) 넘김 처리
             *  -말일(last day) 처리
             */
            var newYear = DateUtil.getNewYear(isAfter, yyyy, mm);
            yyyy = newYear.yyyy;
            mm = newYear.mm;
            var ago_last_dd = DateUtil.getEndOfMonthDay(yyyy, mm);
            dd = dd>ago_last_dd?ago_last_dd:dd;


            /*
             * format 설정
             */
            if( (''+dd).length == 1 )
                dd = "0"+ dd;


            /*
             * 결과 반환
             */
            var obj = new Object();
            obj.date = ""+yyyy+mm+dd;
            obj.yyyy = ""+yyyy;
            obj.mm = ""+mm;
            obj.dd = ""+dd;
            return obj;
        }
    },

    //+ 한달 후 말일 계산
    getAddMonth : function(stdDay){
        //날짜 계산

        var rtnVal = calcDate(0,stdDay);
        return rtnVal;


        function calcDate(addMonth, stdDay){
            if(addMonth!=undefined)
                addMonth = addMonth + 1;
            addMonth = addMonth==undefined?1:addMonth;


            /*
             * 필수값 설정
             *  -날짜 설정
             *  -ago OR after 여부 설정
             */
            stdDay = stdDay.replace(/[^0-9]/gi,'');
            var	yyyy = stdDay.substring(0,4);
            var	mm = stdDay.substring(4,6);
            var	dd = stdDay.substring(6,8);
            mm = Number(mm)+addMonth;
            if(addMonth==13)
                yyyy = Number(yyyy)+1;

            var isAfter = false;
            if((addMonth*1)>0)
                isAfter = true;

            /*
             * 유효성 처리
             *  -해(year) 넘김 처리
             *  -말일(last day) 처리
             */
            var newYear = DateUtil.getNewYear(isAfter, yyyy, mm);
            yyyy = newYear.yyyy;
            mm = newYear.mm;
            var ago_last_dd = DateUtil.getEndOfMonthDay(yyyy, mm);
            dd = ago_last_dd;


            /*
             * format 설정
             */
            if( (''+dd).length == 1 )
                dd = "0"+ dd;


            /*
             * 결과 반환
             */
            var obj = new Object();
            obj.date = ""+yyyy+mm+dd;
            obj.yyyy = ""+yyyy;
            obj.mm = ""+mm;
            obj.dd = ""+dd;
            return obj;
        }
    },

    /*============================
     * 현재날짜(or 기준일)로부터 일 단위로 계산된 날짜(yyyymmdd) 반환
     *  -addDay가 0 이면 금일
     *  -음의 숫자면 전일 (ex: -1 작일, -2 재작일, -3 ...)
     *  -양의 숫자면 차일 (ex: 1 명일, 2 재명일, 3 ...)
     ============================*/
    getDateDay: function(addDay){
        var result = new Object();
        switch (arguments.length) {
            case 1:
                result = calcDate(arguments[0], DateUtil.getDate().date);
                break;
            default:
                result = calcDate(0, DateUtil.getDate().date);
                break;
        }
        return result;


        //날짜 계산
        function calcDate(addDay, stdDay){
            addDay = addDay==undefined||addDay==null?0:addDay*1;

            /*
             * 필수값 설정
             *  -날짜 설정
             *  -ago OR after 여부 설정
             */
            var yyyy = stdDay.substring(0,4);
            var mm = stdDay.substring(4,6);
            var dd = stdDay.substring(6,8);
            var dateObj = new Date(yyyy, (mm-1)*1, dd*1);
            dateObj.setDate(dateObj.getDate()+(addDay));

            yyyy = dateObj.getFullYear();
            mm = dateObj.getMonth()+1;
            dd = dateObj.getDate();

            if( (''+mm).length == 1 )
                mm = "0"+ mm;
            if( (''+dd).length == 1 )
                dd = "0"+ dd;

            /*
             * 결과 반환
             */
            var obj = new Object();
            obj.date = ""+yyyy+"-"+mm+"-"+dd;
            obj.yyyy = yyyy;
            obj.mm = mm;
            obj.dd = dd;
            return obj;
        }
    },
    /*============================
     * 달의 마지막 날짜(dd) 반환
     ============================*/
    getEndOfMonthDay : function(yy, mm){
        var max_days=0;
        if(mm == 1 || mm == '01') {
            max_days = 31 ;
        } else if(mm == 2 || mm == '02') {
            if ((( yy % 4 == 0) && (yy % 100 != 0)) || (yy % 400 == 0))
                max_days = 29;
            else
                max_days = 28;
        }
        else if (mm == 3 || mm == '03')  max_days = 31;
        else if (mm == 4 || mm == '04')  max_days = 30;
        else if (mm == 5 || mm == '05')  max_days = 31;
        else if (mm == 6 || mm == '06')  max_days = 30;
        else if (mm == 7 || mm == '07')  max_days = 31;
        else if (mm == 8 || mm == '08')  max_days = 31;
        else if (mm == 9 || mm == '09')  max_days = 30;
        else if (mm == 10 || mm == '10')  max_days = 31;
        else if (mm == 11 || mm == '11')  max_days = 30;
        else if (mm == 12 || mm == '12')  max_days = 31;
        else         return '';
        return max_days;
    },

    /*============================
     * 해(year) 넘김 처리
     ============================*/
    getNewYear : function(isAfter, yyyy, mm){
        /*
         * 해(year) 넘김 처리
         */
        if(isAfter){
            if(mm>12){
                var formula = Math.floor(mm/12);
                yyyy = Number(yyyy)+(formula);
                mm = mm - ((formula)*12);
            }
        }else{
            if(mm<1){
                var formula = Math.floor((mm*(-1))/12)+1;
                yyyy = yyyy-(formula);
                mm = mm + ((formula)*12);
            }
        }

        /*
         * 포맷 설정
         *  -월(month) 두자리 설정
         */
        if( (''+mm).length == 1 )
            mm = "0"+ mm;

        /*
         * 결과 반환
         */
        var obj = new Object();
        obj.yyyy = ''+yyyy;
        obj.mm = ''+mm;
        return obj;
    }
}


function getDateObject(dateStr){
	var year  = dateStr.substr(0,4);
    var month = dateStr.substr(4,2) - 1;
    var day   = dateStr.substr(6,2);
   
    return new Date(year,month,day);
}

function getDateString(dateObj) {
  var result = "";
 
  var dateFormat = "YYYYMMDD";

  for (var i = 0; i < dateFormat.length; i++) {
    result += dateFormat.indexOf("YYYY", i) == i ? (i+=3, dateObj.getFullYear()      ) :
              dateFormat.indexOf("MM",   i) == i ? (i+=1, to2(dateObj.getMonth()+1)  ) :
              dateFormat.indexOf("DD",   i) == i ? (i+=1, to2(dateObj.getDate())    ) :
                                                   (dateFormat.charAt(i)             );
  }
  return result;
};

function to2(numberObj) { 
	return (numberObj > 9 ? "" : "0") + numberObj; 
};

/**
 * 입력일의 이전일 계산
 */
function getPrevDay(datestr, days) {
    if ( days == "0") return datestr;
    datestr = datestr.replace(/-/g, "");
    if (datestr == "") return "";
    var dateObj = window.getDateObject(datestr);

    dateObj.setDate(dateObj.getDate() - parseInt(days, 10));

    return window.getDateString(dateObj);
};

/**
 * 입력일의 다음일 계산
 */
function getNextDay(datestr, days) {
    if ( days == "0") return datestr;
    datestr = datestr.replace(/-/g, "");
    if (datestr == "") return "";
    var dateObj = window.getDateObject(datestr);

    dateObj.setDate(dateObj.getDate()+ parseInt(days, 10));

    return window.getDateString(dateObj);
};

/**
 * 해당월의 마지막날
 */
function getLastDay(datestr) {
    datestr = datestr.replace(/-/g, "");
    if (datestr == "") return "";
    var strNextMonth = window.addMonth(datestr, 1);
    strNextMonth = strNextMonth.replace(/-/g, "");
    datestr = strNextMonth.substring(0, 6) + '01';
    var strLastDay = window.addDate(datestr, -1);
    strLastDay = strLastDay.replace(/-/g, "");
    var dateObj = window.getDateObject(strLastDay);
    return dateObj.getDate();
};

/**
 * 년, 월, 일을 입력 받아 Date String으로 변환
 */
function getDatetime(nYear, nMonth, nDate){
    var dateObj = null;

    if (nYear.toString().trim().length >= 5) {
        var sDate    = new String(nYear);
        var nYear    = sDate.substr(0,4);
        var nMonth   = sDate.substr(4,2);
        var nDate    = ((sDate.substr(6,2) == "") ? 1 : sDate.substr(6,2));
        var nHours   = ((sDate.substr(8,2) == "") ? 0 : sDate.substr(8,2));
        var nMinutes = ((sDate.substr(10,2) == "") ? 0 : sDate.substr(10,2));
        var nSeconds = ((sDate.substr(12,2) == "") ? 0 : sDate.substr(12,2));

        dateObj = new Date(parseInt(nYear), parseInt(nMonth)-1, parseInt(nDate), parseInt(nHours), parseInt(nMinutes), parseInt(nSeconds));
    } else {
        dateObj = new Date(parseInt(nYear), parseInt(nMonth)-1, parseInt(((nDate == null) ? 1 : nDate)));
    }

    var strYear  = dateObj.getFullYear().toString();
    var strMonth = (dateObj.getMonth() + 1).toString();
    var strDate  = dateObj.getDate().toString();
    if (strMonth.length == 1)  strMonth  = "0" + strMonth;
    if (strDate.length == 1)   strDate   = "0" + strDate;
    return strYear + "-" + strMonth + "-" + strDate;
};

/**
 * 년 계산
 */
function addYear(date, nOffSet){
    date = date.replace(/-/g, "");
    var nYear  = parseInt(date.substr(0, 4), 10) + nOffSet;
    var nMonth = parseInt(date.substr(4, 2), 10);
    var nDate  = parseInt(date.substr(6, 2), 10);
    return window.getDatetime(nYear, nMonth, nDate);
};

/**
 * 월 계산
 */
function addMonth(date, nOffSet) {
    date = date.replace(/-/g, "");
    var nYear  = parseInt(date.substr(0, 4), 10);
    var nMonth = parseInt(date.substr(4, 2), 10) + nOffSet;
    var nDate  = parseInt(date.substr(6, 2), 10);
    return window.getDatetime(nYear, nMonth, nDate);
};

/**
 * 일 계산
 */
function addDate(date, nOffSet) {
    date = date.replace(/-/g, "");
    var nYear  = parseInt(date.substr(0, 4), 10);
    var nMonth = parseInt(date.substr(4, 2), 10);
    var nDate  = parseInt(date.substr(6, 2), 10) + nOffSet;
    return window.getDatetime(nYear, nMonth, nDate);
};

/**
 * 이전해 계산
 */
function getPrevYear(datestr, year) {
    if ( year == "0") return datestr;
    datestr = datestr.replace(/-/g, "");
    if (datestr == "") return "";
    var dateObj = window.getDateObject(datestr);

    dateObj.setYear(dateObj.getFullYear() - year);

    return window.getDateString(dateObj);
};

/**
 * 다음해 계산
 */
function getNextYear(datestr, year) {
    if ( year == "0") return datestr;
    datestr = datestr.replace(/-/g, "");
    if (datestr == "") return "";
    var dateObj = window.getDateObject(datestr);

    dateObj.setYear(dateObj.getFullYear() + year);

    return window.getDateString(dateObj);
};

/**
 * select 연도
 */
function setYearCombo(id,isAll,isSelect,range){
    var now = new Date();
    var dayYear = now.getFullYear();
    var str = "";
    if(range == null || range <= 0){
        range = 5;
    }
    if(isAll){
        str += "<option value=''>선택</option>";
    }
    for(var year=dayYear-range; year<dayYear+range + 1 ; year++){
        str += "<option value='"+year+"'>"+year+"</option>";

    }

    $("#"+id).append(str);

    if(isSelect){
        $("#"+id).val(dayYear).attr("selected", "selected");
    }
};

/**
 * select 연도(올해이후)
 */
function setYearComboNext(id,isAll,isSelect,range){
    var now = new Date();
    var dayYear = now.getFullYear();
    var str = "";
    if(range == null || range <= 0){
        range = 5;
    }
    if(isAll){
        str += "<option value=''>선택</option>";
    }
    for(var year=dayYear; year<dayYear+range + 1 ; year++){
        str += "<option value='"+year+"'>"+year+"</option>";

    }

    $("#"+id).append(str);

    if(isSelect){
        $("#"+id).val(dayYear).attr("selected", "selected");
    }
};


/**
 * select 년월
 */
function setYearMonCombo(id,isAll,isSelect){
    var day = new Date();
    var dayYear = day.getFullYear().toString();
    var now = day.getMonth()+1;
    now = dayYear + (now < 10 ? "0" : "") + now;
    var month = "";
    var str = "";

    if(isAll){
        str += "<option value=''>선택</option>";
    }
    for(var i = 1; i <13 ; i++){
        month = i < 10 ? "0" + i : "" + i;
        str +=  "<option value='"+dayYear +"" + month +"'>"+ dayYear + "/" + month + "</option>";
    }
    $("#"+id).append(str);
    if(isSelect){
        $("#"+id).val(now).attr("selected", "selected");
    }
};


/**
 * 두 일자간의 일수 계산
 * @param1 day1 : 일자 8자리 - 'YYYYMMDD', 'YYYY-MM-DD', 'YYYY/MM/DD', etc
 * @param2 day2 : 일자 8자리 - 'YYYYMMDD', 'YYYY-MM-DD', 'YYYY/MM/DD', etc
 * @return 두 일자간의 일수
 */
function calcDayCount(day1, day2) {
    day1 = day1.replace(/-/g, "");
    day2 = day2.replace(/-/g, "");
    if (day1 == "" || day2 == "") return "";
    var date1 = window.getDateObject(day1);
    var date2 = window.getDateObject(day2);

    if(date1 > date2) return ((date1.getTime() - date2.getTime()) / 1000 / 60 / 60 / 24) + 1;
    else              return ((date2.getTime() - date1.getTime()) / 1000 / 60 / 60 / 24) + 1;
};

/**
 * Get 요일
 */
function getWeek(datestr, isConvert){
    datestr = datestr.replace(/-/g, "");
    var dateObj = window.getDateObject(datestr);
    var week = dateObj.getDay() + 1;

    if(!isConvert)	return week;

    if(week == 1)           week = '일';
    else if(week == 2)     week = '월';
    else if(week == 3)     week = '화';
    else if(week == 4)     week = '수';
    else if(week == 5)     week = '목';
    else if(week == 6)     week = '금';
    else if(week == 7)     week = '토';
    return week;
};


/**
 * 날짜형식이 올바른지 검사
 *
 * @param    astrValue    날짜포맷(yyyymmdd, yyyy/mm/dd, yyyy-mm-dd)
 * @param    astrNotNull:    nn:not null, "": null 허용
 * @return    true/false
 **/
function blnOkDate(astrValue, astrNotNull) {
    var arrDate;

    if (astrValue==''){
        if (astrNotNull == "nn")
            return false;
        else
            return true;
    }

    if (astrValue.indexOf("-") != -1){
        arrDate = astrValue.split("-");
	} else if (astrValue.indexOf("/") != -1){
        arrDate = astrValue.split("/");
	} else {
        if (astrValue.length != 8) return false;
        astrValue = astrValue.substring(0,4)+"/"+astrValue.substring(4,6)+"/" +astrValue.substring(6,8);
        arrDate = astrValue.split("/");
    }

    if (arrDate.length != 3) return false;

    var chkDate = new Date(arrDate[0] + "/" + arrDate[1] + "/" + arrDate[2]);
    if (isNaN(chkDate) == true 
		|| (arrDate[1] != chkDate.getMonth() + 1 || arrDate[2] != chkDate.getDate())) {
        return false;
    }
    
    return true;
}


