Il codice che hai postato è obsoleto (oltre che prolisso). Qui avevo postato un modo semplice semplice per costruire un calendario. Ti incollo il codice:

codice:
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Esempio</title>
<script type="text/javascript">
function appendCalendar () {

	var
		oTD, oTR = document.createElement("tr"), oTBody = document.createElement("tbody"),
		oTHead = document.createElement("thead"), oTable = document.createElement("table"),
		nIter = 0, oMonthStart = new Date(), aMonthsLen = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
		aDaysNames = ["Lun", "Mar", "Mer", "Gio", "Ven", "Sab", "Dom"];

	for (nIter; nIter < 7; nIter++) {
		oTD = document.createElement("th");
		oTD.innerHTML = aDaysNames[nIter];
		oTR.appendChild(oTD);
	}

	oTHead.appendChild(oTR);
	oMonthStart.setDate(1);
	nIter = 0;

	for (var nEndBlanks = (oMonthStart.getDay() + 6) % 7, nEnd = aMonthsLen[oMonthStart.getMonth()] + nEndBlanks, nTotal = nEnd + ((7 - nEnd % 7) % 7); nIter < nTotal; nIter++) {
		if (nIter % 7 === 0) {
			oTR = document.createElement("tr");
			oTBody.appendChild(oTR);
		}
		oTD = document.createElement("td");
		oTD.innerHTML = nIter < nEndBlanks || nIter + 1 > nEnd ? " " : nIter - nEndBlanks + 1;
		oTR.appendChild(oTD);
	}

	oTable.appendChild(oTHead);
	oTable.appendChild(oTBody);
	document.getElementById("calendar").appendChild(oTable);

}
</script>

</head>

<body onload="appendCalendar();">

<div id="calendar"></div>

</body>
</html>