// ID/type storage for gallery items
var gallery = {
  id:   [],
  type: [],
  sub:  [],
  new_item_html: '',
  new_gallery_id: 0,
  
  // Build gallery from thumbnails
  set_up_gallery: function() {
    if ($(".convert-gallery").length) {
      var s = "";
      var titl = $("#gallery-blurb").html();
      titl = titl ? titl : ($("h2").text() ? '<h2 style="margin-bottom: 10px;">' + $("h2").text() + '</h2>' : '');
      var imgs = $(".convert-gallery img");
      var txts = $(".convert-gallery div");
      
      for (var i = 0; i < imgs.length; i++) {
        var w = $(imgs[i]).attr("data-width");
        var h = $(imgs[i]).attr("data-height");
        var r = $(imgs[i]).attr("data-src");
        
        s += '<a href="' + (r ? r : imgs[i].src) + '" title="' + htmlchars($(txts[i]).text()) + '" class="lightbox">';
        s += '<img src="' + imgs[i].src + '" style="width: ' + w + 'px; height: ' + h + 'px;">';
        s += '</a>';
      }
      
      $(".convert-gallery").parent().html(titl + '<div class="gallery-thumbnail-container">' + s + '</div>');
      
      $('.lightbox').lightBox();
    }
  },
  
  build_gallery_items: function(data) {
    var s = "";
    
    // Loop through gallery items and add them to the page
    for (var i = 0; i < data.length; i++) {
      var row = data[i];
      s += '<div class="stage-thumbnail convert-gallery" style="' + (i % 2 == 0 ? 'margin-right: 20px; clear: left;' : 'clear: right;') + '">';
      s += '  <img src="' + row["image"] + '" alt="Photo" style="width: ' + row["width"] + 'px; height: ' + row["height"] + 'px;" data-width="' + row["tw"] + '" data-height="' + row["th"] + '">';
      s += '  <div>' + row["desc"] + '</div>';
      s += '</div>';
      
      s += (i % 2 != 0 ? '<div style="clear: both;"></div>' : '');
    }
    gallery.new_item_html = s; // Save the new gallery
    
    // Hide galleries that are on display, then display new gallery
    if ($(".gallery-item-container:visible").length) {
      $(".gallery-item-container").slideUp("slow", function() {
        $(this).html(gallery.new_item_html);
        gallery.set_up_gallery();
        //$(this).append('<a href="' + location.href.substring(0, location.href.indexOf("?") < 0 ? location.href.length : location.href.indexOf("?")) + '?id=' + (gallery.new_gallery_id + 1) + '" class="gallery-link"><span>Album Link</span></a>');
        $(this).slideDown();
      });
    }
    else {
      $(".gallery-item-container").html(gallery.new_item_html);
      gallery.set_up_gallery();
      //$(".gallery-item-container").append('<a href="' + location.href.substring(0, location.href.indexOf("?") < 0 ? location.href.length : location.href.indexOf("?")) + '?id=' + (gallery.new_gallery_id + 1) + '" class="gallery-link"><span>Album Link</span></a>');
      $(".gallery-item-container").slideDown();
    }
  }
};

// Can this browser play MP3 files in audio elements?
function canPlayMP3() {
  if (!!(document.createElement('audio').canPlayType)) {
    if (!!(document.createElement('audio').canPlayType('audio/mpeg'))) {
      return true;
    }
  }
}

