$(function() {
    // there's the gallery and the album
    var $gallery = $('#gallery'), $album = $('#album');
    var $photos = $("input:hidden[name=album_photos]");

    // let the gallery items be draggable
    $('li',$gallery).draggable({
        cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
        revert: 'invalid', // when not dropped, the item will revert back to its initial position
        containment: $('#album-frame').length ? '#album-frame' : 'document', // stick to album-frame if present
        helper: 'clone',
        cursor: 'move'
    });

    // let the album be droppable, accepting the gallery items
    $album.droppable({
        accept: '#gallery > li',
        activeClass: 'ui-state-highlight',
        drop: function(ev, ui) {
            addImage(ui.draggable);
        }
    });

    // let the gallery be droppable as well, accepting items from the album
    $gallery.droppable({
        accept: '#album li',
        activeClass: 'custom-state-active',
        drop: function(ev, ui) {
            removeImage(ui.draggable);
        }
    });

    // image removoval function
    var remove_icon = '<a href="#" title="Remove this image" class="ui-icon ui-icon-minus">Remove image</a>';
    function addImage($item) {

        // populate hidden form field
        var $images = $photos.val().split(',');
        $images.push($item.children('img').attr('name').replace('photo_', ''));
        $photos.val($images.join(','));

        // move effect
        $item.fadeOut(function() {
            var $list = $('ul',$album).length ? $('ul',$album) : $('<ul class="gallery ui-helper-reset"/>').appendTo($album);

            $item.find('a.ui-icon-plus').remove();
            $item.append(remove_icon).appendTo($list).fadeIn(function() {
                $item.animate({
                    width: '48px'
                }).find('img').animate({
                    height: '36px'
                });
            });
        });
    }

    // image remove function
    var add_icon = '<a href="" title="Add this image" class="ui-icon ui-icon-plus">Add image</a>';
    function removeImage($item) {

        // populate hidden form field
        var $photo_id = $item.children('img').attr('name').replace('photo_', '');
        var $images = $photos.val().split(',');
        var $images2 = new Array();
        for(var i=0; i < $images.length; i++) {
            if($images[i] != $photo_id) {
                $images2.push($images[i]);
            }
        }
        $photos.val($images2.join(','));

        // move effect
        $item.fadeOut(function() {
            $item.find('a.ui-icon-minus').remove();
            $item.css('width','96px').append(add_icon).find('img').css('height','72px').end().appendTo($gallery).fadeIn();
        });
    }

    // image preview function, demonstrating the ui.dialog used as a modal window
    function viewLargerImage($link) {
        var src = $link.attr('href');
        var title = $link.siblings('img').attr('alt');

        openLargerImage(src, title);
    }
    
    function openLargerImage(src, title) {
        var $modal = $('img[src$="'+src+'"]');

        if ($modal.length) {
            $modal.dialog('open');
        } else {
            var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />')
            .attr('src',src).appendTo('body');
            setTimeout(function() {
                img.dialog({
                    title: title,
                    width: 400,
                    modal: true
                });
            }, 1);
        }
    }

    // resolve the icons behavior with event delegation
    $('ul.gallery > li').click(function(ev) {
        var $item = $(this);
        var $target = $(ev.target);

        if ($target.is('a.ui-icon-plus')) {
            addImage($item);
        } else if ($target.is('a.ui-icon-zoomin')) {
            viewLargerImage($target);
        } else if ($target.is('a.ui-icon-minus')) {
            removeImage($item);
        }

        return false;
    });

    $(".photo-zoom a").click(function(ev) {
        var src = $(this).attr('href');
        var title = $(this).children('img').attr('alt');

        openLargerImage(src, title);
        return false;
    });
});


