<%! from django.utils.translation import ugettext as _ %>
<%! from django.template import RequestContext %>

<%!
  from django.core.urlresolvers import reverse
  import waffle
%>

<%
  cert_name_short = settings.CERT_NAME_SHORT
  cert_name_long = settings.CERT_NAME_LONG
%>

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

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

<%block name="pagetitle">${_("Dashboard")}</%block>
<%block name="bodyclass">view-dashboard is-authenticated</%block>
<%block name="nav_skip">#my-courses</%block>

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

    $('.message.is-expandable .wrapper-tip').bind('click', toggleExpandMessage);

    function toggleExpandMessage(e) {
        (e).preventDefault();

        $(this).closest('.message.is-expandable').toggleClass('is-expanded');
    }

    $("#failed-verification-button-dismiss").click(function(event) {
      $.ajax({
        url: "${reverse('verify_student_toggle_failed_banner_off')}",
        type: "post",
        data: { 'user_id': ${user.id}, }
        })
      $("#failed-verification-banner").addClass('is-hidden');
      })

    $("#upgrade-to-verified").click(function(event) {
      user = $(event.target).data("user");
      course = $(event.target).data("course-id");
      Logger.log('edx.course.enrollment.upgrade.clicked', [user, course], null);
      % if waffle.flag_is_active(request, 'alternate_upsell_copy'):
      analytics.track("Clicked on Alternate Upsell Copy", {
        course: course
      });
      % else:
      analytics.track("Clicked on Regular Upsell Copy", {
        course: course
      });
      % endif
    });

    $(".email-settings").click(function(event) {
      $("#email_settings_course_id").val( $(event.target).data("course-id") );
      $("#email_settings_course_number").text( $(event.target).data("course-number") );
      if($(event.target).data("optout") == "False") {
        $("#receive_emails").prop('checked', true);
      }
    });

    $(".unenroll").click(function(event) {
      $("#unenroll_course_id").val( $(event.target).data("course-id") );
      $("#unenroll_course_number").text( $(event.target).data("course-number") );
    });

    $('#unenroll_form').on('ajax:complete', function(event, xhr) {
      if(xhr.status == 200) {
        location.href = "${reverse('dashboard')}";
      } else if (xhr.status == 403) {
        location.href = "${reverse('signin_user')}?course_id=" +
          $("#unenroll_course_id").val() + "&enrollment_action=unenroll";
      } else {
        $('#unenroll_error').html(
          xhr.responseText ? xhr.responseText : "${_('An error occurred. Please try again later.')}"
        ).stop().css("display", "block");
      }
    });

    $('#pwd_reset_button').click(function() {
      $.post('${reverse("password_reset")}',
             {"email"  : $('#id_email').val()},
             function(data){
               $("#password_reset_complete_link").click();
             });
    });

    $("#submit-lang").click(function(event, xhr) {
        event.preventDefault();
        $.post('/lang_pref/setlang/',
            {"language": $('#settings-language-value').val()})
        .done(
            function(data){
                // submit form as normal
                $('.settings-language-form').submit();
            }
        );
    });

    $("#change_email_form").submit(function(){
      var new_email = $('#new_email_field').val();
      var new_password = $('#new_email_password').val();

      $.post('${reverse("change_email")}',
               {"new_email" : new_email, "password" : new_password},
               function(data) {
                 if (data.success) {
                   $("#change_email_title").html("${_('Please verify your new email')}");
                   $("#change_email_form").html("<p>${_(('You\'ll receive a confirmation in your in-box.'
                                                    ' Please click the link in the email to confirm'
                                                    ' the email change.'))}</p>");
                 } else {
                   $("#change_email_error").html(data.error).stop().css("display", "block");
                 }
               });
      return false;
    });

    $("#change_name_form").submit(function(){
      var new_name = $('#new_name_field').val();
      var rationale = $('#name_rationale_field').val();

      $.post('${reverse("change_name")}',
             {"new_name":new_name, "rationale":rationale},
             function(data) {
               if(data.success) {
                 location.reload();
               } else {
                 $("#change_name_error").html(data.error).stop().css("display", "block");
               }
             });
       return false;
    });

    $("#email_settings_form").submit(function(){
      $.ajax({
        type: "POST",
        url: '${reverse("change_email_settings")}',
        data: $(this).serializeArray(),
        success: function(data) {
          if(data.success) {
            location.href = "${reverse('dashboard')}";
          }
        },
        error: function(xhr, textStatus, error) {
          if (xhr.status == 403) {
            location.href = "${reverse('signin_user')}";
          }
        }
      });
      return false;
    });
  })(this);

  $(function(){
    accessible_modal(".edit-name", "#apply_name_change .close-modal", "#apply_name_change", "#dashboard-main");

    accessible_modal(".edit-email", "#change_email .close-modal", "#change_email", "#dashboard-main");

    accessible_modal("#pwd_reset_button", "#password_reset_complete .close-modal", "#password_reset_complete", "#dashboard-main");


    $(".email-settings").each(function(index){
      $(this).attr("id", "unenroll-" + index);
      // a bit of a hack, but gets the unique selector for the modal trigger
      var trigger = "#" + $(this).attr("id");
      accessible_modal(trigger, "#email-settings-modal .close-modal", "#email-settings-modal", "#dashboard-main");
    });

    $(".unenroll").each(function(index){
      $(this).attr("id", "email-settings-" + index);
      // a bit of a hack, but gets the unique selector for the modal trigger
      var trigger = "#" + $(this).attr("id");
      accessible_modal(trigger, "#unenroll-modal .close-modal", "#unenroll-modal", "#dashboard-main");
    });
  });
  </script>
