/*
Note: ISO 8601 claims that

- A week starts with Monday (day 1) and ends with Sunday (day 7).

 - Week 01 of a year is per definition the first week that has the Thursday in this year, which is equivalent to the week that contains the fourth day of January. In other words, the first week of a new year is the week that has the majority of its days in the new year. Week 01 might also contain days from the previous year and the week before week 01 of a year is the last week (52 or 53) of the previous year even if it contains days from the new year. 

*/
var currentDate = new Date();
	currentDate.month = currentDate.getMonth();
	currentDate.day = currentDate.getDate();
	currentDate.year = currentDate.getFullYear();

//Constructor
//		 calendar('prevMonth',new Date(),'dateselect', 'date_von', false);
function calendar(id,d,formName,inputName,multipleFields){
	this.id = id;
	this.dateObject = d;
	this.write = writeCalendar;
	this.form = formName;
	this.input = inputName;
	this.fields = multipleFields;
	this.length = getLength;
	this.month = d.getMonth();
	this.date = d.getDate();
	this.day = d.getDay();
	this.year = d.getFullYear();
	this.getFormattedDate = getFormattedDate;
	//get the first day of the month's day
	d.setDate(1);
	// monday is the first day of the week
	this.firstDay = (d.getDay() == 0) ? 7 : d.getDay();
	// sunday is the first day of the week
	//	this.firstDay = d.getDay();
	//then reset the date object to the correct date
	d.setDate(this.date);
	
}


// monday is first day of the week
var days = new Array('Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag','Sonntag');
// sunday is first day of the week
//var days = new Array('Sonntag','Montag','Dienstag','Mittwoch','Donnerstag','Freitag','Samstag');
var months = new Array('Januar','Februar','März','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember');

function getFormattedDate(){
	var dayNum =  ((this.day) == 0 ) ? 6 : (this.day-1);

	var formattedDay = this.date;
	formattedDay = (formattedDay <= 9) ? '0'+ formattedDay : formattedDay;

	var formattedMonth = (this.month + 1);
	formattedMonth = (formattedMonth <= 9) ? '0'+ formattedMonth : formattedMonth;

	return formattedDay + '.' + formattedMonth + '.' + this.year;
	//return this.date + '.' + this.month+ '.' + this.year;
	//return days[dayNum] + ',  ' + this.date + '. ' + months[this.month] + ' ' + this.year;
	//return this.month + '/' + this.date + '/' + this.year;
}


function writeCalendar(){
	var k = 0;

	var calString = '<div id="' + this.id + '">';
	//write month and year at top of table
	calString += '<table id="cal' + this.id + '" class="calendar" cellspacing="0">';

	//write the nav / header row
	calString += '<tr>';
	calString += '<th class="nav" title="Ein Jahr zurück" onClick="changeMonth(-12,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')">&lt;</th>';
	calString += '<th class="nav" title="Einen Monat zurück" onClick="changeMonth(-1,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')">&lt;</th>';
	//write the month

	calString += '<th colspan="4" class="month" title="Ein Jahr weiter"  onClick="changeToMonth('+currentDate.month+',\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')" align="center"><strong>'+ months[this.month] + ',&nbsp;' + this.year + '</strong></th>';

	calString += '<th class="nav" title="Einen Monat weiter" onClick="changeMonth(1,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')">&gt;</th>';
	calString += '<th class="nav" title="Ein Jahr weiter" style="text-decoration:underline;text-align:right;" onClick="changeMonth(12,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')">&gt;</th>';
	calString += '</tr>';

	
	//write nav month row
	calString += '<tr class="navmonthtr">';
	calString += '<th class="navmonth">&nbsp;</th>';
	calString += '<th class="navmonth" onClick="changeToMonth(0,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacertop" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">JAN</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(1,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacertop" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">FEB</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(2,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacertop" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">MÄR</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(3,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacertop" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">APR</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(4,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacertop" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">MAI</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(5,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacertop" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">JUN</span></th>';

	calString += '<th class="navmonth">&nbsp;</th>';
	calString += '</tr>';
	
	calString += '<tr class="navmonthtr">';
	calString += '<th class="navmonth">&nbsp;</th>';
	calString += '<th class="navmonth" onClick="changeToMonth(6,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacerbottom"  onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">JUL</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(7,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacerbottom" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">AUG</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(8,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacerbottom" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">SEP</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(9,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacerbottom" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">OKT</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(10,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacerbottom" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">NOV</span></th>';
	calString += '<th class="navmonth" onClick="changeToMonth(11,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')"><span class="spacerbottom" onmouseover="simulateFormHover(this,\'onmouseover\',\'monthhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'monthhover\')">DEZ</span></th>';
	calString += '<th class="navmonth">&nbsp;</th>';
	calString += '</tr>';
	

	//write a row containing days of the week
	calString += '<tr>';
	
	calString += '<th class="kwheader">KW</th>';
	for(var i=0;i<days.length;i++){
		calString += '<th class="dayheader">' + days[i].substring(0,2) + '</th>';
	}
	//write the body of the calendar
	calString += '<tr>';
	
	//calculate max number of needed cells to prevent an empty row at the bottom
	var emtyCellsInFront = parseInt(this.firstDay -1) ;
	var emtyFrontPlusDays = parseInt(emtyCellsInFront) + parseInt(this.length()) ;
	// 7 * 5 = 35
	var neededCells = (emtyFrontPlusDays > 35) ? '42' : '35';

	//create 6 rows so that the calendar doesn't resize
	for(var j=0;j<neededCells;j++){
		// monday is first day of the week
		var displayNum = (j-this.firstDay+2);

		// sunday is first day of the week
//		var displayNum = (j-this.firstDay+1);

		//add kw
		// monday is first day of the week
		if(j%7==0 && (displayNum -1) < this.length()){
		// sunday is first day of the week
//		if(j%7==0 && (displayNum ) < this.length()){
			var thisKw = new kalenderwochen(this.year, this.month, displayNum)
			calString += '<td class="kw">'+ (parseInt(thisKw.kw)) +'</td>';
		}
		// monday is first day of the week
		if(j<(this.firstDay -1)){
		// sunday is first day of the week
//		if(j<(this.firstDay)){
			//write the leading empty cells
			calString += '<td class="empty">&nbsp;</td>';
		}
		else if(displayNum == currentDate.day && this.month == currentDate.month && this.year == currentDate.year ){		
//		else if(displayNum==this.date){
			calString += '<td id="' + this.id +'today" class="today" onClick="javascript:changeDate(this,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')" onmouseover="simulateFormHover(this,\'onmouseover\',\'calhover\')"  onmouseout="simulateFormHover(this,\'onmouseout\',\'calhover\')">' + displayNum + '</td>';
		}else if(displayNum > this.length()){
			//Empty cells at bottom of calendar
			calString += '<td class="empty">&nbsp;</td>';
		}else{
			//the rest of the numbered cells
			calString += '<td id="" class="days" onClick="javascript:changeDate(this,\'' + this.id + '\',\'' + this.form + '\',\'' + this.input + '\',\'' + this.fields + '\')" onmouseover="simulateFormHover(this,\'onmouseover\',\'calhover\')" onmouseout="simulateFormHover(this,\'onmouseout\',\'calhover\')">' + displayNum + '</td>';
		}
		if(j%7==6){
			calString += '</tr><tr>';
		}
	}
	//close the last number row
	calString += '</tr>';
	
	calString += '</table>';
	calString += '</div>';
	return calString;
}

