// JavaScript Document
jQuery(hookupCarouselEditor);

function hookupCarouselEditor() {
    jQuery('#edit_carousel ul.banner_select').sortable({
        containment: '#edit_carousel div',
        items: 'li:gt(0)',
        zIndex: 30000,
        update: updateCarouselItem
    });
    jQuery('#edit_carousel ul.banner_select.unused').sortable('option', 'connectWith', '#edit_carousel ul.banner_select.active');
    jQuery('#edit_carousel ul.banner_select.active').sortable('option', 'connectWith', '#edit_carousel ul.banner_select.unused');
}

function updateCarouselItem(event, ui) {
    // IE6 doesn't show dropped items without some nudging...
    ui.item.effect("highlight", { color: '#F5F5F5' }, 1);

    if (jQuery('#edit_carousel ul.banner_select.active img').length > 5) {
        jQuery('#banner_count_error').show();
        jQuery('#carousel_okay_button').hide();
        jQuery('#banner_count_zero').hide();
    } else if (jQuery('#edit_carousel ul.banner_select.active img').length < 1){
        jQuery('#banner_count_error').hide();
        jQuery('#banner_count_zero').show();
        jQuery('#carousel_okay_button').hide();
    } else {
        jQuery('#banner_count_error').hide();
        jQuery('#banner_count_zero').hide();
        jQuery('#carousel_okay_button').show();
    }
}

function hideCarousel() {
    jQuery('#edit_carousel').hide();
    jQuery('#overlay_control').hide();
    return false;
}

function saveBannerOrder() {
    var cssIDs = jQuery('#edit_carousel ul.banner_select.active').sortable('toArray');
    var bannerIDs = jQuery.map(cssIDs, getBannerID);
    PizzaExpress.Core.Web.Cms.ReorderBanners(bannerIDs,
                                             jQuery('#carousel_start_date').val(),
                                             jQuery('#carousel_start_time').val(),
                                             jQuery('#carousel_end_date').val(),
                                             jQuery('#carousel_end_time').val(),
                                             hideCarousel, carouselError);
    refreshCarousel();
}

function getBannerID(cssID) {
    return cssID.split("_")[1];
}

function carouselError(error) {
    alert("Error: " + error);
    hideCarousel();
}

function refreshCarousel() {
    $.ajax({type: "GET",
            url: location.href,
            dataType: "html",
            success: function(data) {
                var refreshed = jQuery(data).find('#banner');
                jQuery('#banner').replaceWith(refreshed);
                hookupSlidingBanner();
            }
    }); 
}