function mycarousel_itemLoadCallback(carousel, state)
{
    // Check if the requested items already exist
    if (carousel.has(carousel.first, carousel.last)) {
        return;
    }

    jQuery.get(
        'http://www.bruliamwines.com/get-images/',
        {
            first: carousel.first,
            last: carousel.last
        },
        function(xml) {
            mycarousel_itemAddCallback(carousel, carousel.first, carousel.last, xml);
        },
        'xml'
    );
};

function mycarousel_itemAddCallback(carousel, first, last, xml)
{
    // Set the size of the carousel
    carousel.size(parseInt(jQuery('total', xml).text()));
    
    jQuery('item', xml).each(function(i) {
    	
    	var thumb = jQuery(this).children('thumb').text();
    	var full = jQuery(this).children('full').text();
    
        carousel.add(
        	first + i,
        	'<a href="'+ full +'" rel="pictures_list"><img src="'+ thumb +'" width="121" height="92" alt="" /></a>'
        );
    });
    
    jQuery("#mycarousel a[rel=pictures_list]").fancybox({
    	'transitionIn'		: 'none',
    	'transitionOut'		: 'none',
    	'titlePosition' 	: 'over',
    	'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
    		return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
    	}
    });
};

/**
 * Initialize our slider
 * And the fancybox overlays.
 */
jQuery(document).ready(function($) {
    $('#mycarousel').jcarousel({
        // Uncomment the following option if you want items
        // which are outside the visible range to be removed
        // from the DOM.
        // Useful for carousels with MANY items.

        // itemVisibleOutCallback: {onAfterAnimation: function(carousel, item, i, state, evt) { carousel.remove(i); }},
        itemLoadCallback: mycarousel_itemLoadCallback,
        scroll: 6
    });
    
    /**
     * Fancybox on brigade gallery.
     * This must be done AFTER the jCarousel is loaded, as images are now loaded via AJAX.
     */
    $("#mycarousel a[rel=pictures_list]").fancybox({
    	'transitionIn'		: 'none',
    	'transitionOut'		: 'none',
    	'titlePosition' 	: 'over',
    	'titleFormat'		: function(title, currentArray, currentIndex, currentOpts) {
    		return '<span id="fancybox-title-over">Image ' + (currentIndex + 1) + ' / ' + currentArray.length + (title.length ? ' &nbsp; ' + title : '') + '</span>';
    	}
    });
    
    /**
     * Fancybox for Brigade registration form.
     */
    $("#form").fancybox({
    	'titlePosition'		: 'inside',
    	'transitionIn'		: 'none',
    	'transitionOut'		: 'none',
    	'autoScale'			: false
    });
    
    /**
     * Tweaks, to allow for better styling.
     */
    $('#register_form fieldset').each(function(i) {
    	$(this).addClass('index-'+i);
    });
    $('.index-9 label').each(function(i) {
    	$(this).addClass('abs-'+i)
    });
});
