/*
 * This loads the image gallery images then calls the image gallery methods
 *
 * Relys on content files located at: /root/json/ContentType.js which look like this: 
 *
 * {
 *   imageDir: 'image directory path',
 *   thumbDir: 'thumb directory path', // if not included assumed to be the same as the image dir.
 *   images: [
 *     {
 *       imageName: 'image name',
 *       thumbName: 'thumb name', // if not included assumed to be the same as the image name.
 *       title: 'the image title',
 *       desc: 'the description'
 *     },
 *     .....
 *   ]
 * }
 */
(function($) {
  $.extend($.fn, {
    loadGalleryThumbnails: function(options) {
      return this.each(function() {
        var root = $(this);
        var loader = $('<div class="gallery-loader"><div class="gallery-loader-text">Loading Thumbnails: <span id="percent">0</span>%</div</div>');
        var percent = $('span#percent', loader);
        if (root.is('.not-loaded')) { // if its not loaded already
         
          root.append(loader);
          root.removeClass('not-loaded');
          
          var contentType = root.attr('id');
          contentType = contentType.substring(0, contentType.length - 7);
          var url = 'content/pages.php?p=' + contentType;

          var ul = $('<div class="gallery"></div>');
          ul.hide();
          root.append(ul);

          var imageDir = null;
          var thumbDir = null;
          var images = null;
          var imgTags = null;

          var imagesLoaded = 0;
          var totalImages = 0;

          var loadImage = function(image, el) {
            var imageFile = image.image_src + "&w=530&h=400";
            var thumbFile = image.thumb_src + "&w=75&h=50";
            
            el.load(function() {
              imagesLoaded++;
              var perc = (imagesLoaded / totalImages) * 100;
              setTimeout(function() {percent.text(perc.toFixed(0)) }, 10);

              if (imagesLoaded == totalImages) {
                if (loader) { loader.remove(); }
                ul.show();
                ul.gallery(options);
                $("div.gallery-light-box", root).shadowBox('inverted');
              }
            }).attr('src', thumbFile).attr('rel', imageFile);
            if (image.title) { el.attr('title', image.title); }
            if (image.description) { el.attr('alt', '<em>'+image.caption + "</em><br />" + image.description); }
          };            

          $.getJSON(url, function(json) {
            var gallery = json.gallery;
            totalImages = json.gallery.length;
           
            for (var i = 0; i < gallery.length; i++) {
              ul.append('<div></div>');
              var img = new Image();
              $('div:last', ul).append(img);
              loadImage(gallery[i], $(img));
            }
          });
        }
      });
    } 
  });
})(jQuery);

