EASY.utils.toggleMultiSelect = function (select_id, size) {
  if (typeof event !== 'undefined') {
    $(event.target).toggleClass('open');
  }
  var select = $('#' + select_id.replace(/(:|\.|\[|\])/g, "\\$1"))[0];
  if (select.multiple === true) {
    select.multiple = false;
    select.size = 1;
  } else {
    select.multiple = true;
    select.size = size || 10;
  }
};

EASY.utils.toggleDiv = function (el_or_id) {
  var el;
  if (typeof(el_or_id) === 'string') {
    el = $('#' + el_or_id);
  } else if (typeof(el_or_id) === 'undefined') {
    return;
  } else {
    el = el_or_id;
  }
  el.slideToggle(0).toggleClass('collapsed');
  $(document).trigger("erui_interface_change_vertical");
  $(document).trigger("erui_interface_change_horizontal");
};

EASY.utils.toggleDivAndChangeOpen = function (toggleElementId, changeOpenElement) {
  EASY.utils.toggleDiv(toggleElementId);
  $(changeOpenElement).toggleClass('open');
};

EASY.utils.updateUserPref = function (uniq_id, user_id, open) {
  $.ajax({
    url: window.saveButtonSettingsUrl || window.urlPrefix + '/users/save_button_settings',
    type: 'POST',
    data: {
      'uniq_id': uniq_id,
      'user': user_id,
      'open': open
    },
    noLoader: true
  });
};

/*
 * ToggleTableRowVisibility('project_index_', 'project', '55', '51');
 */
EASY.utils.toggleTableRowVisibility = function (uniq_prefix, entity_name, entity_id, user_id, update_user_pref) {
  var uniq_id = uniq_prefix + entity_name + '-' + entity_id;
  var tr = $('#' + uniq_id);
  if (update_user_pref) {
    EASY.utils.updateUserPref(uniq_id, user_id, tr.hasClass('open'));
  }
  if (tr.hasClass('open')) {
    EASY.utils.hideTableRow(uniq_prefix, entity_name, entity_id, true);
  } else {
    EASY.utils.showTableRow(uniq_prefix, entity_name, entity_id, false);
  }
  $(document).trigger("erui_interface_change_vertical");
};

EASY.utils.hideTableRow = function (uniq_prefix, entity_name, entity_id, recursive) {
  var tr = $('#' + uniq_prefix + entity_name + '-' + entity_id);
  tr.removeClass('open');
  $('.' + uniq_prefix + 'parent' + entity_name + '_' + entity_id).each(function () {
    $(this).hide();
    if (recursive && this.id) {
      EASY.utils.hideTableRow(uniq_prefix, entity_name, this.id.substring((uniq_prefix + entity_name + '-').length), recursive);
    }
  });
  $(document).trigger("erui_interface_change_vertical");
};

EASY.utils.showTableRow = function (uniq_prefix, entity_name, entity_id, recursive) {
  var tr = $('#' + uniq_prefix + entity_name + '-' + entity_id);
  tr.addClass('open');
  $('.' + uniq_prefix + 'parent' + entity_name + '_' + entity_id).each(function () {
    $(this).show();
    if (recursive && this.id) {
      EASY.utils.showTableRow(uniq_prefix, entity_name, this.id.substring((uniq_prefix + entity_name + '-').length), uniq_prefix, recursive);
    }
  });
  $(document).trigger("erui_interface_change_vertical");
};


EASY.utils.toggleMyPageModule = function (expander, element, user, ajaxUpdateUserPref) {
  var group = $(expander).parent('div');
  group.toggleClass('open');
  if (ajaxUpdateUserPref) {
    EASY.utils.updateUserPref(element, user, !group.hasClass('open'));
  }
  $('#' + element).fadeToggle(function () {
    $(document).trigger("erui_interface_change_vertical");
  });
  affix.recalculateHeads(ERUI.tableHeads);
  responsivizer.fakeResponsive();
  $('#' + element).find('.thumbnails').each(function (index) {
    EASY.utils.initGalereya($(this));
  });
};

EASY.utils.openTogglingContainer = function (expander, element) {
  var group = $(expander).parent('div');
  group.addClass('open');
  $('#' + element).fadeIn();
  responsivizer.fakeResponsive();
  $(document).trigger("erui_interface_change_vertical");
};


