/*
 * positionFooter
 * plaats de footer onderaan de pagina.
function positionFooter() {
	var windowHeight = $(window).height();
	var documentHeight = $("#header").outerHeight(true) + $("#main").innerHeight();
	
	if( windowHeight > documentHeight ) {
		$("#footer").css({
			position: "absolute",
			bottom: 0,
			width: "100%"
		});
	} else {
		$("#footer").css({
			"position": "relative"
		});
	}
}
*/

/**
 * loadData
 * laad de data 
 * @param element Element waarop geklikt is
 * @param e Element waarop geklikt is
 * @param onSucces Callback functie die aangeroepen wordt na uitvoering van de functie
 */
function loadData(element, e, onSucces) {
	e.preventDefault(); //Gaat niet naar de link :).
	
	$.ajax({
		url      : $(element).attr('href'),
		type     : 'GET',
		dataType : 'json',
		error    : function() {
			alert('020 error!');
		},
		success: function(data) {
			onSucces( data.html );
		}
	});
}

/**
 * openColorbox
 * open een colorbox met flash movie.
 * @param lightbox HTML van de inhoud van de colorbox
 */
function openColorbox(lightbox) {
	$.fn.colorbox({
		html : lightbox,
		opacity: 0.5,
		innerWidth: '970px',
		innerHeight: '535px',
		onComplete: function() {
			styleColorbox();
			
			$(".panorama-list a").live( "click", function(e) {
				loadData( this, e, function(newContent) {
					$(".panorama-lightbox").html(newContent);
					styleColorbox();
				});
			});
		},
		onClosed: function() {
			$(".panorama-list a").die("click");
			$(".panorama-lightbox").remove();
		}
	});
}

/**
 * openGalleryColorbox
 * open een colorbox met gallery daarin.
 * @param lightbox HTML van de inhoud van de colorbox
 */
function openGalleryColorbox(lightbox) {
	$.fn.colorbox({
		html : lightbox,
		opacity: 0.5,
		innerWidth: '970px',
		innerHeight: '585px',
		onComplete: function() {
			styleGalleryColorbox();
			
			$(".gallery-lightbox .gallery-list a").live( "click", function(e) {
				loadData( this, e, function(newContent) {
					$(".gallery-lightbox").html(newContent);
					styleGalleryColorbox();
				});
			});
			
			$(document).delegate("#description-info", "mouseover", function() {
			    if (!$(this).data("tooltip")) {
			        
			    	$(this).tooltip({
			        	bodyHandler: function() {
							$(".description p:last").css("margin-bottom", 0);
					    	return $(".description").html();
					    },
					    showURL: false
			        });
			        
			        $(this).trigger("mouseover");
			    }
			});
		},
		onClosed: function() {
			$(".gallery-lightbox .gallery-list a").die("click");
			$(".gallery-lightbox").remove();
		}
	});
	
}

function styleGalleryColorbox() {
	var textHeight = $(".gallery-item .meta p").innerHeight()
	$(".gallery-item .meta p").css("padding-top", (textHeight/2) );
	
	Cufon.replace('h1');
	Cufon.replace('h2');
}

function styleColorbox() {
	var textHeight = $(".panorama-item .meta p").innerHeight()
	$(".panorama-item .meta p").css("padding-top", (textHeight/2) );
	
	Cufon.replace('h1');
	Cufon.replace('h2');
}

/*
function filterForm() {
	var form = $("form#filters");
	
	$.ajax({
		url      : form.attr("action"),
		type     : form.attr("method"),
		data     : form.serialize(),
		dataType : 'json',
		error    : function() {
			alert('020 error!');
		},
		success: function(data) {
			var singleitem = $(data.html).find(".col.main").html();
			var list = $(data.html).find(".side .agendaitems").html();
			
			$(".col.main").html(singleitem);
			$(".agendaitems").html(list);
			
			// set to false immediately
			$("input[name='nextpage']").val("false");
			
			Cufon.replace( $("h2[class!='no-cufon']") );
			Cufon.replace('#nav_primary li a');
			Cufon.replace('.submenu .nav li a');
			Cufon.replace('.date');
			Cufon.replace('.title');
		}
	});
}
*/

