<%inherit file="shopping_cart_flow.html" />
<%block name="review_highlight">class="active"</%block>

<%!
from courseware.courses import course_image_url, get_course_about_section
from django.core.urlresolvers import reverse
from edxmako.shortcuts import marketing_link
from django.utils.translation import ugettext as _

%>

<%block name="custom_content">

<div class="container">
  % if shoppingcart_items:
        <%block name="billing_details_highlight">
         % if order.order_type == 'business':
            <li>${_('Billing Details')}</li>
         % endif
        </%block>
 <% discount_applied = False %>
  <section class="wrapper confirm-enrollment shopping-cart">
    % for item, course in shoppingcart_items:
       % if loop.index > 0 :
        <hr>
      %endif
     <div class="user-data">
      <div class="clearfix">
      <div class="image">

           <img style="width: 100%; height: 100%;" src="${course_image_url(course)}"
                alt="${course.display_number_with_default | h} ${get_course_about_section(course, 'title')} Cover Image" />

      </div>
      <div class="data-input">
        <h3>${_('Registration for:')} <span class="pull-right">${_('Course Dates:')}</span></h3>
        <h1>${ course.display_name }<span class="pull-right">${course.start_datetime_text()} -  ${course.end_datetime_text()}</span></h1>
        <hr />
        <div class="three-col">
            <div class="col-1">
                % if item.list_price != None:
                <% discount_applied = True %>
                <div class="price">${_('Price per student:')} <span class="line-through">  $${"{0:0.2f}".format(item.list_price)}</span></div>
                <div class="price green">${_('Discount Applied:')} <span>  $${"{0:0.2f}".format(item.unit_cost)} </span></div>
                % else:
                <div class="price">${_('Price per student:')} <span>  $${"{0:0.2f}".format(item.unit_cost)}</span></div>
                % endif
            </div>
            <div class="col-2">
              <div class="numbers-row">
                <label for="students">${_('Students:')}</label>
                <div class="counter">
                    <input maxlength="3" max="999" type="text" name="students" value="${item.qty}" id="${item.id}" >
                </div>
                <div class="inc button"><i class="icon-caret-up"><span>+</span></i></div><div class="dec button"><i class="icon-caret-down"></i></div>
                    <a name="updateBtn" class="updateBtn hidden" id="updateBtn-${item.id}" href="#">update</a>
                <span class="error-text hidden" id="students-${item.id}"></span>
            </div>
              </div>

            <div class="col-3 no-width">
               <a href="#" class="btn-remove" data-item-id="${item.id}"><i class="icon-remove-sign"></i></a>
            </div>
        </div>
      </div>
          </div>

  </div>
    % endfor
      <div class="discount">

          <div class="code-text">
           % if not discount_applied:
           <div class="code-input">
              <input type="text" placeholder="discount or activation code" id="input_code">
              <input type="submit" value="Apply" class="blue" id="submit-code">
              <span class="error-text hidden" id="code" ></span>
           </div>
           % else:
           <div class="code-applied">
              <span class="green"><i class="icon-ok"></i>${_('code has been applied')}</span>
              <input type="submit" value="Reset" class="blue-border" id="submit-reset-redemption">
           </div>
            %endif
              <span class="pull-right">${_('Total:')} <b id="total-amount">$${"{0:0.2f}".format(amount)} USD</b></span>
          </div>
      </div>
      <div class="col-two">
          <div class="col-2 relative">
             % if amount == 0:
                <input type="submit" value = "Register" id="register" >
             % elif item.order.order_type == 'business':
                <input type="submit" value = "Billing Details" id="billing-details"><i class="icon-caret-right"></i>
                <p>
                    ${_('After this purchase is complete, a receipt is generated with relative billing details and registration codes for students.')}
                </p>
             % else:
                ${form_html}
                <p>
                    ${_('After this purchase is complete,')}<br/><b>${order.user.username}</b>
                    ${_('will be enrolled in this course.')}
                </p>
             %endif
          </div>
      </div>
   </section>
    % else:
      <div class="empty-cart" >
        <h2>${_('Your Shopping cart is currently empty.')}</h2>
          <a href="${marketing_link('COURSES')}" class="blue">${_('View Courses')}</a>
      </div>
    % endif

