var calPopup = window.createPopup();
var calDoc = calPopup.document.body;

var calObj;

// °¢°¢ÀÇ °´Ã¼µé
var calType = "1";
var sDialog;
var sHead;
var sTitle;
var sArrow;
var sBody;
var sCell = new Array;
var sWeek = new Array;

var calEmonth = new Array;
var calHweek = new Array;
var calEweek = new Array;

var calDay = new Array;

calEmonth[ 1] = "January";		calEmonth[ 2] = "February";		calEmonth[ 3] = "March";
calEmonth[ 4] = "April";		calEmonth[ 5] = "May";			calEmonth[ 6] = "June";
calEmonth[ 7] = "July";			calEmonth[ 8] = "August";		calEmonth[ 9] = "September";
calEmonth[10] = "October";		calEmonth[11] = "November";		calEmonth[12] = "December";

calHweek[0] = "ÀÏ";				calHweek[1] = "¿ù";				calHweek[2] = "È­";
calHweek[3] = "¼ö";				calHweek[4] = "¸ñ";				calHweek[5] = "±Ý";
calHweek[6] = "Åä";

calEweek[0] = "Sunday";			calEweek[1] = "Monday";			calEweek[2] = "Tuesday";
calEweek[3] = "Wednesday";		calEweek[4] = "Thursday";		calEweek[5] = "Friday";
calEweek[6] = "Saturday";

// PUBLIC

var cell = "cursor:default; text-align: right; padding: 5px; color: windowtext; font-size: 11px; font-family: Tahoma; background-color: window;";
var nocell = "cursor:default; text-align: right; padding: 5px; color: #D7D7D7; font-size: 11px; font-family: Tahoma; background-color: window;";
var weekCell = "cursor:default; text-align: right; padding: 5px; color: windowtext; font-size: 11px; font-family: Tahoma; background-color: window;background-color: buttonface; color: graytext;";
var SelweekCell = "cursor:default; text-align: right; padding: 5px; color: windowtext; font-size: 11px; font-family: Tahoma; background-color: window;background-color: buttonface; color: graytext;cursor:hand";
var overCell = "cursor:default; text-align: right; padding: 5px; color: windowtext; font-size: 11px; font-family: Tahoma; background-color: window;color: highlighttext; background-color: highlight;";
var todayCell = "cursor:default; text-align: right; padding: 5px; color: windowtext; font-size: 11px; font-family: Tahoma; background-color: #E6D2D2;";

// PRIVATE

var calSkipFrame;
var calStep;
var calInterval;

function startInterval(step)
{
	if (calInterval)
		stopInterval();

	var movedelay = 10;

	calSkipFrame = parseInt(500 / (movedelay ? movedelay : 1));
	if (calSkipFrame > 50) calSkipFrame = 50;

	calStep = step;
	calInterval = window.setInterval(runInterval, movedelay);
}

function runInterval()
{
	if (calSkipFrame)
		calSkipFrame--;
	else
		increaseMonth(calStep);
}

function stopInterval()
{
	clearInterval(calInterval);
	calInterval = null;
	calSkipFrame = 0;
}

function increaseMonth(step)
{
	var year = getProperty(sTitle, "year");
	var month = getProperty(sTitle, "month");

	month += step;

	if (month > 12)
	{
		year++;
		month = month - 12;
	}
	else if (month <= 0)
	{
		year--;
		month = 12 + month;
	}

	refreshCalendar(year, month);
}

function getCalFormat(format, year, month, day)
{
	var now = new Date(year, month - 1, day);
	var Y, M, D, W, y, m, d, w;

	if (getProperty(calObj, "english") == null) // ÇÑ±ÛÇü½Ä
	{
		M = fillZero(month, 2);
		m = fillZero(month, 1);

		W = calHweek[now.getDay()]+"¿äÀÏ";
		w = calHweek[now.getDay()];
	}
	else
	{
		M = calEmonth[month];
		W = calEweek[now.getDay()];

		m = M.substr(0, 3);
		if (W) w = W.substr(0, 3);
	}

	Y = fillZero(year, 4);
	y = Y.substr(2, 2);

	D = fillZero(day, 2);
	d = fillZero(day, 1);

	format = format.replace(/%Y/g, Y);
	format = format.replace(/%M/g, M);
	format = format.replace(/%D/g, D);
	format = format.replace(/%W/g, W);

	format = format.replace(/%y/g, y);
	format = format.replace(/%m/g, m);
	format = format.replace(/%d/g, d);
	format = format.replace(/%w/g, w);

	return format;
}