EASY.utils.submitForm = function (form_id, url) {
  var frm = $('#' + form_id);
  frm.attr('action', url);
  frm.submit();
};

(function () {
  /**
   *
   * @param {String} field
   * @param {Array.<int>} indexes
   * @param {String} modul_uniq_id
   */
  function enableValues(field, indexes, modul_uniq_id) {
    var div_values = $('#' + modul_uniq_id + "div_values_" + field);
    div_values.toggle(indexes.length > 0);
  }

  /**
   *
   * @param {String} field
   * @param {String} modul_uniq_id
   */
  EASY.utils.toggleOperator = function (field, modul_uniq_id) {
    var operator = $('#' + modul_uniq_id + "operators_" + field);
    if (typeof(operator.val()) === 'undefined') {
      $('#' + modul_uniq_id + "div_values_" + field).show();
    } else {
      switch (operator.val()) {
        case "!*":
        case "*":
        case "t":
        case "ld":
        case "w":
        case "lw":
        case "l2w":
        case "m":
        case "lm":
        case "y":
        case "o":
        case ">dd":
        case "c":
          enableValues(field, [], modul_uniq_id);
          break;
        case "*o":
        case "!o":
          enableValues(field, [], modul_uniq_id);
          break;
        case "><":
          enableValues(field, [0, 1], modul_uniq_id);
          break;
        case "<t+":
        case ">t+":
        case "><t+":
        case "t+":
        case ">t-":
        case "<t-":
        case "><t-":
        case "t-":
          enableValues(field, [2], modul_uniq_id);
          break;
        case "=p":
        case "=!p":
        case "!p":
          enableValues(field, [1], modul_uniq_id);
          break;
        default:
          enableValues(field, [0], modul_uniq_id);
          break;
      }
    }
  };
})();


// Function for updating textareas to content from CKEDITOR
EASY.utils.updateCKE = function () {
  if (!(typeof CKEDITOR === "undefined")) {
    var instance;
    for (instance in CKEDITOR.instances) {
      CKEDITOR.instances[instance].updateElement();
    }
  }
};

// Function for updating form and sendind data also from CKEDITOR
//
// e.g. onchange status, tracker, ...
EASY.utils.updateForm = function (form, url) {
  EASY.utils.updateCKE();

  $.ajax({
    url: url,
    type: 'post',
    data: $(form).serialize()
  });
};

EASY.utils.submitModalForm = function (modalElement, appendContinue) {
  EASY.utils.updateCKE();
  var frm = $(modalElement).find('form:first');
  if (appendContinue) {
    frm.append('<input type="hidden" value="1" name="continue" />');
  }
  frm.submit();
};

EASY.utils.goToUrl = function (url, e) {
  var target = e.target || e.srcElement;
  if (target && (target.nodeName === 'INPUT' || target.nodeName === 'A' ||
    $(target).parents().hasClass('easy-autocomplete-tag'))) {
    return false;
  }
  if (e !== null && e !== 'undefined') {
    if (!e.ctrlKey && !e.shiftKey && !e.metaKey) {
      window.location = url;
    } else {
      // do nothing
    }
  } else {
    window.location = url;
  }
  return true;
};

EASY.utils.showAndScrollTo = function (element_id, offsetDelta, container_id) {
  if (!offsetDelta) {
    offsetDelta = 0;
  }
  var $container;
  var $el = $('#' + element_id);
  if (container_id) {
    $container = $("#" + container_id);
  } else {
    $container = $el;
  }
  $el.show();
  $('html, body').animate({
    scrollTop: $container.offset().top + offsetDelta
  }, 500);
  $(document).trigger("erui_interface_change_vertical");
};

EASY.utils.displayTabsButtons = function (css_selector) {
  var lis;
  var tabsWidth = 0;
  var liEl;
  $(css_selector).each(function () {
    lis = $(this).find('ul').children('li');
    lis.each(function (index, li) {
      liEl = $(li);
      if (liEl.is(":visible")) {
        tabsWidth += liEl.outerWidth();
      }
    });
    $(this).find('div.tabs-buttons, td.tabs-button').toggle(!((tabsWidth < $(this).width() - 120) && (lis.first().is(":visible"))));
  });
};