</%block>

% if reverifications["must_reverify"] or reverifications["denied"]:
  <section class="dashboard-banner">
    <%include file='dashboard/_dashboard_prompt_midcourse_reverify.html' />
  </section>
% endif

<section class="container dashboard" id="dashboard-main" aria-hidden="false">

  %if message:
    <section class="dashboard-banner">
      ${message}
    </section>
  %endif

  <section class="profile-sidebar">
    <header class="profile">
      <h1 class="user-name">${ user.username }</h1>
    </header>
    <section class="user-info">
      <ul>
        <li class="info--username">
          <span class="title"><div class="icon name-icon"></div>${_("Full Name")} (<a href="#apply_name_change" rel="leanModal" class="edit-name">${_("edit")}</a>)</span> <span class="data">${ user.profile.name | h }</span>
        </li>
        <li class="info--email">
          <span class="title"><div class="icon email-icon"></div>${_("Email")}
            % if external_auth_map is None or 'shib' not in external_auth_map.external_domain:
            (<a href="#change_email" rel="leanModal" class="edit-email">${_("edit")}</a>)
            % endif
          </span> <span class="data">${ user.email | h }</span>
        </li>

        %if len(language_options) > 1:
        <%include file='dashboard/_dashboard_info_language.html' />
        %endif

        % if external_auth_map is None or 'shib' not in external_auth_map.external_domain:
        <li class="controls--account">
          <span class="title"><div class="icon"></div><a href="#password_reset_complete" rel="leanModal" id="pwd_reset_button">${_("Reset Password")}</a></span>
          <form id="password_reset_form" method="post" data-remote="true" action="${reverse('password_reset')}">
            <input id="id_email" type="hidden" name="email" maxlength="75" value="${user.email}" />
            <!-- <input type="submit" id="pwd_reset_button" value="${_('Reset Password')}" /> -->
          </form>
        </li>
        % endif

        <%include file='dashboard/_dashboard_status_verification.html' />

        <%include file='dashboard/_dashboard_reverification_sidebar.html' />

      </ul>
    </section>

  </section>

  <section class="my-courses" id="my-courses">
    <header>
      <h2>${_("Current Courses")}</h2>
    </header>

    % if len(course_enrollment_pairs) > 0:
      <ul class="listing-courses">
        % for course, enrollment in course_enrollment_pairs:
            <% show_courseware_link = (course.id in show_courseware_links_for) %>
            <% cert_status = cert_statuses.get(course.id) %>
            <% show_email_settings = (course.id in show_email_settings_for) %>
            <% course_mode_info = all_course_modes.get(course.id) %>
            <% show_refund_option = (course.id in show_refund_option_for) %>
            <%include file='dashboard/_dashboard_course_listing.html' args="course=course, enrollment=enrollment, show_courseware_link=show_courseware_link, cert_status=cert_status, show_email_settings=show_email_settings, course_mode_info=course_mode_info, show_refund_option = show_refund_option" />
      % endfor

      </ul>
    % else:
      <section class="empty-dashboard-message">
        % if settings.FEATURES.get('COURSES_ARE_BROWSABLE'):
          <p>${_("Looks like you haven't registered for any courses yet.")}</p>
          <a href="${marketing_link('COURSES')}">
            ${_("Find courses now!")}
          </a>
        % else:
          <p>${_("Looks like you haven't been enrolled in any courses yet.")}</p>
        %endif
      </section>
    % endif

    % if staff_access and len(errored_courses) > 0:
      <div id="course-errors">
        <h2>${_("Course-loading errors")}</h2>

      % for course_dir, errors in errored_courses.items():
         <h3>${course_dir | h}</h3>
             <ul>
           % for (msg, err) in errors:
               <li>${msg}
                 <ul><li><pre>${err}</pre></li></ul>
               </li>
           % endfor
             </ul>
      % endfor
    % endif
  </section>
</section>

<section id="email-settings-modal" class="modal" aria-hidden="true">
  <div class="inner-wrapper" role="dialog" aria-labelledby="email-settings-title">
    <button class="close-modal">&#10005;
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_('Close Modal')}
      </span>
    </button>

    <header>
      <h2 id="email-settings-title">
        ${_('Email Settings for {course_number}').format(course_number='<span id="email_settings_course_number"></span>')}
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("modal open")}
        </span>
      </h2>
      <hr/>
    </header>

    <form id="email_settings_form" method="post">
      <input name="course_id" id="email_settings_course_id" type="hidden" />
      <label>${_("Receive course emails")} <input type="checkbox" id="receive_emails" name="receive_emails" /></label>
      <div class="submit">
        <input type="submit" id="submit" value="${_('Save Settings')}" />
      </div>
    </form>
  </div>