function SetEvent(obj)
{
	var INPUT =obj;
	var idx =INPUT.id.replace("sWeek","");
	obj.onclick=function(){
				SelectWeek(Number(idx));
			};
}
function SetNoEvent(obj)
{
	obj.onclick=function(){};
}
function refreshCalendar(year, month, day)
{
	var topformat;

	if (getProperty(calObj, "english") == null) // ÇÑ±ÛÇü½Ä
		topformat = "%Y³â %m¿ù";
	else
		topformat = "%M, %Y";



	for (var ci = 0; ci < 7; ci++)
	{
		if (getProperty(calObj, "english") == null) // ÇÑ±ÛÇü½Ä
			sWeek[ci].innerHTML = calHweek[ci];
		else
			sWeek[ci].innerHTML = calEweek[ci].substring(0, 3).toUpperCase();

		sWeek[ci].style.cssText = weekCell;
		if (calType == "2")
		{
			SetEvent(sWeek[ci]);
			sWeek[ci].style.cssText = SelweekCell;
		}
		else
		{
			SetNoEvent(sWeek[ci]);
			sWeek[ci].style.cssText = weekCell;
		}
	}

	if (getProperty(calObj, "topformat") != null)
		topformat = getProperty(calObj, "topformat");

	sTitle.innerHTML = getCalFormat(topformat, year, month, day);

	setProperty(sTitle, "year", year);
	setProperty(sTitle, "month", month);

	var date = new Date(year, month - 1, 1);
	var firstweek = date.getDay();

	var lastdate;

	for (lastdate = 31; lastdate >= 28; lastdate--)
		if (validDay(year, month, lastdate)) break;

	if (day > lastdate) day = lastdate;
	var pday = -firstweek;

	var text;

	var DMinL = getProperty(calObj, "MinL","");
	var DMaxL = getProperty(calObj, "MaxL","");

	var iVal,monthVal;
	for (var i = 0; i < 42; i++)
	{
		++pday;

		text = ((pday > 0 && pday <= lastdate) ? pday : "");
		if(text)
		{
			iVal = ((Number(text) < 10) ? "0"+ String(text) : String(text));
			monthVal = ((month < 10) ? "0"+ String(month) : String(month));

			SelDate = String(year)+ '-'+ monthVal+ '-'+ iVal;
			if(DMinL !="" && SelDate < DMinL)
			{
				setEnableCell(i, text,GetToday(SelDate), nocell, nocell, todayCell,false);
			}
			else if(DMaxL !="" && SelDate > DMaxL)
			{
				setEnableCell(i, text,GetToday(SelDate), nocell, nocell, todayCell,false);
			}
			else
				setEnableCell(i, text, GetToday(SelDate), cell, overCell, todayCell,true);
		}
		else
			setEnableCell(i, text, false, cell, overCell, todayCell,false);

	}
}
function GetToday(IDate)
{

	Vdate = getProperty(calObj, "value","");
	DArray = Vdate.split(",");
	for(var i = 0 ; i< DArray.length ;i++)
	{
		if(DArray[i] == IDate)
			return true;
	}
	return false;
}
function setEnableCell(i, text, today, cellStyle, overCellStyle, todayCellStyle,SelTye)
{
	sCell[i].style.cssText = cellStyle;

	if (text)
	{
		sCell[i].innerHTML = text;
		if (SelTye)
		{
			sCell[i].onmouseover = function() { highLight(sCell[i], true, cellStyle, overCellStyle, todayCellStyle); }
			sCell[i].onmouseout = function() { highLight(sCell[i], false, cellStyle, overCellStyle, todayCellStyle); }
			sCell[i].onclick = function() { selectDay(sCell[i]); }
		}
		else
		{
			sCell[i].onmouseout = sCell[i].onmouseover = sCell[i].onclick = function() {}
		}
	}
	else
	{
		sCell[i].innerHTML = "&nbsp;";
		sCell[i].onmouseout = sCell[i].onmouseover = sCell[i].onclick = function() {}
	}

	setProperty(sCell[i], "today", today);
	if (getProperty(sCell[i], "today"))
	{
		sCell[i].style.cssText = todayCellStyle;
	}
}

