/**
 * PhotoBit
 * © Martin Veverka
 */

$().ready(function(){
	if ($('#GalleryController').size())
	{
		$('#slideshow').show();
		if ($('#slideshow > div').size() > 1)
		{
			$('#slideshow').cycle({
				timeout: 8000,
				speed: 500,
				delay: 2000
			});
		}
		$('#showPhotoOptions').click(function(){
			$('.photoOptions').toggle();
			return false;
		});
	}
	if ($('#GalleryAdminController').size() && $('ul.sortable').size())
	{
		$('ul.sortable').each(function(i){
			$(this).sortable({
				handle: 'span',
				update : function(){
					obj = $('ul.sortable:eq('+i+')');
					var url = obj.attr('rel') + '&' + obj.sortable('serialize');
					$.get(url);
				}
			});
		});
	}

	$('#labelList span.photoLabel').each(function(){
		tagInit($(this));
	});
	if (typeof authorList == 'object')
	{
		$('form input[name="authorName"]').autocompleteArray(
			authorList,
			{
				delay: 20,
				matchSubset: 1,
				matchContains: 1,
				cacheLength: 20,
				width: 200,
				autoFill: true,
				maxItemsToShow: 5,
				onItemSelect: function()
				{
					$('form input[name="authorName"]').focus();
				},
				formatItem: function(r)
				{
					return '<div>'+r[0]+'</div>';
				},
				selectOnly: 1
			}
		);
	}
	if (typeof labelList == 'object')
	{
		$('#labelAdd :text').autocompleteArray(
			labelList,
			{
				delay: 20,
				matchSubset: 1,
				matchContains: 1,
				cacheLength: 20,
				width: 200,
				autoFill: true,
				maxItemsToShow: 5,
				onItemSelect: function()
				{
					$('#labelAdd :text').focus();
				},
				formatItem: function(r)
				{
					return '<div>'+r[0]+'</div>';
				},
				selectOnly: 1
			}
		);
	}
	$('#labelAdd').submit(function(){
		objF = $(this);
		if ($(':text', objF).val())
		{
			$.getJSON(
				$(this).attr('action'),
				{ label: $(':text', objF).val() },
				function(data)
				{
					if (data.errorCode == 0)
					{
						$(':text', objF).val('');
						obj = $('#labelList').append(data.labelFormatted);
						tagInit(obj);
					}
				}
			);
		}
	  return false;
	});
});

function tagInit(obj)
{
	$('a.delete', obj).focus(function(){$(this).blur();});
	$('a.delete', obj).click(function(){
		$.getJSON(
			$(this).attr('href'),
			function(data)
			{
			  if (data.errorCode == 0)
				{
					$('#label-' + data.labelId).remove();
				}
			}
		);
		return false;
	});
}
