/*
 * OBMG gallery scripts
 *
 * Copyright (c) 2009-2012 Dialect Communications Group (dialect.ca)
 *
 * $Package: OBMG $
 */

/*jslint browser: true, white: true, plusplus: false, newcap: true,
     eqeqeq: true, evil: true, nomen: false, regexp: true, undef: true,
     onevar: true, indent: 2 */

/*global OBMG,jQuery,Mustache,window,log,_gaq */
 
(function ($, OBMG, document, window, undefined) {
  OBMG.Gallery = function (id, gallery, tmpl) {  
    var original = gallery.html(),
        original_css = {},
        expanded_css = {width: 580, height: 270, marginLeft: 0}, // 
        media_idx = 0,
        media = [],
        is_open = false;

    
    function loadMedia() {
      var imgs = $('.preload img', gallery);

      if (imgs.length > 0) {
        imgs.each(function (idx) {
          var src = $(this).attr('src');
          media.push({src: src, caption: $(this).attr('title')});
          try {
            OBMG.preloadImage(src);
          } catch (e) { }
        });

        if (media.length <= 1) {
          gallery.addClass('nonav');
        }
      }
      
      return imgs.length > 0;
    }
    
    function show(idx) {
      if (idx < 0) {
        idx = media.length - 1;
      } else if (idx > media.length - 1) {
        idx = 0;
      }

      if (media[idx]) {
        gallery.html(Mustache.to_html(tmpl, media[idx]));
        media_idx = idx;
        try {
          OBMG.trackEvent('Inline Gallery', 'View', id + '/' + idx, 1);
        } catch (e) { }
      }
    }
    
    function close() {
      is_open = false;
      $('*', gallery).fadeOut(300);

      gallery.animate(original_css, {
        duration: 1000,
        complete : function () {
          gallery.removeClass('mediagallery');
          gallery.html(original);
        }
      });

    }
    
    function updateDimensions() {
      log('exp', $('#content').width(), parseInt($('#content').css('padding-right'), 10));
      expanded_css.width = ($('#content').width() + (parseInt($('#content').css('padding-right'), 10)));
      // TODO : test on desktop
      //expanded_css.height = 'auto';
    }
    
    function open(evt) {
      evt.preventDefault();
      
      // save the collapsed state so we can restore it on close
      original_css = {
        width: gallery.width(),
        height: gallery.height(),
        marginLeft: gallery.css('margin-left')
      };
      
      updateDimensions();
      
      $('*', gallery).fadeOut(300);
      gallery.animate(expanded_css, { 
        duration: 1000,
        complete : function () {
          gallery.addClass('mediagallery');
          show(0);
        }
      });
      is_open = true;
    }
    
    function onNavClick(evt) {
      evt.preventDefault();
      var el = $(this);
      switch (el.attr('rel')) {
      case 'prev':
        show(media_idx - 1);
        break;
      case 'next':
        show(media_idx + 1);
        break;
      case 'close':
        close();
        break;          
      }
      return false;
    }

    if (loadMedia()) {
      $(document).on('click.gallery', '#' + id + ' > img, #' + id + ' > cite', open);
      $(document).on('click.gallery', '#' + id + ' .navl', onNavClick);
    }
    
    
    function resize() {
      if (is_open) {
        updateDimensions();
        log('resizing in gal', is_open, expanded_css);
        gallery.css(expanded_css);
      }  
    }
    
    return { resize: resize };
  };
  
  
  OBMG.Galleries = (function () {
    var galleries = [];

    function initExpandables() {
      var expandables = $('.expandable'), 
          expandableTmpl = $('#inline_gallery_tmpl');

      if (expandableTmpl.length === 0) {
        log('OBMG.Galleries.initExpandables', 'Template missing');
        return;
      }
      
      expandableTmpl = expandableTmpl.html();
      
      $.each(expandables, function (idx, el) {
        var gallery = $(el),
            gallery_id = gallery.attr('id');

        galleries.push({
          gallery: new OBMG.Gallery(gallery_id, gallery, expandableTmpl),
          id: gallery_id
        });

      });
    }
    
    function onResize(e) {    
      var i = galleries.length;
      while (i--) {
        log('gal', i, galleries[i]);
        galleries[i].gallery.resize();
      }
    }

    function init() {
      initExpandables();
      log('OBMG.Galleries.init', galleries);
      
      if (galleries.length > 0) {
        $(window).on('resize', onResize);
      }
      
    }


    return { init: init };
  }());

  $(document).on('ready', function () {
    OBMG.Galleries.init();
  });
}(jQuery, OBMG || {}, document, window));

