(function() {
	$.portlet_shoppinglist = {
		create: function(label, callback) {
			callback = callback || function(){};
			$.ajax({url: '/shoppinglist/create/' + encodeURIComponent(label),
					data: {},
					dataType: 'json', 
					error: function(req, errorType) {
						callback();
					},
					success: function(json) {
						if (typeof json == 'number') {
							document.location.href = '/shoppinglist/view/' + json;
						} else {
							if (json.message) {
								$('#shoppinglist-creator-error').text(json.message).show();
							} else {
								$('#shoppinglist-creator-error').hide();
							}
							
							$.portlet_shoppinglist.update(json);
						}
					}
				}
			);
		},
		
		update: function(json) {
			$('#portlet-shoppinglist-count').text(json.container_count);
		}
	};
	
	$.attachUpdater(function() {
		$('#shoppinglist-creator').bind('submit.update', function(event) {
			event.preventDefault();
			event.stopPropagation();
			var label = $('#shoppinglist-creator-label');
			if ($.trim(label.val()) == '') {
				label.focus();
				return;
			}
			
			$.portlet_shoppinglist.create(label.val());
		});

		$('.shoppinglist-button-import').bind('click.update', function(event) {
			event.preventDefault();
			event.stopPropagation();
			$('#shoppinglist-import-popup').popup();
		});
	});
	
	$(window).load(function() {
		if ($('#shoppinglist-import-popup-error').length && $('#shoppinglist-import-popup-error').css('display') != 'none') {
			$('#shoppinglist-import-popup').popup();
		}
	});
	
})();
