/* makes sure javascript loading is not interrupted by ckeditor jquery adapter
 * throwing an error about the environment being incompatible. */
CKEDITOR.env.origIsCompatible = CKEDITOR.env.isCompatible;
CKEDITOR.env.isCompatible = true;

$(document).ready( function() {
  if (CKEDITOR.env.origIsCompatible == false) {
    /* bail out if ckeditor advertised itself as not supported */
    return;
  }
  if (typeof($().ckeditor) === 'undefined') {
    /* the jquery adapter couldn't be loaded, don't bother failing further down */
    return;
  }
  $('div.WysiwygTextWidget textarea').ckeditor({allowedContent: true});
  if ($('.block-edit-custom-text').length  > 0) {
    $('.block-edit-custom-text a.edit-custom-text').hide();
    $('.block-edit-custom-text').tooltip({
       content: LIVE_EDIT_TOOLTIP, items: 'div', track: true,
       show: {delay: 0}
    });
  }
  $('.block-edit-custom-text').dblclick(function(event) {
    var edit_url = $(this).find('a.edit-custom-text').attr('href');
    var custom_text = $(this).find('div.block-custom-text');
    $.ajax({
      url: edit_url,
      beforeSend: function(xhr) {xhr.setRequestHeader('X-Popup', 'true'); },
      success: function(html) {
        dialog = $('<form>');
        $(html).find('input[name="_form_id"]').appendTo(dialog);
        $(html).find('textarea').appendTo(dialog);
        var title = $(html).find('label').text();
        var ckname = $(html).find('textarea').attr('name');
        var submit = $(html).find('button[name="submit"]').text();
        var cancel = $(html).find('button[name="cancel"]').text();
        $(dialog).dialog({
             modal: true,
             resizable: false,
             title: title,
             show: { effect: 'fade', duration: 400 },
             width: '50em'});
        $(dialog).dialog('option', 'buttons', [
            {text: cancel,
             click: function() { $(this).dialog('close'); }},
            {text: submit,
             click: function() {
                 $.ajax({
                   url: edit_url,
                   beforeSend: function(xhr) {xhr.setRequestHeader('X-Ajax', 'true'); },
                   data: $(this).serialize(),
                   type: 'POST'
                 });
                 $(this).dialog('close');
                 $(custom_text).empty();
                 $(CKEDITOR.instances[ckname].getData()).appendTo(custom_text);
             }
            }]);

        $(dialog).find('textarea').ckeditor();
        return true;
      }
    });
    event.preventDefault();
    return false;
  });

  $(document).on('wcs:dialog-loaded', function(e, dialog) {
    $(dialog).find('div.WysiwygTextWidget textarea').ckeditor({allowedContent: true});
  });
});
