(function($) {
  $(document).ready(function() {
    // -- for feeds --
    $('.edit-feed-row').click(function() {
      var placeholder = $('.inline-edit-feed-form');
      var fid = $(this).data('id');
      var parentTr = $(this).closest('tr');
      parentTr
        .addClass('hidden')
        .after(
          "<tr class='quick-edit-form'><td colspan='4'>" +
            placeholder.html() +
            '</td></tr>',
        );
      var addedTr = parentTr.next();

      // need to edit things below
      addedTr.find("[name='id']").val(fid);
      addedTr.find("[name='url']").val(
        parentTr
          .find('.column-url > div:first-child')
          .text()
          .trim(),
      );
      addedTr.find("[name='contentType']").val(
        parentTr
          .find('.column-contentType')
          .text()
          .trim(),
      );
      addedTr
        .find("[name='titlesetId']")
        .val(parentTr.find('.column-titlesetId span').data('titleset-id'));
      addedTr
        .find("[name='ioId']")
        .val(parentTr.find('.column-ioId span').data('io-id'));
    });

    $(document).on('click', '.inline-edit-cancel', function() {
      var form = $(this).closest('.quick-edit-form');
      form.prev().removeClass('hidden');
      form.remove();
    });

    $(document).on('click', '.inline-edit-feed-update', function() {
      var form = $(this).closest('.quick-edit-form');
      var backend = $('#inline-edit-link').data('url');
      var originalTr = form.prev();

      // need to edit these
      var data = {
        id: form.find("[name='id']").val(),
        url: form.find("[name='url']").val(),
        contentType: form.find("[name='contentType']").val(),
        titlesetId: form.find("[name='titlesetId']").val(),
        ioId: form.find("[name='ioId']").val(),
        target: 'smfeeds',
      };

      $.ajax({
        type: 'POST',
        url: backend,
        data: data,
        success: function(res) {
          originalTr.find('.column-url > div:first-child').text(data.url);
          originalTr.find('.column-contentType').text(data.contentType);

          originalTr
            .find('.column-titlesetId span')
            .text(
              form.find("select[name='titlesetId'] option:selected").text(),
            );
          originalTr
            .find('.column-ioId span')
            .text(form.find("select[name='ioId'] option:selected").text());

          originalTr.removeClass('hidden');
          form.remove();
        },
      }).fail(function(err) {
        alert('Error occured. Try again later.');
        console.log(err);
      });
    });

    $('.delete-feed-row').click(function() {
      var backend = $('#inline-edit-link').data('url');
      var parentTr = $(this).closest('tr');
      var fid = $(this).data('id');
      parentTr.attr('disabled', 'disabled');
      $.ajax(backend + '?delete=1&target=smfeeds&id=' + fid)
        .then(res => {
          parentTr.fadeOut(400, function() {
            parentTr.remove();
          });
        })
        .fail(err => {
          alert('Error occured. Try again later.');
          console.log(err);
        });
    });

    // -- --
    $(document).on('click', '.add-more-title', function() {
      var newId =
        $(this)
          .closest('table')
          .find('tr').length - 1;

      $(this)
        .closest('tr')
        .before(
          '<tr><td></td><td>\
        <input type="text" name="title[' +
            newId +
            ']" size="50">\
        <a href="#" class="delete-title">&times;</a>\
        </td></tr>',
        );
    });

    $(document).on('click', '.delete-title', function() {
      if (
        $(this)
          .closest('table')
          .find('tr').length > 3
      ) {
        $(this)
          .closest('tr')
          .remove();
      }
    });

    // ---------------------- tts ------------------------
    $('.edit-tts-row').click(function() {
      var placeholder = $('.inline-edit-tts-form');
      var fid = $(this).data('id');
      var parentTr = $(this).closest('tr');
      parentTr
        .addClass('hidden')
        .after(
          "<tr class='quick-edit-form'><td colspan='3'>" +
            placeholder.html() +
            '</td></tr>',
        );
      var addedTr = parentTr.next();

      // need to edit things below
      addedTr.find("[name='id']").val(fid);
      addedTr.find("[name='setname']").val(
        parentTr
          .find('.column-setname > div:first-child')
          .text()
          .trim(),
      );

      var titles = parentTr.find('.column-title div');
      for (var i = 0; i < titles.length; i++) {
        if (i === 0) {
          addedTr.find("[name='title[0]']").val($(titles[i]).text());
          continue;
        }
        addedTr
          .find('.add-more-title')
          .closest('tr')
          .before(
            '<tr><td></td><td>\
          <input type="text" name="title[' +
              i +
              ']" size="50">\
          <a href="#" class="delete-title">&times;</a>\
          </td></tr>',
          );
        addedTr.find("[name='title[" + i + "]']").val($(titles[i]).text());
      }
    });

    $(document).on('click', '.inline-edit-tts-update', function() {
      var form = $(this).closest('.quick-edit-form');
      var backend = $('#inline-edit-tts').data('url');
      var originalTr = form.prev();

      // need to edit these
      var data = {
        id: form.find("[name='id']").val(),
        setname: form.find("[name='setname']").val(),
        target: 'smtitlesets',
        title: [],
      };

      $.each(form.find('input'), function(key, obj) {
        var name = $(obj).attr('name');
        if (name.indexOf('title') === 0) {
          data.title.push($(obj).val());
        }
      });

      $.ajax({
        type: 'POST',
        url: backend,
        data: data,
        success: function(res) {
          originalTr
            .find('.column-setname > div:first-child')
            .text(data.setname);
          originalTr.find('.column-title').empty();
          $.each(data.title, function(key, val) {
            originalTr.find('.column-title').append('<div>' + val + '</div>');
          });

          originalTr.removeClass('hidden');
          form.remove();
        },
      }).fail(function(err) {
        alert('Error occured. Try again later.');
        console.log(err);
      });
    });

    $('.delete-tts-row').click(function() {
      var backend = $('#inline-edit-tts').data('url');
      var parentTr = $(this).closest('tr');
      var fid = $(this).data('id');
      parentTr.attr('disabled', 'disabled');
      $.ajax(backend + '?delete=1&target=smtitlesets&id=' + fid)
        .then(res => {
          parentTr.fadeOut(400, function() {
            parentTr.remove();
          });
        })
        .fail(err => {
          alert('Error occured. Try again later.');
          console.log(err);
        });
    });

    $('input[name=smAddFeed]').on('click', function(e) {
      var url = $(this)
        .closest('table')
        .find('input[name=feedurl]')
        .val()
        .trim();

      if (url === '') {
        $(this)
          .closest('table')
          .find('input[name=feedurl]')
          .focus();
        e.preventDefault();
        e.stopPropagation();
        return false;
      }
      var contentType = $(this)
        .closest('table')
        .find('select[name=content-type]')
        .val();
      var titleset = $(this)
        .closest('table')
        .find('select[name=titlesetId]')
        .val();

      if (
        contentType === 'facebook-fan-page' ||
        contentType === 'instagram-account'
      ) {
        if (titleset == 0) {
          alert('You cannot use title from feed. Select a title set');
          e.preventDefault();
          e.stopPropagation();
          return false;
        }
      }
    });

    // --------------- ios -----------------
    $('.edit-ios-row').click(function() {
      var placeholder = $('.inline-edit-ios-form');
      var fid = $(this).data('id');
      var parentTr = $(this).closest('tr');
      parentTr
        .addClass('hidden')
        .after(
          "<tr class='quick-edit-form'><td colspan='3'>" +
            placeholder.html() +
            '</td></tr>',
        );
      var addedTr = parentTr.next();

      // need to edit things below
      addedTr.find("[name='id']").val(fid);
      addedTr.find("[name='setname']").val(
        parentTr
          .find('.column-setname > div:first-child')
          .text()
          .trim(),
      );
      addedTr.find("[name='intro']").val(
        parentTr
          .find('.column-intro')
          .text()
          .trim(),
      );
      addedTr.find("[name='outro']").val(
        parentTr
          .find('.column-outro')
          .text()
          .trim(),
      );
    });

    $(document).on('click', '.inline-edit-ios-update', function() {
      var form = $(this).closest('.quick-edit-form');
      var backend = $('#inline-edit-ios').data('url');
      var originalTr = form.prev();

      // need to edit these
      var data = {
        id: form.find("[name='id']").val(),
        setname: form.find("[name='setname']").val(),
        intro: form.find("[name='intro']").val(),
        outro: form.find("[name='outro']").val(),
        target: 'smintrosoutros',
      };

      $.ajax({
        type: 'POST',
        url: backend,
        data: data,
        success: function(res) {
          originalTr
            .find('.column-setname > div:first-child')
            .text(data.setname);
          originalTr.find('.column-intro').text(data.intro);
          originalTr.find('.column-outro').text(data.outro);

          originalTr.removeClass('hidden');
          form.remove();
        },
      }).fail(function(err) {
        alert('Error occured. Try again later.');
        console.log(err);
      });
    });

    $('.delete-ios-row').click(function() {
      var backend = $('#inline-edit-ios').data('url');
      var parentTr = $(this).closest('tr');
      var fid = $(this).data('id');
      parentTr.attr('disabled', 'disabled');
      $.ajax(backend + '?delete=1&target=smintrosoutros&id=' + fid)
        .then(res => {
          parentTr.fadeOut(400, function() {
            parentTr.remove();
          });
        })
        .fail(err => {
          alert('Error occured. Try again later.');
          console.log(err);
        });
    });

    // --------------- custom -----------------
    $('.edit-custom-row').click(function() {
      var placeholder = $('.inline-edit-custom-form');
      var fid = $(this).data('id');
      var parentTr = $(this).closest('tr');
      parentTr
        .addClass('hidden')
        .after(
          "<tr class='quick-edit-form'><td colspan='3'>" +
            placeholder.html() +
            '</td></tr>',
        );
      var addedTr = parentTr.next();

      // need to edit things below
      addedTr.find("[name='id']").val(fid);
      addedTr.find("[name='headline']").val(
        parentTr
          .find('.column-headline > div:first-child')
          .text()
          .trim(),
      );
      addedTr.find("[name='message']").val(
        parentTr
          .find('.column-message')
          .text()
          .trim(),
      );
      addedTr.find("[name='url']").val(
        parentTr
          .find('.column-url')
          .text()
          .trim(),
      );

      addedTr
        .find("[name='image']")
        .val(parentTr.find('.column-image img').attr('src'));
    });

    $(document).on('click', '.inline-edit-custom-update', function() {
      var form = $(this).closest('.quick-edit-form');
      var backend = $('#inline-edit-custom').data('url');
      var originalTr = form.prev();

      // need to edit these
      var data = {
        id: form.find("[name='id']").val(),
        headline: form.find("[name='headline']").val(),
        message: form.find("[name='message']").val(),
        url: form.find("[name='url']").val(),
        image: form.find("[name='image']").val(),
        target: 'smcustom',
      };

      $.ajax({
        type: 'POST',
        url: backend,
        data: data,
        success: function(res) {
          originalTr
            .find('.column-headline > div:first-child')
            .text(data.headline);
          originalTr.find('.column-message').text(data.message);
          originalTr.find('.column-url').text(data.url);
          originalTr.find('.column-image img').attr('src', data.image);

          originalTr.removeClass('hidden');
          form.remove();
        },
      }).fail(function(err) {
        alert('Error occured. Try again later.');
        console.log(err);
      });
    });

    $('.delete-custom-row').click(function() {
      var backend = $('#inline-edit-custom').data('url');
      var parentTr = $(this).closest('tr');
      var fid = $(this).data('id');
      parentTr.attr('disabled', 'disabled');
      $.ajax(backend + '?delete=1&target=smcustom&id=' + fid)
        .then(res => {
          parentTr.fadeOut(400, function() {
            parentTr.remove();
          });
        })
        .fail(err => {
          alert('Error occured. Try again later.');
          console.log(err);
        });
    });
  });
})(jQuery);
