<div class="dashboard-wrapper">
  <div class="main-container">
    <div class="row-fluid">
      <div class="span12">
        <div id="success" style="display: none;" class="alert alert-block alert-success fade in">
                <h4 class="alert-heading">
                  Success!
                </h4>
                <p>
                  Information successfully updated.
                </p>
              </div>
      </div>
    </div>
    <div class="row-fluid">
      <div class="span12">
        <div id="failure" style="display: none;" class="alert alert-block alert-error fade in">
                    <h4 class="alert-heading">
                      Error!
                    </h4>
                    <p>
                      Failed to update.
                    </p>
                  </div>
      </div>
    </div>
    <!-- Begin Row-Fluid for Inputs -->
    <div class="row-fluid">
        <div class="span9">
              <div class="widget">
                <div class="widget-header">
                  <div class="title">
                    <span class="fs1" aria-hidden="true" data-icon="&#xe08e;"></span> Direct Deposit
                  </div>
                </div>
                <div class="widget-body">
          <div class="row-fluid">
            <%= form_tag "#", {:class => "form-horizontal", :id => "bank_info_form" } do %>
              <!-- Begin inputs-->

                <div class="input-append">
                  <%= text_field_tag :bank_account_num, params[:bank_account_num], {:placeholder => "Bank Account Number"} %>
                  <span class="add-on">#</span>
                </div>

                <div class="input-append">
                  <%= text_field_tag :bank_routing_num, params[:bank_routing_num], {:placeholder => "Bank Routing Number"} %>
                  <span class="add-on">#</span>
                </div>


                    <div class="input-append">
                  <%= text_field_tag :dd_percent, params[:dd_percent], {:placeholder => "Percentage of Deposit"} %>
                            <span class="add-on">%</span>
                          </div>

              <!-- End Inputs -->
              <%= submit_tag "Submit", {:id => "dd_form_btn", :style => "margin-left: 10px;", :class => "btn btn-medium btn-primary"} %>
            <% end %>
            </div>
                </div>
              </div>
            </div>
    </div>
    <!-- End  Row-Fluid for Inputs-->

    <!-- ###################-->
    <!-- Begin Dynamic Table ColSpan Table -->
    <div class="row-fluid">
      <div class="span9">
        <div class="widget">

          <!-- Begin Widget Header-->
          <div class="widget-header">
            <div class="title">
              <span class="fs1" aria-hidden="true" data-icon="&#xe14a;"></span> Accounts
            </div>
          </div>
      <!-- End Widget Header-->
      <div class="widget-body">
        <div id="dt_example" class="example_alt_pagination">
          <table class="table table-condensed table-striped table-hover table-bordered pull-left" id="data_table">
            <thead>
              <tr>
                <th style="width:30%">
                  Encrypted Bank Account Number
            <%=link_to "#", { :style => "color:#AA6F93", :id => "encrypted_acct_question"} do %>
            <span class="box1">
                <span aria-hidden="true" class="icon-question"></span>
            </span>
            <% end %>
                </th>
                <th style="width:25%">
                  Bank Routing Number
                </th>
                <th style="width:20%">
                  Percentage of Deposit
                </th>
                <th style="width:25%">
                  Action
                </th>
              </tr>
            </thead>
            <tbody>

            </tbody>
          </table>
          <div class="clearfix">
          </div>
      </div>
      </div> <!-- end of widget body-->
      </div>
    </div>
   </div
    <!-- End Dynamic Table ColSpan Table -->
    <!-- ###################-->

    <!-- Begin Row-Fluid for Decryption Input -->
    <div class="row-fluid">
        <div class="span9">
              <div class="widget">
                <div class="widget-header">
                  <div class="title">
                    <span class="fs1" aria-hidden="true" data-icon="&#xe11b;"></span> Decrypt Bank Account Number
                  </div>
                </div>
                <div class="widget-body">
          <div class="row-fluid">
            <%= form_tag "#", {:class => "form-horizontal", :id => "decrypt_form" } do %>
              <!-- Begin inputs-->

                <div class="input-append">
                  <%= text_field_tag :value_to_decrypt, params[:value_to_decrypt], {:placeholder => "Bank Account Number"} %>
                  <span class="add-on">#</span>
                </div>

              <!-- End Inputs -->
              <%= submit_tag "Submit", {:id => "decrypt_btn", :style => "margin-left: 10px;", :class => "btn btn-medium btn-primary"} %>
            <% end %>
          </div>
                </div>
              </div>
            </div>
    </div>
    <!-- Row-Fluid for Decryption Input -->
  </div>
</div>

