/** 
 * 
 * 날짜관련 자바스크립트 공통함수
 *
 * 분단위 이하(= 초)는 고려하지 않았습니다.
 * YYYYMMDDHHMI 형식의 String => 'Time'으로 칭함
 *
 * 주로 YYYYMMDD 까지만 쓰인다면 아래 함수들을
 * YYYYMMDD 형식의 String => 'Date'로 하여 적당히
 * 수정하시거나 아니면 함수를, 예를들어 isValidDate()처럼,
 * 추가하시기 바랍니다.
 * 
 * @author  장영조 (Jang Young jo), foresight@topnwise.com
 * @version 1.0, 2003/02/24
 * @since   1.0
 *
 * Copyright. (c) 2004 by Kyobo Life
 */

function CN_DateUtil() {
	this.isValidMonth   	= isValidMonth;
	this.isValidDay			= isValidDay;
	this.isValidHour		= isValidHour;
	this.isValidMin			= isValidMin;
	this.isValidTimeFormat 	= isValidTimeFormat;
	this.isValidTime		= isValidTime;
	this.isValidDate		= isValidDate;
	this.isValidDate2		= isValidDate2;
	this.toTimeObject		= toTimeObject;
	this.toTimeString		= toTimeString;
	this.toTimeString2		= toTimeString2;
	this.isFutureTime		= isFutureTime;
	this.isPastTime			= isPastTime;
	this.shiftTime			= shiftTime;
	this.getMonthInterval	= getMonthInterval;
	this.getDayInterval		= getDayInterval;
	this.getHourInterval	= getHourInterval;
	this.getCurrentTime		= getCurrentTime;
	this.getRelativeTime	= getRelativeTime;
	this.getYear			= getYear;
	this.getMonth			= getMonth;
	this.getDay				= getDay;
	this.getHour			= getHour;
	this.getDayOfWeek		= getDayOfWeek;
	this.displayDateForm	= displayDateForm;
	this.chkDate			= chkDate;
	this.chkDate2			= chkDate2;
	this.chkDateNoAlert     = chkDateNoAlert;
	this.slashCut			= slashCut;
	this.colonCut			= colonCut;
}

 /* =============================================================
  Function : isValidMonth
  Return   : N/A
  Usage    : 유효한(존재하는) 월(月)인지 체크
================================================================= */
function isValidMonth(mm) {
    var m = parseInt(mm,10);
    return (m >= 1 && m <= 12);
}

 /* =============================================================
  Function : isValidDay
  Return   : N/A
  Usage    : 유효한(존재하는) 일(日)인지 체크
 ================================================================= */
function isValidDay(yyyy, mm, dd) {
    var m = parseInt(mm,10) - 1;
    var d = parseInt(dd,10);

    var end = new Array(31,28,31,30,31,30,31,31,30,31,30,31);
    if ((yyyy % 4 == 0 && yyyy % 100 != 0) || yyyy % 400 == 0) {
        end[1] = 29;
    }

    return (d >= 1 && d <= end[m]);
}

  /* =============================================================
  Function : isValidHour
  Return   : N/A
  Usage    : 유효한(존재하는) 시(時)인지 체크
  ================================================================= */
function isValidHour(hh) {
    var h = parseInt(hh,10);
    return (h >= 1 && h <= 24);
}

/* =============================================================
  Function : isValidMin
  Return   : N/A
  Usage    : 유효한(존재하는) 분(分)인지 체크
  ================================================================= */
function isValidMin(mi) {
    var m = parseInt(mi,10);
    return (m >= 0 && m <= 60);
}

 /* =============================================================
  Function : isValidTimeFormat
  Return   : N/A
  Usage    : Time 형식인지 체크(느슨한 체크)
  ================================================================= */
function isValidTimeFormat(time) {
    return (!isNaN(time) && time.length == 12);
}

/* =============================================================
  Function : isValidTime
  Return   : N/A
  Usage    : 유효하는(존재하는) Time 인지 체크 
  			ex) var time = form.time.value; //'200102310000'
      		if (!isValidTime(time)) {
          		alert("올바른 날짜가 아닙니다.");
      		}
  ================================================================= */
