'use strict';

(function () {

  // import Objects
  var ContactService = exports.contactService,
  ContactStorage = exports.contactStorage,
  Message = exports.message,

  // code
  notification = document.getElementById('notification'),
  step1 = document.getElementById('step1'),
  step215 = document.getElementById('step2-15'),
  ddd = step1.querySelector('#ddd'),
  checkbox = step1.querySelector('#check-inp'),
  convert = step1.querySelector('#convert'),
  backup = step1.querySelector('#backup-revert'),
  questionMark = step1.querySelector('#question-mark'),
  faqLink = step1.querySelector('#faq-link'),
  termLink = step1.querySelector('#term-link'),
  dismissCounter;

  checkbox.addEventListener('click', function (e) {
    toggleCheckbox(checkbox);
  });

  toggleCheckbox(checkbox);

  convert.addEventListener('click', function (e) {
    e.preventDefault();
    if (checkbox.checked) {
      Animation.currentToLeft(step1, step1, step1.nextElementSibling);
      ContactService.convert(ddd.value || '');
    } else {
      Notifier.notify(notification, Message['validation.useterm'], '');
    }
  });

  questionMark.addEventListener('click', function (e) {
    Notifier.notify(notification, '', Message['text.question']);
  });

  faqLink.addEventListener('click', function (e) {
    Notifier.notify(notification, Message['title.faq'], Message['text.faq']);
  });

  termLink.addEventListener('click', function (e) {
    Notifier.notify(notification, Message['title.useterm'], Message['text.useterm']);
  });

  // ddd.addEventListener('keyup', function (e) {
  //   if (ddd.value.length == 2) {
  //     dismissCounter = setTimeout(dismiss, 3000);
  //   } else {
  //     clearTimeout(dismissCounter);
  //   }
  // });

  document.addEventListener('app.close', function (e) {
    enableBackupButton();
  });

  document.addEventListener('convert.end', function (e) {
    enableBackupButton();
  });  

  document.addEventListener('revert.end', function (e) {
    enableBackupButton();
  });

  backup.addEventListener('click', function (e) {
    if (hasClass(backup, 'btn3')) {
      if (checkbox.checked) {
        Animation.currentToLeft(step1, step1, step215);
        ContactService.revert();
      } else {
        Notifier.notify(notification, Message['validation.useterm'], '');
      }
    }
  });

  function enableBackupButton() {
    if (ContactStorage.hasBackup()) {
      addClass(backup, 'btn3');
      removeClass(backup, 'btn2');
    } else {
      addClass(backup, 'btn2');
      removeClass(backup, 'btn3');
    }
  }

  function dismiss() {
    var enter = document.createEvent('KeyEvents');
    enter.initKeyEvent('keypress', false, true, document.defaultView, false, false, false, false, 0x0D, 0);
    ddd.dispatchEvent(enter);
  }

  enableBackupButton();
}());
