$(document).ready(function(){
	$("#idp-login-form input[name='name']").parent().sdu_overlabel('Gebruikersnaam');
	$("#idp-login-form input[name='pass']").parent().sdu_overlabel('Wachtwoord');
	
	/**
	 * Main menu tab hovers
	 */
	$('ul.ap-main-menu li').hover(
		function() {
			if (!$(this).hasClass('active')) {
				$(this).addClass('active');
				$(this).addClass('hover');
			}
		},
		function () {
			if ($(this).hasClass('hover')) {
				$(this).removeClass('active');
				$(this).removeClass('hover');	
			}
		}
	);
	
	$('#scws-group-all').click(function(){
		$('.scws-search-collections').removeAttr("checked");
	});
	
	$('.scws-search-collections').click(function(){
		$('#scws-group-mixed').attr("checked", "checked");
	});
	
	/**
	 * Make the default search box autocomplete compatible
	 */
	$('#block-faceted_search_ui-1_keyword input[name=\'keywords\']')
		.addClass('scws-search-text-clean autocomplete')
		.attr('autocomplete', 'off')
		.wrap('<div class="autocomplete-wrapper"></div>')
		.after('<div class="autocomplete-results"></div>')
		.wrap('<div class="sdu-search-text-wrapper"></div>');
	
	/**
	 * Automatically set up autocompleters.
	 */
	$('.autocomplete').sdu_search_autocomplete();
	
	/**
	 * Add interaction to selection checkboxes.
	 */
	$('.scws-search-selection-checkboxes').sdu_search_selection_checkboxes();
	
	/**
	 * Add interaction to vocabulary lists.
	 */
	$('.scws-search-vocabulary-list').sdu_search_vocabulary_list();
	
	/**
	 * Make sure the "alle/selectie uit" buttons work for steekwoorden in advanced search
	 */
	$('.ext-search-pane-steekwoorden').sdu_search_selection_checkboxes();
	
	/**
	 * Do the same for the steekwoorden selection in the advanced search profile
	 */
	$('#sdu-content-alerts-profile-form #edit-tids-wrapper').sdu_search_selection_checkboxes();
	
	/**
	 * When a search is performed on a wenr field, select only the wenr content type
	 */
	$('.ext-search-pane-wenr input').change(function () {
		$('.sdu-search-selection-types input:checkbox:checked').attr('checked', '');
		$('#type-wenr').attr('checked', 'checked').triggerHandler('change');
	});
	
	/**
	 * Synchronize input fields.
	 */
	$(".scws-ext-search-form input[name='text']").sdu_search_sync_fields();
	$(".scws-ext-search-form input[name='textTitel']").sdu_search_sync_fields();
	$(".scws-ext-search-form input[name='toDate']").sdu_search_sync_fields();
	$(".scws-ext-search-form input[name='fromDate']").sdu_search_sync_fields();
	
	/**
	 * When a search is performed on a jurisprudentie field, select only the jurt content type
	 */
	$('.ext-search-pane-jurisprudentie input').change(function () {
		$('.sdu-search-selection-types input:checkbox:checked').attr('checked', '');
		$('#type-jurt').attr('checked', 'checked').triggerHandler('change');
	});
	
	/**
	 * Popups for extra terms in the faceted search
	 */
	$(".faceted-search-facet li.last a[href *= '/zoeken/facet/']").sdu_search_more_link();
	
	/**
	 * Table of contents for wenr content
	 */
	$('ul.toc').sdu_collapsible_toc();
	
	$('h3.artikel-kop').append('<a href="#top" class="back-to-top">terug naar boven</a>');
	
	/**
	 * Bookmark a node
	 * @base sdu_dossier
	 */
	$('#sdu-dossier-bookmark').unbind('click').click(function(){
		var link = $(this).attr('href');
		var element = $(this);
		$.getJSON(link, function(data){
			if (data.status == 'BOOKMARK_ADDED') {
				$('#sdu-dossier-toolbar').replaceWith(data.content);
			}
		});
		return false;
	});
	
	/**
	 * Remove node from bookmarks 
	 * @base sdu_dossier
	 */
	$('#sdu-dossier-remove-bookmark').unbind('click').click(function(){
		var link = $(this).attr('href');
		var element = $(this);
		$.getJSON(link, function(data){
			if (data.status == 'BOOKMARK_REMOVED') {
				$('#sdu-dossier-toolbar').replaceWith(data.content);
			}
		});
		return false;
	});
	
	/**
	 * Basic confirm dialoge
	 */
	$('.confirm').unbind('click').click(function(){
		if (confirm($(this).attr('title'))) {
			return true;
		} else {
			return false;
		}
	});
	
	/**
	 * Allow folding & unfolding of the advanced search sections
	 */
	$('.ext-search-pane-header a').click(function (e) {
		e.preventDefault();
		
		var header = $(this).parent();
		var content = header.next('div').eq(0);
		
		if (content.is(':visible')) {
			$('.ext-search-active', header)
				.removeClass('ext-search-active')
				.addClass('ext-search-inactive');
			content.slideUp();
		} else {
			$('.ext-search-inactive', header)
				.removeClass('ext-search-inactive')
				.addClass('ext-search-active');
			content.slideDown();
		}
	});
	
	/**
	 * Set up datepickers.
	 */
	if ($.datepicker) {
		$(".datepicker").datepicker({
			showOn: 'button',
			buttonImage: '/sites/all/themes/aanbestedingsproces/images/icon-calender.png',
			buttonImageOnly: true,
			dateFormat: 'dd-mm-yy',
			changeMonth: true,
			changeYear: true,
			showButtonPanel: true,
			yearRange: '1970:' + ((new Date()).getFullYear() + 1)
		},$.datepicker.regional['nl']);
	}
	
	/**
	 * Catch save search clicks and handle them through AJAX.
	 */
	$('a.sdu-content-alerts-save-search').click(function (e) {
		e.preventDefault();
		var link = $(this);
		var status = $("<div>").addClass('sdu-content-alerts-save-search-status').insertBefore(link);
		var url = link.attr('href');
		link.remove();
		status.text('Bezig met opslaan...');
		$.get(url, function () {
			status.text('Uw zoekopdracht is opgeslagen.');
			setTimeout(function () {
				status.fadeOut('slow');
			}, 6000);
		});
	});
	
	/**
	 * Catch clear saved search clicks and handle them through AJAX.
	 */
	$('.sdu-content-alerts-clear-search a').click(function (e) {
		e.preventDefault();
		var link = $(this);
		var url = link.attr('href');
		var li = link.closest('li');
		li.empty();
		
		var status = $("<div>").addClass('sdu-content-alerts-clear-search-status').appendTo(li);
		status.text('Bezig met beëindigen...');
		$.get(url, function () {
			status.text('Deze zoekopdracht is beëindigd.');
			setTimeout(function () {
				li.fadeOut('slow');
			}, 6000);
		});
	});
	
	/**
	 * Make sure the nieuwsbrief form can't be sent without checking the box etc.
	 */
	$('form.nieuwsbrief').submit(function (e) {
		var frm = $(this);
		var listCheckbox = frm.find('#list');
		var problems = [];
		if (!listCheckbox.is(':checked')) {
			problems.push('Kruis alstublieft het vakje "' + listCheckbox.parent().text().replace(/^\s+/, '').replace(/\s+$/, '') + '" aan.');
		}
		if (!frm.find("input[name='email']").val()) {
			problems.push('Vul een e-mailadres in.');
		}
		
		if (problems.length > 0) {
			e.preventDefault();
			var div = $('<div>').addClass('messages error').html('<p>Het formulier kan niet worden verzonden:</p>').insertAfter('h2.page-title');
			var ul = $('<ul>').appendTo(div);
			for (var i = 0; i < problems.length; i++) {
				$('<li>').text(problems[i]).appendTo(ul);
			}
		}
	});
});

