var calendar = {
	baseUrl:'',
	selectedMonth:new Date().getMonth(),
	selectedYear:new Date().getFullYear(),
	
	init:function() {
		baseUrl = $('.calendar .calendarHeader a').attr('href');
		this.loadMonth(this.selectedMonth, this.selectedYear);
		return;
	},
	loadMonth:function(month, year)
	{
		var box = $('.calendar');
		var cal = null;
		if(box.length > 0)
		{	
			cal = $('.calendar table');
			cal.hide();
			box.children('.loading').show();
			this.clearDayDetail(cal.find('.eventDetail'));
			this.setMonth(month, year, cal);
			this.buildMonthCalendar(month, year, cal);
			this.setPreviousMonth(month, year, cal);
			this.setNextMonth(month, year, cal);
			box.children('.loading').hide();
			cal.show();
		}
		return;
	},
	buildMonthCalendar:function(month,year,calendar)
	{
		
		var date = new Date(year,month,1);
		var currentBox = 0;
		var startBox = this.getDayIndex(date);
		while(currentBox < startBox)
		{
			var box = this.getDayBox(currentBox, calendar);
			this.clearDayData(box);
			//box.addClass('nonDay');
			currentBox++;
		}
		
		while(date.getMonth() == month)
		{
			var box = this.getDayBox(currentBox, calendar);
			this.setDayData(box, date);
			date.setDate(date.getDate() + 1);
			currentBox++;
		}
		
		while(currentBox <= 42)
		{
			var box = this.getDayBox(currentBox, calendar);
			this.clearDayData(box);
			box.addClass('nonDay');
			currentBox++;
		}
		return;
	},
	getDayIndex:function(date)
	{
		if(date.getDay() == 0) { return 7; }
		else { return date.getDay(); }
	},
	getDayBox:function(boxIndex, calendar)
	{
		boxIndex--;
		var column = boxIndex%7;
		var row = Math.floor(boxIndex/7);
		return calendar.find('tr:nth-child(' + (row + 3) + ')').children('td:nth-child(' + (column + 1) + ')');
	},
	setMonth:function(month, year, calendar)
	{
		calendar.find('.calendarHeader a').html(this.monthName(month) + ' ' + year);
		calendar.find('.calendarHeader a').attr('href', baseUrl + '&month=' + month + '&year=' + year);
		return;
	},
	monthName:function(month)
	{
		switch(month)
		{
			case 0: return 'Januari'; break;
			case 1: return 'Februari'; break;
			case 2: return 'Maart'; break;
			case 3: return 'April'; break;
			case 4: return 'Mei'; break;
			case 5: return 'Juni'; break;
			case 6: return 'Juli'; break;
			case 7: return 'Augustus'; break;
			case 8: return 'September'; break;
			case 9: return 'Oktober'; break;
			case 10: return 'November'; break;
			case 11: return 'December'; break;
		}

	},
	dayName:function(date)
	{
		switch(date.getDay())
		{
			case 0: return 'Zondag'; break;
			case 1: return 'Maandag'; break;
			case 2: return 'Dinsdag'; break;
			case 3: return 'Woensdag'; break;
			case 4: return 'Donderdag'; break;
			case 5: return 'Vrijdag'; break;
			case 6: return 'Zaterdag'; break;
		}
	},
	setPreviousMonth:function(month, year, cal)
	{
		var previous = cal.find(".previousMonth img");
		previous.unbind('click');
		//check if there are events
		var intDate = (year * 10000)  + ((month + 1) * 100) + 1; 
		var events = $.grep(calendarDays, function(n, i) { return ((n.year * 10000) + (n.month * 100) + n.day) < intDate ; });
		if(events.length > 0){
			previous.show();
			if(month != 0){
				previous.click(function() { calendar.loadMonth(month - 1, year); return; })
			}
			else {
				previous.click(function() { calendar.loadMonth(11, year - 1); return; })
			}
		}
		else
		{
			previous.hide();
		}
		return;
	},
	setNextMonth:function(month, year, cal)
	{
		var next = cal.find(".nextMonth img");
		next.unbind('click'); 
		//check if there are events
		var intDate = (year * 10000)  + ((month + 1) * 100) + 31; 
		var events = $.grep(calendarDays, function(n, i) { return ((n.year * 10000) + (n.month * 100) + n.day) > intDate ; });
		if(events.length > 0){
			next.show();
			if(month == 11){
				next.click(function() { calendar.loadMonth(0, year + 1); return; })
			}
			else {
				next.click(function() { calendar.loadMonth(month + 1, year); return; })
			}
		}
		else
		{
			next.hide();
		}
		return;
	},
	groupEvents:function(events){
		var arGroupedResult = [];
		$.each(events, 
			function(index, value) {
				var arSub = $.grep(arGroupedResult, function(n, i) { return n.item.title.toUpperCase() == value.title.toUpperCase(); });
				var strGroup;
				switch(value.type.toUpperCase())
				{
					case 'EERSTE KLEUTERKLAS':
						strGroup = 'K1';
						break;
					case 'TWEEDE KLEUTERKLAS':
						strGroup = 'K2';
						break;
					case 'DERDE KLEUTERKLAS':
						strGroup = 'K3';
						break;
					case 'EERSTE LEERJAAR':
						strGroup = 'L1';
						break;
					case 'TWEEDE LEERJAAR':
						strGroup = 'L2';
						break;
					case 'TWEEDE GRAAD':
						strGroup = 'L3 + L4';
						break;
					case 'DERDE LEERJAAR':
						strGroup = 'L3 + L4';
						break;
					case 'VIERDE LEERJAAR':
						strGroup = 'L4';
						break;
					case 'DERDE GRAAD':
						strGroup = 'L5 + L6';
						break;
					case 'VIJFDE LEERJAAR':
						strGroup = 'L5';
						break;
					case 'ZESDE LEERJAAR':
						strGroup = 'L6';
						break;
					default:
						strGroup = '';
						break;
				}
				if(arSub.length == 0)
				{
					arGroupedResult.push({ item:value, groups:strGroup });
				}
				else
				{
					arSub[0].groups += (arSub[0].groups!=''&&strGroup!='')?' + ':'' 
					arSub[0].groups += strGroup;
				}
			}
		);
		return arGroupedResult;
	},
	setDayData:function(box, date) {
		var day = date.getDate();
		var month = date.getMonth() + 1;
		var year = date.getFullYear();
		this.clearDayData(box);
		//search events
		var events = $.grep(calendarDays, function(n, i) { return n.day == day && n.month == month && n.year == year ; });
		var detail = '';
		if(events.length > 0)
		{
			var result = '';
			$.each(this.groupEvents(events),
				function(index, value) {
					if(index > 0) { result += '\n'; detail += '\n'; } result += value.item.title; detail += value.item.title; 
					if(value.groups != '')
					{
						detail += ' (' + value.groups + ')';
						result += ' (' + value.groups + ')';
					}
					if(value.item.description != '')
					{
						detail += ' : ' + value.item.description; 
					}
					if(value.item.type != 'Vakantie')
					{
						box.addClass(' Kalender ' + value.item.type.replace(" ", "_"));
					}
					else
					{
						box.addClass(' ' + value.item.type.replace(" ", "_"));
					}
				}
			);
			result = result.replace(/<br\s?\/?>\s?/gi, '\n');
			box.attr('title', result);
			box.click(function () { return calendar.showDayDetail($(this), events); });
		}
		box.html(day);
		if(detail != ''){
			var det = $('<div class=\"dayDetail\"></div>');
			det.html(detail);
			det.appendTo(box);
		}
		box.removeClass('empty');
		return;
	},
	clearDayData:function(box) 
	{
		box.unbind('click');
		box.attr('title', '');
		
		var saturday = box.hasClass('saturday');
		var sunday = box.hasClass('sunday');
		box.removeClass();
		box.addClass('empty');
		if(saturday) { box.addClass('saturday'); }
		if(sunday) { box.addClass('sunday'); }
		box.html('&nbsp;');
		box.parent('.calendar').find('.eventDetail').hide();
		return;
	},
	showDayDetail:function(box, events) {
		var cal = box.parents('.rightmenu .calendar')[0];
		if($(cal).length > 0)
		{
			var detail = $(cal).find('.eventDetail');
			calendar.clearDayDetail(detail);
			if(events.length > 0)
			{
				var result = '<span class="date">' + calendar.dayName(new Date(events[0].year, events[0].month - 1, events[0].day));
				result += ' ' + events[0].day + ' ' + calendar.monthName(events[0].month - 1) + '</span>';
				$.each(this.groupEvents(events), function(index, value) 
					{ 
						if(index > 0) { result += '\n'; } 
						result += value.item.title;
						if(value.groups != '')
						{
							result += ' (' + value.groups + ')';
						}
						if(value.item.description != '')
						{
							result += ' : ' + value.item.description; 
						}
					}
				);
				result = result.replace(/\n|\r/gi, '<br />');
				detail.find('div').html(result);
				detail.show();
			}		
			else
			{
				detail.hide();
			}
		}
		return;
	},
	clearDayDetail:function(detail) 
	{
		detail.find('div').html('');
		detail.hide();
		return;
	}
};


