// Global stickerbook variables are stored here.
var stickerbook = {
    id: null,
    dirty: false,
    zIndex: 0,
    nextZ: function () {
	       return stickerbook.zIndex++;
    }
}

$(document).ready(function() {

/* DRAG N DROP FUNCTIONALITY */

    // Helper function executed whenever icons are moved.
    // It marks a change in the page and makes the most recently moved icon
    // topmost.
    function updateState () {
	stickerbook.dirty = true;
	$(this).css('zIndex', stickerbook.nextZ());
    }

    // Make icons draggable.
    $('img.icon').not('img.fixed').draggable({
	helper: 'clone',
	revert: 'invalid', // This prevents dropping any old where.
        stop: updateState
    });

    // Make photo a drop target for icons.
    $('div.photo').droppable({
	drop:
	    function (e, ui) {
		// Only clone and append on the first drop.
		if ($(ui.helper).find('img.icon').hasClass('dropped'))
		    return;
		var clone = $(ui.helper).clone().removeAttr('id');
		$('div.photo').append(clone);
		$('div.photo img.icon').not('img.fixed').addClass('dropped').resizable({aspectRatio:1}).parent().draggable({revert: 'invalid', stop:updateState});
	    }
    });

    // Make the icon container a drop target for icons.
    // (Icons dragged back to their source are deleted)
    $('div.iconscontainer').droppable({
	drop:
	    function(e,ui) {
		if ($(ui.draggable).hasClass('icon'))
		    return;
		$(ui.draggable).fadeOut();
	    }
    });
});


/* POSITION REPORTING */
// Build an array of Objects with details on stickers sizes and placements.
function sticker_stats () {
    var stickers = new Array();
    $('img.icon.dropped').each(function () {
				   var offset = $(this).offset();
				   // Safari workaround
				   if (offset.top == 'auto' || offset.left == 'auto')
				       offset = $(this).parent().offset();
				   var stats = new Object();
				   stats = {
				       filename : $(this).attr('src'),
				       offset : offset,
				       ratio : $(this).width(),
				       zIndex: $(this).css('zIndex'),
				       rotation: 0
				   };
				   stickers.push(stats);
			       });
    return (stickers);
}

function stickers_save (url) {
    var stats = sticker_stats();
    if (stats.length && stickerbook.id != null) {
	/* .toJSON can't seem to build a proper nested array for us so we
	   need to roll the elements together ourselves. */
	for (i in stats) {
	    stats[i] = '"' + i + '": ' + $.toJSON(stats[i]);
	}
	var json = '{' + stats.join(', ') + '}';
	$.post(stickerbook.url,
	       {id: stickerbook.id,
		stickers: json},
	       function () {
		   stickerbook.dirty = false;
		   if (url != '')
		       document.location = url;

	       }
	);
    } else {
        if (url != '')
	    document.location = url;
    }
    return false;
}
