$(function () {
  'use strict';

  var OAUTH3 = window.OAUTH3;

  //var myPort = window.location.host.replace(/[^:]+(:)?/, '$1');
  //var providerUri = 'https://localhost.bar.daplie.me' + myPort;
  var providerUri = 'oauth3.org';

  var auth = OAUTH3.create();

  auth.init().then(function () {
    $('.mock-main').addClass('in');
  });

  auth.setProvider(providerUri).then(function () {
    $('.js-signin').removeAttr('disabled');

    return auth.authenticate({ windowType: 'background' }).then(function (session) {
      console.info("Previously Granted:", session);

      $('.js-signin').removeClass('in').hide();
      $('.js-logout').show().addClass('in');
    }, function (err) {
      console.info("Pre-Auth Fail (okay):", err);
    });
  });

  $('body').on('click', '.js-signin', function (ev) {
    ev.preventDefault();
    ev.stopPropagation();

    auth.login().then(function (session) {
      console.info('authorization tokens!', session);

      $('.js-signin').removeClass('in').hide();
      $('.js-logout').show().addClass('in');
    }, function (err) {
      window.alert(err.message);
    });

  });

  $('body').on('click', '.js-logout', function (ev) {
    ev.preventDefault();
    ev.stopPropagation();

    return auth.logout().then(function () {

      localStorage.clear();
      $('.js-signin').show().addClass('in');
      $('.js-logout').removeClass('in').hide();
    });
  });

  $('.js-logout').hide();
});