var menu = {
	init:function() {
		var items = $('.header .menu > ul > li');
		items.each(function(index, element) {
			var el = $(element);
			if(el.children('ul').length > 0){
				el.mouseenter(function() { $(this).children('ul').slideDown('fast'); });
				el.mouseleave(function() { $(this).children('ul').slideUp('fast'); });	
			}
		});
	}
};

var scrollbox = {
	init:function() {
		$('.scrollbox').each(function(index, element) {
			scrollbox.startAnimation(element);
		});
		return;
	},
	startAnimation:function(element) {
		var child = $(element).children()[0];
		$(child).css('top', 0);
		var height = $(child).height();
		var vTop = (height - $(element).height()) * -1;
		if(vTop < 0)
		{
			$(child).animate({ top : vTop }, 25000, 'linear', function() { scrollbox.startAnimation(element); });
		}
		return;
	}
};

var imageGallery = {
	init:function() {
		var galleries = $('.rightmenu .galleries');
		if(galleries.length > 0)
		{
			//remove empty galleries
			$.each(galleries.children('.gallery'), 
				function(n,i) { 
					if($(i).children('img').length == 0) { $(i).remove(); } 
				}
			);
		
			galleries.children('.loading').show();
			galleries.children('.gallery:first').fadeIn();
			imageGallery.positionImage(galleries.children('.gallery:first > img')[0]);
			galleries.children('.loading').hide();
			$(document).everyTime(5000, function() { imageGallery.moveToNext(); });
		}
		
		//Details
		var images = $(imageGallery.giveImages());
		if(images.length > 0)
		{
			images.click(function() { imageGallery.openDetail($(this)); });
		}
		return;
	},
	giveImages:function() {
		//'.content .gallery .imageGallery img'
		return '.content img:not(src$=".png")';
	},
	moveToNext:function() {
		var current = $('.rightmenu .galleries .gallery:visible');
		var galleryList = $('.rightmenu .galleries .gallery');
		var currentIndex = galleryList.index(current);
		var next = $(galleryList[currentIndex + 1]);
		if(next.length == 0) { next = $(galleryList[0]); }
		current.fadeOut();
		next.fadeIn();
		imageGallery.positionImage(next.children('img')[0]);
	},
	positionImage:function(image) {
		if(image != null)
		{
			var width = $(image).width();
			var height = $(image).height();
			var parent = $(image).parent();
			if(width > height)
			{
				$(image).width(parent.width());
			}
			else
			{
				$(image).height(parent.height());
			}
			var dif = parent.height() - $(image).height();
			$(image).css('margin-top', dif / 2);
			dif = parent.width() - $(image).width();
			$(image).css('margin-left', dif/2);

			var frame = $('.rightmenu .galleries .frame');
			var link = parent.find('a');
			frame.unbind();
			frame.click(function() { window.location.href = link.attr('href'); });
		}
	},	
	openDetail:function(image) {
		var background = $('#galBackground');
		background.remove();
		$('body').append(background);
		background.show();
		background.unbind();
        background.click(function() { imageGallery.closeDetail(); return; });
		
		var detail = $('#galDetail');
		detail.remove();
		$('body').append(detail);

        detail.css('display', 'block');
        detail.centerScreen();
		detail.show();

        $('#galDetail .closeImage img').click(function() { imageGallery.closeDetail(); return; });

		imageGallery.showDetail(image);
		return;
	},
	closeDetail:function() {
        $('#galDetail').hide();
        $('#galBackground').hide();
        $('#imgDetail img').remove();
		return;
	},
	showDetail:function(image)
	{
		var url = image.attr('src');
		url = url.replace(/_t\./i, '.');
        var objI = new Image();
        objI.onload = function() { imageGallery.imagePreloaded(image, objI); return; };
        objI.src = url;    
		return;
	},
	imagePreloaded:function(objThumbnail, objImage){
      var qw = $(window); 
      var qImg = $(objImage);
      var qFrame = $('#galDetail');
      var qDetail = $('#imgDetail');
      if(qDetail.children('img').length > 0) 
      { 
        qDetail.children('img').fadeOut('slow', function() { $(this).remove(); return; })
      }
      qDetail.show();
      qImg.appendTo(qDetail);

      objImage.style.display = 'none';

      var intHeight = objImage.height;
	  var dblFactorHeight = 1;
	  if(intHeight > qw.height() - 40) 
	  { 
		intHeight = qw.height() - 40; 
		dblFactorHeight = intHeight / objImage.height;
	  }
      var intWidth = objImage.width;
	  var dblFactorWidth = 1;
	  if(intWidth > qw.width() - 40) 
	  { 
		intWidth = qw.width() - 40; 
		dblFactorWidth = intWidth / objImage.width;
	  }
	  if(dblFactorWidth > dblFactorHeight)
	  {
		intHeight = objImage.height * dblFactorHeight;
		intWidth = objImage.width * dblFactorHeight;
	  }
	  else
	  {
		intHeight = objImage.height * dblFactorWidth;
		intWidth = objImage.width * dblFactorWidth;
	  }
      var intTop = qw.scrollTop() + (qw.height() - intHeight)/2;
      var intLeft = qw.scrollLeft() + (qw.width() - intWidth)/2;
      	  
      qFrame.animate({top: intTop, 
                        left: intLeft, 
                        height: intHeight, 
                        width: intWidth},
                       {duration : 100,
                        easing:'linear'}); 

	  qImg.width(intWidth);
	  qImg.height(intHeight);
      qImg.fadeIn('slow');
      imageGallery.addControls(objThumbnail, intHeight);            

      return;
    },
	addControls:function(objThumbnail, intHeight){
      var qimages = $(imageGallery.giveImages());
      var intIndex = qimages.index(objThumbnail) + 1;
	  var qNext = $('#galDetail .nextImage img');
	  var qPrevious = $('#galDetail .previousImage img');
      if(intIndex == qimages.length) { qNext.parent().hide(); }
      else 
      { 
        qNext.parent().show();
		qNext.unbind();
		qNext.click(function() { imageGallery.clickNext(objThumbnail); });
		qNext.parent().css('top', (intHeight - qNext.parent().height()) / 2);
      }
      if(intIndex == 1) { qPrevious.parent().hide(); }
      else 
      { 
        qPrevious.parent().show(); 
		qPrevious.unbind();
		qPrevious.click(function() { imageGallery.clickPrevious(objThumbnail); });
		qPrevious.parent().css('top', (intHeight - qPrevious.parent().height()) / 2);
      }

      return;
    },
    clickPrevious:function(objThumbnail){
      var qimages = $(imageGallery.giveImages());
      var intIndex = qimages.index(objThumbnail);
      if(intIndex > 0){ 
        //imageGallery.showDetail($('.content .gallery .imageGallery img:eq(' + (intIndex - 1) + ')')); 
		imageGallery.showDetail($(imageGallery.giveImages() + ':eq(' + (intIndex - 1) + ')')); 
      }
      return;
    },
    clickNext:function(objThumbnail){
      var qimages = $(imageGallery.giveImages());
      var intIndex = qimages.index(objThumbnail);
      if(intIndex < qimages.length){ 
		imageGallery.showDetail($(imageGallery.giveImages() + ':eq(' + (intIndex + 1) + ')')); 
	  }
      return;
    }
}
$(document).ready(function() 
{
  jQuery.fn.centerScreen = function(loaded) { 
    var obj = this; 
    var w = $(window); 
    if(!loaded) { 
      obj.css('top', w.scrollTop() + w.height()/2 - this.height()/2); 
      obj.css('left', w.scrollLeft() + w.width()/2 - this.width()/2); 
      //w.resize(function() { obj.centerScreen(!loaded); }); 
    } 
    else {
      obj.stop(false, true); 
      obj.animate({top: w.scrollTop() + w.height()/2 - this.height()/2, left: w.scrollLeft() + w.width()/2 - this.width()/2}, 10, 'linear'); 
    } 
  } 
  return;
});