EASY.utils.moveTabRight = function (el) {
  var lis = $(el).parents('div.tabs').first().find('ul').children();
  var tabsWidth = 0;
  var i = 0;
  var that;
  lis.each(function () {
    that = $(this);
    if (that.is(':visible')) {
      tabsWidth += that.outerWidth();
    }
  });
  if (tabsWidth < $(el).parents('div.tabs').first().width() - 120) {
    return;
  }
  while (i < lis.length && !lis.eq(i).is(':visible')) {
    i++;
  }
  lis.eq(i).hide();
};

/**
 *
 * @param {jQuery} $from_el
 * @param {jQuery} $to_el
 */
EASY.utils.switchElements = function ($from_el, $to_el) {
  $from_el.hide();
  $to_el.show();
};

EASY.utils.toggleCheckbox = function (id) {
  var el = $('#' + id);
  if (el) {
    el.prop("checked", !el.is(":checked"));
  }
};

EASY.utils.warnLeaveUnsaved = function () {
  if (window.enableWarnLeavingUnsaved) {
    $('textarea').closest('form').data('changed', 'changed');
    $('form').on('submit', function () {
      $('textarea').closest('form').removeData('changed');
    });

    var easyBeforeUnload = function beforeUnload() {
      var warn = false;
      for (var name in CKEDITOR.instances) {
        var editor = CKEDITOR.instances[name];

        if ($(editor.element.$.form).data() && $(editor.element.$.form).data().changed && CKEDITOR.instances[name].checkDirty())
          warn = true;
      }

      if (warn) {
        return window.I18n.textWarnLeavingUnsaved;
      }
    };

    if (window.addEventListener)
      window.addEventListener("beforeunload", easyBeforeUnload, false);
    else
      window.attachEvent("onbeforeunload", easyBeforeUnload);
  }
};

EASY.utils.toggleSidebar = function () {
  ERUI.body.toggleClass('nosidebar');
  // ERUI.main.trigger($.Event('resize'));
  EASY.utils.updateUserPref('hide_sidebar', null, ERUI.body.hasClass('nosidebar'));
};

(function () {

  function showImportantJournalDetails(journal) {
    journal.find(".journal-details-container ul.details > li").each(function () {
      var self = $(this);
      self.toggle(self.hasClass('important'));
    });
  }

  EASY.journals.collapseUnnecessary = function () {
    var $toggler = $(".journal-details-toggler");
    var journals_to_hide = $toggler.closest('.journal').toArray();
    if ($(journals_to_hide).last()[0] === $(".journal.has-details:last-child").last()[0]) {
      $(journals_to_hide.pop()).find(".expander").parent().toggleClass('open'); // all except last
    }
    $(journals_to_hide).each(function (index, i) {
      var journal = $(i);
      journal.find(".avatar-container img").toggleClass('smallest-avatar');
      showImportantJournalDetails(journal);
    });
    $toggler.click(function (event) {
      var expander = $(event.target);
      EASY.journals.toggleDetails(expander.closest(".journal"));
    });
  };
  EASY.journals.toggleDetails = function (journal) {
    journal.find(".avatar-container img").toggleClass('smallest-avatar');
    journal.find(".journal-details-container ul.details > li:not(.important)").each(function () {
      $(this).toggle();
    });
    journal.find(".expander").parent().toggleClass('open');
  };
})();


EASY.modalSelector.showModal = function (width) {
  showModal('ajax-modal', width || '70%');
};

EASY.contextMenu.addContextMenuFor = function (url, element) {
  if (!window.contextMenusInitializers) {
    window.contextMenusInitializers = [];
  }
  window.contextMenusInitializers.push("contextMenuInit('" + url + "', '" + element + "')");
};

EASY.contextMenu.reloadInit = function () {
  if (window.contextMenusInitializers) {
    $.each(window.contextMenusInitializers, function (index, fce) {
      eval(fce);
    });
  }
};

EASY.utils.moveMenuLeft = function () {
  var scroll = ERUI.mainMenu.scrollLeft();
  requestFrame(function () {
    ERUI.mainMenu.scrollLeft(scroll - 120);
  });
};

