/**
    * We use the initCallback callback
    * to assign functionality to the controls
    */
function cmc_init(carousel) {
    jQuery('.jcarousel-control a', carousel.container.parent()).bind('click', function() {
        carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text()));
        return false;
    });

    jQuery('.jcarousel-scroll select', carousel.container.parent()).bind('change', function() {
        carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value);
        return false;
    });
   
    jQuery('.cmdistro-next', carousel.container.parent()).bind('click', function() {
        carousel.next();
        return false;
    });

    jQuery('.cmdistro-prev', carousel.container.parent()).bind('click', function() {
        carousel.prev();
        return false;
    });
};
(function () {

  var markup_wrapper = '<div class="CMDistroTagSearch"><div class= "CMDistroHeadline">${headline}</div><ul class="cmdistro_carousel"></ul><div style="clear: both;"></div><div class="blocknavi"><a class="CMDistroCarouselLink cmdistro-prev" href="#">&laquo; Prev</a>&nbsp;&nbsp;<a class="CMDistroCarouselLink cmdistro-next" href="#">Next &raquo;</a></div></div>';
  var markup_item = '<li><div class="CMDistroItem"><div class="CMDistroArtwork"><a href="${URL}" target="_blank"><img src="${ImageURL}" border="0"></a></div><div class="CMDistroTitle">${ArtistName}<br />${Name}</div><div class="CMDistroItemType">(${ItemType})</div><div class="CMDistroPrice">${Price}</div></div></li>';
    
    
  var defaults = {
        'headline': '',
        'url': null,
        'tags': null,
        'affid': null,
        'lengthTitle': 20
    };  
 
  jQuery.fn.cmdistrocarousel = function(o) {
  
    return this.each(function() {
      new jQuery.cmdistrocarousel(this, o);
    });
  };
  
  jQuery.cmdistrocarousel = function(e, o) {
  
    this.options = jQuery.extend({}, defaults, o || {});    
    this.target  = jQuery(e);
    this.list = null;
    
    var self = this;
    
    jQuery.getJSON(this.options.url + '?jsoncallback=?', {  'Tags': this.options.tags, 'Affid': this.options.affid}, 
    function(data){
    
      if (data.length > 0) {
        jQuery.tmpl( markup_wrapper, {'headline' : self.options.headline} ).appendTo(self.target);
        data = jQuery.map(data, function(item) {
          item.Name = item.Name.substring(0,self.options.lengthTitle);
          return item;
        });
        self.list = self.target.find('ul');
        jQuery.each(data, function(index,obj){
          jQuery.tmpl( markup_item, obj).appendTo(self.list);  
        });
        
        self.list.jcarousel({
          initCallback: cmc_init,
          // This tells jCarousel NOT to autobuild prev/next buttons
          buttonNextHTML: null,
          buttonPrevHTML: null
        });
      }
    });
     
  };


}) ( jQuery );
    
