var community;
if (!community || typeof community != "object") throw new Error("Не загружен модуль Community");

Community.Favorite = Class.create({
  initialize: function(element,obj_id,type,included)
  {
  this.id = Community.Favorite.id++;
  this.type = type || 0;
  this.obj_id = obj_id;
  this.element = $(element);
  if (!this.element) throw new Error("На странице отсутствует место для избранного!");
  if (community.prop.user_id == 0) return;
  if (included == undefined)
  {
    this.element.update("Идет загрузка...").show();
    new Ajax.Request(community.url.favorites,
       {
        parameters: {cmd:"favorite.get",id:this.obj_id,type:this.type},
         onSuccess: this.init_success.bind(this),
        onFailure: community.ajax_failure.bind(community)
       }
      );
  }
  else
  {
      this.included = Number(included) ? true : false;
      this.display();
  }
  community.init.add_unload(this.clean.bind(this));
  },

  clean: function()
  {
  this.stop();
  this.element = null;
  },

  stop: function()
  {
  var favorite_element = $(this.favorite_mod_id());
  if (favorite_element) favorite_element.stopObserving("click");
  },

  favorite_mod_id: function() { return "Community_Favorite_Mod_"+this.id; },

  init_success: function(transport)
  {
  var response = transport.responseText.split(" ");
  if (response[0] != "OK") throw new Error("Ошибка получения избранного: "+transport.responseText);
  response.splice(0,1);
  this.included = (response[0] == "yes" ? true : false);
  this.display();
  },


  toggle: function(id,type)
  {
  this.element.toggle();
  },

  display: function()
  {
  this.stop();
  this.element.update(this.html()).show();
  $(this.favorite_mod_id()).observe("click",this.mod_favorite.bindAsEventListener(this));
  },

  html: function()
  {
  var value='';
  if (this.included) value += '<a href="#" id="'+this.favorite_mod_id()+'" onclick="return false;">Удалить из избранного</a>';
  else value += '<a href="#" id="'+this.favorite_mod_id()+'" onclick="return false;">Добавить в избранное</a>';
  return value;
  },

  mod_favorite: function(event)
  {
  if (this.included)
  {
    new Ajax.Request(community.url.favorites,
         {
          parameters: {cmd:"favorite.delete",id:this.obj_id,type:this.type,check:community.prop.check},
           onSuccess: this.del_favorite_success.bind(this),
          onFailure: community.ajax_failure.bind(community)
         }
        );
  }
  else
  {
    new Ajax.Request(community.url.favorites,
         {
          parameters: {cmd:"favorite.add",id:this.obj_id,type:this.type,check:community.prop.check},
           onSuccess: this.add_favorite_success.bind(this),
          onFailure: community.ajax_failure.bind(community)
         }
        );
  }
  },

  add_favorite_success: function(transport)
  {
  var response = transport.responseText;
  if (response != "OK") { alert("Ошибка добавления: "+transport.responseText); return; }
  this.included = true;
  this.stop();
  this.display();
  },

  del_favorite_success: function(transport)
  {
  var response = transport.responseText;
  if (response != "OK") { alert("Ошибка удаления: "+transport.responseText); return; }
  this.included = false;
  this.stop();
  this.display();
  }

});

Community.Favorite.id = 0;

//----------------------------------------------------------------------------------------------------

Community.Favorite.Calendar = Class.create({
  initialize: function(element,options)
  {
  if (!options) options = {};
  this.element = $(element);
  if (!this.element) throw new Error("Отсутствует контейнер для календаря!");
  this.cache = new Hash();
  this.minyear = 2008;
  this.maxyear = (new Date()).getFullYear();
  this.counts = new Array();
  this.on_select = options.on_select || null;
  this.curyear = Number(options.year) || (new Date()).getFullYear();
  this.selected_month = Number(options.month) || "";
  this.selected_year = Number(options.year) || "";
  this.element.update("Идет загрузка...").show();
  this.month_names = [ "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль",
             "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь"
             ];
  this.change_year(this.curyear);
  community.init.add_unload(this.clean.bind(this));
  },

  previous_year_id: function() { return "Community_Favorite_Calendar_PreviousYear"; },
  next_year_id: function() { return "Community_Favorite_Calendar_NextYear"; },
  select_month_id: function(month) { return "Community_Favorite_Calendar_SelectMonth_"+month; },

  stop: function()
  {
  if ($(this.previous_year_id())) $(this.previous_year_id()).stopObserving("click");
  if ($(this.next_year_id())) $(this.next_year_id()).stopObserving("click");
  for (var i=0;i<12;i++)
  {
    if ($(this.select_month_id(i))) $(this.select_month_id(i)).stopObserving("click");
  }
  },

  clean: function()
  {
  this.stop();
    this.element = null;
  },

  change_year: function(newyear)
  {
  if (this.cache.get(newyear))
  {
    this.curyear = newyear;
    this.counts = this.cache.get(this.curyear);
    this.show();
    return;
  }
  new Ajax.Request(community.url.favorites,
      {
        parameters: {cmd:"favorites.getcounts", where:community.prop.current_id,year:newyear},
        onSuccess: this.change_year_success.bind(this,newyear),
        onFailure: community.ajax_failure.bind(community)
      }
          );
  },

  change_year_success: function(newyear,transport)
  {
  var response = transport.responseText.split(" ");
  if (response[0] != "OK") { alert("Ошибка получения избранного: "+transport.responseText); return; }
  response.splice(0,1);
  if (response.length != 12) { alert("Ошибка получения избранного: "+transport.responseText); return; }
  this.curyear = newyear;
  this.counts = response;
  this.cache.set(newyear,response);
  this.show(response);
  },

  previous_year: function()
  {
  this.change_year(this.curyear-1);
  },

  next_year: function()
  {
  this.change_year(this.curyear+1);
  },

  select_month: function(month)
  {
  if (this.on_select) this.on_select(month,this.curyear);
  },

  show: function()
  {
  this.stop();
  this.element.update(this.html());
  if ($(this.previous_year_id()))
  {
    $(this.previous_year_id()).observe("click",this.previous_year.bind(this));
  }
  if ($(this.next_year_id()))
  {
    $(this.next_year_id()).observe("click",this.next_year.bind(this));
  }
  for (var i=0;i<12;i++)
  {
    if (this.counts[i] != 0)
    {
      $(this.select_month_id(i)).observe("click",this.select_month.bind(this,i+1));
    }
  }
  },

  html: function()
  {
  var value = '';
  if (this.curyear > this.minyear)
  {
    value += '<h3 id="'+this.previous_year_id()+'">'+(this.curyear - 1)+' год</h3>';
  }
  value += '<ul>';
  for (var i=0;i<12;i++)
  {
    if (this.counts[i] > 0) {
      value += '<li id="'+this.select_month_id(i)+'">';
      if (this.curyear == this.selected_year && i+1 == this.selected_month) value += '<b>';
      value += this.month_names[i]+' ('+this.counts[i]+')';
      if (this.curyear == this.selected_year && i+1 == this.selected_month) value += '</b>';
      value += '</li>';
    }
  }
  value += '</ul>';
  if (this.curyear < this.maxyear)
  {
    value += '<h3 id="'+this.next_year_id()+'">'+(this.curyear + 1)+' год</h3>';
  }
  return value;
  }
});