// Replace all HTML characters with safer entities
function htmlchars(html) {
  html = html.replace(/&/g, '&amp;');
  html = html.replace(/"/g, '&quot;');
  html = html.replace(/>/g, '&gt;');
  html = html.replace(/</g, '&lt;');
  return html;
}

// If there are 3 or fewer items, the carousel doesn't need to scroll
function hideUnneededCarouselControls() {
  $.map($(".jcarousel-container-horizontal"), function(n, i) {
    if ($(n).find("li").length <= 3) {
      $(n).find(".jcarousel-prev, .jcarousel-next").hide();
    }
    else {
      $(n).find(".jcarousel-prev, .jcarousel-next").show();
    }
  });
}

// Allow pull quote to cycle through
var marquee = {
  count: -1,
  inc: 1,
  go: function() {
    var quotes = $(".quote-container blockquote");
    
    if (quotes[marquee.count]) {
      $(quotes[marquee.count]).fadeOut("slow");
    }
    
    marquee.count += marquee.inc;
    
    if (marquee.count >= quotes.length) {
      marquee.count = 0;
    }
    
    if (marquee.count < 0) {
      marquee.count = quotes.length - 1;
    }
    
    $(quotes[marquee.count]).fadeIn("slow");
    setTimeout(marquee.go, 15000);
  }
};

// Startup
$(document).ready(function() {
  
  // Store gallery info
  $.map($(".jcarousel img[data-id]"), function(n, i) {
    gallery.id.push(parseInt($(n).attr("data-id")));
    gallery.type.push(parseInt($(n).attr("data-type")));
  });
  
  // Set up jCarousel
  var isVertical = !!$('.jcarousel').attr("data-vertical");
  $('.jcarousel').jcarousel({
    vertical: isVertical,
    wrap: 'circular'
  });
  
  hideUnneededCarouselControls();
  
  // Set up gallery linking behavior
  $.map($(".jcarousel-list li"), function(n, i) {
    
    // This item is a gallery group
    if (gallery.type[i] == 0) {
      $(n).bind("click", function() {
        $(".subgallery-container:visible").slideUp();
        $.post("scrape_galleries.php", {id:gallery.id[i]}, function(data) {
          
          gallery.sub = [];
          
          // Build subgalleries
          data = $.parseJSON(data);
          var s = '<div class="gallery-container" style="float: none; margin: auto;"><ul class="jcarousel">';
          for (var k = 0; k < data.length; k++) {
            var row = data[k];
            s += '<li onclick="$.post(\'scrape_gallery_items.php\', {id:gallery.sub[' + k + ']}, function(data) {';
            s += '  data = $.parseJSON(data);';
            s += '  gallery.new_gallery_id = gallery.sub[' + k + '];';
            s += '  gallery.build_gallery_items(data);';
            s += '});"><img src="' + row["image"] + '" alt="Image" style="width: ' + row["width"] + 'px; height: ' + row["height"] + 'px; top: ' + row["otop"] + 'px; left: ' + row["oleft"] + 'px;">' + row['title'] + '</li>';
            gallery.sub.push(parseInt(row["id"]));
          }
          s += '</ul></div>';
          
          // Set up carousel for subgallery
          $(".subgallery-container").html(s);
          $('.subgallery-container .jcarousel').jcarousel({wrap:'circular'});
          $(".subgallery-container").slideToggle();
          hideUnneededCarouselControls();
        });
      });
    }
    
    // Item is a gallery
    else {
      $(n).bind("click", function() {
        $(".subgallery-container:visible").slideUp();
        gallery.new_gallery_id = i;
        $.post("scrape_gallery_items.php", {id:gallery.id[i]}, function(data) {
          data = $.parseJSON(data);
          gallery.build_gallery_items(data);
        });
      });
    }
  });
  
  gallery.set_up_gallery();
  
  // Press kit page
  if ($(".press-kit").length) {
    $.post("pull_quotes.php", function(data) {
      var s = '<div class="quote-container">';
      data = $.parseJSON(data);
      for (var i = 0; i < data.length; i++) {
        s += '<blockquote>';
        s += '<p>' + data[i]['quote'] + '</p>';
        s += '<p>' + data[i]['source'] + '</p>';
        s += '</blockquote>';
      }
      s += '</div>';
      $(".press-kit").append(s);
      marquee.go();
    });
  }
  
  // Try HTML5 audio
  /*if (canPlayMP3()) {
    $("object[data-song-src]").map(function() {
      $($(this).parent()).css("position", "relative");
      $(this).parent().html('<audio src="' + $(this).attr('data-song-src') + '" style="width: 250px; vertical-align: middle; margin: 5px 0;" controls></audio><div class="audio-caption">' + $(this).attr('data-song-title') + '</div>');
    });
  }
  
  // Fall back to Flash player
  else {
    ap_registerPlayers();
  }*/
  
  ap_registerPlayers();
  
  // Set video overlays to be replaced by actual videos when clicked
  $("div.video-overlay").bind("click", function() {
    $(this).hide();
    $(this).next().show();
  });
});
