/* 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(),
    calendarId: 'calendarDiv',
    inputClass: 'calendarSelectDate',
    
	init: function () {
        var x = getElementsByClass(popUpCal.inputClass, document, 'input');
        var y = document.getElementById(popUpCal.calendarId);
        // set the calendar position based on the input position
        for (var i=0; i<x.length; i++) {
            x[i].onfocus = function () {
            	isBottom = this.getAttribute("alt") == "bottom";
				popUpCal.selectedMonth = new Date().getMonth();
                setPos(this, y, isBottom); // setPos(targetObj,moveObj)
                y.style.display = 'block';
                popUpCal.drawCalendar(this); 
                popUpCal.setupLinks(this);
            }
			//on blur close date picker
			/*
			x[i].onblur = function () {
				y.style.display = 'none';
			}
			*/
        }
    },
    
    drawCalendar: function (inputObj) {
		
		var html = '';
		html += '<div id="Layer1" style="position:absolute; width:180px!important; width:180px; width:180px!important; z-index:1;left: 0px!important; left:0px; top: 0px!important;top: 0px;">';
		html += '<iframe id="selectblocker" style="position: relative; left: 0pt; top: 0pt; width: 180px; height: 100px; z-index: -1;" scrolling="no" frameborder="0"></iframe>';
		html += '<table cellpadding="0" cellspacing="0" border="0" style="position: absolute; left: 0pt; top: 0pt; width: 180x;">';
		html += '<tr><td>';
		html += '<table cellpadding="0" cellspacing="0" border="0" id="linksTable"><tr>';
		html += '<td width="15"><a id="prevYear" title="Tahun Sebelumnya"><img src="../image/prev_year.gif" border="0"></a></td>';
		html += '<td width="15"><a id="prevMonth" title="Bulan Sebelumnya"><img src="../image/prev_mon.gif" border="0"></a></td>';
        html += '<td align="center" nowrap><font color="#FFFFFF">'+getMonthName(popUpCal.selectedMonth)+'<input type="text" id="inputYear" name="inputYear" maxlength="4" size="3" class="swifttext" value="'+popUpCal.selectedYear+'" style="text-align:right; width:40px; background:#3b5998; border:0px; color:#fff;"></font></td>';
		html += '<td width="15"><a id="nextMonth" title="Bulan Berikutnya" border="0"><img src="../image/next_mon.gif" border="0"></a></td>';
		html += '<td width="15"><a id="nextYear" title="Tahun Berikutnya"><img src="../image/next_year.gif" border="0"></a></td>';
		html += '<td width="15"><a id="closeCalender" title="Tutup Kalender"><img src="../image/close.gif" border="0"></a></td>';		
		html += '</tr></table>';		
		html += '<table id="calendar" cellpadding="0" cellspacing="0"><tr class="weekDaysTitleRow">';
        var weekDays = new Array('M','S','S','R','K','J','S');
        //var weekDays = new Array('&nbsp;' + getDayName(0) + '&nbsp;','&nbsp;' + getDayName(1) + '&nbsp;','&nbsp;' + getDayName(2) + '&nbsp;','&nbsp;' + getDayName(3) + '&nbsp;','&nbsp;' + getDayName(4) + '&nbsp;','&nbsp;' + getDayName(5) + '&nbsp;','&nbsp;' + getDayName(6) + '&nbsp;');
        for (var j=0; j<weekDays.length; j++) {
			html += '<td class="weekDaysTitleRow">'+weekDays[j]+'</td>';
        }
		
        var daysInMonth = getDaysInMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        var startDay = getFirstDayofMonth(popUpCal.selectedYear, popUpCal.selectedMonth);
        var numRows = 0;
        var 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
        if (startDay != 7) {
            var noPrintDays = startDay + 1; 
        } else {
            var noPrintDays = 0; // if sunday print right away	
        }
		var today = new Date().getDate();
		var thisMonth = new Date().getMonth();
		var 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 == today) 
					 && (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>';
        html += '</td></tr></table></div>';        
        // add calendar to element to calendar Div
        var calendarDiv = document.getElementById(popUpCal.calendarId);
        calendarDiv.innerHTML = html;
        
        // close button link
        document.getElementById('closeCalender').onclick = function () {
            calendarDiv.style.display = 'none';
        }
				// setup next and previous links
        document.getElementById('prevMonth').onclick = function () {
            popUpCal.selectedMonth--;
            if (popUpCal.selectedMonth < 0) {
                popUpCal.selectedMonth = 11;
                popUpCal.selectedYear--;
            }
            popUpCal.drawCalendar(inputObj); 
            popUpCal.setupLinks(inputObj);
        }
        document.getElementById('nextMonth').onclick = function () {
            popUpCal.selectedMonth++;
            if (popUpCal.selectedMonth > 11) {
                popUpCal.selectedMonth = 0;
                popUpCal.selectedYear++;
            }
            popUpCal.drawCalendar(inputObj); 
            popUpCal.setupLinks(inputObj);
        }
        
        document.getElementById('prevYear').onclick = function () {
            popUpCal.selectedYear--;
            popUpCal.drawCalendar(inputObj); 
            popUpCal.setupLinks(inputObj);
        }
        
        document.getElementById('nextYear').onclick = function () {
            popUpCal.selectedYear++;
            popUpCal.drawCalendar(inputObj); 
            popUpCal.setupLinks(inputObj);
        }
 		document.getElementById('inputYear').onblur = function () {
            if(document.getElementById('inputYear').value.length <=0){
                alert('Tahun harus diisi');
                document.getElementById('inputYear').value=popUpCal.selectedYear;
                document.getElementById('inputYear').focus();
                return false;
            }else if(document.getElementById('inputYear').value.length <4 || isNaN(document.getElementById('inputYear').value || document.getElementById('inputYear').value<0)){
                alert('Format tahun salah');
                document.getElementById('inputYear').value=popUpCal.selectedYear;
                document.getElementById('inputYear').focus();
                return false;
            }
            popUpCal.selectedYear=document.getElementById('inputYear').value;
            popUpCal.drawCalendar(inputObj);
            popUpCal.setupLinks(inputObj);
        }        
    }, // end drawCalendar function
    
    setupLinks: function (inputObj) {
        // set up link events on calendar table
        var y = document.getElementById('calendar');
        var x = y.getElementsByTagName('a');
        for (var i=0; i<x.length; i++) {
            x[i].onmouseover = function () {
                this.parentNode.className = 'weekDaysCellOver';
            }
            x[i].onmouseout = function () {
                this.parentNode.className = 'weekDaysCell';
            }
            x[i].onclick = function () {
                document.getElementById(popUpCal.calendarId).style.display = 'none';
                popUpCal.selectedDay = this.innerHTML;
                inputObj.value = formatDate(popUpCal.selectedDay, popUpCal.selectedMonth, popUpCal.selectedYear);		
            }
        }
    }
    
}
// Add calendar event that has wide browser support
if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", popUpCal.init, false );
else if ( typeof window.attachEvent != "undefined" )
    window.attachEvent( "onload", popUpCal.init );