</section>



<section id="password_reset_complete" class="modal" aria-hidden="true">
  <div class="inner-wrapper" role="dialog" aria-labelledby="password-reset-email">
    <button class="close-modal">&#10005;
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_('Close Modal')}
      </span>
    </button>

    <header>
      <h2 id="password-reset-email">
        ${_('Password Reset Email Sent')}
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("modal open")}
        </span>
      </h2>
      <hr/>
    </header>
    <div>
      <form> <!-- Here for styling reasons -->
        <section>
          <p>${_('An email has been sent to {email}. Follow the link in the email to change your password.').format(email=user.email)}</p>
        </section>
      </form>
    </div>
  </div>
</section>

<section id="change_email" class="modal" aria-hidden="true">
  <div class="inner-wrapper" role="dialog" aria-labelledby="change_email_title">
    <button class="close-modal">&#10005;
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_('Close Modal')}
      </span>
    </button>

    <header>
      <h2>
        <span id="change_email_title">${_("Change Email")}</span>
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("modal open")}
        </span>
      </h2>
      <hr/>
    </header>
    <div id="change_email_body">
      <form id="change_email_form">
        <div id="change_email_error" class="modal-form-error"> </div>
        <fieldset>
          <div class="input-group">
            <label>${_('Please enter your new email address:')}</label>
            <input id="new_email_field" type="email" value="" />
            <label>${_('Please confirm your password:')}</label>
            <input id="new_email_password" value="" type="password" />
          </div>
          <section>
            <p>${_('We will send a confirmation to both {email} and your new email as part of the process.').format(email=user.email)}</p>
          </section>
          <div class="submit">
            <input type="submit" id="submit_email_change" value="${_('Change Email')}"/>
          </div>
        </fieldset>
      </form>
    </div>
  </div>
</section>

<%include file='modal/_modal-settings-language.html' />

<section id="apply_name_change" class="modal" aria-hidden="true">
  <div class="inner-wrapper" role="dialog" aria-labelledby="change-name-title">
    <button class="close-modal">&#10005;
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_('Close Modal')}
      </span>
    </button>

    <header>
      <h2 id="change-name-title">
        ${_("Change your name")}
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("modal open")}
        </span>
      </h2>
      <hr/>
    </header>
    <div id="change_name_body">
      <form id="change_name_form">
        <div id="change_name_error" class="modal-form-error"> </div>
        ## Translators: note that {platform} {cert_name_short} will look something like: "edX certificate". Please do not change the order of these placeholders.
        <p>${_("To uphold the credibility of your {platform} {cert_name_short}, all name changes will be logged and recorded.").format(platform=settings.PLATFORM_NAME, cert_name_short=cert_name_short)}</p>
        <br/>
        <fieldset>
          <div class="input-group">
            ## Translators: note that {platform} {cert_name_short} will look something like: "edX certificate". Please do not change the order of these placeholders.
            <label>${_("Enter your desired full name, as it will appear on your {platform} {cert_name_short}:").format(platform=settings.PLATFORM_NAME, cert_name_short=cert_name_short)}</label>
            <input id="new_name_field" value="" type="text" />
            <label>${_("Reason for name change:")}</label>
            <textarea id="name_rationale_field" value=""></textarea>
          </div>
          <div class="submit">
            <input type="submit" id="submit" value="${_('Change My Name')}">
          </div>
        </fieldset>
      </form>
    </div>
  </div>
</section>

<section id="unenroll-modal" class="modal unenroll-modal" aria-hidden="true">
  <div class="inner-wrapper" role="alertdialog" aria-labelledy="unenrollment-modal-title">
    <button class="close-modal">&#10005;
      <span class="sr">
        ## Translators: this is a control to allow users to exit out of this modal interface (a menu or piece of UI that takes the full focus of the screen)
        ${_('Close Modal')}
      </span>
    </button>

    <header>
      <h2 id="unenrollment-modal-title">
        ${_('<span id="track-info"></span> {course_number}?  <span id="refund-info"></span>').format(course_number='<span id="unenroll_course_number"></span>')}
        <span class="sr">,
          ## Translators: this text gives status on if the modal interface (a menu or piece of UI that takes the full focus of the screen) is open or not
          ${_("modal open")}
        </span>
      </h2>
      <hr/>
    </header>
    <div id="unenroll_error" class="modal-form-error"></div>
    <form id="unenroll_form" method="post" data-remote="true" action="${reverse('change_enrollment')}">
      <input name="course_id" id="unenroll_course_id" type="hidden" />
      <input name="enrollment_action" type="hidden" value="unenroll" />
      <div class="submit">
        <input name="submit" type="submit" value="${_('Unregister')}" />
      </div>
    </form>
  </div>
</section>