</div>
</%block>
<script>
    $(function() {

        $('a.btn-remove').click(function(event) {
      event.preventDefault();
      var post_url = "${reverse('shoppingcart.views.remove_item')}";
      $.post(post_url, {id:$(this).data('item-id')})
        .always(function(data){
        location.reload(true);
      });
    });

   $('#submit-code').click(function(event){
      event.preventDefault();
      var post_url = "${reverse('shoppingcart.views.use_code')}";
      if($('#input_code').val() == "") {
        showErrorMsgs('Must enter a valid code','code');
        return;
      }
      $.post(post_url,{
                  "code" :  $('#input_code').val()
              }
      )
      .success(function(data) {
                  location.reload(true);
              })
      .error(function(data,status) {
                  if(status=="parsererror"){
                       location.reload(true);
                  }else{
                        showErrorMsgs(data.responseText, 'code')
                      }
              })
   });

   $('#submit-reset-redemption').click(function(event){
       event.preventDefault();
       var post_url = "${reverse('shoppingcart.views.reset_code_redemption')}";
       $.post(post_url)
       .success(function(data) {
                   location.reload(true);
              })
       .error(function(data,status) {
                   if(status=="parsererror"){
                       location.reload(true);
                  }else{
                        showErrorMsgs(data.responseText,'code')
                      }
               })
   });

   $('#register').click(function(event){
       event.preventDefault();
       var post_url = "${reverse('shoppingcart.views.register_courses')}";
       $.post(post_url)
       .success(function(data) {
                   window.location.href = "${reverse('dashboard')}";
               })
       .error(function(data,status) {
                   if(status=="parsererror"){
                       location.reload(true);
                   }else{
                        showErrorMsgs(data.responseText)
                      }
               })
   });

   $('#billing-details').click(function(event){
       event.preventDefault();
       location.href = "${reverse('shoppingcart.views.billing_details')}";
   });


 $(".button").on("click", function() {
     var studentField =  $(this).parent().find('input');
     var ItemId = studentField.attr('id');
     var $button = $(this);
     var oldValue = $button.parent().find("input").val();
     var newVal = 1; // initialize with 1.
     hideErrorMsg('students-'+ItemId);
     if ($.isNumeric(oldValue)){
         if ($button.text() == "+") {
             if(oldValue > 0){
                 newVal = parseFloat(oldValue) + 1;
                 if(newVal > 1000){
                     newVal = 1000;
                 }
             }
         } else {
     // Don't allow decrementing below one
     if (oldValue > 1) {
         newVal = parseFloat(oldValue) - 1;
     }
         }
     }
     $button.parent().find("input").val(newVal);
     $('#updateBtn-'+ItemId).removeClass('hidden');

 });

$('a[name="updateBtn"]').click(function(event) {
    var studentField =  $(this).parent().find('input');
    var number_of_students = studentField.val();
    var ItemId = studentField.attr('id');

    if($.isNumeric(number_of_students) && number_of_students > 0 ){
        hideErrorMsg('students-'+ItemId);
        update_user_cart(ItemId, number_of_students);
    }else{
        showErrorMsgs('quantity must be greater then 0.', 'students-'+ItemId);
    }
});

  function showErrorMsgs(msg, msg_area){

      $( "span.error-text#"+ msg_area +"" ).removeClass("hidden");
      $( "span.error-text#"+ msg_area +"" ).html(msg).show();

      if(msg_area=='code'){
        $("#input_code").addClass('error');
      }
  }

  function hideErrorMsg(msg_area){
      $( "span.error-text#"+ msg_area +"" ).addClass("hidden");
  }

  function update_user_cart(ItemId, number_of_students){
      var post_url = "${reverse('shoppingcart.views.update_user_cart')}";
      $.post(post_url, {
          ItemId:ItemId,
          qty:number_of_students
          }
      )
      .success(function(data) {
                    location.reload(true);
            })
      .error(function(data,status) {
                  location.reload(true);
              })
  }

$('input[name="students"]').on("click", function() {
    $('#updateBtn-'+this.id).removeClass('hidden');
});

// allowing user to enter numeric qty only.
  $("input[name=students]").keydown(function(event) {
      var eventDelete       = 46;
      var eventBackSpace    = 8;
      var eventLeftKey      = 37;
      var eventRightKey     = 39;
      var allowedEventCodes = [eventDelete, eventBackSpace, eventLeftKey, eventRightKey ];
      // Allow only backspace and delete
	  if (allowedEventCodes.indexOf(event.keyCode) > -1) {
          // let it happen, don't do anything
		}
      else {
	     /*
          Ensure that it is a number.
          KeyCode range 48 - 57 represents [0-9]
          KeyCode range 96 - 105 represents [numpad 0 - numpad 9]
         */
		if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105) ) {
            $('#updateBtn-'+this.id).removeClass('hidden');
        }else{
            event.preventDefault();
        }
	  }

	});
});
</script>
