/**
 * Common functions/objects & page scripts
 * 
 * Also Peppered config (jQuery.ppprd) is defined here 
 * 
 * Requires: jQuery (1.4.x)
 * load: head
 * 
 * @author AK
 */

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; }

var P = {};

;(function($, undefined){
	
//Additional selectors (blatantly borrowed from jQuery UI)
$.extend($.expr[':'], {

	focusable: function(element) {
		var nodeName = element.nodeName.toLowerCase(),
			tabIndex = $.attr(element, 'tabindex');
		return (/input|select|textarea|button|object/.test(nodeName)
			? !element.disabled
			: 'a' == nodeName || 'area' == nodeName
				? element.href || !isNaN(tabIndex)
				: !isNaN(tabIndex))
		// the element and all of its ancestors must be visible
		// the browser may report that the area is hidden
		&& !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length;
	},

	tabbable: function(element) {
		var tabIndex = $.attr(element, 'tabindex');
		return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable');
	}
});


/**
 * various functions and definitions
 *
 */
/**
 * Peppered config
 */
$.ppprd = {
	debug: {
		enabled: true,
		logAlerts: false // alerts for clients that don't have the firebug console (otherwise silent)
	}
};


/**
 * Debug/logging
 * Uses Firebug (window.console) when present
 */
$.log = function(message){
	if (!$.ppprd.debug.enabled) {
		return false;
	}
	if (window.console && window.console.debug) {
		console.debug(message);
	}
	else {
		if ($.ppprd.debug.logAlerts) {
			alert(message);
		}
		else {
			return;
		}
	}
};


/**
 * Image Replace
 * Appends some spans to selection, to aid in IR (css)
 * @author AK|Peppered
 */
$.fn.ImageReplace = function(){
	return this.each(function(){
		$(this).addClass('ir');
		$(this).append('<span class="ir-aid"><span></span></span>');
	});
};


/**
 * 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;
};

/**
 * P object
 */

//nice blockquotes
P.niceBQ = function(selection) {
	var $bq = $(selection);
	$bq.wrap('<div class="bq"></div>');
	$bq.parent().prepend('<span class="lq"><span></span></span>').append('<span class="rq"><span></span></span>');
};

// menu
P.menu = {
	enhance: function() {
		$('#menu a').append('<span class="line-l"/><span class="line-r"/>');
	}
};

//footer
P.footer = {
	ir: function() {
		return false;
		$('#ftr h2')
			.addClass('ir')
			.wrapInner('<span class="txt"/>')
			.append('<span class="img"/>');
	}
};


/**
 * Production stuff
 */

P.production = {};

P.production.teamNCast = {
	
enhance: function(){
	var $items = $('#teamNCast li a'),
		$activeItems = $();
	
	$items.each(function(){
		var $this = $(this),
			$listItem = $this.parent(),
			$name = $this.find('.name').hide(),
			$desc = $this.find('.desc').hide(),
			active = false,
			aTitle = $this.attr('title'),
			fadeIn = function(){
				//console.log('in')
				$activeItems.not($this).find('.desc').fadeOut().end().data('hoverIntent-out', false);
				$listItem.addClass('fade-in');
				$desc.fadeIn('fast', function(){
					$listItem.removeClass('fade-in').addClass('active');
				});
				active = true;
				$activeItems = $activeItems.add($this);
			},
			fadeOut = function(){
				//console.log('out')
				$listItem.addClass('fade-out');
				$desc.fadeOut('fast', function(){
					$listItem.removeClass('fade-out active');
				});
				active = false;
				$this.data('hoverIntent-out', true);
				$activeItems = $activeItems.not($this);
			};		
		
		$this.attr('title', '');
		
		$name.prependTo($desc).show();
		$desc.wrapInner('<span class="wrap"/>').append('<span class="pntr"/>');
		
		$this
			.hoverIntent({
				over: function(){
					fadeIn();
				},
				out: function(){
					fadeOut();
				},
				timeout: 200,
				sensitivity: 8
			})
			.focus(function(){
				fadeIn();
			})
			.blur(function(){
				fadeOut();
			});
		
		// add common hover, to handle hoverIntent timeout (when user goes back to item within the timeout span)
		$this.hover(function(){
			if ($this.data('hoverIntent-out') === false) {
				//console.log('forceIn');
				$activeItems.not($this).find('.desc').fadeOut();
				$desc.fadeIn('fast');
			}
		}, function(){
		});
			
		
	});
	
	$('<img/>')[0].src= '/images/tooltip_pointer.gif'
}

};

P.production.info = {
	init: function(){
		// iframe z-index (YT embed)
		$('#production div.text iframe').each(function(){
			var $this = $(this),
				url = $this.attr('src');
			if (url.indexOf('youtube') > -1) {
				$(this).attr("src", url + ((url.indexOf('?') > -1) ? "&" : "?") + "wmode=transparent");
			}
		});
	}
};

P.production.writings = {
	
	_slide: function($section, direction){
		
	},
	
	init: function(){
		
		var $texts = $(),
			$top = $('#main div.hSocialWrap')
		;
		
		$('#writings > div').each(function(i){
			var $section = $(this),
				$h = $section.children('h2:eq(0)'),
				$text = $section.children('div.text'),
				$a = $('<a href="#" role="button">openen/sluiten</a>'),
				spaceHold = false // prevent continuous toggling while spacebar pressed
			;			
			$texts = $texts.add($text);
						
			if (i != 0) {
				$text.hide();
				$section.addClass('closed');
			}
			
			
			$a
				.click(function(e){
					e.preventDefault();
					$text.slideToggle(function(){
						if ($text.is(':visible')) {
							$section.removeClass('closed');
						}
						else {
							$section.addClass('closed');
						}
					});
					$texts.not($text).slideUp(function(){
						$(this).parent().addClass('closed');
					});
					
					if ($(window).scrollTop() > $top.offset().top) {
						$.scrollTo($top, 500, {axis: 'y'});
					}
				})
				.keydown(function(e){
					if (e.which == 32) { // space
						if (!spaceHold) {
							$a.click();
						}
						spaceHold = true;
						e.preventDefault();
					}
				})
				.keyup(function(e){
					if (e.which == 32) { // space
						spaceHold = false;
						e.preventDefault();
					}
				})
				.append('<span class="toggle"></span>')
				.appendTo($h)
			;

			
		});
		
		$('#writings').addClass('enh');		
		
	}
}

P.production.lightboxCombo = function($a, prodId, part) {
	var $cbox = $('#colorbox'),
		href = $a.attr('href'),
		fragment = $.url(href).attr('fragment');
	;
	
	$cbox.addClass('prodcontent').attr({'role': 'dialog', 'aria-labelledby': 'cboxTitle'});
	$.colorbox({
		iframe: true,
		innerWidth: 630,
		innerHeight: 520,
		opacity: 0.6,
		href: href.replace('#'+fragment, '') + (href.indexOf('?') > -1 ? '&' : '?') + 'modal=true' + (!isEmpty(fragment) ? '#'+fragment : ''),
		title: P.production.lightboxCombo.genMenu(prodId, part),
		onOpen: function(a){
		},
		onLoad:function(){
			//console.log($cbox);
			$cbox.attr('tabIndex', -1).focus();
			$('#cboxClose').attr({'role': 'button', 'tabIndex': 0});
		},
		onComplete:function(){
			$('#cboxLoadingOverlay, #cboxLoadingGraphic').show();
			var $iframe = $('#colorbox iframe').attr('tabIndex', -1).focus();
			$iframe.load(function() {
				$('#cboxLoadingOverlay, #cboxLoadingGraphic').hide();
				
				// Keep focus inside dialog
				// Code blatantly borrowed from jQuery UI
				var $iframe_contents = $iframe.contents(),
					tabbables_dialog = $(':tabbable', $cbox),
					tabbables_iframe = $(':tabbable', $iframe_contents),
					first = tabbables_iframe.filter(':first') || tabbables_dialog.filter(':first'),
					last = tabbables_dialog.filter(':last');
				
				$iframe_contents.find("body").attr('tabIndex', -1).focus();	// setting focus to $iframe (see above) doesn't cut it in IE
				$cbox.add($iframe_contents).bind('keydown.dialog', function(event) {
					if (event.keyCode !== 9) { // tab
						return;
					}					
		            if (event.target === last[0] && !event.shiftKey) {
		            	first.focus();		               
		                return false;
		            } else if (event.target === first[0] && event.shiftKey) {
		                last.focus();
		                return false;
		            }
				});
				
			});
		}
	});	
};

P.production.lightboxCombo.genMenu = function(prodId, activeItem) {
	var $ul = $('<ul class="menu" />'),
	$li, $a;
	
	var menu = ['speellijst', 'reacties', 'recensies'],
		menuLabels = ['speellijst', 'reacties', 'in \'t nieuws'];
	for (var i=0, l=menu.length; i<l; i++) {
		$li = $('<li/>');
		$a = $('<a href="/'+menu[i]+'/'+prodId+'/">'+menuLabels[i]+ '<span class="line-l"></span><span class="line-r"></span></a>')
			.click(function(e){
				var $this = $(this);
				$.colorbox({
					iframe: true,
					innerWidth: 630,
					innerHeight: 520,
					opacity: 0.6,
					href: $this.attr('href')+'?modal=true',
					title: P.production.lightboxCombo.genMenu(prodId, $this.text()),
					onComplete:function(){
						$('#cboxLoadingOverlay, #cboxLoadingGraphic').show();
						var $iframe = $('#colorbox iframe');
						$iframe.load(function(){
							$('#cboxLoadingOverlay, #cboxLoadingGraphic').hide();
						});
					}
				});
				e.preventDefault();
			})
			.appendTo($li)
		;
		$li.appendTo($ul);
		if (menu[i] == activeItem) {
			$li.addClass('active')
		}
	}
	
	return $('<div class="menu" />').append($ul);
};

P.production.showingDates = {
		
	initLB: function(prodId) {
		$('#showingDates p.more a, #featured #showingDates h3 a').click(function(e) {
			var $this = $(this);
			P.production.lightboxCombo($this, prodId, 'speellijst');
			e.preventDefault();
		});
	},
	
	initLBinDev: function(prodId) {
		$('#inDevelopment a.showingDates').click(function(e) {
			var $this = $(this);
			P.production.lightboxCombo($this, prodId, 'speellijst');
			e.preventDefault();
		});
	},
	
	enhanceList: function() {
		$('ul.showingDates li').hover(
			function(){
				$(this)
					.addClass('hover')
					.prev()
					.addClass('hover-prev')
				;
			},
			function(){
				$(this)
					.removeClass('hover')
					.prev()
					.removeClass('hover-prev')
				;
			}
		)
		.click(function(){
			var $a = $(this).find('.status a');
			if ($a.length) {
				$a.click();
			}
		})
		;
	}
	
};

P.production.reactions = {
	init: function(prodId) {
		$('#block-reactions p.more a, #block-reactions ul a').click(function(e) {
			var $this = $(this);
			P.production.lightboxCombo($this, prodId, 'reacties');
			e.preventDefault();
		});
	}
};

P.production.reaction_form = {
	
	init: function() {
		// toggle btn & close when appropriate
		var $cont = $('#leaveReaction'),
			$h = $cont.children('h2'),
			$form = $('#reactionForm'),
			$report, $backlink
		;
		
		$cont.addClass('enh');
		
		if ($cont.hasClass('success')) {
			$form.hide();
			$report = $cont.find('.report');
			$backlink = $report.find('a.backlink');
			$backlink.click(function(e){
				if ($('body').hasClass('modal')) {
					parent.$.colorbox.close();					
					e.preventDefault();
				}
			});
		}
		
		if ($.url().param('newreaction') === undefined && !$.url().param('submitted')) {
			$form.hide();
			$cont.addClass('closed');
		}
		
		$h.click(function(){
			$form.slideToggle(function(){
				if ($form.is(":visible")) {
					$cont.removeClass('closed');
				}
				else {
					$cont.addClass('closed');
				}
			});
		});
		
		// textareaCount
		$('#formReaction-reaction').textareaCount({
			maxCharacterSize: 1024,
			displayFormat: '#input / #max',
			originalStyle: '',
			warningStyle: 'warning',
			warningNumber: 80
		});		
		
	}
	
};

P.production.recensions = {
	
	init: function(prodId) {
		$('#block-recensions ul a, #block-recensions.YT a.img, #block-recensions.YT p.more a').click(function(e) {
			var $this = $(this);
			P.production.lightboxCombo($this, prodId, 'recensies');
			e.preventDefault();
		});
	},
	
	// ytAutoplay = autoplays an item that's specifically opened (hash is used)
	ytAutoplay: function(id){
		if (parseInt($.url().param('r')) > 0) {
			var $iframe = $('#recension-' + $.url().param('r') +' iframe'),
				url = $iframe.attr('src');
			;
			$iframe.attr("src", url + ((url.indexOf('?') > -1) ? "&" : "?") + "autoplay=1");
		}
	}
	
};


P.production.gallery = {
	init: function() {
		var $gallery = $('#gallery ul'),
			$items = $gallery.children(),
			h = $gallery.height(),
			expanded = false;
		
		if ($items.length > 4) {
			$gallery.height(56);
			var $a = $('<a href="#" class="more">Meer foto\'s&hellip;</a>').click(function(e) {
				$a.fadeOut(200);
				if (expanded) {
					expanded = false;
					$gallery.animate({ height: 56 }, function(){ $a.html('Meer foto\'s&hellip;').fadeIn(200); });
				}
				else {
					expanded = true;
					$gallery.animate({ height: h }, function(){ $a.text('Verbergen').fadeIn(200); });
				}
				e.preventDefault();
			})
				.insertAfter($gallery)
				.wrap('<p class="more"></p>')
			;
	
		}
		
		$('#gallery li a').colorbox({
			slideshow: false,
			transition: "elastic",
			speed: 475,
			initialWidth: 200,
			initialHeight: 100,
			scalePhotos: true,
			maxWidth: '90%',
			maxHeight: '90%',
			opacity: 0.6,	
			onOpen: function() {
				var $cbox = $('#colorbox');
				$cbox
					.removeClass('prodcontent')
				;
			},
			onComplete: function() {
				$('#cboxTitle').wrapInner('<div class="wrap"/>');
				$('#cboxPrevious').wrapInner('<div class="wrap"></div>');
				$('#cboxNext').wrapInner('<div class="wrap"/>');
			}
		});
	}
};


P.production.pressGallery = {
	init: function() {
		var $gallery = $('#pressImageGallery ul');
				
		$('#pressImageGallery li a').colorbox({
			slideshow: false,
			transition: "elastic",
			speed: 475,
			initialWidth: 200,
			initialHeight: 100,
			scalePhotos: true,
			maxWidth: '90%',
			maxHeight: '90%',
			opacity: 0.6,
			onOpen: function() {
				var $cbox = $('#colorbox');
				$cbox
					.removeClass('prodcontent')
				;
				//console.log($cbox)
				
			},
			onComplete: function() {
				$('#cboxTitle').wrapInner('<div class="wrap"/>');
				$('#cboxPrevious').wrapInner('<div class="wrap"></div>');
				$('#cboxNext').wrapInner('<div class="wrap"/>');
			},
			title: function(){
				var $this = $(this);
				return $this.attr('title') + ' / <a href="' + $this.data('origfile') + '" target="_blank">download</a>';
			}
		});
	}
};


P.production.mediaSlide = function(config) {
	var flashConfig = {};
	
	flashConfig = $.extend(true, {
		file: '/flash/' + config.swfFile,
		id: config.id,
		width: 460,
		height: 330,
		version: '9.0.0',
		expressInstallSwfurl: null,
		flashvars: {
			mediaID: config.mediaID,
			slideTime: 5,
			fadeTime: 0.5,
			navHighlight: 'f9714d'
		},
		params: {
			wmode: 'transparent',
			bgscolor: '#ff0000'
		},
		attributes: {},
		callbackFn: function(e){
			if (e.success) {
				$('#slide').addClass('swfobject');		
			}
			// wait a bit before undoing fixed height (replacement is not perse finished)
			//window.setTimeout(function(){ $cont.height('auto') }, 200);
		}
	}, flashConfig);	
	
	swfobject.embedSWF(flashConfig.file, flashConfig.id, flashConfig.width, flashConfig.height, flashConfig.version, flashConfig.expressInstallSwfurl, flashConfig.flashvars, flashConfig.params, flashConfig.attributes, flashConfig.callbackFn);
};

P.production.archiveYearsDropdown = {
	init: function(){
		var $form = $('#formArchiveYears'),
			$select = $('#formArchiveYears-year');
		
		$form.find('input[type="submit"]').hide();
		
		$select.selectmenu({
			style:'popup',
			width: 105,
			menuWidth: 105, 
			change: function(){
				$form.submit();
			}
		});
	}
};

P.production.formProductionSelect = {
	init: function(){
		var $form = $('#formProductionSelect'),
			$select = $('#formProductionSelect-production').addClass('enh');
		
		$form.find('input[type="submit"]').hide();
		
		$select.selectmenu({
			style:'popup',
			change: function(){
				$form.submit();
			}
		});
	}
};

// 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();
			}
		});
	}
};