<%= javascript_include_tag "jquery.dataTables.min.js" %>

<script type="text/javascript">

/*
  buildDeleteLink accepts a direct deposit ID and builds a link that enables
  a user to delete that direct deposit entry
*/
function buildDeleteLink(dd_id){
  var link = '<a href="/users/' + '<%= current_user.id %>' + '/pay/'+ dd_id + '" data-method="delete" rel="nofollow" class="delete-row">' +
                              '<i class="icon-trash">'+
                              '</i></a>'
  return link
};

/*
  parseDirectDepositInfo accepts the response object and parses the JSON response, then
  populates the direct deposit data table.
*/
function parseDirectDepostInfo(response){
  var msg = jQuery.parseJSON(JSON.stringify(response));
   $.each(msg.user, function(index, val){
    $('#data_table').dataTable().fnAddData( [
        val.bank_account_num,
        val.bank_routing_num,
        val.percent_of_deposit,
          buildDeleteLink(val.id)
    ] );
  });

};

/*
  populateTable will first clear the existing dd table, then call the appropriate
  endpoint to retrieve direct deposit entries and finally, provide parseDirectDepositInfo
  with the response from the endpoint in order to populate the data table.
*/
function populateTable() {
  $('#data_table').dataTable().fnClearTable();
  $.ajax({
      url: <%= sanitize(user_pay_path(:format => "json", user_id: current_user.id, id: current_user.id).inspect) %>,
    type: "GET",
    success: function(response) {
    parseDirectDepostInfo(response);
    },
    error: function(event) {
    $('#failure').show(500).delay(1500).fadeOut();
    }
  });
};

/*
  createDataTable initializes the dd table as a datatable
*/
function createDataTable(){
  $('#data_table').dataTable({
      "sPaginationType": "full_numbers"
    });
};

/*
  This function doesn't really work right now but is supposed to offer the user a
  "delete confirmation" message
*/
$('.delete-row').click(function () {
        var conf = confirm('Continue delete?');
        if (conf) $(this).parents('tr').fadeOut(function () {
          $(this).remove();
        });
    return false;
});

/*
  decryptShow parses the json response from the application and then renders
  a decrypted version of the user's account number
*/
function decryptShow(response){
  var msg = jQuery.parseJSON(JSON.stringify(response));
  alert("Decrypted Account Number: " + msg.account_num);
};

/*
  This function overrides the decrypt buttons (submit button's) native behavior,
  allowing an ajax call to be made with the decrypt_form's inputs which is decrypted
  server side with a JSON response containing the decrypted value. The decrypted value is
  then passed to decryptShow();
*/
$("#decrypt_btn").click(function(event){
  var valuesToSubmit = $("#decrypt_form").serialize();
  event.preventDefault();
  $.ajax({
      url: <%= sanitize(decrypted_bank_acct_num_user_pay_index_path(:format => "json", user_id: current_user.id).inspect) %>,
    data: valuesToSubmit,
    type: "POST",
    success: function(response) {
    $('#success').show(500).delay(1500).fadeOut();
    decryptShow(response);
    },
    error: function(event) {
    $('#failure').show(500).delay(1500).fadeOut();
    }
  });
});

/*
  This function overrides the dd_form_btn's native behavior in order to submit an ajax request
  that updates the user's direct deposit information. Upon success, the populateTable() function
  is called in order to update the dataTable on the page to reflect the latest entry.
*/
$("#dd_form_btn").click(function(event) {
     var valuesToSubmit = $("#bank_info_form").serialize();
     event.preventDefault();
     $.ajax({
      url: <%= sanitize(update_dd_info_user_pay_index_path(:format => "json").inspect) %>,
    data: valuesToSubmit,
    type: "POST",
    success: function(response) {
    $('#success').show(500).delay(1500).fadeOut();
    populateTable();
    },
    error: function(event) {
    $('#failure').show(500).delay(1500).fadeOut();
    }
  });
 });

$("#encrypted_acct_question").click(function(event) {
  event.preventDefault();
  alert("For your safety your account number is stored encrypted as well as presented to you \nin an encrypted form.\n\n" +
       "For your convenience, you can decrypt your bank account number at any time using our\n" +
       "conveniently located decryption function."
    )
});

/*
  Make the sidebar element "Pay" active.
*/
function makeActive(){
  $('li[id="pay"]').addClass('active');
};

/*
  1) makeActive - Adds the active class to the sidebar element
  2) createDataTable - Initializes the dataTable as such
  3) populateTable - populates the newly initialized dataTable
*/
$(document).ready(
   makeActive,
   createDataTable(),
   populateTable()
 )

</script>