/**
 * showItem
 * laad een item
 * 
 * @param a JQuery object van a-element waar op geklikt is.
 */
function showItem(a) {
	var item = $(a).parents(".agenda_item");
	var href = $(a).attr('href');
	
	if( href.indexOf("#") >= 0 ) {
		var id = $(a).attr('href').split( "#" );
		id = id[1];
	} else {
		var split = $(item).attr("id").split("-");
		var id = split[split.length-1];
	}
	
	$.ajax({
		url      : "/m3ajax/getAgendaItem?id=" + id,
		type     : "GET",
		dataType : 'json',
		error    : function() {
			alert('020 error!');
		},
		success: function(data) {
			var singleitem = $(data.html).find(".single_item.agenda_item");
			
			//Share replace (voor addthis)
			$(".single_item.agenda_item").html( $(singleitem).html() );
			
			addthis.init();
			addthis.toolbox(".addthis_toolbox");
			
			$(singleitem).find('a.twitter-share-button').each(function()
			{
				twttr.widgets.load();
			});
			
			/*
			$(".at300b").each(function() {
				$(this).attr('href', $(a).attr('href'));
			});
			*/
			
			Cufon.replace( $("h2[class!='no-cufon']") );
			Cufon.replace('.single_item.agenda_item .date');
			Cufon.replace('.single_item.agenda_item .title');
		}
	});
	
	currentItem(item);
	
	return id;
}

/**
 * currentItem
 * selecteer het item
 * 
 * @param item JQuery object van het item-element
 */
function currentItem(item) {
	$(".agendaitems .agenda_item").removeClass("current");
	$(item).addClass("current");
	
	var offset = $(item).position().top;
	var ulheight = $(item).parents(".jspPane").height();
	
	if( ulheight - offset > 400 )
		$(".jspPane").css("top", (-1 * offset) + "px");
	else
		$(".jspPane").css("top", (-1 * (ulheight - 400)) + "px");
}

/**
 * resizeList
 * resize functie van de unsigned list, die plaats vindt nadat de li's verandert.
 */
function resizeList() {
	var listHeight = 0;
	
	$(".agendaitems .agenda_item:visible").each(function() {
		listHeight += $(this).height();
	});
	
	if( listHeight > 400 ) {
		listHeight = 400;
		$(".move").show();
	} else {
		$(".move").hide();
	}
	
	$("ul.slider_nav").height(listHeight);
	$(".agendaitems ul.slider_nav").jScrollPane();
}

/**
 * filterGenre
 * functie die gecalld wordt na een change van select
 * 
 * @param genre : String met genre.
 */
function filterGenre( genre ) {
	$(".theater_item").show();
	
	if( genre != "" ) {
		$(".theater_item").hide();
		$(".theater_item." + genre).show();
	}

	if( $(".theater_item:visible:first").length ) {
		showItem( $(".theater_item:visible:first h2 a") );
	}
	
	resizeList();
	
	$("select[name='genre']").val(genre);
}

/**
 * scrollItems
 * Scroll de items in een bepaalde richting
 * 
 * @param dir richting. Mogelijk: "down" en "up"
 */
function scrollItems(dir) {
	var totalHeight = $(".jspPane").height();
	var viewportHeight = $("ul.slider_nav").height();
	var visibleStart = -1 * parseInt( $(".jspPane").css("top") );
	var visibleEnd = visibleStart + viewportHeight;
	
	if( totalHeight <= viewportHeight ) {
		return;
	}
	var newFirstItem = null;
	
	if(dir == "down") {
		$("ul.slider_nav").find(".agenda_item").each(function() {
			var bottom = $(this).position().top + $(this).height();
			
			if( bottom > visibleEnd ) {
				newFirstItem = $(this);
				return false;
			}
		});
	} else if(dir == "up") {
		var maxUp = visibleStart - viewportHeight;
		
		$("ul.slider_nav").find(".agenda_item").each(function() {
			var top = $(this).position().top;
			
			if( top > maxUp ) {
				newFirstItem = $(this);
				return false;
			}
		});
	}
	
	if( newFirstItem !== null ) {
		$(".jspPane").animate(
			{
				top: (-1 * $(newFirstItem).position().top)
			},
			{
				duration: 750,
				easing: "easeInQuart"
			}
		);
	}
}