/**
 * moreText
 * 
 * used to toggle event description
 * 
 * @param {String} id
 * 
 * @author AK
 */

P.moreText = function(id) {
	var $obj = $('#'+id).hide(),
		$eventTeaserToggle = $('<p id="eventTeaserToggle" />'),
		spaceHold = false, // prevent continuous toggling while spacebar pressed		
		$a = $('<a class="more" role="button" href="#' + id + '">Lees verder</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.text('Verberg').fadeIn(200);
						//$.scrollTo($obj, 400, {axis: 'y'});
					}
					else {
						$a.text('Lees verder').fadeIn(200);
						//$.scrollTo($('.teaser'), 400, {axis: 'y'});
					}
				});
				$.scrollTo($('.teaser'), 400, {axis: 'y'});
				e.preventDefault();
				
			})
			.keydown(function(e){
				if (e.which == 32) { // space
					if (!spaceHold) {
						$a.click();
					}
					spaceHold = true;
					e.preventDefault();
				}
			})
			.keyup(function(e){
				if (e.which == 32) { // space
					spaceHold = false;
					e.preventDefault();
				}
			})
	;
	
	$obj.after( $eventTeaserToggle.append($a) );
};


/**
 * DOM ready stuff
 */
$(function(){

	// body js/jquery is enabled class
	$('body').removeClass('nojs').addClass('jsfx');
	
	// refresh queue (prevent timeout)
	if (typeof Xajax != 'undefined') 
		window.setInterval("xajax_UpdateActivity()", 270000);
	
	/**
	 * cross browser stuff
	 */

	// ie6 workarounds for unsupported css
	if ($.browser.msie && parseFloat($.browser.version) < 7) {
		$("body").addClass("IE6");
		$("acronym[title]").addClass('hasTitle'); /* note: ie6 doesn't support abbr element */
	}
	
	
	/**
	 * Anchors
	 */
		
	/**
	 * external (rel="external") and
	 * popup (rel="popup") handling
	 */
	var oPopWin = null;
	$("a[rel='external']").click(function(){
		window.open(this.href);
		return false
	});
	$("a[rel='popup']").click(function(e){
		popWin = new PopupWindow();
		popWin.anchor = $(this);
		popWin.width = 500;
		popWin.height = 500;
		if (popWin.spawn()) {
			e.preventDefault();
		}
	});
	
});
	
	
})(jQuery);