function highLight(obj, flag, cellStyle, overCellStyle, todayCellStyle)
{
	if (flag)
		obj.style.cssText = overCellStyle;
	else if (getProperty(obj, "today"))
		obj.style.cssText = todayCellStyle;
	else
		obj.style.cssText = cellStyle;
}

function selectDay(obj)
{

	if(obj.innerHTML == "" || obj.innerHTML == "&nbsp;" )
		return;


	if(obj.style.color == "#d7d7d7")
		return;

	var year = getProperty(sTitle, "year");
	var month = getProperty(sTitle, "month");

	var format = "%Y-%M-%D";

	if (getProperty(calObj, "format") != null)
		format = getProperty(calObj, "format");
	
	var SelDay =  getFormat(format, year, month, obj.innerText);
	if (calType == "1")
	{
		calObj.value = SelDay;
	}
	else
	{
		Vdate = getProperty(calObj, "value","");
		var DArray = Vdate.split(",");
		DArray.sort();
		var rtnValue = "";

		if(GetToday(SelDay))
		{
			for(var i = 0 ; i< DArray.length ;i++)
			{
				if(DArray[i] != SelDay)
				{
					rtnValue += ((rtnValue !="") ? ",":"") + DArray[i];
				}
			}
			setProperty(obj, "today",false);
			obj.style.cssText = cell;
		}
		else
		{
			DArray.push(SelDay);
			DArray.sort();
			rtnValue = DArray.join(",");
			setProperty(obj, "today",true);
			obj.style.cssText = todayCell;
		}
		calObj.value = rtnValue;
	}


	eval("setProperty(calObj, 'year', '"+year+"');");
	eval("setProperty(calObj, 'month', '"+month+"');");
	eval("setProperty(calObj, 'day', '"+obj.innerText+"');");

	if (getProperty(calObj, "onok") != null)
		eval(getProperty(calObj, "onok"));

	if (calType == "1")
	{
		calObj = null;
		calPopup.hide();
	}
}

function getFormat(format, year, month, day)
{
	var now = new Date(year, month - 1, day);
	var Y, M, D, W, y, m, d, w;

	if (getProperty(calObj, "english") == null) // ÇÑ±ÛÇü½Ä
	{
		M = fillZero(month, 2);
		m = fillZero(month, 1);

		W = calHweek[now.getDay()]+"¿äÀÏ";
		w = calHweek[now.getDay()];
	}
	else
	{
		M = calEmonth[month];
		W = calEweek[now.getDay()];

		m = M.substr(0, 3);
		if (W) w = W.substr(0, 3);
	}

	Y = fillZero(year, 4);
	y = Y.substr(2, 2);

	D = fillZero(day, 2);
	d = fillZero(day, 1);

	format = format.replace(/%Y/g, Y);
	format = format.replace(/%M/g, M);
	format = format.replace(/%D/g, D);
	format = format.replace(/%W/g, W);

	format = format.replace(/%y/g, y);
	format = format.replace(/%m/g, m);
	format = format.replace(/%d/g, d);
	format = format.replace(/%w/g, w);

	return format;
}

// HANDLER

