<%! from django.utils.translation import ugettext as _ %>
<%page args="section_data"/>
<%include file="add_coupon_modal.html" args="section_data=section_data" />
<%include file="edit_coupon_modal.html" args="section_data=section_data" />
<%include file="set_course_mode_price_modal.html" args="section_data=section_data" />
<%include file="generate_registarion_codes_modal.html" args="section_data=section_data" />
<div class="ecommerce-wrapper">
   <h3 class="error-msgs" id="error-msg"></h3>
   <div id = "accordion">
      <div class="wrap">
         <h2>Registration Codes</h2>
         <div>
            <span class="code_tip">Click to generate Registration Codes
            <a id="registration_code_generation_link" href="#reg_code_generation_modal" class="add blue-button">Generate Registration Codes</a>
            </span>
            <p>Click to generate a CSV file of all Course Registrations Codes:</p>
            <p>
            <form action="${ section_data['get_registration_code_csv_url'] }" id="download_registration_codes" method="post">
               <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }">
               <input type="text" name="download_company_name" placeholder="Company Name (Optional)"/>
               <input type="submit" name="list-registration-codes-csv" value="${_("Download Registration Codes")}" data-csv="true">
            </form>
            </p>
            <p>Click to generate a CSV file of all Active Course Registrations Codes:</p>
            <p>
            <form action="${ section_data['active_registration_code_csv_url'] }" id="active_registration_codes" method="post">
               <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }">
               <input type="text" name="active_company_name" placeholder="Company Name (Optional)"/>
               <input type="submit" name="active-registration-codes-csv" value="${_("Active Registration Codes")}" data-csv="true">
            </form>
            </p>
            <p>Click to generate a CSV file of all Spent Course Registrations Codes:</p>
            <p>
            <form action="${ section_data['spent_registration_code_csv_url'] }" id="spent_registration_codes" method="post">
               <input type="hidden" name="csrfmiddlewaretoken" value="${ csrf_token }">
               <input type="text" name="spent_company_name" placeholder="Company Name (Optional)"/>
               <input type="submit" name="spent-registration-codes-csv" value="${_("Spent Registration Codes")}" data-csv="true">
            </form>
            </p>
         </div>
      </div>
      <!-- end wrap -->
      <div class="wrap">
         <h2>${_("Course Price")}</h2>
         <div>
            <span class="tip">${_("Course Price: ")}<span>$${section_data['course_price']}</span>
            %if section_data['access']['finance_admin'] is True:
            <a id="course_price_link" href="#set-course-mode-price-modal" rel="leanModal" class="add blue-button">+ Set Price</a>
            %endif
            </span>
         </div>
      </div>
      <!-- end wrap -->
      %if section_data['access']['finance_admin'] is True:
      <div class="wrap">
         <h2>${_("Transactions")}</h2>
         <div>
            %if section_data['total_amount'] is not None:
            <span>${_("Total Amount: ")}<span>$${section_data['total_amount']}</span></span>
            %endif

            <span class="csv_tip">${_("Click to generate a CSV file for all purchase transactions in this course")}
                <input class="add blue-button"  type="button" name="list-purchase-transaction-csv" value="${_("Download All e-Commerce Purchases")}" data-endpoint="${ section_data['get_purchase_transaction_url'] }" data-csv="true">
            </span>
         </div>
      </div><!-- end wrap -->
      <div class="wrap">
         <h2>${_("Sales")}</h2>
         <div>
            <span class="csv_tip">${_("Click to generate a CSV file for all sales records in this course")}
                <input type="button" class="add blue-button" name="list-sale-csv" value="${_("Download All e-Commerce Sales")}" data-endpoint="${ section_data['get_sale_records_url'] }" data-csv="true"></p></td>
            </span>
             <hr>
             <p>${_("Enter the invoice number to invalidate or re-validate sale")}</p>
            <span class="invalid_sale">
               <input type="number" id="invoice_number" placeholder= "${_("Enter Invoice Number")}"/>
               <input type="button" class="add blue-button" id="invalidate_invoice" value="${_("Invalidate Sale")}">
               <input type="button" class="add blue-button" id="re_validate_invoice" value="${_("Revalidate Sale")}">
            </span>

         </div>
      </div><!-- end wrap -->
      %endif
      <div class="wrap">
         <h2>${_("Coupons List")}</h2>
         <div>

            <span class="csv_tip">${_("Click to generate a CSV file of all Coupon Codes:")}
                <input class="add blue-button" type="button" name="download-coupon-codes-csv" value="${_("Download coupon codes")}" data-endpoint="${ section_data['download_coupon_codes_url'] }" data-csv="true">
            </span>

            <span class="tip">${_("Coupons Information")} <a id="add_coupon_link" href="#add-coupon-modal" rel="leanModal"
               class="add blue-button">${_("+ Add Coupon")}</a></span>
            <div class="wrapper-content wrapper">
               <section class="content">
                  %if len(section_data['coupons']):
                  <table class="coupons-table">
                     <thead>
                        <tr class="coupons-headings">
                           <th class="c_code">${_("Code")}</th>
                           <th class="c_dsc">${_("Description")}</th>
                           <th class="c_discount">${_("Discount (%)")}</th>
                           <th class="c_count">${_("Count")}</th>
                           <th class="c_action">${_("Actions")}</th>
                        </tr>
                     </thead>
                     <tbody>
                        %for coupon in section_data['coupons']:
                        %if coupon.is_active == False:
                        <tr class="coupons-items inactive_coupon">
                           %else:
                        <tr class="coupons-items">
                           %endif
                           <td>${coupon.code}</td>
                           <td>${coupon.description}</td>
                           <td>${coupon.percentage_discount}</td>
                           <td>
                              ${ coupon.couponredemption_set.all().count() }
                           </td>
                           <!--<td>${coupon.is_active}</td>-->
                           <td><a data-item-id="${coupon.id}" class='remove_coupon' href='#'>[x]</a><a href="#edit-modal" data-item-id="${coupon.id}" class="edit-right">Edit</a></td>
                        </tr>
                        %endfor
                     </tbody>
                  </table>
                  <a id="edit-modal-trigger" href="#edit-coupon-modal" rel="leanModal"></a>
                  <a id="registration_code_generation_link-trigger" href="#registration_code_generation_modal" rel="leanModal"></a>
                  %endif
               </section>
            </div>
         </div>
      </div>
      <!-- end wrap -->
   </div>
