$(function() {
	
	$('ul.navigation li').hover(function() {
		$(this).addClass('hover');
	}, function() {
		$(this).removeClass('hover');
	});
	
	$('#select_all').change(function() {
		var checkboxes = $(this).closest('form').find('input[type="checkbox"]');
		if ($(this).is(':checked')) {
			$.each(checkboxes, function(key, elm) {
				$(elm).attr('checked', true);
			});
		} else {
			$.each(checkboxes, function(key, elm) {
				$(elm).attr('checked', false);
			});
		}
	});
	
	$('.dialog').dialog({
		modal: true,
		width: .75 * $(window).width(),
		beforeClose: function(event, ui) {
			history.back();
			return false;
		}
	});
	
	if ($('.dialog').length > 0) {
		var windowHeight = $(window).height();
		var maxHeight = .75 * windowHeight;
		var margin = (windowHeight - maxHeight) / 3;
		if ($('.dialog').height() > maxHeight) {
			$('.ui-dialog').css('top', margin);
			$('.dialog').height(maxHeight);
		}
	}
	
	$('.datepicker').datepicker();
	$('.datepicker-history').datepicker({maxDate: 0});
	$('.datepicker-future').datepicker({minDate: 0});
	
	/**
	 * Every <a class="ajax"/> will open in a dialog box
	 */
	$('a.ajax').live('click', function() {
		$('body').addClass('loading');
		$dialog = resetDialog();
		$href = $(this).attr('href');
		$title = $(this).attr('title');
		$.get($href, function(response) {
			$('body').removeClass('loading');
			preOpenDialog();
			$dialog.html(response);
			$dialog.dialog({
				title: $title,
				modal: true,
				width: .67 * $(window).width(),
				height: .67 * $(window).height()
			});
			postOpenDialog();			
		});
		return false;
	});
	
	/**
	 * When a form is submitted with ajax, the button pressed in not posted.
	 * Therefore the pressed button's value is stored in a hidden field.
	 */
	$('div#dialog form input[type="submit"]').live('click', function() {
		$name = $(this).attr('name');
		$value = $(this).val();
		$form = $(this).closest('form');
		$hiddenElm = $('<input type="hidden" name="' + $name + '" value="' + $value + '" />');
		$hiddenElm.appendTo($form);
		$form.submit();
		return false;
	});
	
	/**
	 * Every dialog-form will be posted with ajax. The expected return
	 * value is either a json-object, or html (for re-displaying the form).
	 */
	$('div#dialog form').live('submit', function() {
		$('body').addClass('loading');
		$dialog = $('div#dialog');
		$action = $(this).attr('action');
		$.post($action, $(this).serialize(), function(response) {
			if (typeof(response) == 'object') {
				$dialog.dialog('close');
				if (response.reload == true) {
					window.location.reload();
				} else {
					$('body').removeClass('loading');
				}
			} else {
				preOpenDialog(response);
				$dialog.html(response);
				$('body').removeClass('loading');
				postOpenDialog(response);
			}
		});
		return false;
	});
	
	
	$('.dateformat').mask('99-99-9999');
	
	$('ul.sortable').sortable({
		placeholder: 'ui-state-highlight',
		update: function(event, ui) {
			saveState();
		}
	});
	$('ul.sortable').disableSelection();
	
	// simple search
	if ($('div#simple-search input#terms').val() === '') {
		$('div#simple-search input#terms').val('Snel zoeken op naam of relatiecode...');
	}
	$('div#simple-search input#terms').focus(function() {
		$(this).val('');
	});
	$('div#simple-search input#terms').blur(function() {
		if ($(this).val() === '') {
			$(this).val('Snel zoeken op naam of relatiecode...');
		}
	});
	
	$('body.default-module.remark-controller.index-action .remark').toggle(function() {
		var id = $(this).attr('id') + '-text';
		$('#' + id).show('slow');
		
		var cells = $(this).find('td');
		if ($(cells[4]).text().match(/nee/)) {
			// mark as read
			$(cells[4]).text('ja');
			$.post(
				baseUrl + '/remark/mark-as-read',
				{remark: $(this).attr('id').match(/remark-(\d{1,})/)[1]},
				function(response) {
					if (response.unread !== undefined) {
						// correct number of unread messages
						var navItem = $('#content ul.navigation li.active a');
						navItem.text('Opmerkingen (' + response.unread + ')');
					}
				}
			);
		}
	}, function() {
		var id = $(this).attr('id') + '-text';
		$('#' + id).hide('slow');
	});
});

/**
 * Is used for saving the state of a sortable/draggable overview
 * May be overridden for custom logic.
 */
function saveState() {
	return false;
}

function resetDialog() {
	/* create dialog */
	if ($('#dialog').length == 0) {
		$('<div id="dialog"></div>').appendTo('body');
	}
	/* or empty dialog */
	else {
		$('#dialog').html('');
	}
	
	return $('#dialog');
}

/**
 * Is executed before opening a jQuery-dialog.
 * May be overridden for custom logic.
 */
function preOpenDialog() {
}

/**
 * Is executed after opening a jQuery-dialog.
 * May be overridden for custom logic.
 */
function postOpenDialog() {
}

/**
 * Initializes the filter function for a list
 */
function initFilter()
{
	$('#filter').keyup(function() {
		clearTimeout(window.timeoutId);
		window.timeoutId = setTimeout(applyFilter, 200);
	});
	
	$('.selectable.filterable').selectable({
		selected: function(event, ui) {
			$('#dialog form #id').val($(ui.selected).attr('id'));
			$('#dialog form').submit();
			return false;
		}
	});
}

/**
 * Applies the current filter to the list
 */
function applyFilter()
{
	var $filter = $('#filter');
	var $search = $filter.val();
	var $list = $('ul.filterable').first();
	var $items = $list.find('li');
	$.each($items, function($key, $val) {
		$elm = $($val);
		$text = $elm.text();
		if ($text.match(new RegExp($search, 'i'))) {
			$elm.show();
		} else {
			$elm.hide();
		}
	});
}