else {
    if ( window.onload != null ) {
        var oldOnload = window.onload;
        window.onload = function ( e ) {
            oldOnload( e );
            popUpCal.init();
        };
    }
    else
        window.onload = popUpCal.init;
}

/* Functions Dealing with Dates */

function formatDate(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 = Day+'/'+Month+'/'+Year;
    return dateString;
}

function getMonthName(month) {
    var monthNames = new Array('Januari','Februari','Maret','April','Mei','Juni','Juli','Agustus','September','Oktober','November','Desember');
    return monthNames[month];
}

function getDayName(day) {
    var dayNames = new Array('Senin','Selasa','Rabu','Kamis','Jumat','Sabtu','Minggu')
    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;
}

/* Common Scripts */

function getElementsByClass(searchClass,node,tag) {
    var classElements = new Array();
    if ( node == null ) node = document;
    if ( tag == null ) tag = '*';
    var els = node.getElementsByTagName(tag);
    var elsLen = els.length;
    var pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)");
    for (i = 0, j = 0; i < elsLen; i++) {
        if ( pattern.test(els[i].className) ) {
            classElements[j] = els[i];
            j++;
        }
    }
    return classElements;
}

/* Position Functions */

function setPos(targetObj,moveObj,isBottom) {
    var coors = findPos(targetObj);
    moveObj.style.position = 'absolute';
    if (isBottom) {
	    moveObj.style.top = coors[1]-20-120 + 'px';
	} else {
	    moveObj.style.top = coors[1]+20 + 'px';
	}
    moveObj.style.left = coors[0] + 'px';
}

function findPos(obj) {
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        curleft = obj.offsetLeft
        curtop = obj.offsetTop
        while (obj = obj.offsetParent) {
            curleft += obj.offsetLeft
            curtop += obj.offsetTop
        }
    }
    return [curleft,curtop];
}
