// 날자 유효성 확인 ##################################################
function isDate(strDate){
	var tmpArr;
	var tmpYear, tmpMon, tmpDay;

	if (strDate.length != 10) return false;

	tmpArr = strDate.split("-");

	if (tmpArr.length != 3 ) return false;

	tmpYear = tmpArr[0];
	tmpMon = tmpArr[1];
	tmpDay = tmpArr[2];

	var tDateString = tmpYear+'/'+tmpMon+'/'+tmpDay+' 8:0:0';
	var tmpDate = new Date(tDateString);

	if (isNaN(tmpDate)) return false;

	if (((tmpDate.getFullYear()).toString() == tmpYear) && (tmpDate.getMonth() == parseInt(tmpMon, 10)-1) && (tmpDate.getDate() == parseInt(tmpDay, 10))) {
		return true;
	}
	else {
		return false;
	}
}

// # 날짜 기간 계산 ##################################################
var inputDateConfig = function() {
	this.sdate = null;
	this.edate = null;
	this.type = null;
	this.term = null;
}
var cfgInputDate = new inputDateConfig();

function inputDate(sdate, edate, type, term) {
	cfgInputDate.sdate = (sdate.nodeType==1) ? sdate : document.getElementById(sdate);
	cfgInputDate.edate = edate ? ((edate.nodeType==1) ? edate : document.getElementById(edate)) : null;
	cfgInputDate.type = type;
	cfgInputDate.term = term;

	if (type == 'W') {
		if (cfgInputDate.sdate) cfgInputDate.sdate.value = '';
		if (cfgInputDate.edate) cfgInputDate.edate.value = '';
	}
	else {
		dtAjax.execute("/common/ajax/exec_getDate.asp", "", execInputDate);
	}
}

function execInputDate(req) {
	var value = req.responseText;
	var today;

	if (value.replace(/ /g, "") == "") {
		today = new Date();
	}
	else {
		var arrDate = value.split('-');
		today = new Date(arrDate[1]+'/'+arrDate[2]+'/'+arrDate[0]);
	}
	var now_year = today.getFullYear();
	var now_month = today.getMonth()+1;
	var now_day = today.getDate();

	var sdate = cfgInputDate.sdate;
	var edate = cfgInputDate.edate;
	var type = cfgInputDate.type;
	var term = cfgInputDate.term;

	if (isNaN(term)) term = 0;

	var month_temp = now_month - 1;
	var day_temp = getLastDay(now_year, month_temp);

	var the_day = now_day;
	var the_month = now_month;
	var the_year = now_year;

	if (type == 'T') {
		var opt_day = now_day - term;
		if (opt_day > 0) {
			the_day = opt_day;
		}
		else {
			var opt_month = now_month - 1;
			the_day = day_temp + opt_day;
			if (opt_month > 0) {
				the_month = opt_month;
			}
			else {
				the_year = now_year - 1;
				the_month = 12;
			}
		}
	}
	else if (type=='D') {
		var opt_day = now_day-term;
		if (opt_day > 0) {
			the_day = opt_day;
		}
		else {
			var opt_month = now_month-1;
			the_day = day_temp + opt_day;
			if (opt_month > 0) {
				the_month = opt_month;
			}
			else {
				the_year = now_year-1;
				the_month = 12;
			}
		}
	}
	else if (type == 'M') {
		var opt_month = now_month - term;
		if (opt_month > 0) {
			the_month = opt_month;
		}
		else {
			the_year = now_year - 1;
			the_month = 12 + opt_month;
		}
	}
	else if (type=='Y') {
		the_year = now_year-term;
	}

	var the_ymLastDay = getLastDay(the_year, the_month);
	if (the_ymLastDay < the_day) the_day = the_ymLastDay;

	if (the_month < 10) the_month = '0' + the_month;
	if (the_day < 10) the_day = '0' + the_day;

	var the_date = the_year+'-'+the_month+'-'+the_day;
	sdate.value = the_date;

	if (now_month<10) now_month = '0'+now_month;
	if (now_day<10) now_day = '0'+now_day;

	if (type == 'T' && term > 0) {
		if (edate) edate.value = the_date;
	}
	else {
		now_date = now_year+'-'+now_month+'-'+now_day;
		if (edate) edate.value = now_date;
	}
}