function isValidTime(time) {
    var year  = time.substring(0,4);
    var month = time.substring(4,6);
    var day   = time.substring(6,8);
    var hour  = time.substring(8,10);
    var min   = time.substring(10,12);

    if (parseInt(year,10) >= 1900  && isValidMonth(month) &&
        isValidDay(year,month,day) && isValidHour(hour)   &&
        isValidMin(min)) {
        return true;
    }
    return false;
}

/* =============================================================
  Function : isValidDate
  Return   : N/A
  Usage    :  ex) var sdate = form.time.value; //'20010230'
      		if (!isValidDate(sdate)) {
          		alert("올바른 날짜가 아닙니다.");
      		}
  ================================================================= */
function isValidDate(sdate) {

	if( sdate.length != 8 ) return false;

    var year  = sdate.substring(0,4);
    var month = sdate.substring(4,6);
    var day   = sdate.substring(6,8);
    
    if(isNaN(year) || isNaN(month) || isNaN(day) ){
    	return false;
    }

    if (parseInt(year,10) >= 1900  && isValidDay(year,month,day)) {
        return true;
    }
    return false;
}

/* =============================================================
  Function : isValidDate
  Return   : N/A
  Usage    :  유효하는(존재하는) Date(년월까지만) 인지 체크  
  				ex) var sdate = form.time.value; //'200101'
      			if (!isValidDate2(sdate)) {
          			alert("올바른 날짜가 아닙니다.");
      			}
  ================================================================= */
function isValidDate2(sdate) {

	if( sdate.length != 6 ) return false;

    var year  = sdate.substring(0,4);
    var month = sdate.substring(4,6);
    
    if(isNaN(year) || isNaN(month)){
    	return false;
    }

    if (parseInt(year,10) >= 1900) {
        return true;
    }
    return false;
}

/* =============================================================
  Function : toTimeObject
  Return   : N/A
  Usage    :  Time 스트링을 자바스크립트 Date 객체로 변환
  				parameter time: Time 형식의 String
  ================================================================= */
function toTimeObject(time) { //parseTime(time)
    var year  = time.substr(0,4);
    var month = time.substr(4,2) - 1; // 1월=0,12월=11
    var day   = time.substr(6,2);
    var hour  = time.substr(8,2);
	  var min   = time.substr(10,2);

    return new Date(year,month,day,hour,min);
}

/* =============================================================
  Function : toTimeString
  Return   : N/A
  Usage    :  자바스크립트 Date 객체를 Time 스트링으로 변환
  			  parameter date: JavaScript Date Object
  ================================================================= */
function toTimeString(date) { //formatTime(date)
    var year  = date.getFullYear();
    var month = date.getMonth() + 1; // 1월=0,12월=11이므로 1 더함
    var day   = date.getDate();
    var hour  = date.getHours();
    var min   = date.getMinutes();
    

    if (("" + month).length == 1) { month = "0" + month; }
    if (("" + day).length   == 1) { day   = "0" + day;   }
    if (("" + hour).length  == 1) { hour  = "0" + hour;  }
    if (("" + min).length   == 1) { min   = "0" + min;   }

    return ("" + year + month + day + hour + min)
}

/* =============================================================
  Function : toTimeString2
  Return   : N/A
  Usage    :  자바스크립트 Date 객체를 Time 스트링으로 변환(년월일시분초) -- 초 추가.
 			  parameter date: JavaScript Date Object
  ================================================================= */

function toTimeString2(date) { //formatTime(date)
    var year  = date.getFullYear();
    var month = date.getMonth() + 1; // 1월=0,12월=11이므로 1 더함
    var day   = date.getDate();
    var hour  = date.getHours();
    var min   = date.getMinutes();
    var sec	  = date.getSeconds();
    

    if (("" + month).length == 1) { month = "0" + month; }
    if (("" + day).length   == 1) { day   = "0" + day;   }
    if (("" + hour).length  == 1) { hour  = "0" + hour;  }
    if (("" + min).length   == 1) { min   = "0" + min;   }
    if (("" + sec).length   == 1) { sec   = "0" + sec;   }

    return ("" + year + month + day + hour + min + sec)
}

/* =============================================================
  Function : isFutureTime
  Return   : N/A
  Usage    : Time이 현재시각 이후(미래)인지 체크
  ================================================================= */
function isFutureTime(time) {
    return (toTimeObject(time) > new Date());
}

 /* =============================================================
  Function : isPastTime
  Return   : N/A
  Usage    : TTime이 현재시각 이전(과거)인지 체크
  ================================================================= */