/**
 * Removes the autocomplete div and uses the selected
 * value as input value in the quick search form
 * 
 * @param obj DomElement
 * @return void
 */
function autocomplete(obj) 
{
	var target = $(obj).closest('.autocomplete-wrapper').find('input.autocomplete');
	$(target).attr('value',$(obj).html());
	$('.sdu-search-autocomplete').remove();
}

/**
 * Provides animation for the quick search search options
 * panes
 * 
 * @param string section
 * @param obj DomElement
 * @return void
 */
function toggleSearchPane(section)
{
	if ($('.btn-arrow-pane').hasClass('ext-search-active')) {
		$('.btn-arrow-pane').removeClass('ext-search-active');
		$('.btn-arrow-pane').addClass('ext-search-inactive');
	}
	
	$('.ext-search-pane').slideUp('slow');
	$('.ext-search-pane-'+ section).slideDown();
	$('.btn-arrow-'+ section).removeClass('ext-search-inactive');
	$('.btn-arrow-'+ section).addClass('ext-search-active');
	
	return false;
}


/**
 * Sdu-specific autocomplete plugin
 */
$.fn.sdu_search_autocomplete = function () {
	var timer;
	
	/**
	 * Hide all autocomplete boxes right now.
	 */
	function hideAutocompleteResults()
	{
		$('.sdu-search-autocomplete').remove();
		clearTimeout(timer);
		timer = null;
	}
	
	/**
	 * Starts a one second timer which at the end will remove the
	 * search results container
	 * @param int timeout
	 */
	function hideResults(timeout) 
	{
		timer = setTimeout(hideAutocompleteResults, timeout);
	}
	
	/**
	 * Wait another {timeout} MS before hiding the results.
	 * @param int timeout
	 */
	function delayHideResults(timeout)
	{
		if (timer) {
			clearTimeout(timer);
		}
		hideResults(timeout);
	}
	
	$('body').unbind('click.sdu_search_autocomplete').bind('click.sdu_search_autocomplete', function () {
		hideAutocompleteResults();
	});
	
	$(this).unbind('keyup.sdu_search_autocomplete').each(function () {
		var element = $(this);
		
		var loadTimeoutMS = 500;
		var loadTimeout;
		var loadBusy = false;
		
		var currentValue = '';
		
		/**
		 * Activate or deactivate the loader image.
		 * @param bool loading
		 */
		function setLoading(loading)
		{
			var loadingClass = 'scws-search-text-loading';
			var cleanClass = 'scws-search-text-clean';
			if (loading) {
				element.removeClass(cleanClass).addClass(loadingClass);
			} else {
				element.removeClass(loadingClass).addClass(cleanClass);
			}
		}
		
		/**
		 * Apply the selected suggestion.
		 */
		function applySuggestion()
		{
			var suggestion = $('.sdu-search-autocomplete a.autocomplete-word-active');
			if (suggestion.length > 0) {
				currentValue = suggestion.text();
				element.val(currentValue);
				hideAutocompleteResults();
				return true;
			}
			return false;
		}
		
		/**
		 * Activate a specific suggestion.
		 * @param element suggestion
		 */
		function activateSuggestion(suggestion)
		{
			$('.sdu-search-autocomplete a.autocomplete-word-active')
				.removeClass('autocomplete-word-active');
			$(suggestion).addClass('autocomplete-word-active');
		}
		
		function firstSuggestion()
		{
			activateSuggestion($('.sdu-search-autocomplete a.autocomplete-word:first'));
		}
		
		function nextSuggestion()
		{
			var current = $('.sdu-search-autocomplete a.autocomplete-word-active');
			if (current.length == 0) {
				firstSuggestion();
			} else {
				activateSuggestion(current.parent().next().find('a.autocomplete-word'));
			}
		}
		
		function previousSuggestion()
		{
			var current = $('.sdu-search-autocomplete a.autocomplete-word-active');
			if (current.length == 0) {
				firstSuggestion();
			} else {
				activateSuggestion(current.parent().prev().find('a.autocomplete-word'));
			}
		}
		
		/**
		 * Update the list of suggestions.
		 */
		function updateSuggestions(value)
		{
			if (value == currentValue) {
				return;
			}
			currentValue = value;
			
	    	/** Load results, but delayed */
	    	if (loadTimeout) {
	    		clearTimeout(loadTimeout);
	    	}
	    	/** Load results */
	    	loadTimeout = setTimeout(function () {
	    		if (loadBusy) {
	    			return;
	    		}
	    		loadBusy = true;
	    		setLoading(true);
		    	$.get("/sdu/search/autocomplete?text="+ value, function(data) {
	    			setLoading(false);
		    		hideAutocompleteResults();
		    		
		    		$(element)
		    			.closest('div.autocomplete-wrapper')
		    			.children('div.autocomplete-results')
		    			.after(data);
		    		
		    		$('.sdu-search-autocomplete a.autocomplete-word').mousemove(function () {
		    			// select an item when the mouse hovers over it
		    			activateSuggestion(this);
		    		}).click(function (e) {
		    			// activate it when clicked
		    			applySuggestion();
		    			e.preventDefault();
		    		});
		    		
		    		// auto-hide results after 3 seconds
		    		hideResults(3000);
		    	
		    		/**
		    		 * Attaches mouseover and mousout event to the just created anchors,
		    		 * this will remove the search results when the user moves the mouse away
		    		 * from the anchors and resets the timer when they return. 
		    		 */
		    		$('.sdu-search-autocomplete').mousemove(function(){
		    			delayHideResults(3000);
		    		}).click(function (e) {
		    			e.stopPropagation();
		    		});
		    		
		    		loadBusy = false;
		    	});
	    	}, loadTimeoutMS);
		}
		
		element.bind('keyup.sdu_search_autocomplete', function (e) {
			var value = element.val();
			if (typeof value == 'string' && value.length > 2) {
				var keyCode = (e.keyCode ? e.keyCode : e.which);
				
				if (keyCode == 27) {
					/** Hide upon pressing escape */
			    	hideAutocompleteResults();
			    } else if (keyCode == 32) {
			    	/** Apply upon pressing space */
			    	applySuggestion();
			    } else if (keyCode == 38) {
			    	/** Move up */
			    	previousSuggestion();
		    		delayHideResults(3000);
			    } else if (keyCode == 40) {
			    	/** Move down */
			    	nextSuggestion();
		    		delayHideResults(3000);
			    } else {
			    	updateSuggestions(value);
			    }
			}
		});
	});
};