</div>
<script>

   $(function () {
       var icons = {
           header: "ui-icon-circle-arrow-e",
           activeHeader: "ui-icon-circle-arrow-s"
       };
       var act = 0;
       $("#accordion").accordion(
               {
                   heightStyle: 'content',
                   activate: function(event, ui) {
                    var active = jQuery("#accordion").accordion('option', 'active');
                    $.cookie('saved_index', null);
                    $.cookie('saved_index', active);
                    $('#error-msg').val('');
                    $("#error-msg").fadeOut(2000 , function(){
                        $('#error-msg').hide()
                    });
                   },
                   animate: 400,
                   header: "> div.wrap >h2",
                   icons:icons,
                   active:isNaN(parseInt($.cookie('saved_index'))) ? 0 : parseInt($.cookie('saved_index')),
                   collapsible: true
               });

     $('a[rel*=leanModal]').leanModal();
     $.each($("a.edit-right"), function () {
       if ($(this).parent().parent('tr').hasClass('inactive_coupon')) {
         $(this).removeAttr('href')
       }
     });
     $.each($("a.remove_coupon"), function () {
       if ($(this).parent().parent('tr').hasClass('inactive_coupon')) {
         $(this).removeAttr('href')
       }
     });
     $('#registration_code_generation_link').click(function(event){
         event.preventDefault();

         $.ajax({
         type: "POST",
         url: "${section_data['get_user_invoice_preference_url']}",
         success: function (data) {
             $('#invoice-copy').prop('checked', data.invoice_copy);
             $('#registration_code_generation_link-trigger').click();
           }
       });

     });
     $('#invalidate_invoice, #re_validate_invoice').click(function (event) {
         event.preventDefault();
         var event_type = "re_validate"
         if($(event.target).attr('id')=='invalidate_invoice'){
             event_type = "invalidate"
         }
         if($('#invoice_number').val() == "") {
                     $('#error-msg').attr('class','error-msgs')
                     $('#error-msg').html("${_("Invoice number should not be empty.")}").show();
                     return
         }
         $.ajax({
             type: "POST",
             data: {invoice_number: $('#invoice_number').val(), event_type:event_type},
             url: "${section_data['sale_validation_url']}",
             success: function (data) {
                 $('#error-msg').attr('class','success-msgs')
                 $('#error-msg').html(data.message).show();
                 $('#invoice_number').val('');
             },
             error: function(jqXHR, textStatus, errorThrown) {
                 $('#error-msg').attr('class','error-msgs')
                 $('#error-msg').html(jqXHR.responseText).show();
             }
         });
     });

     $('a.edit-right').click(function (event) {
       $('#edit_coupon_form #coupon_form_error').attr('style', 'display: none');
       $('#edit_coupon_form #coupon_form_error').text();
       event.preventDefault();
       event.stopPropagation();
       var coupon_id = $(this).data('item-id');
       $('#coupon_id').val(coupon_id);
       if ($(this).parent().parent('tr').hasClass('inactive_coupon')) {
         return false;
       }
       $.ajax({
         type: "POST",
         data: {id: coupon_id},
         url: "${section_data['ajax_get_coupon_info']}",
         success: function (data) {
             $('#error-msg').val('');
             $('#error-msg').hide()
             $('input#edit_coupon_code').val(data.coupon_code);
             $('input#edit_coupon_discount').val(data.coupon_discount);
             $('textarea#edit_coupon_description').val(data.coupon_description);
             $('input#edit_coupon_course_id').val(data.coupon_course_id);
             $('#edit-modal-trigger').click();
           },
         error: function(jqXHR, textStatus, errorThrown) {
           var data = $.parseJSON(jqXHR.responseText);
           $('#error-msg').attr('class','error-msgs')
           $('#error-msg').html(data.message).show();
         }
       });
     });
     $('a.remove_coupon').click(function (event) {
       var anchor = $(this);
       if (anchor.data("disabled")) {
         return false;
       }
       anchor.data("disabled", "disabled");
       event.preventDefault();
       if ($(this).parent().parent('tr').hasClass('inactive_coupon')) {
           return false;
       }
       $.ajax({
         type: "POST",
         data: {id: $(this).data('item-id')},
         url: "${section_data['ajax_remove_coupon_url']}",
         success: function (data) {
             anchor.removeData("disabled");
             location.reload(true);
           },
         error: function(jqXHR, textStatus, errorThrown) {
           var data = $.parseJSON(jqXHR.responseText);
           $('#error-msg').attr('class','error-msgs')
           $('#error-msg').html(data.message).show();
           anchor.removeData("disabled");
         }
       });
     });
     var generate_registration_code_form = $("form#generate_codes");
     var generate_registration_button = $('input[name="generate-registration-codes-csv"]');
     var registration_code_error = $('#generate_codes #registration_code_form_error');

     function validateEmail(sEmail) {
      filter = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/
      return filter.test(sEmail)
     }
     generate_registration_code_form.submit(function () {
      registration_code_error.attr('style', 'display: none');
      generate_registration_button.attr('disabled', true);
      var total_registration_codes = $('input[name="total_registration_codes"]').val();
      var recipient_name = $('input[name="recipient_name"]').val();
      var recipient_email = $('input[name="recipient_email"]').val();
      var sale_price = $('input[name="sale_price"]').val();
      var company_name = $('input[name="company_name"]').val();
      var company_contact_name = $('input[name="company_contact_name"]').val();
      var company_contact_email = $('input[name="company_contact_email"]').val();

      var address_line = $('input[name="address_line_1"]').val();

      if (company_name == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the company name');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (($.isNumeric(company_name))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the non-numeric value for company name');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (company_contact_name == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the company contact name');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (($.isNumeric(company_contact_name))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the non-numeric value for company contact name');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (company_contact_email == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the company contact email');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (!(validateEmail(company_contact_email))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the valid email address');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (recipient_name == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the recipient name');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (($.isNumeric(recipient_name))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the non-numeric value for recipient name');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (recipient_email == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the recipient email');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (!(validateEmail(recipient_email))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the valid email address');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (address_line == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the billing address');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      if (sale_price == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the sale price');
        generate_registration_button.removeAttr('disabled');
        return false
      }
      if (!($.isNumeric(sale_price))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the numeric value for sale price');
        generate_registration_button.removeAttr('disabled');
        return false
      }
      if (total_registration_codes == '') {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the total registration codes');
        generate_registration_button.removeAttr('disabled');
        return false
      }
      if (!($.isNumeric(total_registration_codes))) {
        registration_code_error.attr('style', 'display: block !important');
        registration_code_error.text('Please enter the numeric value for total registration codes');
        generate_registration_button.removeAttr('disabled');
        return false;
      }
      var modal_overLay = $('#lean_overlay')
      var registration_code_modal = $('#registration_code_generation_modal');
      registration_code_modal.hide();
      modal_overLay.hide();
     });

     $('#edit_coupon_form').submit(function () {
       $("#update_coupon_button").attr('disabled', true);
     });
     $('#course_price_link').click(function () {
       reset_input_fields();
     });
     $('#add_coupon_link').click(function () {
       reset_input_fields();
     });
      $('#registration_code_generation_link').click(function () {
        reset_input_fields();
        $('input[name="generate-registration-codes-csv"]').removeAttr('disabled');
     });
     $('#set_price_form').submit(function () {
       $("#set_course_button").attr('disabled', true);
       // Get the Code and Discount value and trim it
       var course_price = $.trim($('#mode_price').val());
       var currency = $.trim($('#course_mode_currency').val());

       // Check if empty of not
       if (course_price === '') {
         $('#set_price_form #course_form_error').attr('style', 'display: block !important');
         $('#set_price_form #course_form_error').text("${_('Please enter the course price')}");
         $("#set_course_button").removeAttr('disabled');
         return false;
       }
       if (!$.isNumeric(course_price)) {
         $("#set_course_button").removeAttr('disabled');
         $('#set_price_form #course_form_error').attr('style', 'display: block !important');
         $('#set_price_form #course_form_error').text("${_('Please enter the numeric value for course price')}");
         return false;
       }
       if (currency == '') {
         $('#set_price_form #course_form_error').attr('style', 'display: block !important');
         $('#set_price_form #course_form_error').text("${_('Please select the currency')}");
         $("#set_course_button").removeAttr('disabled');
         return false;
       }
     });
     $('#add_coupon_form').submit(function () {
       $("#add_coupon_button").attr('disabled', true);
       // Get the Code and Discount value and trim it
       var code = $.trim($('#coupon_code').val());
       var coupon_discount = $.trim($('#coupon_discount').val());

       // Check if empty of not
       if (code === '') {
         $("#add_coupon_button").removeAttr('disabled');
         $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important');
         $('#add_coupon_form #coupon_form_error').text("${_('Please enter the coupon code')}");
         return false;
       }
       if (coupon_discount == '0') {
         $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important');
         $('#add_coupon_form #coupon_form_error').text("${_('Please enter the coupon discount value greater than 0')}");
         $("#add_coupon_button").removeAttr('disabled');
         return false;
       }
       if (parseInt(coupon_discount) > 100) {
         $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important');
         $('#add_coupon_form #coupon_form_error').text("${_('Please enter the coupon discount value less than or equal to 100')}");
         $("#add_coupon_button").removeAttr('disabled');
         return false;
       }
       if (!$.isNumeric(coupon_discount)) {
         $("#add_coupon_button").removeAttr('disabled');
         $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important');
         $('#add_coupon_form #coupon_form_error').text("${_('Please enter the numeric value for discount')}");
         return false;
       }
     });

     $('#set_price_form').on('ajax:complete', function (event, xhr) {
       if (xhr.status == 200) {
         location.reload(true);
       } else {
         $("#set_course_button").removeAttr('disabled');
         $('#set_price_form #course_form_error').attr('style', 'display: block !important');
         $('#set_price_form #course_form_error').text(xhr.responseText);
       }
     });

     $('#add_coupon_form').on('ajax:complete', function (event, xhr) {
       if (xhr.status == 200) {
         location.reload(true);
       } else {
         $("#add_coupon_button").removeAttr('disabled');
         $('#add_coupon_form #coupon_form_error').attr('style', 'display: block !important');
         $('#add_coupon_form #coupon_form_error').text(xhr.responseText);
       }
     });

     $('#edit_coupon_form').on('ajax:complete', function (event, xhr) {
       if (xhr.status == 200) {
         location.reload(true);
       } else {
         $("#update_coupon_button").removeAttr('disabled');
         $('#edit_coupon_form #coupon_form_error').attr('style', 'display: block !important');
         $('#edit_coupon_form #coupon_form_error').text(xhr.responseText);
       }
     });
     // removing close link's default behavior
     $('.close-modal').click(function (e) {
       $("#update_coupon_button").removeAttr('disabled');
       $("#add_coupon_button").removeAttr('disabled');
       $("#set_course_button").removeAttr('disabled');
       $('input[name="generate-registration-codes-csv"]').removeAttr('disabled');
       reset_input_fields();
       e.preventDefault();
     });

     var onModalClose = function () {
       $("#add-coupon-modal").attr("aria-hidden", "true");
       $(".remove_coupon").focus();
       $("#edit-coupon-modal").attr("aria-hidden", "true");
       $(".edit-right").focus();
       $("#set-course-mode-price-modal").attr("aria-hidden", "true");
       $("#registration_code_generation_modal").attr("aria-hidden", "true");
       $("#add_coupon_button").removeAttr('disabled');
       $("#set_course_button").removeAttr('disabled');
       $("#update_coupon_button").removeAttr('disabled');
       $('input[name="generate-registration-codes-csv"]').removeAttr('disabled');
       reset_input_fields();
     };

     var cycle_modal_tab = function (from_element_name, to_element_name) {
       $(from_element_name).on('keydown', function (e) {
         var keyCode = e.keyCode || e.which;
         var TAB_KEY = 9;  // 9 corresponds to the tab key
         if (keyCode === TAB_KEY) {
           e.preventDefault();
           $(to_element_name).focus();
         }
       });
     };

     $("#add-coupon-modal .close-modal").click(onModalClose);
     $("#edit-coupon-modal .close-modal").click(onModalClose);
     $('#registration_code_generation_modal .close-modal').click(onModalClose);
     $("#set-course-mode-price-modal .close-modal").click(reset_input_fields);


     // Hitting the ESC key will exit the modal
     $("#add-coupon-modal, #edit-coupon-modal, #set-course-mode-price-modal, #registration_code_generation_modal").on("keydown", function (e) {
       var keyCode = e.keyCode || e.which;
       // 27 is the ESC key
       if (keyCode === 27) {
         e.preventDefault();
         $("#add-coupon-modal .close-modal").click();
         $("#set-course-mode-price-modal .close-modal").click();
         $("#edit-coupon-modal .close-modal").click();
         $('#registration_code_generation_modal .close-modal').click();
       }
     });
   });
   var reset_input_fields = function () {
     $('#error-msg').val('');
     $('#error-msg').hide()
     $('#add_coupon_form #coupon_form_error').attr('style', 'display: none');
     $('#set_price_form #course_form_error').attr('style', 'display: none');
     $('#generate_codes #registration_code_form_error').attr('style', 'display: none');
     $('#add_coupon_form #coupon_form_error').text();
     $('input#mode_price').val('');
     $('input#coupon_code').val('');
     $('input#coupon_discount').val('');
     $('textarea#coupon_description').val('');
     $('input[name="company_name"]').val('');
     $('input[name="total_registration_codes"]').val('');
     $('input[name="address_line_1"]').val('');
     $('input[name="address_line_2"]').val('');
     $('input[name="address_line_3"]').val('');
     $('input[name="city"]').val('');
     $('input[name="state"]').val('');
     $('input[name="zip"]').val('');
     $('input[name="country"]').val('');
     $('input[name="customer_reference_number"]').val('');
     $('input[name="recipient_name"]').val('');
     $('input[name="sale_price"]').val('');
     $('input[name="recipient_email"]').val('');
     $('input[name="company_contact_name"]').val('');
     $('input[name="company_contact_email"]').val('');
     $('input[name="invoice"]').attr('checked', 'checked');
     $('input[name="company_reference"]').val('');
     $('input[name="internal_reference"]').val('');
   }
</script>