function isPastTime(time) {
    return (toTimeObject(time) < new Date());
}

  /* =============================================================
  Function : shiftTime
  Return   : N/A
  Usage    : 주어진 Time 과 y년 m월 d일 h시 차이나는 Time을 리턴
  			ex) var time = form.time.value; //'20000101000'
      			alert(shiftTime(time,0,0,-100,0));
      			=> 2000/01/01 00:00 으로부터 100일 전 Time
  ================================================================= */
function shiftTime(time,y,m,d,h) { 
    var date = toTimeObject(time);

    date.setFullYear(date.getFullYear() + y); //y년을 더함
    date.setMonth(date.getMonth() + m);       //m월을 더함
    date.setDate(date.getDate() + d);         //d일을 더함
    date.setHours(date.getHours() + h);       //h시를 더함

    return toTimeString(date);
}

  /* =============================================================
  Function : 두 Time이 몇 개월 차이나는지 구함
  Return   : N/A
  Usage    : time1이 time2보다 크면(미래면) minus(-)
  ================================================================= */
function getMonthInterval(time1,time2) { //measureMonthInterval(time1,time2)
    var date1 = toTimeObject(time1);
    var date2 = toTimeObject(time2);
    
    var years  = date2.getFullYear() - date1.getFullYear();
    var months = date2.getMonth() - date1.getMonth();
    var days   = date2.getDate() - date1.getDate();

    return (years * 12 + months + (days >= 0 ? 0 : -1) );
}
/* =============================================================
  Function : getDayInterval
  Return   : N/A
  Usage    : 두 Time이 며칠 차이나는지 구함
  				time1이 time2보다 크면(미래면) minus(-)
  ================================================================= */
function getDayInterval(time1,time2) {
    var date1 = toTimeObject(time1);
    var date2 = toTimeObject(time2);
    var day   = 1000 * 3600 * 24; //24시간

    return parseInt((date2 - date1) / day, 10);
}

/* =============================================================
  Function : getHourInterval
  Return   : N/A
  Usage    : 두 Time이 몇 시간 차이나는지 구함
  			 time1이 time2보다 크면(미래면) minus(-)
  ================================================================= */
function getHourInterval(time1,time2) {
    var date1 = toTimeObject(time1);
    var date2 = toTimeObject(time2);
    var hour  = 1000 * 3600; //1시간

    return parseInt((date2 - date1) / hour, 10);
}

/* =============================================================
  Function : getCurrentTime
  Return   : N/A
  Usage    : 현재 시각을 Time 형식으로 리턴
  ================================================================= */
function getCurrentTime() {
    return toTimeString(new Date());
}

/* =============================================================
  Function : getRelativeTime
  Return   : N/A
  Usage    : 현재 시각과 y년 m월 d일 h시 차이나는 Time을 리턴
  ================================================================= */
function getRelativeTime(y,m,d,h) {
/*
    var date = new Date();

    date.setFullYear(date.getFullYear() + y); //y년을 더함
    date.setMonth(date.getMonth() + m);       //m월을 더함
    date.setDate(date.getDate() + d);         //d일을 더함
    date.setHours(date.getHours() + h);       //h시를 더함

    return toTimeString(date);
*/
    return shiftTime(getCurrentTime(),y,m,d,h);
}

/* =============================================================
  Function : getYear
  Return   : N/A
  Usage    : 현재 年을 YYYY형식으로 리턴
  ================================================================= */
function getYear() {
/*
    var now = new Date();
    return now.getFullYear();
*/
    return getCurrentTime().substr(0,4);
}

/* =============================================================
  Function : getMonth
  Return   : N/A
  Usage    : 현재 月을 MM형식으로 리턴
  ================================================================= */
function getMonth() {
/*
    var now = new Date();

    var month = now.getMonth() + 1; // 1월=0,12월=11이므로 1 더함
    if (("" + month).length == 1) { month = "0" + month; }

    return month;
*/
    return getCurrentTime().substr(4,2);
}

/* =============================================================
  Function : getMonth
  Return   : N/A
  Usage    :현재 日을 DD형식으로 리턴
  ================================================================= */
function getDay() {
/*
    var now = new Date();

    var day = now.getDate();
    if (("" + day).length == 1) { day = "0" + day; }

    return day;
*/
    return getCurrentTime().substr(6,2);
}

