var P = {};

if (typeof console == 'undefined') {
	console = {
		log: function(){},
		debug: function(){}
	};
}

function isEmpty(str) { if (typeof str == 'undefined' || str === null || str === '' || str == 0) { return true; } return false; }


//parseUri 1.2.2
//(c) Steven Levithan <stevenlevithan.com>
//MIT License

function parseUri (str) {
	var	o   = parseUri.options,
		m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
		uri = {},
		i   = 14;

	while (i--) uri[o.key[i]] = m[i] || "";

	uri[o.q.name] = {};
	uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
		if ($1) uri[o.q.name][$1] = $2;
	});

	return uri;
};

parseUri.options = {
	strictMode: false,
	key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
	q:   {
		name:   "queryKey",
		parser: /(?:^|&)([^&=]*)=?([^&]*)/g
	},
	parser: {
		strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
		loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/
	}
};

/**
 * PopupWindow object
 * spawns/handles ye classic popup windows
 *
 * @author AK
 *
 * requires: jQuery 1.2.x, 1.3.x
 */
window.PopupWindow = function(){
	this.width = 500;
	this.height = 500;
	this.$container = $(window);
	this.offsetLeft = 0;
	this.offsetTop = 0;
	this.menubar = true;
	this.location = false;
	this.resizable = true;
	this.scrollbars = true;
	this.status = true;
	this.name = 'popupWindow';
	this.url = '';
};
window.PopupWindow.prototype.prepare = function(){
	var oAnchor = this.anchor;
	if (typeof oAnchor.data('popWinObject') == 'object') {
		var oPopWin = oAnchor.data('popWinObject');
		if (!oPopWin.closed) {
			oPopWin.close();
		}
	}
	var sHref = oAnchor.attr('href');
	if (sHref.indexOf('?') > -1) {
		sHref += '&';
	} else {
		sHref += '?';
	}
	sHref += 'popup=true';
	this.url = sHref;
};
window.PopupWindow.prototype.spawn = function(){
	this.prepare();
	var x = this.$container.width() / 2 - (this.width / 2);
	var y = this.$container.height() / 2 - (this.height / 2);
	
	if (x < 0) { x = 0; }
	if (y < 0) { y = 0; }
	
	if (typeof window.screenX !== 'undefined') {
		x += window.screenX;
		y += window.screenY;
	}
	else if (typeof window.screenLeft !== 'undefined') {
		x += window.screenLeft;
		y += window.screenTop / 2;
	}
	
	this.offsetLeft = x;
	this.offsetTop = y;
	
	var oPopWin = window.open(this.url, this.name, 'width=' + this.width + ',height=' + this.height + ',left=' + this.offsetLeft + ',top=' + this.offsetTop);
	
	if (typeof oPopWin != 'undefined') {
		this.anchor.data('popWinObject', oPopWin);
		return true;
	}
	return false;
};

/**
 * autoSelect, jQuery plugin
 * 
 * Auto-submit forms when select options have changed
 * Smoothens out (almost) behavioural differences between browsers.
 * Inpsired on: http://themaninblue.com/writing/perspective/2004/10/19/
 * 
 * usage: $selection.autoSelect({options})
 * 
 * @author AK | Peppered
 * @version 1.0.1
 */
(function(a){a.fn.autoSelect=function(){return this.each(function(){var b=a(this);b.validKeyChange=true;b.initValue=a(this).val();b.change(function(){if(b.validKeyChange&&(this.value!=b.initValue)){b.initValue=this.value;this.form.submit()}});b.keydown(function(c){if((c.keyCode==13||c.keyCode==9)&&this.value!=b.initValue){b.validKeyChange=true;b.change()}else{if(c.keyCode==27||((c.keyCode==13||c.keyCode==9)&&this.value==b.initValue)){this.value=b.initValue}else{b.validKeyChange=false}}})})}})(jQuery);



P.submenu = {
	programmeFilter: function() {
		
		// auto-submit genre/maand select		
		if ($.fn.autoSelect) {
			var $form = $('#genreForm');
			//console.log($form);
			var $enabled = $form.find('select').autoSelect({debug: false});		
			if ($enabled.length) {
				$form.addClass('autoSelect');
			}
			$form = $('#maandForm');
			$enabled = $form.find('select').autoSelect();
			if ($enabled.length) {
				$form.addClass('autoSelect');
			}
			$form = $('#seizoenForm');
			$enabled = $form.find('select').autoSelect();
			if ($enabled.length) {
				$form.addClass('autoSelect');
			}
		}
		
		// amateur voorstellingen  onclick
		$('#formToonAmateurvoorstellingen input[type="submit"]').hide();
		$("#amateurvoorstellingen").click(function(){ 
			$("#formToonAmateurvoorstellingen").submit();	
			return false;			
		});
	}
};

