//Arrays to keep track of various information
var Months			= new Array("Januar", "Februar", "Marts", "April", "Maj", "Juni", "Juli", "August", "September", "Oktober", "November", "December");
var Days			= new Array("M","T","O","T","F","L","S");
var daysMonth		= new Array( 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
var daysMonthLeap	= new Array( 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);

// define a Calendar class
function Calendar () 
{
    // add some properties to our Calendar
	this.monthDisp		= null;
	this.yearDisp		= null;
	this.dayDisp		= null;
	this.entireCal		= null;
	this.saveTo			= null;
    this.currentDate	= new Date();
    this.originalDate	= new Date();

    // initialize the member function references
    // for the class prototype
    if (typeof(_calendar_prototype_called) == 'undefined')
    {
       _calendar_prototype_called = true;
       Calendar.prototype.updateCal = updateCal ;
       Calendar.prototype.init = init ;
       Calendar.prototype.Print = Print ;
       Calendar.prototype.Change = Change ;
       Calendar.prototype.Link = Link ;
       Calendar.prototype.ShowCalendar = ShowCalendar ;
       Calendar.prototype.SaveValue = SaveValue;
       Calendar.prototype.Show = Show;
       Calendar.prototype.Hide = Hide;
       Calendar.prototype.dateToString = dateToString;
       Calendar.prototype.stringToDate = stringToDate;
    }

    // define the clock's methods
	function init(monthSpan, yearSpan, table, allCalendar)
	{
		this.monthDisp = document.getElementById(monthSpan);
		this.yearDisp = document.getElementById(yearSpan);
		this.dayDisp = document.getElementById(table);
		this.entireCal = document.getElementById(allCalendar);
		this.currentDate = new Date();
		this.originalDate = new Date(this.currentDate);
		this.updateCal();
	}
	
	function ShowCalendar(currentDate, ypos, xpos, savetofield)
	{
		this.saveTo = document.getElementById(savetofield);
		this.originalDate = new Date(this.stringToDate(this.saveTo.value));
		this.currentDate = new Date(this.originalDate);
		this.entireCal.style.top = ypos+30 + "px";
		this.entireCal.style.left = xpos + "px";
		this.Show();
		this.updateCal();
	}
	
    function updateCal()
    {
		deleteChildren(this.dayDisp);
		deleteChildren(this.yearDisp);
		deleteChildren(this.monthDisp);
		this.yearDisp.appendChild(document.createTextNode( (this.currentDate.getFullYear()+"").substring(2)));
		this.monthDisp.appendChild(document.createTextNode(Months[this.currentDate.getMonth()]));
		
		var tableBody = document.createElement("TBODY");
		this.dayDisp.appendChild(tableBody);
		
		var tableRow = document.createElement("TR");
		tableBody.appendChild(tableRow);
		//All the days are added from the array
		for(i=0;i<Days.length;i++)
		{
			var tableCell = document.createElement("TH");
			tableRow.appendChild(tableCell);
			tableCell.appendChild(document.createTextNode(Days[i]));
		}
				
		//Then all the days must be written
		//Find first day of the month it will be set on the scale 0 - 6 is configured because Date has sunday as 0
		//and in our case it should be 6
		var firstDay = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), 1);
		firstDay = (firstDay.getDay()+Days.length-1)%Days.length;
		
		//dP contains the amount of days in the previous month
		var dP = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth()-1, 1);
		var dPdays = isLeapYear(dP.getFullYear()) ? daysMonthLeap[dP.getMonth()] : daysMonth[dP.getMonth()];

		//Countdays counts the days written
		var countDays = 1;
		var DaysFromPrevious = firstDay;
		//We find the number of days in the current month
		var noDays = isLeapYear(this.currentDate.getFullYear()) ? daysMonthLeap[this.currentDate.getMonth()] : daysMonth[this.currentDate.getMonth()];
		//We create an integer to count the days from the next month
		var extras = 1;

		//We  make a special style for all the dates that does not belong to this month
		//with "visibility:hidden;" in the tag, they would not be shown
		//style = "style=\"color:#666666;\"";
		
		var row = 0;
		
		//We then make a row as long as we have not yet written all the days of the month
		var breaker = 10; //we create a breaker to avoid an infinite loop
		var breakCount = 0;
		while(countDays <= noDays && breakCount++ < breaker)
		{
			tableRow = document.createElement("TR");
			tableBody.appendChild(tableRow);
			//The we add a cell for each day available in the week
			for(var i=0;i<Days.length;i++)
			{
				tableCell = document.createElement("TD");
				tableRow.appendChild(tableCell);
				
				if(row == 0)	//First Row
				{
					if(DaysFromPrevious > 0) //If this should be a date from the previous month
					{ 
						nextDate = dPdays-DaysFromPrevious+1;
						//dato = new Date(dP.getFullYear(),dP.getMonth(),(nextDate));
						dato = null;
						DaysFromPrevious--;
					}
					else
					{ 
						//Creates new Date with (year, month, date)
						//This is a normal day in this month
						dato = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), countDays++); 
					}
				}
				else
				{
					if((countDays+Days.length-1) > noDays) //Last row
					{
						if(countDays > noDays) { dato = null; }
						//	dato = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth()+1,extras++);
						else
							//This is a normal day in this month
							dato = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), countDays++); 
					}
					else
					{
						//This is a normal day in this month
						dato = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth(), countDays++); 
					}
				}
				this.Link(dato, tableCell);
			}
			row++;
		}
    }
    
    function Change(change)
	{
		//if(this.currentDate.getFullYear() > this.originalDate.getFullYear()+1) return;
		this.currentDate.setMonth(this.currentDate.getMonth() + change);
		this.updateCal();
	}
	
	//Function to ensure that a number is printed with a specific number of digits
	function Print(number, digits)
	{
		number = number + "";											//Conversion to force the number to be recognized as a string
		for(var vc=0;vc < (digits-number.length) && vc < 3; vc++) { number = "0"+number; }	//Adds leading zeros to fulfill the required number of digits
		return number;
	}
	
	//Function which sets a link given by a specific date. This is done to ensure that the formatting is the same
	function Link(dato, cell)
	{
		//alert(typeof(cell));
		if(typeof(dato) != 'object' || typeof(cell) == 'undefined' || dato == null)
			return document.createTextNode("");
		var b = this.originalDate; 
		var c = dato;
		var classText = (c.getDate() == b.getDate() && c.getMonth() == b.getMonth() && c.getFullYear() == b.getFullYear()) ? "calendaractivecell" : "";
		
		var link = document.createElement("a");
		
		link.appendChild(document.createTextNode(c.getDate()))
		cell.appendChild(link);
		
		if(classText != "")
		{
			cell.className = classText;
			link.className = classText;
		}
		else
		{
			link.onmouseover	= function() {	 this.className='calendaractivecell'; };
			link.onmouseout		= function()	{ this.className='';};
			cell.onmouseover	= function()	{ this.className='calendaractivecell'; };
			cell.onmouseout		= function()	{ this.className='';};
		}
		
		var result = this.dateToString(c) ;
		link.onclick		= function()	{ calendar.SaveValue(result); };
		cell.onclick		= function()	{ calendar.SaveValue(result); };
		
		//alert(cell.outerHTML);
		return link;
	}
	
	function SaveValue(result)
	{
		this.saveTo.value = result;
		this.Hide();
	}
	
	function Show()
	{
		this.entireCal.style.display = 'block';
		this.entireCal.style.visibility = 'visible';
	}
	function Hide()
	{
		this.entireCal.style.display = 'none';
		this.entireCal.style.visibility = 'hidden';
	}
	
	function stringToDate(datestring)
	{
		var year, month, date = "";
		if(datestring.indexOf("-") > 0)
		{
			date = datestring.substring(0, datestring.indexOf("-"));
			if(datestring.lastIndexOf("-") > datestring.indexOf("-") )
			{
				month = datestring.substring(datestring.indexOf("-")+1, datestring.lastIndexOf("-"));
				if(datestring.indexOf("-") > 0)
				{
					year = datestring.substring(datestring.lastIndexOf("-")+1, datestring.length );
				}
			}
		}
		if(year!="" && month!="" && date != "")
		return new Date(year, month-1, date);
		return new Date();
	}
	
	function dateToString(dato)
	{
		return Print(dato.getDate(),2)+ "-"  + Print(dato.getMonth()+1,2) + "-"+ dato.getFullYear()
	}
}



function deleteChildren(node)
{
	var count = node.childNodes.length;
	for(var i=0;i<count;i++)//First we delete existing calendar
	{ 
		if(node.childNodes[i])
			node.removeChild(node.childNodes[i]);
		else
			node.removeChild(node.childNodes[0]); //Firefox resets the numbering after the first element is removed
		
	}
}
//Function to test whether a year is leap year or not
function isLeapYear(year) 
{
	if ((year/4)   != Math.floor(year/4))   return false;
	if ((year/100) != Math.floor(year/100)) return true;
	if ((year/400) != Math.floor(year/400)) return false;
	return true;
}


