(function($) {
	$.fn.extend({
		imagePreview: function() {
			$('body').click(function(e) {
				if (!($(e.target).is('#preview') || $(e.target).parents().is('#preview')) && !$(e.target).is('div.answers img') && $('#preview').is(':visible')) {
					$('#preview').fadeOut('fast', function() {
						$(this).remove();
					});
				}
			});

			$(this).each(function() {
				var self = this;
				$(self).click(
					function(e) {
						$('body').append('<div id="preview"><div class="faq-img-popup-close"><a href="javascript:void(0);" onclick="$(\'#preview\').remove();" class="faq-popup-close">venster sluiten</a></div><img src="'+ $(self).attr('src') +'" alt="Image preview" /></div>');
						$('#preview')
							.draggable()
							.css('top', $(window).scrollTop() + 15 + 'px')
							.css('left', Math.round(($(window).width() - $('#preview img').width()) / 2) + 'px')
							.hide().css('visibility', 'visible').fadeIn('fast');
				    }
			    );
			});
		}
	});

	$(document).ready(function() {
		$('table.faq-overview tr a.goto-answer, table.faq-overview td.collapser div').click(function () {
			var answerField = $(this).parents('tr:eq(0)').find('div.answers');
			var collapser = $(this).parents('tr:eq(0)').find('td:eq(0)').find('div');
			if (!answerField.is(':visible')) {
				answerField.show();
				$('img', answerField).each(function() {
					// set the width according to the parent.
					$(this).width($(this).parents('div.answers:first').width() - 50 + 'px');
					// add imagepreview to it
					$(this).attr('title', 'Klik op de afbeelding om deze te vergroten').imagePreview(); //.css('cursor', 'pointer')

					$(this).siblings('.magnify-image')
						.css('width', $(this).width())
						.css('height', $(this).height())
						.attr('title', 'Klik op de afbeelding om deze te vergroten');
				});
				collapser.css('background-position', '0px 12px');
			}
			else {
				answerField.hide();
				collapser.css('background-position', '0 0');
			}
		});

		$('table.faq-overview a.print').click(function() {
			$(this).parents('tr:eq(0)').nextAll('tr').prevAll('tr').removeClass('printable');
			$(this).parents('tr:eq(0)').addClass('printable');

			window.print();
		});

		// set an initial width so the parent width does not get stretched.
		// also remove these attributes.
		$('div.answers img').width('10px').removeAttr('width').removeAttr('height');

		// wrap image inside an magnify div
		$('div.answers img').before('<div class="magnify-image"></div>');
		$('.magnify-image').bind('click', function(e) {
			e.stopPropagation();
			$(this).siblings('img').triggerHandler('click');
		});
		
	});
})(jQuery);
