<%! from django.utils.translation import ugettext as _ %>
<%! from microsite_configuration import microsite %>

<%inherit file="main.html" />

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

<%! from django.core.urlresolvers import reverse %>
<%! from django.utils import html %>
<%! from django_countries import countries %>
<%! from django.utils.translation import ugettext as _ %>
<%! from student.models import UserProfile %>
<%! from datetime import date %>
<%! import third_party_auth %>
<%! from third_party_auth import pipeline, provider %>
<%! import calendar %>

<%block name="pagetitle">${_("Register for {platform_name}").format(platform_name=platform_name)}</%block>

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

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

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

      // 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");
      });

    });

    (function() {
      toggleSubmitButton(true);

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

      $('#register-form').on('ajax:error', function() {
        toggleSubmitButton(true);
      });

      $('#register-form').on('ajax:success', function(event, json, xhr) {
        var url = json.redirect_url || "${reverse('dashboard')}";
        location.href = url;
      });

      $('#register-form').on('ajax:error', function(event, jqXHR, textStatus) {
        toggleSubmitButton(true);
        json = $.parseJSON(jqXHR.responseText);
        $('.status.message.submission-error').addClass('is-shown').focus();
        $('.status.message.submission-error .message-copy').html(json.value).stop().css("display", "block");
        $(".field-error").removeClass('field-error');
        $("[data-field='"+json.field+"']").addClass('field-error')
      });
    })(this);

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

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

      if(enable) {
        $submitButton.
          removeClass('is-disabled').
          removeProp('disabled').
          html("${_('Create My {platform_name} Account').format(platform_name=platform_name)}");
      }
      else {
        $submitButton.
          addClass('is-disabled').
          prop('disabled', true).
          text("${_(u'Processing your account information…')}");
      }
    }
  </script>
</%block>

<section class="introduction">
  <header>
    <h1 class="title">
      <span class="title-super">${_("Welcome!")}</span>
      <span class="title-sub">${_("Register below to create your {platform_name} account").format(platform_name=platform_name)}</span>
    </h1>
  </header>
</section>

