/*
 *
 */




$(window).bind('load', function() {
	// make images in the gallery draggable
	$('div.imagebox img').addClass('img_content').draggable({
		helper: 'clone',
		zIndex: 1000
	});
	$('div.trashed img').addClass('img_trash').draggable({
		helper: 'clone',
		zIndex: 1000
     });	

	// make the trash box droppable, accepting images from the content section only
	$('#trash div').droppable({
		accept: '.img_content',
		activeClass: 'active',
		drop: function(ev, ui) {
			var $that = $(this);
			ui.draggable.parent().fadeOut('slow', function() {
				ui.draggable
					.hide()
					.appendTo($that)
					.fadeIn('slow')
					.animate({
						width: '66px',
						height: '50px'
					})
					.removeClass('img_content')
					.addClass('img_trash');
				$(this).remove();
				new ajaxSaveDrop(ui.draggable.attr('id'),'add');
			});
		}
	});

	
	// make the gallery droppable as well, accepting images from the trash only
	$('div.gallery').droppable({
		accept: '.img_trash',
		activeClass: 'active',
		drop: function(ev, ui) {
			var $that = $(this);
			ui.draggable.fadeOut('slow', function() {
				var $item = createGalleryItem(this).appendTo($that);
				$(this)
					.removeClass('img_trash')
					.addClass('img_content')
					.css({ width: '144px', height: '108px' })
					.show();
				$item.fadeIn('slow');
			});
			new ajaxSaveDrop(ui.draggable.attr('id'),'remove');
		}
	});

	// handle the trash icon behavior
	$('a.tb_trash').livequery('click', function() {
		var $this = $(this);
		var $img = $this.parent().siblings('img');
		var $item = $this.parents('li');

		$item.fadeOut('slow', function() {
			$img
				.hide()
				.appendTo('#trash div')
				.fadeIn('slow')
				.animate({
					width: '66px',
					height: '50px'
				})
				.removeClass('img_content')
				.addClass('img_trash');
			$(this).remove();
		});

		return false;
	});

	// handle the magnify button
	$('a.tb_supersize').livequery('click', function() {
		$('<img width="576">')
			.attr('src', $(this).attr('href'))
			.appendTo('#body_wrap')
			.displayBox();
		return false;
	});
});

function createGalleryItem(img) {
	var title = img.getAttribute('alt');
	var href = img.getAttribute('src').replace(/t_/, '');

	var $item = $('<div class="imagebox"><p>'+title+'</p><div class="sizediv"><a href="'+href+'" title="See me supersized" class="tb_supersize"></a></div>').hide();
	$item.prepend($(img));

	return $item;
}