P.playingSoon = {
	$unit: {},
	$items: {},
	$itemActive: {},
	$itemNext: {},
	$pointer: {},
	interval: null,
		
	init: function() {
		var _this = this;
		this.$unit = $('#playingSoon');
		this.$items = this.$unit.find('li');
		this.$itemActive = this.$items.first();
		this.$pointer =  this.$unit.find('span.pointer');
		
		if (this.$items.length < 2) return;
		
		this.$items.find('.title, .subtitle').ellipsis();
		
		this.$items.find('img')
			.hover(function(e){e.stopPropagation()})
			.not(this.$itemActive.find('img')).fadeTo(0,0);
		
		this.interval = window.setInterval(function(){_this.switchEvent()}, 5000);
		
		this.$items.hoverIntent(function(){
			var _this = P.playingSoon;
			window.clearInterval(_this.interval);
			var index = _this.$items.index(this);
			_this.switchEvent(index);
		},
		function(){
			var _this = P.playingSoon;
			_this.interval = window.setInterval(function(){_this.switchEvent()}, 5000);
		});
		
		this.$unit.removeClass('nojs');
	},	
	switchEvent: function(index) {
		var _this = P.playingSoon,
			last = false;
		;
		
		if (index === undefined) {
			_this.$itemNext = _this.$itemActive.next();
			
			if (!_this.$itemNext.length) {
				_this.$itemNext = _this.$items.first();
				last = true;
			}
		}
		else {
			_this.$itemNext = _this.$items.eq(index);
		}
		
		
		// fadeout active item
		_this.$itemActive.animate({ backgroundColor: '#ECE8F1' }, 1000, function(){
			
			// fadein next item
			_this.$pointer.fadeIn(500);
			
			_this.$itemNext.animate({ backgroundColor: '#EC008C' }, 1000);
			_this.$itemNext.find('.dateTime, .subtitle, .title').animate({ color: '#ffffff' });
			
			_this.$itemActive = _this.$itemNext;
			
		});
		_this.$itemActive.find('.dateTime, .subtitle').animate({ color: '#491D74' });
		_this.$itemActive.find('.title').animate({ color: '#A793B9' });
		
		if (last === true) {
			_this.$pointer.fadeOut(500, function(){
				_this.$pointer.css('top', 25);
			});
		}
		else {
			_this.$pointer.animate({top: _this.$itemNext.position().top + 25 }, 1000);
		}
		
		_this.$itemActive.find('img').fadeTo(1000, 0);
		_this.$itemNext.find('img').fadeTo(1500,1);

	}
};

P.imgBrowser = {
	init: function() {
		var $unit = $('#imgBrowser'),
			$loadingDiv = $('<div class="loading"/>').hide();
		;
		$unit.find('.imageContainer').append($loadingDiv);
		
		$unit.find('.fotoSelectButton').click(function() {
			$loadingDiv.show();
			var $this = $(this);
			var parsed = parseUri($this.attr('href'));
			
			$('#mainImg')
				.load(function(){
					$loadingDiv.hide();
				})
				.attr('src', parsed.queryKey.ffile)
			;

			return false;
		});
	}	
};


/**
 * moreText
 * 
 * used to toggle event description
 * 
 * @param {String} id
 * 
 * @author AK
 */

P.moreText = function(id) {
	var $obj = $('#'+id).hide();
	var $eventTeaserToggle = $('<p id="eventTeaserToggle" />');
	
	var $a = $('<a class="down" href="#' + id + '"><span class="ico"></span><span class="lbl">Lees meer</span></a>').click(function(e){
		$a.fadeOut(200);
		
		// set top-margin to 0 for first child node to prevent collpase jump when ani is finished
		$obj.children(':first-child').addClass('noTopMargin');
		$obj.slideToggle(500, function(){
			if ($obj.is(':visible')) {
				$a.html('<span class="ico"></span><span class="lbl">Verberg</span></a>').removeClass('down').addClass('up').fadeIn(200);
				$.scrollTo($obj, 400, {axis: 'y'});
			}
			else {
				$a.html('<span class="ico"></span><span class="lbl">Lees meer</span>').removeClass('up').addClass('down').fadeIn(200);
				$.scrollTo($('.teaser'), 400, {axis: 'y'});
			}
		});
		e.preventDefault();
		
	});
	
	$obj.after( $eventTeaserToggle.append($a) );
};