$(function() {
	$("body").addClass("js-enabled");

	/*
		DROPDOWN MENU
	*/
	$(".nav li a").each(function() {
		var item = $(this).clone();
		$(item).addClass( "hover" );
		$(this).parent('li').prepend( item );
		
		$(item).hide();
	});
	
	$("#nav_primary li ul.nav_subsubmenu").each(function() {
		var maxWidth = $(this).parent('li').outerWidth();
		
		$(this).find("li").each(function() {
			var liWidth = $(this).outerWidth( true );
			
			if( liWidth > maxWidth )
				maxWidth = liWidth;
			
		});
		
		$(this).css({
			position: "absolute",
			"z-index": 999,
			"margin-top": "2px",
			padding: "5px",
			left: 0,
			width: maxWidth
		});
		
		$(this).hide();
	});
	
	$("#nav_primary li").hoverIntent({
		over: function() {
			$(this).addClass("hover");
			$(this).find("ul.nav_subsubmenu").show();
			
			$(this).find("a").hide();
			$(this).find("a.hover").show();
			
			if( $(this).hasClass("current") )
				$(".current-indicator").hide();
		},
		out: function() {			
			$(this).removeClass("hover");
			$(this).find("ul.nav_subsubmenu").hide();
			
			$(this).find("a").show();
			$(this).find("a.hover").hide();
			$(".current-indicator").show();
		},
		interval: 1,
		sensitivity: 1,
		timeout: 0
	});
	
	/*
		HOMEPAGE SLIDER
	*/
    var $tabs = $(".theater.slider").tabs({
    		event: 'mouseover'
	}).tabs("rotate", 5000, true); 
	
	$(".theater.slider li").mouseenter(function(){
		var slideId = $(this).find("a").attr('href');
		
		$tabs.tabs('select', slideId);
    	return false;
	});
	
	/*
		PANORAMA'S
	*/
	$(".panorama a").click(function(e) {
		var data = loadData(this, e, openColorbox);
	});
	
	/*
	 * GALLERY
	 */
	$(".gallery-list li a").click(function(e) {
		var data = loadData(this, e, openGalleryColorbox);
	});
	
	//$(".gallery ul.gallery-list li a").colorbox();
	
	/*
		AGENDA'S THEATER
	*/
	if($(".theateragenda").length) {
		
		var hash = window.location.hash;
		var url = window.location.href.split("/");
		
		//Replace de links in de agenda-items
		$(".theater_item.agenda_item a").not('.addthis_button').each(function() {
			var urlarray = $(this).attr("href").split("/");
			var id = urlarray[urlarray.length-1];
			
			$(this).attr("href", "/theater/theateragenda#" + id ).removeAttr("target");
		});
		
		//Resize de list.
		resizeList();
		
		//Load indien nieuw item.
		if( hash != "" || (!isNaN( url[url.length-1] ) && url[url.length-1] > 0) ) {
			if( hash != "" ) {
				var id = window.location.hash.substring(1, window.location.hash.length);
			} else if( !isNaN( url[url.length-1] ) && url[url.length-1] > 0 ) {
				var id = url[url.length-1];
			}
			
			var item = $("#nav-slide-" + id);
			showItem( $(item).find("h2 a") );
		} else {
			showItem( $(".theater_item:first h2 a") );
		}
		
		//Filters via selector
		$("form#filters").live("change", function() {
			filterGenre( $("select[name='genre']").find("option:selected").val() );
		});
		
		//Filters via click
		$(".genre").live("click",function(e) {
			e.preventDefault();
			
			filterGenre( $(this).find("a").attr("title") );
		})
		
		//Click op agenda item
		$(".theater_item h2").live("click", function(e) {
			if(window.location.pathname == "/theater/theateragenda" || window.location.pathname == "/theater/theateragenda/") {
				e.preventDefault();
				
				var id = showItem( $(this).find("a") );
				window.location.hash = id;
			}
		});
		
		//Click op buttons!
		$(".move.moveUp").live("click",function() {
			scrollItems("up");
		});
		
		$(".move.moveDown").live("click",function() {
			scrollItems("down");
		});
	}
	
	/*
		AGENDA'S MUSEUM
	*/
	if($(".museumagenda").length) {
		//Filters via selector
		$("form#filters").live("change", function() {
			$(this).submit();
		});
		
		$(".agenda_item").click(function() {
			window.location = $(this).find("a").attr('href');
		})
	}
	
	/*
		NIEUWS
	*/	
	$(".archive .nav li.year").click(function() {
		if( $(this).hasClass('open') ) {
			$(this).find("ul").slideToggle();
			$(this).removeClass("open");
		} else {
			$(this).find("ul").slideToggle();
			$(this).addClass("open");
		}
	});
	
	/*
		IMAGE SLIDER
	*/
	if( $(".image-slides").length ) {
		$('.image-slides').cycle({
			timeout: 4000,
			fx:     'scrollLeft',
			pager:  '.image-slides-navigation .image-slides-navigation-wrapper',
	        easing: 'easeInOutQuint',
			speedIn: 1000,
			speedOut: 1000
		});
	}
	
	/*
		EERST CUFONNEN
	*/
	Cufon.replace('h1');
	Cufon.replace( $("h2[class!='no-cufon']") );
	Cufon.replace('#nav_primary li a');
	Cufon.replace('.submenu .nav li a');
	Cufon.replace( $(".date").not('.no-cufon') );
	Cufon.replace('.title');
	Cufon.replace('.archive .parent');
	
	/*
		CURRENT MENU-ITEM
	*/
	if( $("#nav_primary li.current").length ) {
		var currentItem = $("#nav_primary li.current:first");
		
		//disable current background
		currentItem.css("background","none");
		
		var currentIndicator =$("<div class='current-indicator'/>");
		$(currentIndicator).css( "left", (($(currentItem).position().left) - 15) );
		$("#header .wrapper .current-indicator-bar").prepend( $(currentIndicator) );
	}
	
	/*
		CONTACTFORMULIER
	*/
	$("#contactform").validate({
		rules: {
			naam:		"required",
			email:		{
				"required": true,
				"email": true
			}, 
			bericht:	"required"
		},
		messages: {
			naam:		"Het is verplicht om een naam in te vullen",
			email:		"Het is verplicht om een geldig emailadres in te vullen",
			bericht:	"Het is verplicht om een bericht in te vullen"
		},
		errorPlacement: function(error, element) {
			error.appendTo( $(element).parents(".form-row") );
		}
	});
	
	/*
		NIEUWSBRIEFFORMULIER
	*/
	$("#newsletterform").validate({	
		rules: {
			FNAME:		"required",
			LNAME:		"required",
			PLACE:		"required",
			GENDER:		"required",
			EMAIL:		{
				"required": true,
				"email": true
			}
		},
		messages: {
			FNAME:		"Het is verplicht om uw voorletter(s) in te vullen",
			LNAME:		"Het is verplicht om uw achternaam in te vullen",
			PLACE:		"Het is verplicht om uw woonplaats in te vullen",
			GENDER:		"Het is verplicht om uw geslacht te selecteren",
			EMAIL:		"Het is verplicht om een geldig emailadres in te vullen",
		},
		errorPlacement: function(error, element) {
			error.appendTo( $(element).parents(".form-row") );
		}
	});
		
	/*
		Sticky footer
		NU NIET NODIG, BIJ CSS ISSUES ACTIVEREN
		
	positionFooter();
	
	$(window).resize(function() {
		positionFooter();
	});
	
	$(window).scroll(function() {
		positionFooter();
	}); minus3;
	*/
	
});