function clickCalendars(e)
{
	var INPUT = event.srcElement;
	calType = "1";
	if (!calDoc.innerHTML)
	{
		var i;
		var code =	"<table border=0 cellpadding=0 cellspacing=0><tr><td id='sDialog' style='border: 1px outset buttonface; padding: 5px; background-color: buttonface;'><table border=0 cellpadding=0 cellspacing=0 onselectstart='return false'>"+
						"<tr>"+
							"<td id='sHead'  style='border: 1px solid buttonshadow; border-bottom:0px; padding: 3px;'>"+
								"<table border=0 cellpadding=0 cellspacing=0 width=100%>"+
									"<tr id='sArrow' style='color: graytext; font-weight: bold; font-size: 12px; font-family: Arial;'>"+
										"<td align=left style='cursor:hand;' "+
											"ondblclick='parent.increaseMonth(-1);' "+
											"onmousedown='parent.increaseMonth(-1); parent.startInterval(-1);' "+
											"onmouseup='parent.stopInterval();' "+
											"onmouseout='parent.stopInterval();'>&lt;</td>"+
										"<td id='sTitle' nowrap style='font-size: 12px; font-family: Tahoma; color: windowtext; text-align: center; '></td>"+
										"<td align=right style='cursor:hand;' "+
											"ondblclick='parent.increaseMonth(1);' "+
											"onmousedown='parent.increaseMonth(1); parent.startInterval(1);' "+
											"onmouseup='parent.stopInterval();' "+
											"onmouseout='parent.stopInterval();'>&gt;</td>"+
									"</tr>"+
								"</table>"+
							"</td>"+
						"</tr>"+
						"<tr>"+
							"<td id='sBody' style='border: 1px solid buttonshadow; background-color: window; padding: 0px;'>"+
								"<table border=0 cellpadding=0 cellspacing=0 width=100%>"+
									"<tr>";

		for (i = 0; i < 7; i++)
			code +=	"<td id='sWeek"+i+"'>&nbsp;</td>";

		for (i = 0; i < 42; i++)
		{
			if (i % 7 == 0) code += "</tr><tr bgcolor=window height=16>";
			code += "<td id='sCell"+i+"' width=30 >&nbsp;</td>"; 
		}

		code +=
									"</tr>"+
								"</table>"+
							"</td>"+
						"</tr>"+
					"</table></td></tr></table>";

		calDoc.innerHTML = code;

		for (i = 0; i <  7; i++)	sWeek[i] = findLayer("sWeek"+i, calDoc.document);
		for (i = 0; i < 42; i++)	sCell[i] = findLayer("sCell"+i, calDoc.document);

		sDialog = findLayer("sDialog", calDoc.document);
		sHead = findLayer("sHead", calDoc.document);
		sTitle = findLayer("sTitle", calDoc.document);
		sArrow = findLayer("sArrow", calDoc.document);
		sBody = findLayer("sBody", calDoc.document);

	}

		var e =getXY(INPUT)
		var xpos = e.x + e.w + 2;
		var ypos = e.y ;

		calObj = INPUT;

		var date = new Date();
		if(getProperty(calObj, "value","") != "")
		{
			Vdate = getProperty(calObj, "value","");
			DArray = Vdate.split(",");
			if(DArray.length > 0 )
			{
				if(CreateDay(DArray[0]) != "")
					date = CreateDay(DArray[0]);
			}
		}


		calDay["Y"] = date.getFullYear();
		calDay["M"] = date.getMonth() + 1;
		calDay["D"] = date.getDate();



		refreshCalendar(calDay["Y"], calDay["M"], calDay["D"]);

		var width = 200;
		var height = 205;


		calPopup.show(xpos, ypos, width, height, document.body);


}