<section class="register container">
  <section role="main" class="content">
    <form role="form" id="register-form" method="post" data-remote="true" action="/create_account" novalidate>
      <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }">

      <!-- status messages -->
      <div role="alert" class="status message">
        <h3 class="message-title">${_("We're sorry, {platform_name} enrollment is not available in your region").format(platform_name=platform_name)}</h3>
      </div>

      <div role="alert" class="status message submission-error" tabindex="-1">
        <h3 class="message-title">${_("The following errors occurred while processing your registration:")} </h3>
        <ul class="message-copy"> </ul>
      </div>

      % if third_party_auth.is_enabled():

        % if not running_pipeline:

        <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 service (like Google or LinkedIn).
          <button type="submit" class="button button-primary button-${enabled.NAME} register-${enabled.NAME}" onclick="thirdPartySignin(event, '${pipeline_urls[enabled.NAME]}');"><span class="icon ${enabled.ICON_CLASS}"></span>${_('Sign up with {provider_name}').format(provider_name=enabled.NAME)}</button>
        % endfor

        </div>

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

        <p class="instructions">
          ${_('Create your own {platform_name} account below').format(platform_name=platform_name)}
          <span class="note">${_('Required fields are noted by <strong class="indicator">bold text and an asterisk (*)</strong>.')}</span>
        </p>


        % else:

        <p class="instructions">
          ## Translators: selected_provider is the name of an external, third-party user authentication service (like Google or LinkedIn).
          ${_("You've successfully signed in with {selected_provider}.").format(selected_provider='<strong>%s</strong>' % selected_provider)}<br />
          ${_("We just need a little more information before you start learning with edX.")}
        </p>

        % endif

      % else:

      <p class="instructions">
        ${_("Please complete the following fields to register for an account. ")}<br />
        ${_('Required fields are noted by <strong class="indicator">bold text and an asterisk (*)</strong>.')}
      </p>

      % endif

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

        % if has_extauth_info is UNDEFINED:

        <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="${email}" placeholder="${_('example: username@domain.com')}" required aria-required="true" />
          </li>

          <li class="field required text" id="field-name">
            <label for="name">${_('Full Name')}</label>
            <input id="name" type="text" name="name" value="${name}" placeholder="${_('example: Jane Doe')}" required aria-required="true" aria-describedby="name-tip" />
            <span class="tip tip-input" id="name-tip">${_("Needed for any certificates you may earn")}</span>
          </li>
          <li class="field required text" id="field-username">
            <label for="username">${_('Public Username')}</label>
            <input id="username" type="text" name="username" value="${username}" placeholder="${_('example: JaneDoe')}" required aria-required="true" aria-describedby="username-tip"/>
            <span class="tip tip-input" id="username-tip">${_('Will be shown in any discussions or forums you participate in')} <strong>(${_('cannot be changed later')})</strong></span>
          </li>

          % if third_party_auth.is_enabled() and running_pipeline:

          <li class="is-disabled field optional password" id="field-password" hidden>
            <label for="password">${_('Password')}</label>
            <input id="password" type="password" name="password" value="" disabled required aria-required="true" />
          </li>

          % else:

          <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" />
          </li>

          % endif
        </ol>

        % else:

        <div class="message">
          <h3 class="message-title">${_("Welcome {username}").format(username=extauth_id)}</h3>
          <p class="message-copy">${_("Enter a Public Display Name:")}</p>
        </div>

        <ol class="list-input">

          % if ask_for_email:

          <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')}" />
          </li>

          % endif

          <li class="field required text" id="field-username">
            <label for="username">${_('Public Display Name')}</label>
            <input id="username" type="text" name="username" value="${extauth_username}" placeholder="${_('example: JaneDoe')}" required aria-required="true" aria-describedby="username-tip" />
            <span class="tip tip-input" id="id="username-tip>${_('Will be shown in any discussions or forums you participate in')} <strong>(${_('cannot be changed later')})</strong></span>
          </li>

          % if ask_for_fullname:

          <li class="field required text" id="field-name">
            <label for="name">${_('Full Name')}</label>
            <input id="name" type="text" name="name" value="" placeholder="$_('example: Jane Doe')}" aria-describedby="name-tip" />
            <span class="tip tip-input" id="name-tip">${_("Needed for any certificates you may earn")}</span>
          </li>

          % endif

        </ol>

        % endif
      </div>

      <div class="group group-form group-form-secondary group-form-personalinformation">
        <h2 class="sr">${_("Additional Personal Information")}</h2>

        <ol class="list-input">
          % if settings.REGISTRATION_EXTRA_FIELDS['city'] != 'hidden':
          <li class="field ${settings.REGISTRATION_EXTRA_FIELDS['city']} text" id="field-city">
            <label for="city">${_('City')}</label>
            <input id="city" type="text" name="city" value="" placeholder="${_('example: New York')}" aria-describedby="city-tip" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['city'] == 'required' else ''} />
          </li>
          % endif
          % if settings.REGISTRATION_EXTRA_FIELDS['country'] != 'hidden':
          <li class="field-group">
          <div class="field ${settings.REGISTRATION_EXTRA_FIELDS['country']} select" id="field-country">
              <label for="country">${_("Country")}</label>
              <select id="country" name="country" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['country'] == 'required' else ''}>
                <option value="">--</option>
                %for code, country_name in sorted(countries.countries, key=lambda (__, name): unicode(name)):
                <option value="${code}">${ unicode(country_name) }</option>
                %endfor
              </select>
            </div>
          </li>
          % endif
          % if settings.REGISTRATION_EXTRA_FIELDS['level_of_education'] != 'hidden':
          <li class="field-group field-education-level">
          <div class="field ${settings.REGISTRATION_EXTRA_FIELDS['level_of_education']} select" id="field-education-level">
              <label for="education-level">${_("Highest Level of Education Completed")}</label>
              <select id="education-level" name="level_of_education" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['level_of_education'] == 'required' else ''}>
                <option value="">--</option>
                %for code, ed_level in UserProfile.LEVEL_OF_EDUCATION_CHOICES:
                <option value="${code}">${_(ed_level)}</option>
                %endfor
              </select>
            </div>
          </li>
          % endif
          % if settings.REGISTRATION_EXTRA_FIELDS['gender'] != 'hidden':
          <li class="field-group field-gender">
            <div class="field ${settings.REGISTRATION_EXTRA_FIELDS['gender']} select" id="field-gender">
              <label for="gender">${_("Gender")}</label>
              <select id="gender" name="gender" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['gender'] == 'required' else ''}>
                <option value="">--</option>
                %for code, gender in UserProfile.GENDER_CHOICES:
                <option value="${code}">${_(gender)}</option>
                %endfor
              </select>
            </div>
          </li>
          % endif
          % if settings.REGISTRATION_EXTRA_FIELDS['year_of_birth'] != 'hidden':
          <li class="field-group field-yob">
            <div class="field ${settings.REGISTRATION_EXTRA_FIELDS['year_of_birth']} select" id="field-yob">
              <label for="yob">${_("Year of Birth")}</label>
              <select id="yob" name="year_of_birth" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['year_of_birth'] == 'required' else ''}>
                <option value="">--</option>
                %for year in UserProfile.VALID_YEARS:
                <option value="${year}">${year}</option>
                %endfor
              </select>
            </div>
            % endif
          </li>
        </ol>
      </div>

      <div class="group group-form group-form-personalinformation2">
        <ol class="list-input">
          % if settings.REGISTRATION_EXTRA_FIELDS['mailing_address'] != 'hidden':
          <li class="field ${settings.REGISTRATION_EXTRA_FIELDS['mailing_address']} text" id="field-address-mailing">
            <label for="address-mailing">${_("Mailing Address")}</label>
            <textarea id="address-mailing" name="mailing_address" value="" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['mailing_address'] == 'required' else ''}></textarea>
          </li>
          % endif

          % if settings.REGISTRATION_EXTRA_FIELDS['goals'] != 'hidden':
          <li class="field ${settings.REGISTRATION_EXTRA_FIELDS['goals']} text" id="field-goals">
            <label for="goals">${_("Please share with us your reasons for registering with {platform_name}").format(platform_name=platform_name)}</label>
            <textarea id="goals" name="goals" value="" ${'required aria-required="true"' if settings.REGISTRATION_EXTRA_FIELDS['goals'] == 'required' else ''}></textarea>
          </li>
          % endif
        </ol>
      </div>

      <div class="group group-form group-form-accountacknowledgements">
        <h2 class="sr">${_("Account Acknowledgements")}</h2>

        <ol class="list-input">
          <li class="field-group">

            % if has_extauth_info is UNDEFINED or ask_for_tos :
            <div class="field required checkbox" id="field-tos">
              <input id="tos-yes" type="checkbox" name="terms_of_service" value="true" required aria-required="true" />
              <label for="tos-yes">${_('I agree to the {link_start}Terms of Service{link_end}').format(
                link_start='<a href="{url}" class="new-vp" tabindex="-1">'.format(url=marketing_link('TOS')),
                link_end='</a>')}</label>
            </div>
            % endif

            % if settings.REGISTRATION_EXTRA_FIELDS['honor_code'] != 'hidden':
            <div class="field ${settings.REGISTRATION_EXTRA_FIELDS['honor_code']} checkbox" id="field-honorcode">
              <input id="honorcode-yes" type="checkbox" name="honor_code" value="true" />
              <%
                ## TODO: provide a better way to override these links
                if self.stanford_theme_enabled():
                  honor_code_path = marketing_link('TOS') + "#honor"
                else:
                  honor_code_path = marketing_link('HONOR')
              %>
              <label for="honorcode-yes">${_('I agree to the {link_start}Honor Code{link_end}').format(
                link_start='<a href="{url}" class="new-vp" tabindex="-1">'.format(url=honor_code_path),
                link_end='</a>')}</label>
            </div>
            % endif
          </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 register-button">${_('Register')} <span class="orn-plus">+</span> ${_('Create My Account')}</button>
      </div>
    </form>
  </section>

  <aside role="complementary">

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

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

  </aside>
</section>
