/* MarcGrabanski.com */
/* Pop-Up Calendar Built from Scratch by Marc Grabanski */
var popUpCal = {
    selectedMonth: new Date().getMonth(), // 0-11
    selectedYear: new Date().getFullYear(), // 4-digit year
    selectedDay: new Date().getDate(),
	init: function () {
		$('<div id="calendarDiv"></div>').appendTo("body");
		var x = $('input.calendarSelectDate');
		var y = $('#calendarDiv');
		x.focus( function () {
			popUpCal.input = $(this);
			y.hide();
			setPos(this, y); // setPos(targetObj,moveObj)
			setDateFromField();
			popUpCal.drawCalendar('init'); 
		});
    }, // end init function
    drawCalendar: function (strAction) {

        if (strAction && strAction == 'init')
        {
    		var initSelectedDate = popUpCal.input.attr('selectedDate');
    		if (initSelectedDate && initSelectedDate.length == 8) {
    		    popUpCal.selectedYear = parseFloat(initSelectedDate.substr(0,4));
    			popUpCal.selectedMonth = parseFloat(initSelectedDate.substr(4,2))-1;
    		}
    	}

		html = '<a id="closeCalender">달력닫기</a>';
		html += '<table cellpadding="0" cellspacing="0" id="linksTable"><tr>';
    	html += '	<td align="left"><a id="prevYear"> << </a><a id="prevMonth"> < [이전]</a></td>';
		html += '	<td align="right"><a id="nextMonth">[다음] > </a><a id="nextYear"> >> </a></td>';
		html += '</tr></table>';
		html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr>';
		html += '<th colspan="7" class="calendarHeader">'+popUpCal.selectedYear+'년'+getMonthName(popUpCal.selectedMonth)+'</th>';
		html += '</tr><tr class="weekDaysTitleRow">';
        var weekDays = new Array('일','월','화','수','목','금','토');
        for (var j=0; j<weekDays.length; j++) {
			html += '<td>'+weekDays[j]+'</td>';
        }
        
        daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        numRows = 0;
        printDate = 1;
        if (startDay != 7) { numRows = Math.ceil(((startDay+1)+(daysInMonth))/7); } // calculate the number of rows to generate
        // calculate number of days before calendar starts
        (startDay != 7) ? noPrintDays = startDay + 1 : noPrintDays = 0; // if sunday print right away	

		// function with cruft for figuring out what day to highlight
		thisDay = new Date().getDate();
		thisMonth = new Date().getMonth();
		thisYear = new Date().getFullYear();
        // create calendar rows
        for (var e=0; e<numRows; e++) {
			html += '<tr class="weekDaysRow">';
            // create calendar days
            for (var f=0; f<7; f++) {
				if ( (printDate == thisDay) 
					 && (popUpCal.selectedYear == thisYear) 
					 && (popUpCal.selectedMonth == thisMonth) 
					 && (noPrintDays == 0)) {
					html += '<td id="today" class="weekDaysCell">';
				} else {
                	html += '<td class="weekDaysCell">';
				}
                if (noPrintDays == 0) {
					if (printDate <= daysInMonth) {
						html += '<a>'+printDate+'</a>';
					}
                    printDate++;
                }
                html += '</td>';
                if(noPrintDays > 0) noPrintDays--;
            }
            html += '</tr>';
        }
		html += '</table>';
        // add calendar to element to calendar Div
        var calendarDiv = $('#calendarDiv');
		calendarDiv.empty().append(html).show("medium");
		popUpCal.setupLinks();
        // close button link
        $('#closeCalender').click( function () {
            calendarDiv.hide(250);
        });
		// setup next and previous links
		$('#prevMonth').click( function () {
            popUpCal.selectedMonth--;
            if (popUpCal.selectedMonth < 0) {
                popUpCal.selectedMonth = 11;
                popUpCal.selectedYear--;
            }
            popUpCal.drawCalendar(); 
        });
		$('#nextMonth').click( function () {
			popUpCal.selectedMonth++;
            if (popUpCal.selectedMonth > 11) {
                popUpCal.selectedMonth = 0;
                popUpCal.selectedYear++;
            }
            popUpCal.drawCalendar(); 
        });
		$('#prevYear').click( function () {
            popUpCal.selectedYear--;
            popUpCal.drawCalendar(); 
        });
		$('#nextYear').click( function () {
            popUpCal.selectedYear++;
            popUpCal.drawCalendar(); 
        });
        
    }, // end drawCalendar function
    setupLinks: function () {
        // set up link events on calendar table
        var x = $('#calendar a');
		x.mouseover( function () {
			this.parentNode.className = 'weekDaysCellOver';
		});
		x.mouseout( function () {
			this.parentNode.className = 'weekDaysCell';
        });
		x.click( function () {
                $('#calendarDiv').hide(250);
                popUpCal.selectedDay = $(this).html();
                var dateFormat = popUpCal.input.attr('format');
                if (typeof dateFormat == 'undefined')
                {
                    dateFormat = '0';
                }
				var setVal = formatDate(dateFormat, popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
				popUpCal.input.val(setVal);
				
				var rawInputID = popUpCal.input.attr('rawInputID');
				if (typeof rawInputID != 'undefined')
				{
				    setVal = formatDate('0', popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);
				    $("#"+rawInputID).val(setVal);
				}
                
                var funcName = popUpCal.input.attr('callbackFunc');
                if (typeof funcName != 'undefined')
                {
                    eval(funcName);
                }
        });
    } // end setupLinks function
}
// Initialize the calendar
$(document).ready(function(){
   popUpCal.init();
});
/* Functions Dealing with Dates */
function formatDate(dateFormat, Day, Month, Year) {
    Month++; // adjust javascript month
    if (Month <10) Month = '0'+Month; // add a zero if less than 10
    if (Day < 10) Day = '0'+Day; // add a zero if less than 10
    var dateString;
    switch (dateFormat)
    {
        case '1' :
            dateString = Year+'년'+Month+'월'+Day+'일';
            break;
        default :
            dateString = Year+''+Month+''+Day;
            break;
    }
    
    return dateString;
}
function setDateFromField() {
	selectedDate = popUpCal.input.val();
	if (selectedDate.length == 8) {
	    popUpCal.selectedYear = parseFloat(selectedDate.substr(0,4));
		popUpCal.selectedMonth = parseFloat(selectedDate.substr(4,2))-1;
		popUpCal.selectedDay = parseFloat(selectedDate.substr(6,2));
	} else {
		popUpCal.selectedDay = new Date().getDate();
		popUpCal.selectedMonth = new Date().getMonth();
		popUpCal.selectedYear = new Date().getFullYear();
	}
}
function getMonthName(month) {
    var monthNames = new Array('1월','2월','3월','4월','5월','6월','7월','8월','9월','10월','11월','12월');
    return monthNames[month];
}
function getDayName(day) {
    var dayNames = new Array('일요일','월요일','화요일','수요일','목요일','금요일','토요일')
    return dayNames[day];
}
function getDaysInMonth(year, month) {
    return 32 - new Date(year, month, 32).getDate();
}
function getFirstDayofMonth(year, month) {
    var day;
    day = new Date(year, month, 0).getDay();
    return day;
}
/* Position Functions */
function setPos(targetObj,moveObj) {
    var coors = findPos(targetObj);
    moveObj.css('position','absolute');
    moveObj.css('top',coors[1]+18+'px');
    moveObj.css('left',coors[0]+'px');
}
