open_window = function(base_url, object_pk, object_name) {
  var url = base_url + object_pk + '/';
  var current_url = window.location;
  var object_key = object_name + '_id';
  if (window.location.href == window.location.origin + base_url + '?'+ object_key + '=' + object_pk) {
    // remove <object_name>_id from url on modal close if direct access to an object
    window.history.pushState({}, 'no ' + object_name, base_url);
  }
  $.get(url, function(response) {
    var $dialog = $(response).dialog({
      modal: true,
      width: 'auto',
      open: function(event, ui) {
        window.history.pushState({object_key: object_pk}, object_name + ' id', base_url + '?' + object_key + '=' + object_pk);
      },
      close: function (event, ui) {
        window.history.back();
      }
    });
  });
};

open_log_window = function(base_url, log_pk) {
  open_window(base_url, log_pk, 'log');
};

open_job_window = function(base_url, job_pk) {
  open_window(base_url, job_pk, 'job');
};

$(function() {
  $('#panel-logs tbody tr, #logs tbody tr').on('click', function() {
    var base_url = $(this).parents('table.main').data('log-base-url');
    var log_pk = $(this).data('pk');
    open_log_window(base_url, log_pk);
  });
  $('#panel-jobs tbody tr, #jobs tbody tr').on('click', function() {
    var base_url = $(this).parents('table.main').data('job-base-url');
    var job_pk = $(this).data('pk');
    open_job_window(base_url, job_pk);
  });

  /* keep title/slug in sync,
     this code comes from wcs/qommon/static/js/qommon.admin.js
  */
  $('body').delegate('input[data-slug-sync]', 'input change paste',
        function() {
          var $slug_field = $(this).parents('form').find('[name=' + $(this).data('slug-sync') + ']');
          $slug_field.val($.slugify($(this).val()));
        });

  $('.toggler').on('click', function() {
    $(this).parent().toggleClass('toggled');
  });

  if ($('#add-computed-property-form').length) {
    var property_forms = $('.computed-property-form');
    var total_form = $('#id_form-TOTAL_FORMS');
    var form_num = property_forms.length - 1;
    $('#add-computed-property-form').on('click', function() {
      var new_form = $(property_forms[0]).clone();
      var form_regex = RegExp(`form-(\\d){1}-`,'g');
      form_num++;
      new_form.html(new_form.html().replace(form_regex, `form-${form_num}-`));
      new_form.appendTo('#computed-property-forms tbody');
      $('#id_form-' + form_num + '-key').val('');
      $('#id_form-' + form_num + '-value').val('');
      total_form.val(form_num + 1);
    })
  }
});
