// Generated by CoffeeScript 1.6.3
var $, Gallery, exports;

$ = jQuery;

Gallery = (function() {
  var _content_sel, _crypto, _is_image_grid_initialized, _key_cookie_name, _lightbox_close_sel, _lightbox_open_sel, _password_dialog_sel, _password_input_sel, _password_submit_sel, _thumbnail_enrypted_sel, _thumbnail_sel, _use_crypto;

  _content_sel = '#content';

  _thumbnail_sel = '.thumbnail-container';

  _password_dialog_sel = '#password-dialog';

  _password_input_sel = '#js-password-input';

  _password_submit_sel = '#js-password-submit';

  _lightbox_open_sel = '.lightbox';

  _lightbox_close_sel = '.lightbox-close';

  _thumbnail_enrypted_sel = '.thumbnail-img.encrypted';

  _key_cookie_name = 'yasgg_crypto_key';

  _is_image_grid_initialized = false;

  _use_crypto = false;

  _crypto = void 0;

  function Gallery() {
    var body, key, self;
    self = this;
    body = $('body:first');
    self._init_lightbox();
    if (body.attr('data-use-crypto')) {
      self._use_crypto = true;
    }
    if (self._use_crypto) {
      key = self.key_get();
      if (key) {
        self._crypto = new YASGGCrypto(key);
        if (self._decrypt_thumbnails() === true) {
          self._handle_initial_request();
        }
      } else {
        self._init_password_dialog();
      }
    } else {
      self._handle_initial_request();
      self._init_image_grid();
    }
  }

  Gallery.prototype.password_set = function(password) {
    if (password) {
      return $.cookie(_key_cookie_name, CryptoJS.MD5(password).toString());
    } else {
      return $.removeCookie(_key_cookie_name);
    }
  };

  Gallery.prototype.key_get = function() {
    return $.cookie(_key_cookie_name);
  };

  Gallery.prototype._handle_initial_request = function() {
    var hash_components;
    hash_components = window.location.hash.split('#');
    if (hash_components.length > 1 && $.isNumeric(hash_components[1])) {
      return $(_lightbox_open_sel + ':eq(' + hash_components[1] + ')').click();
    }
  };

  Gallery.prototype._init_image_grid = function() {
    var self;
    self = this;
    self._is_image_grid_initialized = true;
    return $(_content_sel).isotope({
      itemSelector: _thumbnail_sel,
      layoutMode: 'fitRows'
    });
  };

  Gallery.prototype._init_password_dialog = function() {
    var self;
    self = this;
    $.magnificPopup.open({
      items: {
        src: $(_password_dialog_sel),
        type: 'inline'
      },
      showCloseBtn: false,
      midClick: false,
      enableEscapeKey: false,
      closeOnBgClick: false
    });
    $(_password_submit_sel).click(function() {
      var initial_submit_text, password, password_input;
      password_input = $(_password_input_sel);
      password = password_input.val();
      if (!password) {
        return;
      }
      initial_submit_text = $(_password_submit_sel).html();
      $(_password_submit_sel).html('checking password...').attr('disabled', 'disabled');
      $(_password_input_sel).attr('disabled', 'disabled');
      self.password_set(password);
      self._crypto = new YASGGCrypto(self.key_get());
      $(_password_submit_sel).html(initial_submit_text).removeAttr('disabled');
      $(_password_input_sel).removeAttr('disabled');
      self._decrypt_thumbnails();
      return password_input.val('');
    });
    return $(document).on('keypress', _password_input_sel, function(e) {
      var code;
      code = (e.keyCode ? e.keyCode : e.which);
      if (code === 13) {
        return $(_password_submit_sel).click();
      }
    });
  };

  Gallery.prototype._init_lightbox = function() {
    var self;
    self = this;
    $(_lightbox_open_sel).magnificPopup({
      type: 'image',
      showCloseBtn: false,
      gallery: {
        preload: [1, 1],
        enabled: true,
        navigateByImgClick: true,
        arrowMarkup: '<button title=\'%title%\' type=\'button\' class=\'mfp-arrow mfp-arrow-%dir%\'></button>',
        tPrev: 'Previous (Left arrow key)',
        tNext: 'Next (Right arrow key)',
        tCounter: '%curr% of %total% &nbsp;&nbsp;<button class=\'lightbox-close\' type=\'button\' title=\'Close (Esc)\'> × </button>'
      },
      callbacks: {
        elementParse: function(item) {
          var img;
          img = item.el;
          if (!img.hasClass('encrypted')) {
            return;
          }
          return $.ajax({
            type: 'GET',
            url: img.attr('data-src-encrypted'),
            async: false
          }).done(function(data) {
            self._decrypt_image(img, data, 'href');
            item.src = img.attr('href');
            return img.removeClass('encrypted');
          });
        },
        imageLoadComplete: function() {
          var mp;
          mp = $.magnificPopup.instance;
          window.location = '#' + mp.index;
          return $('.mfp-img').on('swipeleft', function() {
            return mp.next();
          }).on('swiperight', function(e) {
            return mp.prev();
          });
        },
        close: function() {
          return window.location = '#';
        }
      }
    });
    return $(document).on('click', _lightbox_close_sel, function() {
      return $.magnificPopup.close();
    });
  };

  Gallery.prototype._decrypt_image = function(img, data, target_attr, check_password) {
    var decrypted, self;
    self = this;
    decrypted = self._crypto.decrypt(data);
    if (check_password) {
      if (decrypted.checksum !== CryptoJS.SHA1(decrypted.data.toString()).toString()) {
        return false;
      }
    }
    img.attr(target_attr, 'data:image/jpeg;base64,' + decrypted.data.toString(CryptoJS.enc.Base64));
    img.removeClass('loading').removeClass('encrypted');
    return img;
  };

  Gallery.prototype._decrypt_thumbnails = function() {
    var first_image, images_decrypted_count, images_to_decrypt_count, password_ok, password_wrong_rumble, self;
    self = this;
    password_wrong_rumble = void 0;
    password_ok = true;
    images_to_decrypt_count = $(_thumbnail_enrypted_sel).length;
    images_decrypted_count = 1;
    first_image = $(_thumbnail_enrypted_sel + ':first');
    $.ajax({
      type: 'GET',
      url: first_image.attr('data-src-encrypted'),
      async: false
    }).done(function(data) {
      if (self._decrypt_image(first_image, data, 'src', true)) {
        $.magnificPopup.close();
        return $(_thumbnail_enrypted_sel).each(function() {
          var img;
          img = $(this);
          return $.ajax({
            type: 'GET',
            url: img.attr('data-src-encrypted'),
            async: true
          }).done(function(data) {
            self._decrypt_image(img, data, 'src');
            images_decrypted_count++;
            if (!self._is_image_grid_initialized && images_decrypted_count >= images_to_decrypt_count) {
              return self._init_image_grid();
            }
          });
        });
      } else {
        self.password_set(null);
        password_ok = false;
        $(_password_dialog_sel).jrumble({
          x: 40,
          y: 0,
          rotation: 0
        });
        clearTimeout(password_wrong_rumble);
        $(_password_dialog_sel).trigger("startRumble");
        return password_wrong_rumble = setTimeout(function() {
          return $(_password_dialog_sel).trigger("stopRumble");
        }, 300);
      }
    });
    return password_ok;
  };

  return Gallery;

})();

exports = this;

exports.Gallery = Gallery;