/**
 * Add interaction to selection checkboxes. This is used mainly in the advanced search.
 */
$.fn.sdu_search_selection_checkboxes = function () {
	$(this).each(function () {
		var element = $(this);
		
		var check = function (el, check) {
			el.each(function () { this.checked = check; });
		}
		
		check(element.find('.scws-group-mixed'), false);
		check(element.find('.scws-group-all'), true);
		
		function activateSelectionRadioButton() {
			check(element.find('.scws-group-all'), false);
			check(element.find('.scws-group-mixed'), true);
		}
		
		if (element.find('input:checkbox:checked').not('.scws-group-boolean-and').length > 0) {
			activateSelectionRadioButton();
		} else {
			// no items selected? then this is no boolean AND search
			check(element.find('.scws-group-boolean-and'), false);
		}
		element.find('input:checkbox').click(function () {
			activateSelectionRadioButton();
		});
		element.find('.scws-group-all').click(function () {
			check(element.find('input:checkbox').not('.scws-group-boolean-and'), false);
		});
	});
};

/**
 * Add interaction to a vocabulary list like the one used for "steekwoorden" in the advanced search.
 */
$.fn.sdu_search_vocabulary_list = function () {
	$(this).each(function () {
		var element = $(this);
		
		element.find('.scws-search-vocabulary-fold-unfold a').click(function (e) {
			e.preventDefault();
			e.stopPropagation();
			
			var link = $(this);
			
			var subListDiv = link.closest('div').next();
			if (subListDiv.is(':visible')) {
				subListDiv.slideUp();
				link.text('meer');
			} else {
				subListDiv.slideDown();
				link.text('verberg');
			}
		});
	});
}

