/***************************************************************
*  Copyright notice
*
*  (c) 2011 Netcreators <klaus@netcreators.com>
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
* ncverdictsearch.js
*
* @author Klaus Bitto <klaus@netcreators.com> 
*/

$(document).ready(function() {
	var datepickerOptions = {
		changeMonth: true,
		changeYear: true,
		dateFormat: 'dd-mm-yy',
		dayNames: [ "Zondag", "Maandag", "Dinsdag", "Woensdag", "Donderdag", "Vrijdag", "Zaterdag"],
		dayNamesShort: [ "Zon", "Maan", "Din", "Woe", "Don", "Vrij", "Zat"],
		dayNamesMin: [ "Zo", "Ma", "Di", "Wo", "Do", "Vr", "Za"],
		firstDay: 1,
		monthNames: [ "Januari", "Februari", "Maart", "April", "Mei", "Juni", "Juli", "Augustus", "September", "Oktober", "November", "December"],
		monthNamesShort: [ "Jan", "Feb", "Mrt", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dec"],
		showOtherMonths: true,
		yearRange: '1995:'+(new Date()).getFullYear()
	};
	$('#ncverdictsearch-date-after').datepicker(datepickerOptions);
	$('#ncverdictsearch-date-before').datepicker(datepickerOptions);
	$('#ncverdictsearch-date-exact').datepicker(datepickerOptions);
	$('#ncverdictsearch-searchword1').keyup(showSearchwordFields);
	$('#ncverdictsearch-searchword2').keyup(showSearchwordFields);
	$('#ncverdictsearch-search-methods').accordion({
		autoHeight: false,
		header: 'h3',
		// if 'code' has a non-empty value, start with 'code' method open. Otherwise start with 'normal search'.
		active: $('#ncverdictsearch-code').attr("value") ? 0 : 1,
		change: function(event, ui) {
			var active = ui.newContent.parent().attr('id') == 'ncverdictsearch-selectby-code' ? 0 : 1;
			if(active != 0) {
				$('#ncverdictsearch-code').attr("value","");
				autoShowHideAll();
			}
		}
	});
	$('#ncverdictsearch-show-date-options').change(showDateOptionsFields);
	$('#ncverdictsearch-date-after').change(ensureValidDates);
	$('#ncverdictsearch-date-before').change(ensureValidDates);
	$('#ncverdictsearch-date-exact').change(ensureValidDates);
	$('.ncverdictsearch-keyword').change(showKeywordFields);
	$('#ncverdictsearch-form').submit(showSearchThrobber);

	// click on 'meer' link shows hidden (cropped) part of verdict bodytext.
	$('span[class="ncverdictsearch-search-result-more-link"]').click(function() {
		$(this).next('span[class="ncverdictsearch-search-result-more"]').show();
		$(this).hide();
	});

	autoShowHideAll();

	// Open all documents in a new tab
	$.each(['pdf','doc','docx','xls','xlsx','ppt','pptx','odt','ods','odp','rtf','txt','csv'],
		   function(index, value) { $('a[href$=".'+value+'"]').attr('target', '_blank');
	});

	// submit on ENTER
	$(window).keydown(function(event) {
		// Do not submit uitspraken search form if we are hitting Return in the indexed search form
		if(typeof(document.activeElement !== 'undefined') 
			&& (document.activeElement.id == 'top-searchbox-inputText' || document.activeElement.id == 'top-searchbox-submitButton')) {
			return;
		}
		if(event.which == 13) {
			$('#ncverdictsearch-form').submit();
			event.preventDefault();
		}
	});
	
	$('#ncverdictsearch-form :submit').removeAttr('disabled');
});

function autoShowHideAll() {
	showDateOptionsFields();
	$('#ncverdictsearch-searchword1').keyup(); // call showSearchwordFields() in appropriate context (setting the right "this").
	showKeywordFields();
}

function showDateOptionsFields() {
	if($('#ncverdictsearch-show-date-options').attr('checked'))
		$('#ncverdictsearch-date-options').show();
	else
		$('#ncverdictsearch-date-options').hide();
}

function ensureValidDates() {
	var after = $('#ncverdictsearch-date-after'),
	before = $('#ncverdictsearch-date-before'),
	exact = $('#ncverdictsearch-date-exact');

	if($(this).attr('id') == after.attr('id') || $(this).attr('id') == before.attr('id')) {
		exact.attr('value','');

		var beforeDate = makeDateFromLocalizedStr(before.val()),
		afterDate = makeDateFromLocalizedStr(after.val());

		// everything ok? Break if all fine; break also if invalid dates.
		if(afterDate && beforeDate && afterDate < beforeDate)
			return;

		if($(this).attr('id') == after.attr('id')) {
			before.attr('value','');
			return
		}
		
		if($(this).attr('id') == before.attr('id')) {
			after.attr('value','');
			return
		}
	}
	if($(this).attr('id') == exact.attr('id')) {
		after.attr('value','');
		before.attr('value','');
	}
}

// str in format DD-MM-YYYY
function makeDateFromLocalizedStr(str) {
	var tokens = str.split('-');
	if(tokens.length < 3)
		return null;
	return new Date(tokens[2], tokens[1], tokens[0]);
}

function showKeywordFields() {
	// hide all except for the first empty select field
	var fields = $('.ncverdictsearch-keyword');
	fields.each(function(index, element) {
		if(element.options[element.selectedIndex].value == '0') {
			var container = $(element).parent();
			// hide & reorder, bring to the bottom
			container.addClass('ncverdictsearch-hidden'); // using slideUp/Down here creates too much commotion.
			container.parent().append(container);
		}
	});
	var isFirstEmpty = true;
	fields.each(function(index, element) {
		if(element.options[element.selectedIndex].value != '0')
			return;
		if(!isFirstEmpty)
			return;
		$(element).parent().removeClass('ncverdictsearch-hidden');
		isFirstEmpty = false;
	});
}

function showSearchThrobber() {
  $('#ncverdictsearch-searchThrobber span').fadeIn();
}

var searchwordAutoShow = {
  "ncverdictsearch-searchword1": "#ncverdictsearch-searchword-extrabox1",
  "ncverdictsearch-searchword2": "#ncverdictsearch-searchword-extrabox2"
};

function showSearchwordFields(e) {
	var influencedElement = $(searchwordAutoShow[this.id]);
	var influencedElementInput = $(searchwordAutoShow[this.id]+' input');
	if(this.value.length > 0) {
		influencedElement.show(); // was slideDown(), but SOG does not like animations.
		influencedElementInput.keyup(); // cascade / recursion
	} else {
		influencedElement.hide();
		influencedElementInput.attr('value','');
		influencedElementInput.keyup(); // cascade / recursion
	}
}
