// Globals
var updates_per_year = 26; // Every two weeks
var date_variance = 3; // To make it not look like exactly ever 2 weeks
var tag_name = 'span';
var class_name = 'date_fixup';

// Call this function to fixup all dates on the page marked to be fixed up
function date_fixup() {
	var spans = document.getElementsByTagName(tag_name);
	for( var i=0; i<spans.length; i++ ) {
		if( spans[i].className == class_name ) {
			spans[i].innerHTML =
				_date_fixup( spans[i].innerHTML, new Date() );
		}
	}
}

// Call this function somewhere in the page to test functionality. Will print
// out every day for the year and what date is calcualated.
function test_fixup() {
	var dt = new Date(); dt.setMonth(0); dt.setDate(1);
	for( var i=1; i<365; i++ ) {
		dt.setDateOfYear(i);
		document.write(dt.toString()+': ');
		document.write(_date_fixup("January 12, 2005", dt.clone()));
		document.writeln('<br/>');
	}
}

// Internal function actually calculate the date.
// * dtstr - The actual date
// * today - Today's date
function _date_fixup( dtstr, today ) {
	var dt = new Date();
	var todayish = today.clone();
	todayish.setHours(0, 0, 0, 0);
	dt.setTime(Date.parse(dtstr.replace( /\s/, '' )));
	var days_per_change = Math.floor(365/updates_per_year);
	todayish.setDateOfYear(
		Math.floor(todayish.getDateOfYear()/days_per_change)
		*days_per_change);
	var offset = (((todayish.getMonth()+1)+todayish.getDate()+
		todayish.getFullYear())%(date_variance+1));
	todayish.setDate(todayish.getDate() + offset );
	if( todayish < dt ) {
		todayish = dt;
	} else if( todayish > today ) {
		todayish = today;
	}
	return todayish.toString();
}

// Extensions to Javascript's standard date class
var days_per_month = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
var month_names = [ 'January', 'Feburary', 'March', 'April', 'May', 'June',
	'July', 'August', 'September', 'October', 'November', 'December' ];
Date.prototype.getDateOfYear = function() {
	var ret = 0;
	for( var i=0; i<this.getMonth(); i++ ) {
		ret += days_per_month[i];
	}
	return ret + this.getDate();
}
Date.prototype.setDateOfYear = function( dt ) {
	var i=0;
	for(; i<this.getMonth(); i++ ) {
		dt -= days_per_month[i];
	}
	this.setMonth(i);
	this.setDate(dt);
}
Date.prototype.clone = function() {
	var ret = new Date();
	ret.setTime(this.getTime());
	return ret;
}
Date.prototype.toString = function() {
	return month_names[this.getMonth()]+' '+this.getDate()+', '+this.getFullYear();
}
