<%inherit file="main.html" />
<%namespace name='static' file='static_content.html'/>

<%!
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
import third_party_auth
from third_party_auth import provider, pipeline
from microsite_configuration import microsite
%>

<%block name="pagetitle">${_("Log into your {platform_name} Account").format(platform_name=platform_name)}</%block>

<%block name="bodyclass">view-login</%block>

<%block name="js_extra">
  <script type="text/javascript">
    $(function() {

      // adding js class for styling with accessibility in mind
      $('body').addClass('js');

      // show forgot password modal UI if URL contains matching DOM ID
      if ($.deparam.fragment()['forgot-password-modal'] !== undefined) {
        $('.pwd-reset').click();
      }

      // new window/tab opening
      $('a[rel="external"], a[class="new-vp"]')
      .click( function() {
        window.open( $(this).attr('href') );
        return false;
      });

      // form field label styling on focus
      $("form :input").focus(function() {
        $("label[for='" + this.id + "']").parent().addClass("is-focused");
      }).blur(function() {
        $("label").parent().removeClass("is-focused");
      });

      $("#email").focus();
    });

    (function() {
      toggleSubmitButton(true);

      $('#login-form').on('submit', function() {
        toggleSubmitButton(false);
      });

      $('#login-form').on('ajax:error', function(event, request, status_string) {
        toggleSubmitButton(true);

        if (request.status === 403) {
          $('.message.submission-error').removeClass('is-shown');
          $('.third-party-signin.message').addClass('is-shown').focus();
          $('.third-party-signin.message .instructions').html(request.responseText);
        } else {
          $('.third-party-signin.message').removeClass('is-shown');
          $('.message.submission-error').addClass('is-shown').focus();
          $('.message.submission-error').html(gettext("Your request could not be completed.  Please try again."));
        }
      });

      $('#login-form').on('ajax:success', function(event, json, xhr) {
        if(json.success) {
          var nextUrl = "${login_redirect_url}";
          if (json.redirect_url) {
            nextUrl = json.redirect_url; // Most likely third party auth completion. This trumps 'nextUrl' above.
          }
          if (!isExternal(nextUrl)) {
            location.href=nextUrl;
          } else {
            location.href="${reverse('dashboard')}";
          }
        } else if(json.hasOwnProperty('redirect')) {
          // Shibboleth authentication redirect requested by the server:
          var u=decodeURI(window.location.search);
          if (!isExternal(json.redirect)) { // a paranoid check.  Our server is the one providing json.redirect
              location.href=json.redirect+u;
          } // else we just remain on this page, which is fine since this particular path implies a login failure
            // that has been generated via packet tampering (json.redirect has been messed with).
        } else {
          toggleSubmitButton(true);
          $('.message.submission-error').addClass('is-shown').focus();
          $('.message.submission-error .message-copy').html(json.value);
        }
      });
      $("#forgot-password-link").click(function() {
        $("#forgot-password-modal").show();
        $("#forgot-password-modal .close-modal").focus();
      });

    })(this);

    function toggleSubmitButton(enable) {
      var $submitButton = $('form .form-actions #submit');

      if(enable) {
        $submitButton.
          removeClass('is-disabled').
          attr('aria-disabled', false).
          removeProp('disabled').
          html("${_('Log into My {platform_name} Account').format(platform_name=platform_name)} <span class='orn-plus'>+</span> ${_('Access My Courses')}");
      }
      else {
        $submitButton.
          addClass('is-disabled').
          prop('disabled', true).
          text("${_(u'Processing your account information')}");
      }
    }

    function thirdPartySignin(event, url) {
      event.preventDefault();
      window.location.href = url;
    }

    (function post_form_if_pipeline_running(pipeline_running) {
       // If the pipeline is running, the user has already authenticated via a
       // third-party provider. We want to invoke /login_ajax to loop in the
       // code that does logging and sets cookies on the request. It is most
       // consistent to do that by using the same mechanism that is used when
       // the use does first-party sign-in: POSTing the sign-in form.
       if (pipeline_running) {
         $('#login-form').submit();
       }
    })(${pipeline_running})
  </script>
</%block>

<%include file="forgot_password_modal.html" />

