// JavaScript Document

//Calendar stuff
function Calendar() {
	var cDate = new Date();
	var thisRef = this;
	var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
	var dows = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];	
	
	this.Year = cDate.getFullYear();
	this.Month = cDate.getMonth()+1;
	this.Date = cDate.getDate();
	this.Day = cDate.getDay();
	
	//sets Cursor to today
	this.gotoToday = function() {
		setVariables(cDate);
	}
	//Determines if year is leap
	this.isLeap = function(y) {  
		var leap = (y % 4==0) && ((y % 100!=0) || (y % 400==0));
		return leap;
	}
	//Returns maximum days in a month
	this.getMaxDays = function(mo, yr) {
		return 32 - new Date(yr, mo, 32).getDate();
	}
	//Returns a DOW
	this.firstDayOfWeek = function(m, y) { 
	    var dt = new Date(y, m-1, 1);
	    return dt.getDay(); 
	}
	//Returns Week of the year for the current date
	this.weekOfTheYear = function() {
		var firstDay = new Date(thisRef.Year, 0, 1).getDay();
		var diff = 7 - firstDay + 1;
		var doy = 0;
		var i = 0;
		do {
			doy += thisRef.getMaxDays(i, thisRef.Year);		
		} while(i++ < (thisRef.Month-1));		
		doy -= (thisRef.getMaxDays(thisRef.Month-1, thisRef.Year) - thisRef.Date);
		
		return Math.round(((doy+diff)-firstDay) / 7); 
	}	
	//Returns Month Name
	this.getMonthName = function(m) {
		return (m == null)?months[thisRef.Month-1]:months[m-1];
	}
	//Returns Day name
	this.getDayName = function(d) {
		return (d == null)?dows[thisRef.Day]:dows[d];
	}
	//Sets current callendar date
	this.setCurrentDate = function(yy,mm,dd) {
		var nDate = new Date(yy, (mm-1), dd);
		setVariables(nDate);
	}
	//Advances current date by days (negative numbers will advance backwards)
	this.advanceDays = function(d) {
		var nDate = new Date(thisRef.Year, thisRef.Month-1, (thisRef.Date + d));
		setVariables(nDate);
	}	
	//Advances current date by weeks (negative numbers will advance backwards)
	this.advanceWeeks = function(wks) {
		var wDays = wks * 7
		var nDate = new Date(thisRef.Year, thisRef.Month-1, (thisRef.Date + wDays));
		setVariables(nDate);
	}
	//Advances current date by month (negative numbers will advance backwards)
	this.advanceMonths = function(m) {		
		var nDate = new Date(thisRef.Year, ((thisRef.Month-1) + m), thisRef.Date);
		setVariables(nDate);
	}
	//Advances current date by year (negative numbers will advance backwards)
	this.advanceYears = function(y) {		
		var nDate = new Date((thisRef.Year + y), thisRef.Month-1, thisRef.Date);
		setVariables(nDate);
	}
	//Returns a date object
	this.toDate = function() {
		var nDate = new Date(thisRef.Year, (thisRef.Month-1), thisRef.Date);
		return nDate;
	}
	
	//Internal
	function setVariables(nDate) {
		thisRef.Year = nDate.getFullYear();
		thisRef.Month = nDate.getMonth()+1; 
		thisRef.Date = nDate.getDate();
		thisRef.Day = nDate.getDay();
	}
}
