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

Community.LettersCheck = Class.create({
  initialize: function(element,options)
  {
  this.id = Community.LettersCheck.id++;
  if (!options) options = {};
  this.element = $(element);
  if (!this.element) throw new Error("Отсутствует контейнер для проверки новых писем!");
  this.update_interval = options.update_interval || 30;
  this.popup_interval = options.popup_interval || 30;
  this.time = 0;
  this.unread = 0;
  this.is_first_update = true;
  this.is_updating = true;
  this.popup_pe = null;
  this.popup_move_pe = null;
  this.popup_move_frames = options.popup_move_frames || 30;
  this.popup_move_fps = options.popup_move_fps || 30;
  this.direction = options.popup_direction || "down";
  if (this.direction != "down" && this.direction != "up") this.direction = "down";
  this.popup_state = "none";
  this.element.update(this.root_html());
  this.pe = new PeriodicalExecuter(this.update.bind(this),this.update_interval);
  this.update(this.pe);
  community.init.add_unload(this.clean.bind(this));
  },

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

  stop: function()
  {
   var letters_check_rolldown = $(this.letters_check_rolldown_id());
   if (letters_check_rolldown) letters_check_rolldown.stopObserving("click");
   var letters_check_popup = $(this.letters_check_popup_id());
   if (letters_check_popup) letters_check_popup.setStyle({'visibility':'hidden'});
  },

  letters_check_popup_id: function() { return "Community_LettersCheck_Popup_"+this.id; },
  letters_check_rolldown_id: function() { return "Community_LettersCheck_RollDown_"+this.id; },

  update: function(pe)
  {
  new Ajax.Request(community.url.letters_ajax,
    {
      parameters: { cmd: "check.unread",time: this.time },
      onSuccess: this.update_success.bind(this),
      onFailure: this.update_failure.bind(this)
    });
  },

  update_success: function(transport)
  {
  var response = transport.responseText.split(" ");
  if (response[0] != "OK")
  {
    this.is_updating = false;
    if (this.pe) this.pe.stop();
    return;
  }
  this.time=response[1];
  response.splice(0,2);
  var income = $A(response.join(" ").evalJSON(true));
  var count = income.length;
  if (count)
  {
    this.unread += count;
    if ($("LettersCount"))
    {
     $("LettersCount").update(' <b>('+this.unread+')</b>');
     if (!this.is_first_update)
     {
       if (Number(community.prop.sounds) && community.sound.letter) community.sound.letter.play();
       this.popup(income);
     }
    }

    if (!this.is_first_update)
    {
      if ($("Folders")) UpdateFolders();
      else if ($("LettersArea")) UpdateChat();
    }
  }
  this.is_first_update = false;
  },

  update_failure: function(transport)
  {
  this.is_updating = false;
  if (this.pe) this.pe.stop();
  },

  root_html: function()
  {
  var value = '';
  value += '<div id="'+this.letters_check_popup_id()+'" class="letters_check_popup" style="visibility: hidden;"></div>';
  return value;
  },

  popup: function(income)
  {
  var title1 = "Получено новое письмо!";
  var title2 = "!!!!!ВНИМАНИЕ!!!!!!!!!";
  var key = true;
  setInterval(function() {
    if (key) document.title = title1;
    else document.title = title2;
    key = !key;
  },1000);

  if (this.popup_pe) this.popup_pe.stop();
  if (this.popup_move_pe) this.popup_move_pe.stop();
  var letters_check_popup = $(this.letters_check_popup_id());
  this.stop();
  letters_check_popup.update(this.popup_html(income));
  $(this.letters_check_rolldown_id()).observe("click",this.popup_rolldown.bindAsEventListener(this));
  this.check_popup_height = letters_check_popup.getHeight();

  if (this.direction == "up")
  {
   letters_check_popup.setStyle({left:"0px",top:this.check_popup_height+"px",
              clip:"rect(auto auto 0px auto)"}
            );
  }
  else
  {
   letters_check_popup.setStyle({left:"0px",top:-this.check_popup_height+"px",
              clip:"rect("+this.check_popup_height+"px auto auto auto)"}
            );
  }
  letters_check_popup.setStyle({'visibility':'visible'});
  this.popup_move_counter = 0;
  this.popup_state = "showing";
  this.popup_move_pe = new PeriodicalExecuter(this.popup_move.bind(this),1/this.popup_move_fps);
  },

  popup_move: function(pe)
  {
  this.popup_move_counter++;
  var num = (this.check_popup_height/this.popup_move_frames)*this.popup_move_counter;
  if (this.direction == "up")
  {
   $(this.letters_check_popup_id()).setStyle({
    top: (this.check_popup_height - num)+"px",
    clip: "rect(auto auto "+num+"px auto)"
             });
  }
  else
  {
   $(this.letters_check_popup_id()).setStyle({
    top: (-this.check_popup_height + num)+"px",
    clip: "rect("+(this.check_popup_height - num)+"px auto auto auto)"
             });
  }
  if (this.popup_move_counter >= this.popup_move_frames)
  {
    pe.stop();
    this.popup_state = "showed";
    this.popup_pe = new PeriodicalExecuter(this.popup_hide.bind(this),this.popup_interval);
  }
  },

  popup_move_back: function(pe)
  {
  this.popup_move_counter++;
  var num = (this.check_popup_height/this.popup_move_frames)*this.popup_move_counter;
  if (this.direction == "up")
  {
   $(this.letters_check_popup_id()).setStyle({
    top: num+"px",
    clip: "rect(auto auto "+(this.check_popup_height - num)+"px auto)"
             });
  }
  else
  {
   $(this.letters_check_popup_id()).setStyle({
    top: (-num)+"px",
    clip: "rect("+num+"px auto auto auto)"
             });
  }
  if (this.popup_move_counter >= this.popup_move_frames)
  {
    pe.stop();
    $(this.letters_check_popup_id()).setStyle({'visibility':'hidden'});
    this.popup_state = "none";
  }
  },

  popup_hide: function(pe)
  {
  if (this.popup_pe) this.popup_pe.stop();
  if (this.popup_move_pe) this.popup_move_pe.stop();
  this.popup_move_counter = 0;
  this.popup_state = "hiding";
  this.popup_move_pe = new PeriodicalExecuter(this.popup_move_back.bind(this),1/this.popup_move_fps);
  },

  popup_rolldown: function(event)
  {
    if (this.popup_state == "showed") this.popup_hide(null);
  },

  popup_html: function(income)
  {
  var value = '<ul><li class="mb5"><a href="#" id="'+this.letters_check_rolldown_id()+'" onclick="return false"><img class="fr" src="/i/comm/skin' + community.prop.skin + '/window_fold_up.gif" /></a>';
  if (income.length == 1) value += 'Новое письмо от:';
  else value += 'Новые письма от:';
  value += '</li>';
  var was_array = new Array();
  var num = 0;
  income.each(function(letter)
        {
          if (num > 4) { throw $break; }
          if (was_array.indexOf(letter.title_from) != -1) return;
          num = num + 1;
          was_array.push(letter.title_from);
          var link = community.url.letters+'?id='+letter.id;
          if (!Number(letter.from)) value += '<li><a href="'+link+'"' + letter.title_from + '</a></li>';
          else value += '<li>' + community.user_title(letter.title_from,{link:link,nopopup:true}) + '</li>';
        });
  value += '</ul>';
  return value;
  }

});

Community.LettersCheck.id = 0;