EASY.utils.moveMenuRight = function () {
  var scroll = ERUI.mainMenu.scrollLeft();
  requestFrame(function () {
    ERUI.mainMenu.scrollLeft(scroll + 120);
  });
};

EASY.utils.backToTop = function () {
  $("html, body").animate({
    scrollTop: 0
  }, 200);
};

EASY.utils.contentHeightSwitchable = function (class_name, label_more, label_less, overflow_element_selector) {
  var contentSelector = '.' + class_name,
    overflow_element_selector = (typeof overflow_element_selector === 'undefined') ? contentSelector + '> div' : overflow_element_selector,
    buttonFull = $('<a />').text(label_more).addClass('switchFull'),
    buttonLess = $('<a />').text(label_less).addClass('switchLess');

  $(overflow_element_selector).each(function () {
    var block = $(this);

    if (block[0].scrollHeight > block[0].offsetHeight) {
      block.after(buttonFull.clone());
    }
  });

  ERUI.document.on('click', '.switchFull', function () {
    var switchFullLink = $(this);
    switchFullLink.closest(contentSelector).removeClass(class_name);
    switchFullLink.replaceWith(buttonLess.clone());
  });

  ERUI.document.on('click', '.switchLess', function () {
    var switchLessLink = $(this);
    switchLessLink.closest('div').addClass(class_name);
    switchLessLink.replaceWith(buttonFull.clone());
  });
};

EASY.utils.setNameToModuleHead = function (input) {
  var textFromInput;
  if (input.tagName === 'SELECT') {
    textFromInput = $("option:selected", input).text();
  } else {
    textFromInput = input.value;
  }
  $(input).closest('div.easy-page-module.box').find('.module-heading-title').text(textFromInput);
};

EASY.utils.setInfiniteScrollDefaults = function () {
  $.extend($.infinitescroll.defaults, {
    behavior: 'easy',
    previousSelect: null
  });
  $.infinitescroll.prototype._nearbottom_easy = function () {
    var documentHeight = $(document).height();
    var opts = this.options;
    var pixelsFromWindowBottomToBottom = documentHeight - (opts.binder.scrollTop()) - $(window).height();
    var cnt = $(opts.contentSelector);
    var navToBottom = documentHeight - cnt.position().top - cnt.height();
    return pixelsFromWindowBottomToBottom < navToBottom + opts.bufferPx;
  };
  $.infinitescroll.prototype._setup_easy = function () {
    this._binding('bind');
    if (this.options.previousSelect === null || $(this.options.previousSelect).length === 0) {
      $(".infinite-scroll-load-next-page-trigger").parent().show();
    }
    return false;
  };
  $.extend($.infinitescroll.defaults.loading, {
    selector: '#main .infinite-scroll-load-next-page-trigger-container',
    msgText: '',
    localMode: true,
    finishedMsg: '',
    debug: true
  });
};

EASY.utils.initProjectEdit = function () {
  /*
   * Project inline editing with autocomplete.
   */
  $('.project-autocomplete-edit').not('.initialized').on('click', function (evt) {
    evt.stopPropagation();
    var target = $(evt.currentTarget);
    target.siblings('.editable').toggle();
    target.siblings('.easy-autocomplete-tag').toggle();
  }).addClass('initialized');
};

EASY.utils.initFileUploads = function () {
  ERUI.document.ready(function () {
    if (typeof cbImagePaste !== 'undefined' && typeof cbImagePaste.adjustCbpImageParts === "function") {
      cbImagePaste.adjustCbpImageParts();
    }
  });
  return true;
};

(function () {
  function closeBroadcast(broadcastId) {
    $.ajax({
      type: "POST",
      url: (window.urlPrefix + "/easy_broadcasts/mark_as_read.json"),
      noLoader: true,
      data: {id: broadcastId}
    });
  }

  EASY.utils.broadcast.showBroadcastFlashMessage = function (type, message, broadcastId) {
    return $("<div/>").attr({"class": "flash warning"})
      .addClass(type)
      .html($("<span/>").html(message))
      .append($("<a/>").attr({"href": "javascript:void(0)", "class": "icon-close"}).click(function () {
          closeBroadcast(broadcastId);
          $(this).closest('.flash').fadeOut(500, function () {
            $(this).remove();
          });
        }
      ))
      .prependTo($("#content"));
  };
})();
