<%inherit file="main.html" />
<%namespace name="profile_graphs" file="profile_graphs.js"/>
<%namespace name="survey_fields" file="survey_fields.html"/>

<%block name="title"><title>Profile - MITx 6.002x</title></%block>

<%!
    from django.core.urlresolvers import reverse
    from django.conf import settings
%>

<%block name="headextra">
<script type="text/javascript" src="/static/js/flot/jquery.flot.js"></script>
<script type="text/javascript" src="/static/js/flot/jquery.flot.stack.js"></script>
<script type="text/javascript" src="/static/js/flot/jquery.flot.symbol.js"></script>
<script>
${profile_graphs.body(grade_sheet['grade_summary'], grade_cutoffs, "grade-detail-graph")}
</script>

<script>
var loc=true; // Activate on clicks? Not if already clicked.
var lang=true;
$(function() {
      $("#change_location").click(function() {
         $(this).hide();

         log_event("profile", {"type":"location_show", "old":$("#location_sub").text()});

         if(loc) {
           $("#description").html('<div>'+
                                  "Preferred format is city, state, country (so for us, "+
                                  "&quot;Cambridge, Massachusetts, USA&quot;), but give "+
                                  "as much or as little detail as you want. </div>");

           loc=false;

           $("#location_sub").html('<form>'+'<input id="id_loc_text" type="text" name="loc_text" />'+
             '<input type="submit" id="change_loc_button" value="Save" />'+'</form>');

           $("#change_loc_button").click(function() {
             $("#change_location").show();

              postJSON('/change_setting', {'location':$("#id_loc_text").attr("value")}, function(json) {
                $("#location_sub").text(json.location);
                loc=true;
                $("#description").html("");
               log_event("profile", {"type":"location_change", "new":json.location});
              });
           });
         }
      });

      $("#change_language").click(function() {
         $(this).hide();
         log_event("profile", {"type":"language_show", "old":$("#language_sub").text()});

         if(lang) {
           lang=false;
           $("#language_sub").html('<form>'+'<input id="id_lang_text" type="text" name="lang_text" />'+
             '<input type="submit" id="change_lang_button" value="Save" />'+'</form>');
           $("#change_lang_button").click(function() {
             $("#change_language").show();
              postJSON('/change_setting', {'language':$("#id_lang_text").attr("value")}, function(json) {
                $("#language_sub").text(json.language);
                lang=true;
                $("#description").html("");
               log_event("profile", {"type":"language_change", "new":json.language});
              });
           });
         }
      });

      $('#change_password').click(function(){
        $('.modal').trigger('click');
        log_event("profile", {"type":"password_show"});
      });

    $('#pwd_reset_button').click(function() {
      $.post('/password_reset/',{ "csrfmiddlewaretoken" : "${ csrf }",
                    "email"  : $('#id_email').val()}, function(data){
         $("#password_reset_complete_link").click();
         log_event("profile", {"type":"password_send"});
      });
    });


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

      postJSON('/change_email',{"new_email":new_email, 
                                "password":new_password},
               function(data){
          if(data.success){
          $("#change_email").html("<h1>Please verify your new email</h1><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);
          }
       });
       log_event("profile", {"type":"email_change_request", 
                               "old_email":"${email}",
                               "new_email":new_email});
       return false;
    });
    

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

      postJSON('/change_name',{"new_name":new_name, 
                                "rationale":rationale},
               function(data){
          if(data.success){
          $("#apply_name_change").html("<h1>Your request has been submitted.</h1><p>We'll send you an e-mail when approve the change or need further information. Please allow for up to a week for us to process your request.</p>");
          } else {
            $("#change_name_error").html(data.error);
          }
       });
       log_event("profile", {"type":"name_change_request", 
                               "new_name":new_name,
                               "rationale":rationale});
       return false;
    });
});
</script>
</%block>


<%include file="navigation.html" args="active_page='profile'" />

