(function($)
{
	var validate_add_functions = new Array();
	var validate_update_functions = new Array();
	var initialize_functions = new Array();
	var destroy_functions = new Array();

	jQuery.add_validation_new = function(func)
	{
		validate_add_functions.push(func);
	};
	
	jQuery.add_validation_update = function(func)
	{
		validate_update_functions.push(func);
	};
	
	jQuery.add_initialize = function(func)
	{
		initialize_functions.push(func);
		func.apply(document);
	};
	
	jQuery.add_destroy = function(func)
	{
		destroy_functions.push(func);
	};

	$(document).ready(function()
	{
	    $(this).initialize();
	    
	    
	    // MENU
	    
	    $("#nav > li.active").animate({ marginLeft: "14px" }, 500);
	    $("#nav a").not(".active").click(function()
	    {
	        if ($(this).parents("li.active").length == 0)
	            $("#nav > li.active").animate({ marginLeft: "0px" }, 500);
	    });
	    
	    
	    // INFO BOX
	
	    $('.info_box .info_link_show > a, .info_box .info_link_hide > a').live('click', function()
	    {
	    	var box = $(this).closest('.info_box');
	    	$('.info_link_show', box).toggle();
	    	$('.info_link_hide', box).toggle();
	    	$('.info_text', box).slideToggle(500);
	        return false;
	    });
	
	
		// TABS
	
		$('.tabs .tab-links a').live('click', function()
		{
			var tabs = $(this).closest('.tabs');
			
			$('.tab-links a.active', tabs).removeClass('active');
			$(this).addClass('active');
			
			$('.tab-visible', tabs).removeClass('tab-visible').addClass('tab-hidden');
			$('#' + $(this).attr('rel'), tabs).removeClass('tab-hidden').addClass('tab-visible').select();
			
			return false;
		});
		$('.tabs .tab-links a').live('hover',
		function()
		{
			if (!$(this).hasClass('active'))
				$(this).addClass('hover');
		},
		function()
		{
			$(this).removeClass('hover');
		});
		
		
		// LIST NAVIGATION
		
		$('.item_list_navigation .prev_button, .item_list_navigation .next_button').live(
			'click', $.ajaxutils.ajax_link_click);
		
		
		// AJAX
		
		$('.link_button:not(.no_ajax)').live('click', $.ajaxutils.ajax_link_click);
		
		
		// FORM DIALOGS
		
		if ($.dialogutils)
	    {
	    	$.dialogutils.texts.confirm = 'Weet je zeker dat je';
	    	$.dialogutils.texts.confirm_twice = 'Weet je heel zeker dat je';
	    	$.dialogutils.texts.yes_button = 'Ja';
	    	$.dialogutils.texts.cancel_button = 'Annuleer';
	    	$.dialogutils.texts.confirm_button = 'Opslaan';
		
			$('.delete_button').live('click', function()
			{
				var name = $('.item_name input:not(input[type="hidden"])', $(this).closest('tr')).val();
				$.dialogutils.confirm_twice_dialog('Verwijderen', "'"+name+"' wilt verwijderen",
					function (result, link) {
						if (result) $(link).ajax_link_click();
					}, this);
				return false;
			});
			
			$('.add_button').live('click', function()
			{
				for (var i in validate_add_functions)
				{
					if (!validate_add_functions[i].apply(this))
						return false;
				}
			
				var name = $('.item_name input:not(input[type="hidden"]), ' +
					'input.item_name:not(input[type="hidden"])', $(this).closest('form')).val();
				$.dialogutils.confirm_dialog('Toevoegen', "'"+name+"' wilt toevoegen",
					function (result, link) {
						if (result)
						{
							if ($(link).hasClass('no_ajax'))
								$(link).closest('form').submit();
							else
								$(link).ajax_form_submit();
						}
					}, this);
				return false;
			});
			
			$('.update_button').live('click', function()
			{
				if (!$(this).closest('form').hasClass('no_validate'))
				{
					for (var i in validate_update_functions)
					{
						if (!validate_update_functions[i].apply(this))
							return false;
					}
				}
				
				$.dialogutils.confirm_dialog('Wijzigen', "de wijzigingen op wilt slaan",
					function (result, link) {
						if (result)
						{
							if ($(link).hasClass('no_ajax'))
								$(link).closest('form').submit();
							else
								$(link).ajax_form_submit();
						}
					}, this);
				return false;
			});
		}
		
		
		// PICTURE LIST
		
		$('.picture_list .item_list_navigation a').live('click', function()
		{
			if ($(this).hasClass('busy'))
				return false;
			
			$('.picture_list .item_list_navigation a', nav).addClass('busy');
			
			var list = $(this).closest('.picture_list');
			var nav = $(this).closest('.item_list_navigation');
	
			var currPage = parseInt($('.nav_info .nav_current_page', nav).text());
			var maxPage = parseInt($('.nav_info .nav_max_page', nav).text());
			var nextPage = $(this).hasClass('gallery_prev_button') ? currPage - 1 : currPage + 1;
			
			if (currPage == 1 || nextPage == 1)
				$('.nav_link_prev', nav).toggleClass('hide');
			if (currPage == maxPage || nextPage == maxPage)
				$('.nav_link_next', nav).toggleClass('hide');
			
			$(list).css('height', $(list).height() + 'px');
			$('.album_table_' + currPage, list).fadeOut(400,
		    function()
		    {
		        $('.album_table_' + nextPage, list).fadeIn(400,
		        function()
		        {
		            $('a', nav).removeClass('busy');
					$(list).css('height', '');
		        });
		    });
			
			$('.nav_info .nav_current_page', nav).text(nextPage);
			return false;
		});
		
		
		// INPUT VALIDATION
		
		if ($.validation)
		{
			$.validation.texts.error_dialog_title = 'Foutieve gegevens';
			$.validation.texts.error_dialog_msg = 'Niet all gegevens zijn goed ingevoerd. Verbeter alsjeblieft de fouten.';
		}
		
		
		// CKEDITOR
		
		if ($.fn.ckeditor)
		{
			CKEDITOR.on('dialogDefinition', function(ev)
			{
				var dialogName = ev.data.name;
				var dialogDefinition = ev.data.definition;
		 
				if (dialogName == 'link') {
					dialogDefinition.removeContents('advanced');
				}
		 
				if (dialogName == 'image') {
					dialogDefinition.removeContents('advanced');
				}
			});
			
			CKEDITOR.on('instanceReady', function(e) {
				e.editor.on('key', function(e2) {
					var textarea = $(e2.editor.element.$);
					if (textarea.hasClass('input_validation')) {
						setTimeout(function() {
							textarea.click();
						}, 500);
					}
				});
				e.editor.on('blur', function(e2) {
					var textarea = $(e2.editor.element.$);
					if (textarea.hasClass('input_validation')) {
						textarea.click();
					}
				});
			});
			
			$.add_destroy(function() {
				$('.input_textarea:not(.no_html), textarea.wysiwyg', this).each(function() {
					var editor = $(this).ckeditorGet();
					if (editor) {
						editor.destroy();
					}
				});
			});
		}
	});
	
	$.fn.initialize = function()
	{
		return this.each(function()
		{
			$('a.external[href], a.external_img[href]', this).attr('target', '_blank');
    
    		$('a.fancybox_ajax_link', this).each(function() {
				$(this).attr('href', $(this).attr('href') + '/ajax');
			});
    		
    		$('a.fancybox_link, a.fancybox_ajax_link', this).each(function() {
    			$(this).fancybox({
    				transitionIn: 'elastic',
    				transitionOut: 'elastic',
    				overlayShow: true,
    				autoDimensions: $(this).hasClass('fancybox_autodimensions'),
    				autoScale: !$(this).hasClass('fancybox_noscale')
    			});
    		});

		    $('.picture_gallery', this).each(function()
			{
				var gallery = this;
				var max_page = parseInt($('.nav_info .nav_max_page', gallery).text());

				$('a.picture_gallery_link', this).fancybox({
					transitionIn: 'elastic',
					transitionOut: 'elastic',
					overlayShow: true,
					onStart: function(array, index) {
						var table = $(array[index]).closest('.album_table');
						var new_table = $('.album_table', gallery).index(table) + 1;
						var current_table = parseInt($('.nav_current_page', gallery).text());
						
						if (current_table != new_table)
						{
							$('.album_table_'+current_table, gallery).hide();
							$('.album_table_'+new_table, gallery).show();
							$('.nav_current_page', gallery).text(new_table);
							
							$('.nav_link_prev', gallery).toggleClass('hide', new_table == 1);
							$('.nav_link_next', gallery).toggleClass('hide', new_table == max_page);
						}
					},
					onComplete: function(array, index)
					{
						if ($(array[index]).hasClass('flowplayer'))
						{
							var href = $(array[index]).attr('rel');
							$('#fancybox-inner .flowplayer').flowplayer({ src: '/flash/flowplayer-3.1.5.swf', wmode: 'opaque' }, {
								clip: {
									autoPlay: true,
									bufferLength: 10,
									scaling: 'fit',
									url: href
								},
								canvas: {
									backgroundColor: '#27241D'
								},
								plugins: {
									controls: {
										url: '/flash/flowplayer.controls-3.1.5.swf',
										backgroundColor: '#27241D'
									}
								}
							});
						}
					}
				});
			});
			
			$('.info_box', this).each(function()
			{
				if ($(this).hasClass('show_directly'))
				{
					$('.info_text', this).css('border-top', 'none');
					$('.info_link_hide', this).show();
				}
				else
				{
					$('.info_text', this).hide().css('border-top', 'none');
					$('.info_link_show', this).show();
				}
			});
			
			$('.picture_list').each(function()
			{
				$('table', this).not(':first').hide();
				$('.item_list_navigation').show();
			});
			
			if ($.fn.sortable)
			{
				$('.drag_lists .drag_list_entries', this).sortable({
					cursor: 'move',
					cancel: 'img, input',
					placeholder: 'placeholder drag_list_entry',
					opacity: 0.8,
					appendTo: 'body'
				});
				
				$('.drag_lists .left .drag_list_entries', this).sortable(
				'option', 'connectWith', '.drag_lists .right .drag_list_entries');
				$('.drag_lists .right .drag_list_entries', this).sortable(
					'option', 'connectWith', '.drag_lists .left .drag_list_entries');
			}
			
			if ($.mask)
			{
				$('.input_date', this).mask('?99/99/9999');
			    $('.input_time', this).mask('?99:99');
			    $('.input_postcode', this).mask('?9999 aa');
			    $('.input_phone', this).mask('?9999999999');
			}
		    
		    if ($.fn.ckeditor)
			{
				$('.input_textarea:not(.no_html), textarea.wysiwyg', this).ckeditor(function() {
					if ($(this.element.$).attr('readonly')) {
						this.readOnly(true);
					}
				}, {
					skin: 'v2',
					language: 'nl',
					enterMode: CKEDITOR.ENTER_BR,
					shiftEnterMode: CKEDITOR.ENTER_P,
					resize_enabled: false,
					toolbar: [
					    ['Source'],
					    ['Cut','Copy','Paste','PasteText','PasteFromWord'],
					    ['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
					    ['Bold','Italic','Underline','-','Subscript','Superscript'],
					    ['NumberedList','BulletedList','-','Outdent','Indent'],
					    ['JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock'],
					    ['Link','Unlink','Anchor','Image']
					],
					toolbarCanCollapse: false,
					scayt_autoStartup: false,
					disableNativeSpellChecker: false
				});
			}
		    
		    for (var i in initialize_functions)
		    	initialize_functions[i].apply(this);
		});
	};
	
	$.fn.destroy = function()
	{
		return this.each(function()
		{
			for (var i in destroy_functions)
				destroy_functions[i].apply(this);
		});
	};
	
})(jQuery);
