<%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 class="billing">${_('Billing Details')}</li>
         % else:
            <li class="billing hidden">${_('Billing Details')}</li>
         % endif
        </%block>

     % if is_course_enrollment_closed:
      <p id="expiry-msg">${_('{course_names} has been removed because the enrollment period has closed.').format(course_names=appended_expired_course_names)}</p>
     % endif:
 <%
    discount_applied = False
    order_type = 'personal'
 %>

  <section class="wrapper confirm-enrollment shopping-cart cart-view">
    % for item, course in shoppingcart_items:
       % if loop.index > 0 :
        <hr>
      %endif
      % if item.order.order_type == 'business':
       <% order_type = 'business' %>
      %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 }</h1><span class="pull-right">${course.start_datetime_text()} -  ${course.end_datetime_text()}</span>
        <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">  ${currency_symbol}${"{0:0.2f}".format(item.list_price)}</span></div>
                <div class="price green">${_('Discount Applied:')} <span>  ${currency_symbol}${"{0:0.2f}".format(item.unit_cost)} </span></div>
                % else:
                <div class="price">${_('Price per student:')} <span>  ${currency_symbol}${"{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" title="Input qty and press enter." max="999" type="text" name="students" value="${item.qty}" id="${item.id}" data-unit-cost="${item.unit_cost}" data-qty="${item.qty}">
                </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">
               <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" data-amount="${'{0:0.2f}'.format(amount)}">${currency_symbol}${"{0:0.2f}".format(amount)} ${currency.upper()}</b></span>
          </div>
      </div>
      <div class="col-two">
          <div class="col-2 relative">
             % if amount == 0:
                <input type="submit" value = "Register" id="register" >
             % elif order_type == 'business':
              <div name="billing">
                  <input type="submit" value = "Billing Details" name="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>
              </div>
               <div name="payment" class="hidden">
                ${form_html}
                <p>
                    ${_('After this purchase is complete,')}<br/><b>${order.user.username}</b>
                    ${_('will be enrolled in this course.')}
                </p>
              </div>
             % else:
              <div name="payment">
                ${form_html}
                <p>
                    ${_('After this purchase is complete,')}<br/><b>${order.user.username}</b>
                    ${_('will be enrolled in this course.')}
                </p>
              </div>
              <div name="billing" class="hidden">
                  <input type="submit" value = "Billing Details" name="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>
              </div>
             %endif
          </div>
      </div>
   </section>
    % else:
      <div class="empty-cart" >
        <h2>${_('Your Shopping cart is currently empty.')}</h2>
        % if is_course_enrollment_closed:
          <p>${_('{course_names} has been removed because the enrollment period has closed.').format(course_names=appended_expired_course_names)}</p>
        % endif
        <a href="${marketing_link('COURSES')}" class="blue">${_('View Courses')}</a>
      </div>
    % endif

</div>
</%block>
<script>
    $(function() {
        var isSpinnerBtnEnabled = true;
        var prevQty = 0;

      $('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)
                      }
               })
   });

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


 $(".button").on("click", function() {
     if(isSpinnerBtnEnabled){
         var isBusinessType = false;
         var wasBusinessType = false;
         var studentField =  $(this).parent().find("input[type='text']");
         var unit_cost = parseFloat(studentField.data('unit-cost'));
         var ItemId = studentField.attr('id');

         var $button = $(this);
         var oldValue =   $("#"+ItemId).data('qty');
         var newVal = 1; // initialize with 1.
         oldValue = parseFloat(oldValue);
         hideErrorMsg('students-'+ItemId);
         if ($.isNumeric(oldValue)){
             if ($button.text() == "+") {
                 if(oldValue > 0){
                     newVal = oldValue + 1;
                     if(newVal > 1000){
                         newVal = 1000;
                     }
                 }
             }
             else {
                 // Don't allow decrementing below one
                 if (oldValue > 1) {
                     newVal = oldValue - 1;
                 }
             }
         }

         wasBusinessType = getBusinessType();
         $button.parent().find("input").val(newVal);
         isBusinessType = getBusinessType();
         update_user_cart(ItemId, newVal, oldValue, unit_cost, wasBusinessType, isBusinessType);
         $("#"+ItemId).data('qty', newVal);
     }
 });

  function getBusinessType(){
      var isTypeBusiness = false;
      var elements = $('.numbers-row').find("input[type='text']");
      elements.each(function(index){
          if(this.value > 1){
              isTypeBusiness = true;
          }
      });
      return isTypeBusiness;
  }

  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 getNewTotal(prevQty, newQty, unit_cost, prevTotal){

      var prevQty   = parseInt(prevQty);
      var newQty    = parseInt(newQty);
      var unit_cost = parseFloat(unit_cost);

      return (( newQty - prevQty ) * unit_cost + prevTotal)
  }

  function update_user_cart(ItemId, newQty, prevQty, unit_cost, wasbusinessType, isbusinessType){

      var post_url = "${reverse('shoppingcart.views.update_user_cart')}";
      var typeChanged = false;
      var prevTotal = $('#total-amount').data('amount')
      var newTotal = getNewTotal(prevQty, newQty, unit_cost, prevTotal);
      $('#total-amount').html('$'+newTotal.toFixed(2)+' USD');
      $('#total-amount').data('amount', newTotal);

      if(isbusinessType != wasbusinessType){
          isSpinnerBtnEnabled = false;
          typeChanged = true;
          $('html').css({'cursor':'wait'});
          $(".button").css({'cursor':'wait'});
          $('.col-2.relative').find("input[type='submit']").attr('disabled', true);
      }



      $.post(post_url, {
          ItemId:ItemId,
          qty:newQty
          }
      )
      .success(function(data) {
                  var prevTotal = data['total_cost'];
                  $('html').css({'cursor':'default'});
                  $(".button").css({'cursor':'default'});
                  if(typeChanged){
                      var submit_button = $('.col-2.relative').find("input[type='submit']")
                      submit_button.removeAttr('disabled');
                      for (var i = 0; i< data['oldToNewIdMap'].length; i++) {
                          $('#'+data['oldToNewIdMap'][i]['oldId']+'').attr('id',data['oldToNewIdMap'][i]['newId']);
                          $('a.btn-remove[data-item-id]=' +data['oldToNewIdMap'][i]['oldId']+'').data('item-id', data['oldToNewIdMap'][i]['newId']);
                      }
                      if(isbusinessType){
                          $( "div[name='payment']").addClass('hidden');
                          $( "div[name='billing']").removeClass('hidden');
                          $('li.billing').removeClass('hidden');

                      }else{
                          $( "div[name='payment']").removeClass('hidden');
                          $( "div[name='billing']").addClass('hidden');
                          $('li.billing').addClass('hidden');
                      }

//                      $('#total-amount').html('$'+data['total_cost'].toFixed(2)+' USD');
                      isSpinnerBtnEnabled = true;
                  }

            })
      .error(function(data,status) {
                  location.reload(true);
              })
  }

  $("input[name=students]").keyup(function(event) {
      var eventEnter        = 13;
      if(event.keyCode == eventEnter){

         updateTextFieldQty(event);
      }
      else{
           event.preventDefault();
       }
  });

  function updateTextFieldQty(event){

      if(isSpinnerBtnEnabled){
          var itemId = event.currentTarget.id;
          var prevQty = $("#"+itemId).data('qty');
          var newQty = event.currentTarget.value;
          var unitCost = event.currentTarget.dataset.unitCost;
          var isBusinessType = getBusinessType();

          var wasBusinessType = !isBusinessType;
          isSpinnerBtnEnabled = false;
          update_user_cart(itemId, newQty, prevQty, unitCost, wasBusinessType, isBusinessType);
          $("#"+itemId).data('qty', newQty);

      }
  }

  $("input[name=students]").focusout(function(event) {
      updateTextFieldQty(event);
  });

// allowing user to enter numeric qty only.
  $("input[name=students]").keydown(function(event) {
      if(isSpinnerBtnEnabled){
          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) ) {

            }
            else{
                event.preventDefault();
            }
          }
      }
      else{
          event.preventDefault();
      }

	});
});
</script>
