jQuery(function(){
    pripre_draggable(jQuery('#pripre-book div.pripre-post-item'));
    pripre_droppable(jQuery('#pripre-book div.pripre-drop'));
    pripre_droppable(jQuery('#pripre-book'));
});

function pripre_draggable(e) {
    e.draggable({
        revert:true,
        zIndex:100
    });
}

function pripre_droppable(e) {
    e.droppable({
        hoverClass: "pripre-hover",
        drop: pripre_drop
    });
}

function pripre_update() {
    list = jQuery("#pripre-book");
    
    book_id = jQuery("#pripre_book_id").get(0).value;
    
    bind = 'left';
    if (jQuery('#pripre_bind_right').is(':checked')) {
    	bind = 'right';
    }
    size = jQuery("#pripre_size").get(0).value;
    css = jQuery("#pripre_css").get(0).value;
    epubmeta = jQuery("#pripre_epubmeta").get(0).value;
    etemplate = jQuery("#pripre_etemplate").get(0).value;
    
    ids = list.find('span.pripre-id');
    param = '';
    for (i = 0; i < ids.length; ++i) {
        if (i > 0) {
            param += ',';
        }
        param += jQuery(ids.get(i)).text();
    }
    jQuery.post(pripre_base+"/actions/update-book.php",
        {"book_id": book_id,
    	"bind": bind,
    	"size": size,
    	"css": css,
    	"epubmeta": epubmeta,
    	"etemplate": etemplate,
    	"ids": param});
}

function pripre_reset(item) {
    item.css('top', '0').css('left', '0').css('z-index', '0');
}

function pripre_drop(e, ui) {
    item = ui.draggable;
    pripre_reset(item);
   
    target = jQuery(this);
    if (target.attr('id') == 'pripre-book') {
        return;
    }
    else {
        targetItem = target.parent();
        if (target.hasClass('pripre-after')) {
            item.insertAfter(targetItem.get(0));
        }
        else if (target.hasClass('pripre-before')) {
            item.insertBefore(targetItem.get(0));
        }
    }
    
    pripre_draggable(item);
    pripre_droppable(item.find('div.pripre-drop'));
    
    pripre_update();
}