<section class="introduction">
  <header>
    <h1 class="title">
      <span class="title-super">${_("Please log in")}</span>
      <span class="title-sub">${_("to access your account and courses")}</span>
    </h1>
  </header>
</section>

<section class="login container">
  <section role="main" class="content">
    <form role="form" id="login-form" method="post" data-remote="true" action="/login_ajax" novalidate>

      <!-- status messages -->
      <div role="alert" class="status message">
        <h3 class="message-title">${_("We're Sorry, {platform_name} accounts are unavailable currently").format(platform_name=platform_name)}</h3>
      </div>

      <div role="alert" class="status message submission-error" tabindex="-1">
        <h3 class="message-title">${_("We couldn't log you in.")} </h3>
        <ul class="message-copy">
          <li>${_("Your email or password is incorrect")}</li>
        </ul>
      </div>

      <div role="alert" class="third-party-signin message" tabindex="-1">
        <p class="instructions"> </p>
      </div>

      % if third_party_auth_error:
        <div role="alert" class="status message third-party-auth-error is-shown" tabindex="-1">
          <h3 class="message-title">${_("An error occurred when signing you in to {platform_name}.").format(platform_name=platform_name)} </h3>
          <ul class="message-copy">
            <li>${third_party_auth_error}</li>
          </ul>
        </div>
      % endif

      <p class="instructions sr">
        ${_('Please provide the following information to log into your {platform_name} account. Required fields are noted by <strong class="indicator">bold text and an asterisk (*)</strong>.').format(platform_name=platform_name)}
      </p>

      <div class="group group-form group-form-requiredinformation">
        <h2 class="sr">${_('Required Information')}</h2>

        <ol class="list-input">
          <li class="field required text" id="field-email">
            <label for="email">${_('E-mail')}</label>
            <input class="" id="email" type="email" name="email" value="" placeholder="${_('example: username@domain.com')}" required aria-required="true" aria-described-by="email-tip" />
            <span class="tip tip-input" id="email-tip">${_("This is the e-mail address you used to register with {platform}").format(platform=platform_name)}</span>
          </li>
          <li class="field required password" id="field-password">
            <label for="password">${_('Password')}</label>
            <input id="password" type="password" name="password" value="" required aria-required="true" />
            <span class="tip tip-input">
              <a href="#forgot-password-modal" rel="leanModal" class="pwd-reset action action-forgotpw" id="forgot-password-link" role="button" aria-haspopup="true">${_('Forgot password?')}</a>
            </span>
          </li>
        </ol>
      </div>

      <div class="group group-form group-form-secondary group-form-accountpreferences">
        <h2 class="sr">${_('Account Preferences')}</h2>

        <ol class="list-input">
          <li class="field required checkbox" id="field-remember">
            <input id="remember-yes" type="checkbox" name="remember" value="true" />
            <label for="remember-yes">${_('Remember me')}</label>
          </li>
        </ol>
      </div>

      <div class="form-actions">
        <button name="submit" type="submit" id="submit" class="action action-primary action-update login-button"></button>
      </div>
    </form>

    % if third_party_auth.is_enabled():

      <span class="deco-divider">
        ## Developers: this is a sentence fragment, which is usually frowned upon.  The design of the pags uses this fragment to provide an "else" clause underneath a number of choices.  It's OK to leave it.
        ## Translators: this is the last choice of a number of choices of how to log in to the site.
        <span class="copy">${_('or')}</span>
      </span>

    <div class="form-actions form-third-party-auth">

    % for enabled in provider.Registry.enabled():
      ## Translators: provider_name is the name of an external, third-party user authentication provider (like Google or LinkedIn).
      <button type="submit" class="button button-primary button-${enabled.provider_id} login-${enabled.provider_id}" onclick="thirdPartySignin(event, '${pipeline_url[enabled.provider_id]}');"><span class="icon fa ${enabled.icon_class}"></span>${_('Sign in with {provider_name}').format(provider_name=enabled.name)}</button>
    % endfor

    </div>

    % endif

  </section>

  <aside role="complementary">

<%
  # allow for microsite overrides on the registration sidebars, otherwise default to pre-existing ones
  sidebar_file = microsite.get_template_path('login-sidebar.html')
%>

    <%include file="${sidebar_file}" />

  </aside>
  </section>