// # 월별 일자수 추출 ##################################################
function getLastDay(year, mon) {
	var last_day = 31;

	switch(mon) {
		case(1): last_day=31; break;
		case(2):
			// 윤년 확인
			if(((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) {
				last_day=29;
			}
			else{
				last_day=28;
			}
			break;
		case(3): last_day=31; break;
		case(4): last_day=30; break;
		case(5): last_day=31; break;
		case(6): last_day=30; break;
		case(7): last_day=31; break;
		case(8): last_day=31; break;
		case(9): last_day=30; break;
		case(10): last_day=31; break;
		case(11): last_day=30; break;
		case(12): last_day=31; break;
		default: last_day=31; break;
	}

	return last_day;
}


/* AJAX Request */
var dtAjax = new Object();
dtAjax.xmlHttpReq = null;

dtAjax.execute = function(url, params, returnExec) {
	dtAjax.xmlHttpReq = dtGetXmlHttpRequest();
	if (dtAjax.xmlHttpReq) {
		url += ((url.indexOf('?') >= 0) ? '&' : '?') + "rnd="+Math.random();

		dtAjax.xmlHttpReq.onreadystatechange = function() {
			if (dtAjax.xmlHttpReq.readyState == 4) {
				returnExec(dtAjax.xmlHttpReq);
				dtAjax.xmlHttpReq = null;
			}
		}

		dtAjax.xmlHttpReq.open('GET', url, true);
		dtAjax.xmlHttpReq.send(params);
	}
}

function dtGetXmlHttpRequest() {
	if (window.XMLHttpRequest) {
		// Create XMLHttpRequest object in non-Microsoft browsers
		return new XMLHttpRequest();
	} else if (window.ActiveXObject) {
		// Create XMLHttpRequest via MS ActiveX
		try {
			// Try to create XMLHttpRequest in later versions
			// of Internet Explorer
			return new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e1) {
			// Failed to create required ActiveXObject
			try {
				// Try version supported by older versions
				// of Internet Explorer
				return new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e2) {
				// Unable to create an XMLHttpRequest with ActiveX
			}
		}
	}
	else {
		return null;
	}
}

/*==============================================================
 Description : 날짜와 날짜 차이 일수 계산
 Arg         : start  - 문자형 날짜값  (end보다 날짜가 작아야 됨)
               end    - 문자형 날짜값  (start보다 날짜가 커야 됨)
 return      : 차이 일수
===============================================================*/

function dayDif(start, end){
   
    var arySrtDt = start.split("-");
    var aryEndDt = end.split("-");

	var startDt = new Date(Number(arySrtDt[0]),Number(arySrtDt[1])-1,Number(arySrtDt[2]));
    var endDt   = new Date(Number(aryEndDt[0]),Number(aryEndDt[1])-1,Number(aryEndDt[2]));
  
        resultDt = Math.floor(endDt.valueOf()/(24*60*60*1000)- startDt.valueOf()/(24*60*60*1000));
    
    return resultDt;
 }



/*==============================================================
 Description : 시작일과 종료일 정상여부와 시작일이 작은지 검사
 Arg         : start  - 문자형 날짜값
               end    - 문자형 날짜값
 return      : true  - 정상
               flase - 오류
===============================================================*/
function stratEndCheck(start,end){

    v1=start.split("-");
    v2=end.split("-");

    a1=new Date(v1[0],v1[1],v1[2]).getTime();
    a2=new Date(v2[0],v2[1],v2[2]).getTime();

  if(a1<a2||a2 == ''){
    return true;
  }else{
    return false;
  }
} 


/**
 * 특정날짜의 요일을 구한다.
 */
function getDayOfWeek(strsDate) {
       var weekName = new Array("일요일", "월요일", "화요일", "수요일", "목요일", "금요일", "토요일");
		var strYear = "";
		var strMonth = ""; 
		var strDay = "";
		var aDate = null;

		if( strsDate.indexOf("-")>0){
			aDate = strsDate.split("-");
			strYear = aDate[0];
			strMonth = aDate[1];
			strDay = aDate[2]; 
		}
		else {		
			strYear = strsDate.slice(0,4);
			strMonth = strsDate.slice(4,6);
			strDay = strDate.slice(6,8);
		}

		strDay = parseFloat(strDay);
		var sDate = strYear + "/" + strMonth + "/" + strDay;
		var tmpDate = new Date(sDate);
		var nWeek = tmpDate.getDay();   

		return weekName[nWeek];
}

/**
 * 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);
}

/**
 * 자바스크립트 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 getDateObjToStr(date){
 var str = new Array();
 
 var _year = date.getFullYear();
 str[str.length] = _year;
 
 var _month = date.getMonth()+1;
 if(_month < 10) _month = "0"+_month;
 str[str.length] = _month;
 
 var _day = date.getDate();
 if(_day < 10) _day = "0"+_day;
 str[str.length] = _day
 var getDateObjToStr = str.join("");
 return getDateObjToStr;
}
 
 function getToday(){
 var d = new Date();
 var getToday = getDateObjToStr(d);
 return getToday;
} 

/**
 데이트 계산 함수
 param date : string "yyyymmdd"
 param period : int 
 param period_kind : string "Y","M","D"
 param gt_today : boolean 
 usage : calcDate("20080205",30,"D");
*/

function calcDate(date, period, period_kind){
 
 var today = getToday();
 
 var in_year = date.substr(0,4);
 var in_month = date.substr(4,2);
 var in_day = date.substr(6,2);
 
 var nd = new Date(in_year, in_month-1, in_day);
 if(period_kind == "D"){
  nd.setDate(nd.getDate()+period);
 }
 if(period_kind == "M"){
  nd.setMonth(nd.getMonth()+period);
 }
 if(period_kind == "Y"){
  nd.setFullYear(nd.getFullYear()+period);
 }
 var new_date = new Date(nd);
 var calcDate = getDateObjToStr(new_date);
// if(gt_today){ // 금일보다 큰 날짜 반환한다면
//  if(calcDate > today){
//   calcDate = today;
//  }
// }
  calcDateFull  = calcDate.substr(0,4) +"-"+ calcDate.substr(4,2)+"-"+calcDate.substr(6,2);
 
 return calcDateFull;
}
