<%inherit file="main.html" />
<%! from microsite_configuration import microsite %>
<%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 %>

<%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 u=decodeURI(window.location.search);
          var next = u.split("next=")[1];
          if (next != undefined) {
            // if next is undefined, decodeURI returns "undefined" causing a bad redirect.
            next = decodeURIComponent(next);
          }
          if (next && !isExternal(next)) {
            location.href=next;
          }  else if(json.redirect_url){
            location.href=json.redirect_url;
          } else {
            location.href="${reverse('dashboard')}";
          }
        } else if(json.hasOwnProperty('redirect')) {
          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>

<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>

      <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>

% if course_id and enrollment_action:
      <input type="hidden" name="enrollment_action" value="${enrollment_action | h}" />
      <input type="hidden" name="course_id" value="${course_id | h}" />
% endif

% if email_opt_in:
      <input type="hidden" name="email_opt_in" value="${email_opt_in | h}" />
% endif

      <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.NAME} login-${enabled.NAME}" onclick="thirdPartySignin(event, '${pipeline_url[enabled.NAME]}');"><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>

