var Settings = (function () {
  'use strict';

  var settingsButton = $('.js-settings-button');
  var settingsClose = $('.js-close-settings');
  var settings = $('.js-settings');
  var logoutButton = $('.js-logout');
  var body = $('body');
  var sizeInputs = $('input[type=radio][name=downloadSize]');
  var shouldClipInput = $('.js-should-clip-input');

  return {
    init: init,
    getDownloadSize: getDownloadSize,
    shouldClip: shouldClip
  };

  function init() {
    settingsButton.on('click', openSettings);
    settingsClose.on('click', closeSettings);
    logoutButton.on('click', logout);
    sizeInputs.change(onDownloadSizeChange);
    shouldClipInput.change(onShouldClipChange);

    setDefaultAttributes();
  }

  function setDefaultAttributes() {
    if (!getDownloadSize()) {
      localStorage.setItem('downloadSize', 'original');
    }
    if (!localStorage.getItem('shouldClip')) {
      localStorage.setItem('shouldClip', true);
    }

    $('input[value=' + getDownloadSize() + ']').attr('checked', 'checked');

    if (shouldClip()) {
      shouldClipInput.attr('checked', 'checked');
    }
  }

  function openSettings() {
    body.addClass('is-settings-open');
    logoutButton.toggleClass('hidden', !Authorization.isLoggedIn());
  }

  function closeSettings() {
    body.removeClass('is-settings-open');
  }

  function onDownloadSizeChange() {
    $('.js-size').text('');
    Util.trackSettingChange(this.value);
    localStorage.setItem('downloadSize', this.value);
  }

  function getDownloadSize() {
    return localStorage.getItem('downloadSize');
  }

  function onShouldClipChange() {
    localStorage.setItem('shouldClip', this.checked);
  }

  function shouldClip() {
    return localStorage.getItem('shouldClip') === 'true' ? true : false;
  }

  function logout() {
    Authorization.logout();
    closeSettings();
  }

}());