$(function(){
	$('.cms-user .user-warning.closeable').attr('title', 'Close notification').click(function(){
		$(this).fadeOut();
	});

	$('.planner-button.active').live('click', function(){
		if (typeof loggedin === 'undefined' || loggedin === false){
			window.location = $(this).attr('href');
		}
		if ( ! $(this).hasClass('active')) return false;

		var button = $('img', this);

		$.getJSON($(this).attr('href'), {}, function(data){
			if (data.success){
				button.attr('src', button.attr('src').replace('myecobuild-add', 'myecobuild-added'))
					.parent().removeClass('active');
	
				var node = $('#flash .items-total'),
					total = parseInt($('#flash .items-total').html());
				
				node.html(total+1);
			}

			$.gritter.add({
				title: 'Success!',
				text:  data.response				
			});
		});

		return false;
	});


	/** some planner functions */
	$('.planner-grid-table').bind('grid-refresh', function(){
		if ( ! $('tbody tr', this).length){
			$(this).nextAll('.user-warning').show();
			$(this).remove();
		}		
	});

	$('body').bind('planner-update', function(){
		// update the counter
		var total = $('.planner-grid-table tr.item').length;
		$('#planner-total').html(total);

		// hide the actual functionality
		if (parseInt(total) === 0){
			$('#planner-functions').hide();
		}
	});

	$('.planner-grid-table .action-delete').click(function(){
		if ( ! confirm('Are you sure you want to delete this item from the planner?')){
			return false;
		}

		var button = $(this);

		var grid = button.parents('.planner-grid-table');

		$.getJSON(button.attr('href'), {}, function(data){
			if (data.success){
				var row = button.parent().parent();

				if ( (! row.next().length || ! row.next().children().length) && row.prev().hasClass('date')){
					row.prev().remove();					
				}

				row.remove();
				grid.trigger('grid-refresh');
				$('body').trigger('planner-update');
			}

			$.gritter.add({
				title: 'message',
				text:  data.response,
				sticky: true
			});
		});

		return false;
	});	
});