//share
P.share = {
	init: function() {
		var popWin = null;
		$('.share .facebook a, .share .twitter a, .share .hyves a').click(function(e) { // add twitter when using official share
			var $this = $(this);
			e.preventDefault();
			
			popWin = new PopupWindow();
			popWin.anchor = $this;
			popWin.width = 550;
			popWin.height = 436;
			if (popWin.spawn()) {
				e.preventDefault();
			}			

		});
	}
};


/**
 * 
 * 
 * 
 */

// variables, die in de template op true worden gezet als de auio/videoplayer direct in beeld moet.
var showvideo = false;
var showaudio = false;

$(function(){
	
	var currentMenuItem, currentSubMenuItem;
	var dropMenuHideTimeout, dropSubMenuHideTimeout, dropSubMenuShowTimeout, holdSubMenuTimeout;
	var hoveredMenuId, hoveredSubMenuId; // the items that are just hovered
	var holdSubMenu = false;
	var item;
	
	/*
	$("#submenu > li").hover(function(){
		$(this).children("a").children("span").toggleClass('menuItemOpen');
	}, function(){
		$(this).children("a").children("span").toggleClass('menuItemOpen');
	});
	*/
	
	// dropmenu
		$("#submenu .dropMenu").hide();
		$("#submenu .dropMenuContainer").hover(function(){
			clearTimeout(dropMenuHideTimeout);
			if (hoveredMenuId && $(this).attr("id") != hoveredMenuId) {
				$('#'+hoveredMenuId).children(".dropMenu").hide();
				$(this).children("a").removeClass('active');
			}
			$(this).children(".dropMenu").show();
			$("#submenu .dropMenuContainer a").removeClass('active');
			$(this).children("a").addClass('active');
							
		}, function(){
			//$("#submenu .dropSubMenu").hide();
			currentMenuItem = $(this);
			hoveredMenuId = currentMenuItem.attr("id");
			dropMenuHideTimeout = setTimeout(function(){
				currentMenuItem.children(".dropMenu").hide();
				//currentMenuItem.children("a").children("span").removeClass('menuItemOpen');
				$("#submenu .dropMenuContainer a").removeClass('active');
				}, 500);
			
		});
	
	// dropsubmenu
		$("#submenu .dropSubMenu").hide();
		$("#submenu .dropSubMenuContainer").hover(function(){
			if (holdSubMenu) {
				// don't show this hovered submenu when another is just opened..
				itemId = $(this).attr("id");
				holdSubMenuTimeout = setTimeout(function(){clearHold(itemId)}, 400);
				return;
			}
	
			clearTimeout(dropSubMenuHideTimeout);
			clearTimeout(dropSubMenuShowTimeout);
			//$("#submenu .dropSubMenu").hide();
			if (hoveredSubMenuId && $(this).attr("id") != hoveredSubMenuId) {
				$('#'+hoveredSubMenuId).children(".dropSubMenu").hide();
				$('#'+hoveredSubMenuId).children("span").children("a").removeClass('active');
			}
			//$(this).children(".dropSubMenu").show();
			currentSubMenuItem = $(this);
			dropSubMenuShowTimeout = setTimeout(function(){showSubMenu(currentSubMenuItem)}, 180);
			//showSubMenu(currentSubMenuItem);
			//alert($(this).attr("id"));
			
		}, function(){
			currentSubMenuItem = $(this);
			hoveredSubMenuId = currentSubMenuItem.attr("id");
			//$(this).children(".dropSubMenu").slideUp();
			dropSubMenuHideTimeout = setTimeout(function(){
				currentSubMenuItem.children(".dropSubMenu").hide();
				currentSubMenuItem.children("span").children("a").removeClass('active');			
				}, 500);
		});
	 
		function showSubMenu(theSubMenu) {
			// show subMenu, don't hide it when user hovers over mainmenu item
			clearTimeout(dropSubMenuShowTimeout);
			$("#submenu .dropSubMenu").hide(); // force all to hide
			$("#submenu .dropSubMenuContainer span a").removeClass('active');	
			theSubMenu.children(".dropSubMenu").show();
			holdSubMenu = true;
			theSubMenu.children("span").children("a").addClass('active');
		}
		function clearHold(hoveredSubMenuId) {
			holdSubMenu=false;
			showSubMenu($('#'+hoveredSubMenuId));
			return;
			// if other than holded submenu...
			//if (hoveredSubMenu != currentSubMenuItem) {
			if (hoveredSubMenuId && hoveredSubMenuId != currentSubMenuItem.attr("id")) {
				currentSubMenuItem.children(".dropSubMenu").hide();
				$('#'+hoveredSubMenuId).children(".dropSubMenu").show();
			}
		}
	
		//togglebutton
			$(".toggleItem").hide();
			$(".toggleButton").click(function(){
				$(".toggleItem").toggle();
				$(this).toggleClass('toggleButtonHide');
			});
		
		// calendar columns
			$("table.calendar tr.weekdays th a").mouseover( function() {
				var iIndex = $(this).parent().parent().children('th').index($(this).parent()[0]);
				$("table.calendar tr td:nth-child(" + (iIndex+1) + ") a").addClass('active');
			 });
			$("table.calendar tr.weekdays th a").mouseout( function() {
				var iIndex = $(this).parent().parent().children('th').index($(this).parent()[0]);
				$("table.calendar tr td:nth-child(" + (iIndex+1) + ") a").removeClass('active');
			 });
			 
		// calendar rows
			$("table.calendar th.week a").mouseover( function() {
				$(this).parents('tr').find('a').addClass('active') });
			$("table.calendar th.week a").mouseout( function() {
				$(this).parents('tr').find('a').removeClass('active') });
		
				
		//styled select
			$('.selectorContainer').hover(
				function(){
					$(this).children('.pullDown').show();
				},
				function(){
					$(this).children('.pullDown').hide();
				});
			
			$(".pullDown span").hover(
				function(){
					$(this).addClass('dropMenuHover');
				},
				function(){
					$(this).removeClass('dropMenuHover');
				}
			)
			
		
		
			
			// initially hide form, except when getvar showReactieForm is in url
			$("#reactieColomn").hide();			
			// show reactieform on click
			$(".buttonPlaatsReactie").click(function(){ 
				$("#reactieColomn").show();	
				return false;			
			});
			
			/**
			 * animationtype: Type of animation 'fade' or 'slide' (Default: 'fade'),
			 * speed: Fadingspeed in milliseconds or keywords (slow, normal or fast)(Default: 'normal'),
			 * timeout: Time between the fades in milliseconds (Default: '2000'),
			 * type: Type of slideshow: 'sequence' or 'random' (Default: 'sequence'),
			 * containerheight: Height of the containing element in any css-height-value (Default: 'auto'),
			 * runningclass: CSS-Class which the container get�s applied (Default: 'innerfade')
			 */
			
			/**
			 * Nieuws lichtkrant
			 */
			$('#lichtkrant').innerfade({
				animationtype: 'slide',
				speed: 1000,
				timeout: 8000,
				type: 'sequence',
				containerheight: '18px;'
			});			
			
			/**
			 * Binnenkort slideshow
			 */
//			$('#binnenkortVoorstellingen').innerfade({
//				speed: 2000,
//				timeout: 5000,
//				type: 'sequence',
//				containerheight: '215px'
//			});

			// default teksten voor zoeken
			sDefaultZoekTxt = 'trefwoord...';
			$("#formZoekenInput").focus(function(){
				if (this.value == sDefaultZoekTxt)
					this.value = '';
			});
			$("#formZoekenInput").blur(function(){
				if (this.value == '')
					this.value = sDefaultZoekTxt;
			});
			
			// default teksten voor nieuwsbriefaanmelden.
			sDefaultEmailTxt = 'Vul hier uw e-mailadres in...';
			$("#formNieuwsbriefAanmeldenEmail").focus(function(){
				if (this.value == sDefaultEmailTxt)
					this.value = '';
			});
			$("#formNieuwsbriefAanmeldenEmail").blur(function(){
				if (this.value == '')
					this.value = sDefaultEmailTxt;
			});

			// print button mag alleen verschijnen als er wel javascript is.
			$(".buttonPrintDezePagina").removeClass("hidden");

			
			function show_video() {
				$(".imageContainer").hide();	
				$(".audioContainer").hide();	
				$("#audioPlayer").html('&nbsp;');	// empty audio container to be sure to stop that clip
				$(".videoContainer").removeClass("hidden");	
				$(".videoContainer").show();
				
				$("#videoPlayer").html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8" width="225" height="225">'
				 + '<param name="movie" value="/flash/Video_player_basic_4x3.swf?myFile=' + video_file + '&amp;playMe=true" />'
				 + '<param name=quality value=high />'
				 + '<param name="wmode" value="transparent" />'
				 + '<param name="bgcolor" value="#ffffff" />'
				 + '<embed src="/flash/Video_player_basic_4x3.swf?myFile=' + video_file + '&amp;playMe=true" background="#FFFFFF" wmode="transparent" quality=high pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="225" height="225"></embed>'
				 + '</object>');
			}
			if (showvideo == true) {
				show_video();
			}

			function show_audio() {
				//$("#imageContainer").hide();	
				$("#videoContainer").hide();	
				$("#videoPlayer").html('&nbsp;');	// empty video container to be sure to stop that movie
				$("#audioContainer").removeClass("hidden");	
				$("#audioContainer").show();	
				$("#audioPlayer").html('<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=8" width="225" height="40">'
				 + '<param name="movie" value="/flash/audioplayer2.swf?myFile=' + audio_file + '&amp;playMe=true" />'
				 + '<param name=quality value=high />'
				 + '<param name="wmode" value="transparent" />'
				 + '<param name="bgcolor" value="#ffffff" />'
				 + '<embed src="/flash/audioplayer2.swf?myFile=' + audio_file + '&amp;playMe=true" background="#FFFFFF" wmode="transparent" quality=high pluginspage="http://www.macromedia.com/shockwave/download/index.cgi?P1_Prod_Version=ShockwaveFlash" type="application/x-shockwave-flash" width="225" height="40"></embed>'
				 + '</object>');
				
				$.scrollTo($('#audioContainer'), 400, {axis: 'y', offset: -10 });
			}
			if (showaudio == true) {
				show_audio();
			}

			// bekijk video button
			$(".buttonBekijkFilmpje").click(function(){ 
				show_video();
				// b sure that video is in focus
				//scrollTo(0,0);
				return false;			
			});

			// beluister audio button
			$("#btnAudioFragment").click(function(){
				show_audio();
				$('#btnAudioFragment').addClass('hidden');
				// b sure that audio is in focus
				$.scrollTo($('#audioContainer'), 400, {axis: 'y'});
				return false;			
			});

			// Sluit audio/video button
			$(".buttonSluitAudioVideo").click(function(){ 
				//$("#imageContainer").show();	
				$("#videoContainer").hide();
				$("#audioContainer").hide();
				$("#videoPlayer").html('&nbsp;');	// empty video container to be sure to stop that movie					
				$("#audioPlayer").html('&nbsp;');	// empty audio container to be sure to stop that clip
				$('#btnAudioFragment').removeClass('hidden');
				$.scrollTo($('#btnAudioFragment'), 400, {axis: 'y'});
				return false;			
			});
			
//			$('#audioContainer .otherItems a').click(function(){
//				audio_file = this.href;
//				show_audio();
//				return false;
//			});
			
			// external anchors
			$("a[rel='external']").click(function(){
				window.open(this.href);
				return false
			});
			
});


(function($) {
	$.fn.ellipsis = function(enableUpdating){
		var s = document.documentElement.style;
		if (!('textOverflow' in s || 'OTextOverflow' in s)) {
			return this.each(function(){
				var el = $(this);
				if(el.css("overflow") == "hidden"){
					var originalText = el.html();
					var w = el.width();
					
					var t = $(this.cloneNode(true)).hide().css({
                        'position': 'absolute',
                        'width': 'auto',
                        'overflow': 'visible',
                        'max-width': 'inherit'
                    });
					el.after(t);
					
					var text = originalText;
					while(text.length > 0 && t.width() > el.width()){
						text = text.substr(0, text.length - 1);
						t.html(text + "...");
					}
					el.html(t.html());
					
					t.remove();
					
					if(enableUpdating == true){
						var oldW = el.width();
						setInterval(function(){
							if(el.width() != oldW){
								oldW = el.width();
								el.html(originalText);
								el.ellipsis();
							}
						}, 200);
					}
				}
			});
		} else return this;
	};
})(jQuery);