/**
 * Make the "meer" links in the faceted search use a popup.
 */
$.fn.sdu_search_more_link = function () {
	$('body').unbind('click.sdu_search_more_link').bind('click.sdu_search_more_link', function (e) {
		if ($(e.target).closest('.sdu-search-popup, a').length == 0) {
			$('.sdu-search-popup').remove();
		}
	});
	
	$(this).filter('a').click(function (e) {
		$('.sdu-search-popup').remove();
		
		e.preventDefault();
		var link = $(this);
		var loader = $('<div>')
			.addClass('sdu-search-popup sdu-search-popup-loading')
			.text('Bezig met laden...')
			.insertAfter(link);
		
		$.get(link.attr('href'), function (data) {
			var facet = $('<div>').html(data).find('table.faceted-search');
			loader.removeClass('sdu-search-popup-loading').html('').append(facet);
		}, 'html');
	});
};

/**
 * Apply a vanilla overlabel effect to a form field wrapper.
 * @param string label
 */
$.fn.sdu_overlabel = function (label) {
	var input = $(this).find('input');
	if (input.val() == label) {
		// remove remembered values from old, inferior solutions
		input.val('');
	}
	var label = $('<div>').addClass('overlabel').text(label).hide().prependTo(this);
	
	function tryShowLabel() {
		if (input.val() == '') {
			label.show();
		}
	}
	tryShowLabel();
	
	input.focus(function () {
		label.hide();
	}).blur(function () {
		tryShowLabel();
	});
	
	$(this).click(function () {
		input.focus();
	});
};

/**
 * Make a table of contents UL collapsible through tiny buttons.
 */
$.fn.sdu_collapsible_toc = function () {
	var toc = $(this);
	if (toc.is('.toc-collapsible')) {
		return toc;
	}
	toc.closest('fieldset').addClass('has-toc');
	toc.addClass('toc-collapsible');
	toc.find('> li:has(ul.toc)').addClass('toc-parent').prepend('<span class="toc-button"></span>');
	toc.find('> li > span.toc-button').click(function () {
		var li = $(this).parent();
		var subUl = li.find('> ul');
		if (li.is('.toc-parent-expanded')) {
			li.removeClass('toc-parent-expanded');
			subUl.slideUp('slow');
		} else {
			li.addClass('toc-parent-expanded');
			subUl.slideDown('slow');
		}
	});
	return toc;
};

/**
 * Synchronize input fields, so their value is always the same (after the onchange event).
 */
$.fn.sdu_search_sync_fields = function () {
	var allFields = $(this);
	allFields.change(function () {
		allFields.not(this).val($(this).val());
	});
};