function SelectWeek(idx)
{
	for(var j = idx;j< sCell.length ;j +=7)
	selectDay(sCell[j]);
}
function MclickCalendars(e)
{
	calType = "2";
	var INPUT = event.srcElement;

	if (!calDoc.innerHTML)
	{
		var i;
		var code =	"<table border=0 cellpadding=0 cellspacing=0><tr><td id='sDialog' style='border: 1px outset buttonface; padding: 5px; background-color: buttonface;'><table border=0 cellpadding=0 cellspacing=0 onselectstart='return false'>"+
						"<tr>"+
							"<td id='sHead'  style='border: 1px solid buttonshadow; border-bottom:0px; padding: 3px;'>"+
								"<table border=0 cellpadding=0 cellspacing=0 width=100%>"+
									"<tr id='sArrow' style='color: graytext; font-weight: bold; font-size: 12px; font-family: Arial;'>"+
										"<td align=left style='cursor:hand;' "+
											"ondblclick='parent.increaseMonth(-1);' "+
											"onmousedown='parent.increaseMonth(-1); parent.startInterval(-1);' "+
											"onmouseup='parent.stopInterval();' "+
											"onmouseout='parent.stopInterval();'>&lt;</td>"+
										"<td id='sTitle' nowrap style='font-size: 12px; font-family: Tahoma; color: windowtext; text-align: center; '></td>"+
										"<td align=right style='cursor:hand;' "+
											"ondblclick='parent.increaseMonth(1);' "+
											"onmousedown='parent.increaseMonth(1); parent.startInterval(1);' "+
											"onmouseup='parent.stopInterval();' "+
											"onmouseout='parent.stopInterval();'>&gt;</td>"+
									"</tr>"+
								"</table>"+
							"</td>"+
						"</tr>"+
						"<tr>"+
							"<td id='sBody' style='border: 1px solid buttonshadow; background-color: window; padding: 0px;'>"+
								"<table border=0 cellpadding=0 cellspacing=0 width=100%>"+
									"<tr>";

		for (i = 0; i < 7; i++)
			code +=	"<td id='sWeek"+i+"'  >&nbsp;</td>";

		for (i = 0; i < 42; i++)
		{
			if (i % 7 == 0) code += "</tr><tr bgcolor=window height=16>";
			code += "<td id='sCell"+i+"' width=30 >&nbsp;</td>"; 
		}

		code +=
									"</tr>"+
								"</table>"+
							"</td>"+
						"</tr>"+
					"</table></td></tr></table>";

		calDoc.innerHTML = code;

		for (i = 0; i <  7; i++)	sWeek[i] = findLayer("sWeek"+i, calDoc.document);
		for (i = 0; i < 42; i++)	sCell[i] = findLayer("sCell"+i, calDoc.document);

		sDialog = findLayer("sDialog", calDoc.document);
		sHead = findLayer("sHead", calDoc.document);
		sTitle = findLayer("sTitle", calDoc.document);
		sArrow = findLayer("sArrow", calDoc.document);
		sBody = findLayer("sBody", calDoc.document);

	}

		var e =getXY(INPUT)
		var xpos = e.x + e.w + 2;
		var ypos = e.y ;

		calObj = INPUT;

		var date = new Date();
		if(getProperty(calObj, "value","") != "")
		{
			Vdate = getProperty(calObj, "value","");
			DArray = Vdate.split(",");
			if(DArray.length > 0 )
			{
				if(CreateDay(DArray[0]) != "")
					date = CreateDay(DArray[0]);
			}
		}

		calDay["Y"] = date.getFullYear();
		calDay["M"] = date.getMonth() + 1;
		calDay["D"] = date.getDate();




		refreshCalendar(calDay["Y"], calDay["M"], calDay["D"]);

		var width = 200;
		var height = 205;


		calPopup.show(xpos, ypos, width, height, document.body);


}

function validDay(year, month, day)
{
	var date = new Date(year,parseInt(month -1),day);

	return (date.getFullYear() == year && date.getMonth() == Number(month -1) && date.getDate() == day);

}

function CreateDay(isDate)
{
	isDate = isDate.replace(/\-/gi, "");

	if (isDate == "")
		return "";
	if(!validDay(isDate.substr(0,4),isDate.substr(4,2),isDate.substr(6,2)))
		return "";

	var date = new Date(isDate.substr(0,4),parseInt(isDate.substr(4,2) -1),isDate.substr(6,2));

	return date;
}

function invlDate()
{
	var ActiveControl = event.srcElement;
	var isDate = ActiveControl.value;
	isDate = isDate.replace(/\-/gi, "");
	if (isDate == "")
		return;

	if(!validDay(isDate.substr(0,4),isDate.substr(4,2),isDate.substr(6,2)))
	{
		alert("³¯Â¥ Çü½ÄÀÌ Àß¸øµÇ¾ú½À´Ï´Ù.\n YYYY-MM-DDÇü½ÄÀ¸·Î ÀÔ·ÂÇØÁÖ¼¼¿ä");
		ActiveControl.value =getProperty(ActiveControl,"Backvalue","");
		return;
	}

}