<section class="main-content">
  <div class="profile-wrapper">

    <section class="course-info">
      <header>
        <h1>Course Progress</h1>
      </header>

      %if settings.END_COURSE_ENABLED:
      <div id="grade">
        %if grade_sheet['grade']:
          <p>Final Grade: <strong>${grade_sheet['grade']}</strong></p>
          
          %if certificate_state['state'] == "requestable":
            <a class="cert_request_link" href="/certificate_request">Request Certificate</a>
          %elif certificate_state['state'] == "downloadable":
            %if certificate_state['download_url']:
              <a href="${certificate_state['download_url']}" target="_blank">Download Certificate</a>
            %endif
            %if certificate_state['graded_download_url']:
              <a href="${certificate_state['graded_download_url']}" target="_blank">Download Certificate (with Grade)</a>
            %endif
            
          %elif certificate_state['state'] == "generating":
            <a href="#">Certificate is being generated...</a>
          %else:
            <a href="#">No certificate available</a>
          %endif
          
        %else:
          <p> No letter grade has been earned for this course </p>
        %endif
        
        %if not took_survey:
          <a class="survey_link" href="/exit_survey">Take the survey</a>
        %endif
      </div>

      %endif

      <div id="grade-detail-graph"></div>

      <ol class="chapters">
        %for chapter in grade_sheet['courseware_summary']:
        %if not chapter['chapter'] == "hidden":
        <li>
          <h2><a href="${reverse('courseware_chapter', args=format_url_params([chapter['course'], chapter['chapter']])) }">
          ${ chapter['chapter'] }</a></h2>

          <ol class="sections">
            %for section in chapter['sections']:
            <li>
              <%
              earned = section['section_total'].earned
              total = section['section_total'].possible
              percentageString = "{0:.0%}".format( float(earned)/total) if earned > 0 and total > 0 else ""
              %>
              
              <h3><a href="${reverse('courseware_section', args=format_url_params([chapter['course'], chapter['chapter'], section['section']])) }">
                ${ section['section'] }</a> ${"({0:.3n}/{1:.3n}) {2}".format( float(earned), float(total), percentageString )}</h3>
              ${section['subtitle']}
              %if 'due' in section and section['due']!="":
                due ${section['due']}
              %endif
              
              %if len(section['scores']) > 0:
                <ol class="scores">
                  ${ "Problem Scores: " if section['graded'] else "Practice Scores: "}
                  %for score in section['scores']:
                    <li class="score">${"{0:.3n}/{1:.3n}".format(float(score.earned),float(score.possible))}</li>
                  %endfor
                </ol>
              %endif
              
            </li> <!--End section-->
            %endfor
          </ol> <!--End sections-->
        </li> <!--End chapter-->
        %endif
        %endfor
      </ol> <!--End chapters-->

    </section>

    <section class="user-info">

      <header>
        <h1>Student Profile</h1>
      </header>

      <ul>
        <li>
          Name: <strong>${name}</strong>
          %if True:
          <a href="#apply_name_change" rel="leanModal" class="name-edit">Edit</a>
          %else:
          (Name change pending)
          %endif
        </li>

        <li>
          Forum name: <strong>${username}</strong> 
        </li>

        <li>
          E-mail: <strong>${email}</strong> <a href="#change_email" rel="leanModal" class="edit-email">Edit</a>
        </li>
        <li>
          Location: <div id="location_sub">${location}</div><div id="description"></div> <a href="#" id="change_location">Edit</a>
        </li>
        <li>
          Language: <div id="language_sub">${language}</div> <a href="#" id="change_language">Edit</a>
        </li>
        <li>
          Password reset
          <input id="id_email" type="hidden" name="email" maxlength="75" value="${email}" />
          <input type="submit" id="pwd_reset_button" value="Reset" />
          <p>We'll e-mail a password reset link to ${email}.</p>
        </li>
      </ul>

    </section>
  </div>
</section>

<div id="password_reset_complete" class="leanModal_box">
  <a href="#password_reset_complete" rel="leanModal" id="password_reset_complete_link"></a>
  <h1>Password Reset Email Sent</h1>
  <p>
    An email has been sent to ${email}. Follow the link in the email to change your password.
  </p>
</div>

<div id="apply_name_change" class="leanModal_box">
  <h1>Apply to change your name</h1>
  <form id="change_name_form">
    <div id="change_name_error"> </div>
    <fieldset>
      <p>To uphold the credibility of MITx certificates, name changes must go through an approval process. A member of the course staff will review your request, and if approved, update your information. Please allow up to a week for your request to be processed. Thank you.</p> 
      <ul>
        <li>
          <label>Enter your desired full name, as it will appear on the MITx Certificate: </label>
          <input id="new_name_field" value="" type="text" />
        </li>
        <li>
          <label>Reason for name change:</label>
          <textarea id="name_rationale_field" value=""></textarea>
        </li>
        <li>
          <input type="submit" id="submit">
        </li>
      </ul>
    </fieldset>
  </form>
</div>

<div id="change_email" class="leanModal_box">
  <h1>Change e-mail</h1> 
  <div id="apply_name_change_error"></div>
  <form id="change_email_form">
    <div id="change_email_error"> </div>
    <fieldset>
      <ul>
        <li>
          <label> Please enter your new email address: </label>
          <input id="new_email_field" type="email" value="" />
        </li>

        <li>
          <label> Please confirm your password: </label>
          <input id="new_email_password" value="" type="password" />
        </li>
        <li>
          <p>We will send a confirmation to both ${email} and your new e-mail as part of the process.</p>
          <input type="submit" id="submit_email_change" />
        </li>
      </ul>
      </fieldset>
    </form>
</div>

<div id="deactivate-account" class="leanModal_box">
  <h1>Deactivate MITx Account</h1>
  <p>Once you deactivate you&rsquo;re MIT<em>x</em> account you will no longer recieve updates and new class announcements from MIT<em>x</em>.</p>
  <p>If you&rsquo;d like to still get updates and new class announcements you can just <a href="#unenroll" rel="leanModal">unenroll</a> and keep your account active.</p>

  <form id="unenroll_form">
    <div id="unenroll_error"> </div>
    <fieldset>
      <ul>
        <li>
          <input type="submit" id="" value="Yes, I don't want an MITx account or hear about any new classes or updates to MITx" />
        </li>
      </ul>
    </fieldset>
  </form>
</div>

<div id="unenroll" class="leanModal_box">
  <h1>Unenroll from 6.002x</h1>
  <p>Please note: you will still receive updates and new class announcements from MIT<em>x</em>. If you don&rsquo;t wish to receive any more updates or announcements <a href="#deactivate-account" rel="leanModal">deactivate your account</a>.</p>

  <form id="unenroll_form">
    <div id="unenroll_error"> </div>
    <fieldset>
      <ul>
        <li>
          <input type="submit" id="" value="Yes, I want to unenroll from 6.002x but still hear about any new classes or updates to MITx" />
        </li>
      </ul>
    </fieldset>
  </form>
</div>
