//If the browser is W3 DOM compliant, execute setCalendar function
if (document.getElementsByTagName && document.getElementById) {
if (window.addEventListener) window.addEventListener('load', initCalendar, false);
else if (window.attachEvent) window.attachEvent('onload', initCalendar);
}


var d = document;
	
var y = d.getElementsByName('defaultyear');
var m = d.getElementsByName('defaultmonth');

var year;
var month;
var calList;
	
var calregxp = /calendar-(\d{4})-(\d\d?)/ ;


function initCalendar() {
	if (y[0] != null) {  // default values must be set via <input> tags or calendar will not render
		year = y[0].value;
		month = m[0].value;
		calList = getDivElements();
		setCalendar();
	}	
}


function setCalendar() {
	
	if (curdiv = getCurrentCalendar(year,month)) {
		curdiv.style.display='block';

	}	
	
	curindex = getCurIndex();
	divList = d.getElementsByTagName('div');
	
	for (i=0; div=divList[i]; i++) {
		if (div.id == 'calnext') {
			div.style.visibility = calList[curindex+1] ? 'visible' : 'hidden';
		}
		
		if (div.id == 'calprev') {
			div.style.visibility = calList[curindex-1] ? 'visible' : 'hidden';
		}
	}
}

function nextCal() {
	curindex = getCurIndex();
	if (calList[curindex+1]) {
		nextcal = calList[curindex+1];
		matchd = nextcal.id.match(calregxp);
		year = matchd[1];
		month = matchd[2];
		calList[curindex].style.display='none';
		setCalendar();
	} else {
		//window.alert("no more this way!");
	}
}

function prevCal() {
	curindex = getCurIndex();
	if (calList[curindex-1]) {
		prevcal = calList[curindex-1];
		matchd = prevcal.id.match(calregxp);
		year = matchd[1];
		month = matchd[2];
		calList[curindex].style.display='none';
		setCalendar();
		
	} else {
		//window.alert("no more this way!");
	}
	
}



function getCurrentCalendar(year,month) {		
		for (i=0; div=calList[i]; i++) {
			if (div.id.match(calregxp)) {
				matchd = div.id.match(calregxp);
				if (matchd[1]==year && matchd[2]==month) {
					return div;
				}
				
				// mini-hack to compensate for single-digit month representation with preceding 0
				if (matchd[1]==year && matchd[2]=="0" + month) {
					return div;
				}
				
			}
		}
		
		return false;
}

function getDivElements() {

	divList = d.getElementsByTagName('div');
	cList = new Array;
	for (var i=0; div=divList[i]; i++) {
		if (div.id.match(calregxp)) {
		 	cList.push(div);
		}
	}
	
	return cList;
	
}

function getCurIndex() {
	var curdiv = getCurrentCalendar(year,month);
	var clen = calList.length;
	
	for (i=0; i<clen ; i++) {
		if (calList[i] == curdiv) {
			return i;
		}
	}
	
	return false;
}