/* =============================================================
  Function : getHour
  Return   : N/A
  Usage    :현재 時를 HH형식으로 리턴
  ================================================================= */
function getHour() {
/*
    var now = new Date();

    var hour = now.getHours();
    if (("" + hour).length == 1) { hour = "0" + hour; }

    return hour;
*/
    return getCurrentTime().substr(8,2);
}

/* =============================================================
  Function : getDayOfWeek
  Return   : N/A
  Usage    : 오늘의 요일 구하기
  ================================================================= */
function getDayOfWeek() {
    var now = new Date();

    var day = now.getDay(); //일요일=0,월요일=1,...,토요일=6
    var week = new Array('일','월','화','수','목','금','토');

    return week[day];
}

/* =============================================================
  Function : getDayOfWeek
  Return   : N/A
  Usage    : 특정날짜 요일 구하기
  ================================================================= */
function getDayOfWeek(strtime) {
    var now = toTimeObject(strtime);

    var day = now.getDay(); //일요일=0,월요일=1,...,토요일=6
    var week = new Array('일','월','화','수','목','금','토');

    return week[day];
}

/* =============================================================
  Function : displayDateForm
  Return   : N/A
  Usage    : 날짜 입력 폼을 뿌려주는 script
  ================================================================= */
function displayDateForm(yearFormName,monthFormName,dayFormName, before, after){
	
	if(before==null)before=2; //몇년 전것부터
	if(after==null)after=3;  //몇년후까지
	from_to = before+after;   

	var todaydate = new Date();
	//연도 표시 시작
	year = todaydate.getYear();
	k = todaydate.getYear()-before;
	//alert("year"+k);
	if ( k < 100) {
		k= k+1900 ;  //지난 10년간부터
	}

	var Outline=""
	document.write("<SELECT class=select NAME="+yearFormName+" >");
	for (var i = 0; i < from_to; i++) {
        if (k==year) {//올해이면 선택된 상태로 함
			Outline += "<option value=\"" + (k) + "\" selected>" + (k) + "</option>"
		}
		else {
			Outline += "<option value=\"" + (k) + "\">" + (k) + "</option>"
		}
		k++; //연도 증가시킴
	}
	document.write(Outline); 
	document.write("</select>");
	Outline = ""; //display year 끝
	
	//달  표시 시작
	k = todaydate.getMonth()+1;
	document.write("<SELECT class=select NAME="+monthFormName+" >");
	for (var i = 1; i < 13; i++) {
		if (i == k) { //이번달이면 선택된 상태가 되게함
			Outline += "<option value=\"" + (i<10?("0"+i):i) + "\" selected>" +(i<10?("0"+i):i) + "</option>";
		}
		else {
			Outline += "<option value=\"" + (i<10?("0"+i):i) + "\">" + (i<10?("0"+i):i) + "</option>";
		}		
	}
	document.write(Outline);
	document.write("</select>");
	Outline = "";
	
	//일  표시 시작
	d = todaydate.getDate();
	document.write("<SELECT class=select NAME="+dayFormName+" >");
	for (var i = 1; i <= 31; i++) {
		if (i == d) {  //오늘이면 선택된 상태로 되게함
			Outline += "<option value=\"" + (i<10?("0"+i):i)+ "\" selected>" +(i<10?("0"+i):i) + "</option>" ;
		}else {
			Outline += "<option value=\"" + (i<10?("0"+i):i) + "\">" + (i<10?("0"+i):i) + "</option>" ;
		}		
	}
	document.write(Outline);
	document.write("</select>");
	Outline = ""
}

/* ===================================================================
	Function : chkDate(str)
	Return 	 : 
	Usage 	 : 날짜 유효성 검사
		※ new Date() 부분 수정 - 2003/07/31
=================================================================== */
function chkDate(str){
	//연월의 검사 --yesman75

  if(str.length == 6){
 	vDate = new Date(str.substring(0,4), (str.substring(4,6)-1));
 	
 	if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 ){
   alert("올바른 형식이 아닙니다.");
   return false;
  }
  return true;
  //alert("올바른 형식입니다.");
 }else if(str.length == 8){ 
 	vDate = new Date(str.substring(0, 4), (str.substring(4, 6)-1), str.substring(6));

/*
	vDate = new Date();
  	vDate.setFullYear(str.substring(0, 4));
  	vDate.setMonth(str.substring(4, 6) - 1);
  	vDate.setDate(str.substring(6));
*/

  if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 || vDate.getDate() != str.substring(6)){
   alert("올바른 형식이 아닙니다.");
   return false;
  }
  return true;
  //alert("올바른 형식입니다.");
 }else if(str.length == 14) {
 	vDate = new Date(str.substring(0, 4), (str.substring(4, 6)-1), str.substring(6));

/*
	vDate = new Date();
  	vDate.setFullYear(str.substring(0, 4));
  	vDate.setMonth(str.substring(4, 6) - 1);
  	vDate.setDate(str.substring(6));
*/

  if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 || vDate.getDate() != str.substring(6)){
   alert("올바른 형식이 아닙니다.");
   return false;
  }
  return true;
 }
}

