(function( $ ) {
  'use strict';

  /**
  * All of the code for your admin-facing JavaScript source
  * should reside in this file.
  *
  * Note: It has been assumed you will write jQuery code here, so the
  * $ function reference has been prepared for usage within the scope
  * of this function.
  *
  * This enables you to define handlers, for when the DOM is ready:
  *
  * $(function() {
  *
  * });
  *
  * When the window is loaded:
  *
  * $( window ).load(function() {
  *
  * });
  *
  * ...and/or other possibilities.
  *
  * Ideally, it is not considered best practise to attach more than a
  * single DOM-ready or window-load handler for a particular page.
  * Although scripts in the WordPress core, Plugins and Themes may be
  * practising this, we should strive to set a better example in our own work.
  */
  $(function() {

    $('#radar_industry').multiSelect();
    $('#radar_function').multiSelect();
    $("#radar_id").live('change', function(el){
      $.ajax({
        url: ajaxurl,
        type: 'POST',
        data: {
          'action': 'esi_radar_ajax_action',
          'radar_id': $(this).val()
        },
        success:function(response) {
          var data = JSON.parse(response);

          $("#radar_industry").find("option:gt(0)").remove();
          $.each(data.industry, function(i, d){
            // $("#radar_industry").append($('<option>', {
            //   value: d.id,
            //   text: d.name
            // }));
            $('#radar_industry').multiSelect('addOption', { value: d.id, text: d.name, index: i });
          });


          $("#radar_function").find("option:gt(0)").remove();
          $.each(data.function, function(i, d){
            // $("#radar_function").append($('<option>', {
            //   value: d.id,
            //   text: d.name
            // }));
            $('#radar_function').multiSelect('addOption', { value: d.id, text: d.name, index: i });
          });

        },
        error: function(errorThrown){
          console.log(errorThrown);
        }
      });
    });


    $('#radar_industry').multiSelect();
    $('#radar_function').multiSelect();

    if($(".chosen-select")){
      $(".chosen-select").chosen({disable_search_threshold: 10, width: "350px"});
    }

    $('.esi-filter-entity').live('change', function(){
      var companyFilter = $(this).val();
      if( companyFilter != '' ){
        document.location.href = 'admin.php?page=esi-management-news'+companyFilter;
      }
    });

    $('#esi_form_entities_parents option').hide();
    //Set table item to update
    $('.thickbox').click(function(e) {
      $('#esi_form_entities_parents').prop('selectedIndex',0);;
      if($( this ).attr( "id" ) == 'esi_industry'){
        $('#esi_form_entities_parents option[data-type="industry"]').show();
        $('#esi_form_entities_parents option[data-type="function"]').hide();
      }else{
        $('#esi_form_entities_parents option[data-type="industry"]').hide();
        $('#esi_form_entities_parents option[data-type="function"]').show();
      }
      $('#esi_table').val($( this ).attr( "id" ));
      $('#esi_type').html($( this ).attr( "id" ).split("_")[1]);
    });

    // Save item
    $('#esi_form_entities').submit(function() {

      var data = $(this).serialize();
      jQuery.post(ajaxurl, data, function(response) {
        var data = JSON.parse(response);

        // Clean form
        $(':input','#esi_form_entities')
        .not(':button, :submit, :reset, :hidden')
        .val('');

        // Update selected list
        $('#'+data.table+'_table').append($('<option>', {
          value: data.id,
          text: data.name,
          'data-section':(data.parent)?data.parent.name:'top'
        }));

        // Update current item list
        if(data.parent == 0){
          $('#esi_form_entities_parents').append($('<option>', {
            value: data.parent,
            text: data.name
          }));
        }

        $(".tree-multiselect").remove();

        // Industry
        $("#esi_industry_table").append($("#esi_industry_table option").remove().sort(function(a, b) {
          var at = $(a).data('section'), bt = $(b).data('section');
          return (at > bt)?1:((at < bt)?-1:0);
        }));
        $("select#esi_industry_table").show();
        $("select#esi_industry_table").treeMultiselect({startCollapsed: false});

        // Function
        $("#esi_function_table").append($("#esi_function_table option").remove().sort(function(a, b) {
          var at = $(a).data('section'), bt = $(b).data('section');
          return (at > bt)?1:((at < bt)?-1:0);
        }));
        $("select#esi_function_table").show();
        $("select#esi_function_table").treeMultiselect({startCollapsed: false});

        tb_remove();
      });

      return false;
    });

    $('#esi_form_company').submit(function() {

      var data = $(this).serialize();
      jQuery.post(ajaxurl, data, function(response) {
        var data = JSON.parse(response);

        $('#company_id').append($('<option>', {
          value: data.id,
          text: data.name
        }));
        $('#company_id option:eq('+data.id+')').prop('selected', true);

        $('#company_id_investment').append($('<option>', {
          value: data.id,
          text: data.name
        }));
        $('#company_id_investment option:eq('+data.id+')').prop('selected', true);

        tb_remove();
      });

      return false;
    });

    $('#esi_form_media').submit(function() {

      var data = $(this).serialize();
      jQuery.post(ajaxurl, data, function(response) {
        var data = JSON.parse(response);

        $('#media_id').append($('<option>', {
          value: data.id,
          text: data.name
        }));
        $('#media_id option:eq('+data.id+')').prop('selected', true);

        tb_remove();
      });

      return false;
    });

    $('#esi_form_investment').submit(function() {

      var data = $(this).serialize();
      jQuery.post(ajaxurl, data, function(response) {
        var data = JSON.parse(response);
        $("#investment_id").val(data.id);

        var html = "<b>entity :</b> " + $("#company_id option:selected").text() + "<br>"
        + "<b>Investment type :</b> " + $("#investment_type_id option:selected").text() + "<br>"
        + "<b>Investor :</b>"
        + "entity 1<br>"
        + "<b>Amount :</b> " + data.amount + "<br>"
        + "<b>Date :</b> " + data.investment_date + "<br><br>";

        $(".investment-details").html(html);



        tb_remove();
      });

      return false;
    });

    $("select#esi_industry_table").treeMultiselect({startCollapsed: false});
    $("select#esi_function_table").treeMultiselect({startCollapsed: false});
  });

})( jQuery );