function getLength(){
	//thirty days has September...
	switch(this.month){
		case 1:
			if((this.dateObject.getFullYear()%4==0&&this.dateObject.getFullYear()%100!=0)||this.dateObject.getFullYear()%400==0)
				return 29; //leap year
			else
				return 28;
		case 3:
			return 30;
		case 5:
			return 30;
		case 8:
			return 30;
		case 10:
			return 30
		default:
			return 31;
	}
}
function changeDate(td,cal,formName,inputName,multipleFields){
	//Change the cal argument to the existing calendar object
	//This is why the first argument in the constructor must match the variable name
	//The cal reference also allows for multiple calendars on a page
	cal = eval(cal);

	if (document.getElementById(cal.id + "selected")) {document.getElementById(cal.id + "selected").className = "days";}
	if (document.getElementById(cal.id + "selected")) {document.getElementById(cal.id + "selected").id = "";}

	td.className = "date";
	td.id = cal.id + "selected";
	//set the calendar object to the new date
	cal.dateObject.setDate(td.firstChild.nodeValue);
	cal = new calendar(cal.id,cal.dateObject);
	//here is where you could react to a date change - I'll just display the formatted date
//	alert(cal.getFormattedDate())
//	alert(formName +''+ inputName+''+multipleFields)

	if (multipleFields == 'false') {
		document.forms[formName][inputName].value = cal.getFormattedDate();
	}

	if (multipleFields == 'true') {
		document.forms[formName][inputName+'_dd'].value = cal.getFormattedDate().substr(0,2);
		document.forms[formName][inputName+'_mm'].value = cal.getFormattedDate().substr(3,2);
		document.forms[formName][inputName+'_yyyy'].value = cal.getFormattedDate().substr(6,4);
	}
	
	// hide calender
	var myCalObj  = 'calendar'+ cal.id.substr(3,2);
	var foldObj = document.getElementById(myCalObj);
	foldObj.style.display = (foldObj.style.display == 'none') ? 'block' : 'none';
	var imgObj = document.getElementById('img'+cal.id);
	imgObj.src = (foldObj.style.display == 'none') ? '/img/gen_icon_calendar.gif' : '/img/gen_icon_close.gif';

}

function changeMonth(mo,cal,formName,inputName,multipleFields){

	//more trickery!
	cal = eval(cal);
	//The Date object is smart enough to know that it should roll over in December
	//when going forward and in January when going back
	cal.dateObject.setMonth(cal.dateObject.getMonth() + mo);
	cal = new calendar(cal.id,cal.dateObject,formName,inputName,multipleFields);
	cal.formattedDate = cal.getFormattedDate();
	document.getElementById(cal.id).innerHTML = cal.write();
	
}

function changeToMonth(mo,cal,formName,inputName,multipleFields){
	//more trickery!
	cal = eval(cal);
	//The Date object is smart enough to know that it should roll over in December
	//when going forward and in January when going back
	cal.dateObject.setMonth(mo);
	cal = new calendar(cal.id,cal.dateObject,formName,inputName,multipleFields);
	cal.formattedDate = cal.getFormattedDate();
	document.getElementById(cal.id).innerHTML = cal.write();
	
}

function kalenderwochen(year, month, day) {
	var kwDate = new Date(year,month,day); 
	var firstDo = yearsFirstDo(kwDate);
	var kwYear = firstDo.getFullYear();
	var doKW1 = yearsFirstDo(new Date(kwYear,0,4)); 
	this.kw =Math.floor(1.5+(firstDo.getTime()-doKW1.getTime())/86400000/7)
}

function yearsFirstDo(datum) { 
	var Do=new Date();
	Do.setTime(datum.getTime() + (3-((datum.getDay()+6) % 7)) * 86400000); 
	return Do;
}
