// deprecated
// -- use EASY.schedule for simple tasks
// -- use Majlik's JqueryUI Widgets for complex

function LazyLoader(name, options) {
  this.options = $.extend({}, LazyLoader.defaults, options);
  this.name = name;
  this.cache = {};
}

LazyLoader.defaults = {
  // placeholder elements jquery selector
  elements: null,
  // url to load content from
  url: null,
  // load multiple by one request
  multiple: true,
  //param name of ids array
  param: 'ids',
  // object or function returning object in format {name: value}
  additional_params: null,
  // data attribute or function with element as this
  data_id: 'id'
};

LazyLoader._loaders = {};
LazyLoader.getLoader = function (name, options) {
  if (!LazyLoader._loaders[name])
    LazyLoader._loaders[name] = new LazyLoader(name, options || {});
  return LazyLoader._loaders[name];
};

LazyLoader.reload = function () {
  for (var name in LazyLoader._loaders) {
    if (!LazyLoader._loaders.hasOwnProperty(name))continue;
    LazyLoader._loaders[name].load();
  }
};

LazyLoader.prototype.load = function () {
  var ids = this.idsToLoad();

  if (ids.length === 0)
    return;

  var self = this,
    params = this.additionalParams();

  params[this.options.param] = ids;

  $.ajax({
    url: this.options.url,
    data: params,
    noLoader: true
  }).done(function (data) {
    self.elementsToLoad().each(function () {
      var id = self.idForElement(this);

      if (typeof self.cache[id] === 'undefined')
        self.cache[id] = data[id];

      $(this).append(self.cache[id]).addClass('lazy-loaded');
    });
  });
};

LazyLoader.prototype.elementsToLoad = function () {
  return $(this.options.elements).not('.lazy-loaded');
};

LazyLoader.prototype.additionalParams = function () {
  if (typeof this.options.additional_params === 'function')
    return this.options.additional_params.call(this);

  return $.extend({}, this.options['additional_params']);
};

LazyLoader.prototype.idsToLoad = function () {
  var ids = [],
    self = this;

  this.elementsToLoad().each(function () {
    var id = self.idForElement(this);
    if (id && ids.indexOf(id) === -1 && (typeof self.cache[id] === 'undefined')) {
      ids.push(id);
    }
  });

  return ids;
};

LazyLoader.refresh = function () {
  // For backward compatibility
  EASY.backgroundServices.load("attendance_statuses");

  for (var name in LazyLoader._loaders) {
    if (!LazyLoader._loaders.hasOwnProperty(name))continue;
    LazyLoader._loaders[name].cache = {};
    LazyLoader._loaders[name].load();
  }
};

LazyLoader.prototype.idForElement = function (element) {
  if (typeof this.options.data_id === 'function')
    return this.options.data_id.call(element);

  return $(element).data(this.options.data_id);
};
