;(function($) {

var windowLoaded = false;
$(window).bind('load', function() {
  windowLoaded = true;
});

$.fn.booklist = function(options) {
  var opts = $.extend({}, $.fn.booklist.defaults, options),
      jsonURL = getURL('booklist', opts.category);

  return this.each(function() {
    var $booklist = $(this);

    // The $books variable will be the child UL of the selector
    var $books = $booklist.children('.books').css('opacity', '0.1');

    $(document).bind('activateCarousel', function(event) {
      $.getScript('/assets/scripts/jcarousellite.js', function() {
        $booklist
          .after('<a href="#" class="prev prevnext replace">previous</a><a href="#" class="next prevnext replace">next</a>')
          .jCarouselLite({
            btnPrev: '.prev',
            btnNext: '.next',
            speed: 300,
            visible: 5
          }).parent().css('overflow', 'visible');
      });
    });
    
    $(document).bind('loadCarousel', function(event, info) {
      var data = info.data,
          books = [],
          details = [],
          items = data.category.published_items,
          itemsLength = items.length;
          $tgt = $(event.target);

      for (var i=0; i < itemsLength; i++) {
        var item = items[i];
        var bookURL = getURL('detail', data.category.id + '/' + item.id);
        var bookTitle = '',
            bookTitleWords = item.title.split(/\b/),
            idx = 0;
        if (item.title.length > 32) {
          while (bookTitle.length < 32 && bookTitleWords[idx]) {
            bookTitle += bookTitleWords[idx++];
          }
          if (bookTitle.length < item.title.length) {
            bookTitle += ' &hellip;';
          }
        } else {
          bookTitle = item.title;
        }
        books[i] = '<li class="book">';
        books[i] += '<a class="cluetip" title="' + item.title + '" rel="#item-' + item.id + '" href="' + bookURL + '"><img height="130px" src="' + opts.baseURL + item.api_cover_url + '" alt="" /></a>';
        books[i] += '<div class="title"><a href="' + bookURL + '">' + bookTitle + '</a></div>';
        books[i] += '<div class="author">by ' + item.author + '</div>';
        books[i] += '</li>';
        details[i] = '<div id="item-' + item.id + '">' + $('<div>' + item.amazon_description + '</div>').text().split(/\s/).slice(0,40).join(' ') + '&hellip;';
        details[i] += ' <a href="' + bookURL + '">more info</a></div>';
      }

      $tgt
      .html(books.join(''))
      .parent().before('<h3>' + data.category.name + ' <span>(' + items.length + ' items)</span></h3>');

      if ($tgt.children('li').length > 5) {
        $(document).trigger('activateCarousel').trigger('revealBooks');
      } else {
        $(document).trigger('revealBooks');
      }
      setTimeout(function() {
        $('body').append('<div class="hide">' + details.join('') + '</div>');
        $('.cluetip').cluetip({
          sticky: true,
          local: true, 
          cluetipClass: 'pdl', 
          dropShadow: false, 
          width: 300, 
          height: 215,
          positionBy: 'bottomTop',
          arrows: true
        });
        $(document).bind('mouseover', function(event) {
          var $tgt = $(event.target);
          if (!$tgt.closest('.booklist-wrapper').length && !$tgt.closest('#cluetip').length) {
            $(document).trigger('hideCluetip');
          }
        });
        $('.prevnext').bind('click.hideclue', function(event) {
          $(document).trigger('hideCluetip');
        });
      }, 250);
    });

    $(document).bind('loadCategory', function(event, info) {
      
      if (opts.category == '-1') { return loadAll();}
      var category = info.data.category;
      
      $('h1').html(category.name);
      $('.content-main-right').prepend('<div class="intro">' + category.description + '</div>');
      
      var output = [],
          items = category.published_items;
      var itemsLength = items.length,
          kids = category.published_children,
          kidsLength = kids.length;
      $tgt = $(event.target);
      if (itemsLength) {
        for (var i=0; i < itemsLength; i++) {
          var item = items[i];
          var bookURL = getURL('detail',category.id + '/' + item.id);
          output[i] = '<li class="book col-14">';
          output[i] += '<div class="col-3 cover"><a href="' + bookURL + '"><img height="130px" src="' + getURL(item.api_cover_url) + '" alt="" /></a></div>';
          output[i] += '<div class="col-11 last">';
          output[i] += '<h3 class="title">' + item.title + '</h3>';
          output[i] += '<div class="author">By ' + item.author + '</div>';
          output[i] += $('<div>' + item.amazon_description + '</div>').text().slice(0,100) + '&hellip;';
          output[i] += '<div class="more-info"><em>More Info:</em> <a href="' + bookURL + '">Book Details</a>' + '<a class="last" href="' + getURL('catalog', item.isbn) + '">Catalog Link</a></div>';
          output[i] += '</div>';
          output[i] += '</li>';
        }
        
      } else if (kidsLength) {
        for (var i=0; i < kidsLength; i++) {
          var kidCat = kids[i].category;
          output[i] = '<li><a href="/lists/' + kidCat.id + '">' + kidCat.name + '</a>';
          output[i] += '<div>' +kidCat.description + '</div></li>';
        }
      } else {
        output = ['<li>no books or categories matched your search</li>'];
      }
      $tgt.html(output.join('')).trigger('revealBooks');
      if (itemsLength) {
        $booklist.prepend('<a class="print-page rnd" href="#">Print Booklist</a>')
          .find('.print-page').click(function() {
            window.print();
            return false;
          });
      }
    });

    $(document).bind('loadBook', function(event, info) {
      var category = info.data.category,
          items = category.published_items,
          itemsLength = items.length,
          $tgt = $(event.target);
      
      for (var i=0; i < itemsLength; i++) {
        if (items[i].id == opts.item) {
          var item = items[i];
          var detailNav = '<a href="' + getURL('catalog',item.isbn) + '">Catalog Link</a>' + '<a class="last" href="/lists/' + category.id + '">View all in ' + category.name + '</a>';
          $('h1').html(item.title);
          var book = [
            '<div class="col-6">',
              '<div class="amzn-img"><img width="130px" class="left" src="' + getURL(item.api_cover_url) + '" alt="" /></div>',
              '<div class="nav-sidebar-detail">' + detailNav + '</div>',
            '</div>',
            '<div class="col-12 last">',
              '<h3>by ' + item.author + '</h3>',
              '<div class="description">' + item.amazon_description + '</div>',
              '<div class="more-info">',
                '<h4>More Info</h4>' + detailNav,
              '</div>',
              '<div>Some content and cover art provided by Amazon.com</div>',
            '</div>'
          ].join('');
          break;
        }
      }
      $tgt.html(book).trigger('revealBooks');
    });
    
    $(document).bind('loadAll', function(event, info) {
      var idx = 0, cats = [];
      $('h1').html('Book Lists');
      $.each(info.data, function(index, val) {
        var cat = val.category;
        if (!cat.parent_id && (cat.published_children.length || cat.published_items.length)) {
          cats[idx] = '<li><a href="/lists/' + cat.id + '">' + cat.name + '</a> <div>' + cat.description + '</div></li>';
          idx++;
        };
      });
      $(event.target).html(cats.join('')).trigger('revealBooks');
    });
    
    $(document).bind('revealBooks', function() {
      if (windowLoaded) {
        $books.css('top', '0').fadeTo(400, 1.0, function() {
          $(this).css('opacity', '1.0');
        });
        $('#booklist-loading').remove();
      } else {
        $(window).bind('load', function() {
          $books.css('top', '0').fadeTo(400, 1.0, function() {
            $(this).css('opacity', '1.0');
          });
          $('#booklist-loading').remove();
        });
      }
    });
    

    $(document).bind('getjson', function(event) {
      $.ajax({
        url: jsonURL,
        dataType: 'jsonp',
        success: function(json) {
          $books.trigger('load' + opts.type, {data: json});
        }, 
        error: function(request, status, errorthrown) {
          if (window.console && console.log) { console.log('error', status);}
        }
      });
    });

    $(document).trigger('getjson');
    
  });
  
  function getURL(urlType, suffix) {
    if (arguments.length == 1) {
      suffix = urlType;
      urlType = 'misc';
    }
    var urls = {
      catalog: opts.catalogURL + suffix,
      booklist: function() {
        var url = opts.baseURL + '/categories';
        if (suffix) {
          url += '/' + suffix;
        }
        return url += '.json';
      }, 
      detail: '/lists/detail/' + suffix,
      misc: opts.baseURL + suffix
    };
    
    return $.isFunction(urls[urlType]) ? urls[urlType]() : urls[urlType] ;
  }
};
 
// default options
$.fn.booklist.defaults = {
  type: 'Carousel',
  baseURL: 'http://booklists.portagelibrary.info',
  category: '',
  catalogURL: 'http://eps.portagelibrary.info/rooms/portal/media-type/html/language/en/country/US/user/anon/page/Sirsi_AdvancedCatalogSearch.psml?eventSubmit_doSearch=1&qualifiers=ISBN&terms='
  
};

})(jQuery);