/* ===================================================================
	Function : chkDate2(str)
	Return 	 : 
	Usage 	 : 날짜 유효성 검사
		※ new Date() 부분 수정 - 2003/07/31
=================================================================== */
function chkDate2(obj){
	//연월의 검사 --yesman75
  
  if(obj.value.length == 6){
 	vDate = new Date(str.substring(0,4), (str.substring(4,6)-1));
 	
 	if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 ){
   alert("올바른 형식이 아닙니다.");
   return false;
  }
  return true;
  //alert("올바른 형식입니다.");
 }else if(obj.value.length == 8){ 
 	vDate = new Date(str.substring(0, 4), (str.substring(4, 6)-1), str.substring(6));

/*
	vDate = new Date();
  	vDate.setFullYear(str.substring(0, 4));
  	vDate.setMonth(str.substring(4, 6) - 1);
  	vDate.setDate(str.substring(6));
*/

  if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 || vDate.getDate() != str.substring(6)){
   alert("올바른 형식이 아닙니다.");
   return false;
  }
  return true;
  //alert("올바른 형식입니다.");
 }else if(obj.value.length == 14) {
 	vDate = new Date(str.substring(0, 4), (str.substring(4, 6)-1), str.substring(6));

/*
	vDate = new Date();
  	vDate.setFullYear(str.substring(0, 4));
  	vDate.setMonth(str.substring(4, 6) - 1);
  	vDate.setDate(str.substring(6));
*/

  if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 || vDate.getDate() != str.substring(6)){
   alert("올바른 형식이 아닙니다.");
   return false;
  }
  return true;
 }
}

/* ===================================================================
	Function : chkDateNoAlert(str)
	Return 	 : 
	Usage 	 : 날짜 유효성 검사
		※ new Date() 부분 수정 - 2003/07/31
=================================================================== */
function chkDateNoAlert(str){
	
	switch( str.length ){
		case 6 :
	 		vDate = new Date(str.substring(0,4), (str.substring(4,6)-1));
		 	if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 ){
		   		return false;
		  	}
		  	return true;
		break;
		case 8 : 
	 		vDate = new Date(str.substring(0, 4), (str.substring(4, 6)-1), str.substring(6));
			if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 || vDate.getDate() != str.substring(6)){
				return false;
			}
			return true;
		break;
		case 14 :
	 		vDate = new Date(str.substring(0, 4), (str.substring(4, 6)-1), str.substring(6));
			if(vDate.getFullYear() != str.substring(0, 4) || vDate.getMonth() != str.substring(4, 6)-1 || vDate.getDate() != str.substring(6)){
				return false;
			}
			return true;
		break;
	}
	
	return false;
}

/* ===================================================================
	Function : slashCut(dateStr)
	Return 	 : 
	Usage 	 : '/' 문자열을 제거하여 '20030303' 형식의 날짜 데이터를 만든다.
=================================================================== */
function slashCut(dateStr){
	var date_temp = dateStr.split('/').join('');
	return date_temp;
}

/* ===================================================================
	Function : colonCut(dateStr)
	Return 	 : 
	Usage 	 : ':' 문자열을 제거하여 '1230' 형식의 시간 데이터를 만든다.
=================================================================== */
function colonCut(timeStr){
	var time_temp = timeStr;
	
	if(time_temp.length == 4){
		time_temp = time_temp.substring(0, 2) + time_temp.substring(3, 5);
		return date_temp;
	} else if(time_temp.length > 6){
		time_temp = time_temp.substring(0, 2) + time_temp.substring(3, 5) + time_temp.substring(6, 8);
		return date_temp;
	} else {
		return time_temp;
	}
}


