/*global document, jQuery, window, setTimeout */
var Messages = {

  validate : function(_this) {
    var body = jQuery(_this).find("textarea").val();
    if(!body || body.length <= 0) {
      alert("Напишите чего-нибудь в сообщении");
      return false;
    }
    if(body && body.length >= 1000) {
      alert("Слишком длинное сообщение: "+body.length+" символов вместо 1000");
      return false;
    }
    var user = jQuery(_this).find("input[name='message[user_login]']");
    if(user.length > 0 && (!user.val() || user.val().length <= 0)) {
      alert("Не указан получатель сообщения");
      return false;
    }
    return true;
  },

  // Call this function when user read message first time
  onRead: function(obj){
    jQuery.post("/messages/"+obj.message_id+"/read", {}, function() {
      // obj.id — message id
      //if(!jQuery.browser.msie)
      //  console.log("Message '" + obj.id + "' was read");

    }, "script");
  },

  // Call this function when user send answer on message
  // you have to call "callback" function for future actions (animation)
  onSend: function(obj, callback){
    if(!Messages.validate(obj.answer)) {return false;}
    var reply = jQuery(obj.answer).find("textarea").val();
    jQuery(obj.answer).find("textarea").val("");
    jQuery('#message_'+obj.message_id).addClass('msg-replied');

    callback.call();

    jQuery.post("/messages", {"message[body]" : reply, "message[user_id]" : obj.sender_id, in_reply_to : obj.message_id}, function(reply) {
      var message = reply.message || reply;
    }, "json");
  },

  // User remove message
  onRemove: function(obj, callback){
    callback.call();
    this.increase_message_counters(-1, -1);
    jQuery.post("/messages/"+obj.message_id, {"_method" : "delete"}, function() {
      //if(!jQuery.browser.msie)
      //  console.log("Message '" + message_id + "' was removed");
    }, "json");
  },

  // User remove message
  onRemoveCorrespondence: function(obj, callback){
    callback.call();
    jQuery.post('/correspondences/remove/', {"_method" : "delete", 'ids': obj.message_id}, function() {
      //if(!jQuery.browser.msie)
      //  console.log("Message '" + message_id + "' was removed");
      window.location.href = "/messages";
    }, "json");
  },

  // User restore message
  onRestore: function(obj, callback){
    callback.call();
    this.increase_message_counters(-1, -1);
    jQuery.post("/messages/"+obj.message_id+"/restore", {}, function() {
      //if(!jQuery.browser.msie)
      //  console.log("Message '" + message_id + "' was removed");
    }, "json");
  },

  // User put message to black list
  onBlack: function(obj, callback_fast, callback_slow){
    callback_fast.call();
    jQuery.post("/blacklists", {sender_id : obj.sender_id, type : obj.type, message_id : obj.message_id}, function(reply) {
      var blacklist = reply.blacklist || reply;
      obj.blacklist_id = blacklist.id;
      if(callback_slow) {callback_slow.call();}
    }, "json");
  },

  // User cancel action to put message to black list
  onCancel: function(obj, callback){
    callback.call();
    jQuery.post("/blacklists", {"_method" : "delete", type : obj.type, sender_id : obj.sender_id}, function() {
    }, "json");
  },

  onCommentUnsubscribe: function(obj, callback){
    callback.call();
    jQuery.post("/messages/settings", {'profile[send_comments_message]' : false, 'profile[send_comments_email]' : false}, function() {
    }, "json");
  },

  //
  // Messages object
  //

  aMsg: [],
  s: {
    current: null,
    animate: false,
    prevent: true,
    navigate: true
  },

  filter: function(t){
    var i, j;
    if(t && t.length){
      this.o.empty.stop().removeAttr("style").show();
      for (j=0; j < t.length; j++) {
        for (i=0; i < this.aMsg.length; i++) {
          if(this.aMsg[i].type == t[j] && !this.aMsg[i].removed){
            this.o.empty.stop().hide();
            this.aMsg[i].obj.show();
            this.aMsg[i].visible = true;
          }
        }
      }

    } else {
      this.o.empty.show();
      for (i=0; i < this.aMsg.length; i++) {
        this.aMsg[i].obj.stop().hide();
        this.aMsg[i].visible = false;
      }
    }
  },
  checkVisible: function(){
    var h = this.o.empty.show().height();
    this.o.empty.css({ height: 0, overflow: "hidden", opacity: 0 }).animate({ height: 40, opacity: 1 });
    for (var i=0; i < this.aMsg.length; i++) {
      if(this.aMsg[i].visible){
        this.o.empty.stop().hide();
        return false;
      }
    }
  },

  append: function(id){
    var o = jQuery("#" + id);
    var id_parts = id.split("_");

    this.aMsg.push({
      obj: o,
      id: id,
      message_id : id_parts[id_parts.length - 1],
      sender_id: o.attr('sender_id'),
      visible: true,
      removed: false,
      type: o.attr("messageType"),
      msgAnswer: (o.attr("msgAnswer") && o.attr("msgAnswer") == "false") ? false : true
    });

    this.aMsg[this.aMsg.length - 1].obj.find("*[msgAction]").click(Messages.action_click);
    this.aMsg[this.aMsg.length - 1].obj.find(".msg-removed ins").click(Messages.removed_click);
  },
  init: function(){
    this.events();
    this.o = {
      answer: jQuery(".messages .msg-hide .msg-answer"),
      empty: jQuery(".messages .msg-list-empty")
    };
    jQuery('#j-load_more_messages').click(function(){
      $this = jQuery(this);
      if($this.attr('loading') == 'true'){ return false; }
      $this.attr('loading', 'true');
      jQuery.get('?limit=10&offset='+(Messages.count()), {}, function(){jQuery('#j-messages_on_page_count').text(Messages.count());$this.attr('loading', 'false');}, 'script');
      return false;
    });
    jQuery('#load_all_messages').click(function(){
      $this = jQuery(this);
      if($this.attr('loading') == 'true'){ return false; }
      $this.attr('loading', 'true');
      jQuery.get('?load_all=true', {}, function(){$this.attr('loading', 'false');}, 'script');
      return false;
    });
  },
  events: function(){
    var $this = this;
    this.t = 0;
    jQuery(document).keydown(function(evt){

      $this.s.navigate = true;
      switch(evt.target.tagName){
        case 'INPUT':
          $this.s.navigate = false;
          break;
        case 'TEXTAREA':
          if(jQuery(evt.target).parents(".msg-list")) {
            if(evt.target.value.length > 0) {
              $this.s.navigate = false;
            } else {
              $this.s.navigate = true;
            }
          } else {
            $this.s.navigate = false;
          }

          break;
        case 'SELECT':
          $this.s.navigate = false;
          break;
      }

    });

    var msg_clicker = function(evt){
      $this._onclick(evt, jQuery(this));
    };

    var hover_in = function(){
      var jobj = jQuery(this);
      var k = $this.getById(jobj.attr("id"));

      if(!$this.aMsg[k].answer) {
        jobj.find("div.msg-answer-button").stop().css({ opacity: 0 }).show().animate({ opacity: 1 }, 200);
      }
    };

    var hover_out = function(){
      var jobj = jQuery(this);
      var k = $this.getById(jobj.attr("id"));

      if(!$this.aMsg[k].answer) {
        jobj.find("div.msg-answer-button").stop().animate({ opacity: 0 }, 200, function(){ jQuery(this).hide(); });
      }
    };

    var answer_click = function(){
      var jobj = jQuery(this);
      var k = $this.getById(jobj.parents(".msg-list-item").attr("id"));

      $this.open(k);
    };

    for (var i=0; i < this.aMsg.length; i++) {
      this.aMsg[i].obj.click(msg_clicker);

      if(this.aMsg[i].msgAnswer){
        this.aMsg[i].obj.hover(hover_in, hover_out);
        this.aMsg[i].obj.find("div.msg-answer-button").click(answer_click);
      }
    }
  },

  // Binding events online
  removed_click: function(){
    var jobj = jQuery(this);
    $this = Messages;
    var k = $this.getById(jobj.parents(".msg-list-item").attr("id"));

    if(!jobj.is(".loading")){
      jobj.addClass("loading");
      $this.onCancel($this.aMsg[k], function(){
        $this.cancel(k);
      });
    }
  },

  action_click: function(){
    var jobj = jQuery(this);
    $this = Messages;
    var k = $this.getById(jobj.parents(".msg-list-item").attr("id"));

    if(!jobj.is(".loading")){
      jobj.addClass("loading");

      switch(jobj.attr("msgAction")){
        case 'reply':
          //TODO: for future
          break;

        case 'remove':
          $this.onRemove($this.aMsg[k], function(){
            $this.remove(k);
          });
          break;

        case 'remove_correspondence':
          $this.onRemoveCorrespondence($this.aMsg[k], function(){
            $this.remove(k);
            Messages.increase_message_counters(-1, -1);
          });
          break;

        case 'comment_unsubscribe':
          $this.onCommentUnsubscribe($this.aMsg[k], function(){
            $this.aMsg[k].obj.find(".comment_unsubscribe").hide();
            $this.aMsg[k].obj.find(".comment_unsubscribed").show();
          });
          break;

        case 'restore':
          $this.onRestore($this.aMsg[k], function(){
            $this.remove(k);
          });
          break;

        case 'cancel':
          $this.onCancel($this.aMsg[k], function(){
            $this.cancel(k);
          });
          break;

        case 'black':
          $this.onBlack($this.aMsg[k], function(){
            $this.black_fast(k);
          },   function(){
            $this.black_slow(k);
          });
          break;
      }
    }
  },

  _onclick: function(evt, obj){
    this.clean();
    this.s.current = this.getById(obj.attr('id'));
    if(this.s.current !== null) {
      this.light(this.s.current);
    }
  },

  next: function(){
    var s = this.s.current;
    this.s.current = this.getNextVisible( (this.s.current === null) ? 0 : (this.s.current + 1));
    if(this.s.current !== null && this.s.current != s){
      this.clean();
      this.light(this.s.current);
    }
  },

  prev: function(){
    var s = this.s.current;
    this.s.current = (this.s.current === null) ? this.getNextVisible(0) : this.getPrevVisible((this.s.current - 1));
    if(this.s.current !== null && this.s.current != s){
      this.clean();
      this.light(this.s.current);
    }
  },

  light: function(i){
    var o = this.aMsg[i].obj;

    if(!this.s.prevent){
      jQuery.scrollTo(this.aMsg[i].obj, 300, { offset: -10 });
      this.s.prevent = true;
    }

//  correspondence read once at load
//    o.addClass("msg-active");
//    if(o.is(".msg-not-read")){
//      o.removeClass("msg-not-read");
//      this.onRead(this.aMsg[i]);
//    }
  },

  clean: function(){
    for (var i=0; i < this.aMsg.length; i++) {
      this.aMsg[i].obj.removeClass("msg-active");
    }
  },

  open: function(i){
    var $this = this;
    if(i !== null && !this.aMsg[i].answer && !this.s.animate && this.aMsg[i].msgAnswer && this.aMsg[i].visible){
      var init = false;
      this.s.animate = true;
      this.aMsg[i].obj.find("div.msg-answer-button").hide();

      // copy answer form and animate
      if(this.aMsg[i].obj.find(".msg-answer").length){
        this.aMsg[i].answer = this.aMsg[i].obj.find(".msg-answer");
      } else {
        init = true;
        this.aMsg[i].answer = this.o.answer.clone(true).appendTo(this.aMsg[i].obj);
      }

      var h = this.aMsg[i].answer.removeAttr("style").height()+15;
      this.aMsg[i].answer.hide();

      if(jQuery.browser.msie) {
        h -= 15;
      }

      this.aMsg[i].answer.css({ height: 0, overflow: "hidden" }).animate({ height: h }, function(){
        $this.s.animate = false;
        $this.aMsg[i].answer.find("textarea").focus();
        jQuery(this).removeAttr("style");
      });
      this.aMsg[i].answer.find("div.msg-info, div.msg-ab-in").css({ opacity: 0 }).animate({ opacity: 1 });

      jQuery.scrollTo(this.aMsg[i].answer, 300, { offset: -jQuery(window).height()+h+10 });

      // init actions for answer form
      if(init) {
        this.initAnswerForm(this.aMsg[i].answer, i);
      }
    }
  },

  hide: function(i, remove){
    if(i !== null && this.aMsg[i].answer && !this.s.animate){
      var $this = this;
      this.aMsg[i].answer.animate({ height: 0 }, function(){
        if($this.aMsg[i].answer){
          $this.aMsg[i].answer.removeAttr("style").hide();
          if(remove) {
            $this.aMsg[i].answer.remove();
          }
          delete $this.aMsg[i].answer;
        }
      });
      this.aMsg[i].answer.find("div.msg-info, div.msg-ab-in").animate({ opacity: 0 });
      this.aMsg[i].answer.find("textarea").blur();
      jQuery.scrollTo(this.aMsg[i].obj, 300, { offset: -10 });
    }
  },

  initAnswerForm: function(obj, i){
    var $this = this;
    b_button_init();

    // init cancel action
    obj.find(".msg-ab-cancel a").click(function(){
      $this.hide(i);
      return false;
    });

    obj.find(".button-wrapper").click(function(){

      // move answer form to "loading" state
      obj.find(".msg-ab-in").css({ overflow: "hidden" }).animate({ height: 30 });
      obj.find(".msg-ab-in div.msg-ab-form").animate({ height: 0, opacity: 0 }, function(){
        jQuery(this).hide();
      });
      obj.find(".msg-ab-in div.msg-ab-loader").css({ opacity: 0 }).show().animate({ opacity: 1 });

      // call ajax function
      $this.onSend($this.aMsg[i], function(){
        obj.find(".msg-ab-in").html('Сообщение отправлено');
        setTimeout(function(){
          $this.hide(i, true);
        }, 2000);

      });

      return false;
    });

/*
    obj.find("textarea").focus(function(){
      if(this.value.length > 0)
        $this.s.navigate = false;
      else
        $this.s.navigate = true;
    }).blur(function(){
      $this.s.navigate = true;
    }).keyup(function(){
      if(this.value.length > 0)
        $this.s.navigate = false;
      else
        $this.s.navigate = true;
    })
*/
  },

  black_fast: function(i){
    var $this = this;
    this.aMsg[i].visible = false;
    this.aMsg[i].obj.find(".msg-blacklisted").parent().show();
    this.aMsg[i].obj.find(".msg-blacklisted").show();
    this.aMsg[i].obj.find(".msg-cont").parent().hide();
  },

  black_slow: function(i) {
    // there was some code
  },

  remove: function(i){
    var $this = this;
    this.aMsg[i].obj.css({ overflow: "hidden" }).animate({ height: 0, paddingBottom: 0, marginBottom: 0 }, function(){
      jQuery(this).hide();
    });

    if(!jQuery.browser.msie) {
      this.aMsg[i].obj.find(".msg-list-item-outer").animate({ opacity: 0 });
    }

    this.aMsg[i].visible = false;
    this.aMsg[i].removed = true;
    this.checkVisible();
  },

  cancel: function(i){
    this.aMsg[i].visible = true;
    this.aMsg[i].obj.find(".msg-blacklisted").parent().hide();
    this.aMsg[i].obj.find(".msg-blacklisted").hide();
    this.aMsg[i].obj.find(".msg-cont").parent().show();
  },

  getNextVisible: function(s){
    var i;
    for (i=s; i < this.aMsg.length; i++) {
      if(this.aMsg[i].visible) {
        return i;
      }
    }

    for (i=this.aMsg.length-1; i >= 0; i--) {
      if(this.aMsg[i].visible) {
        return i;
      }
    }
    return null;

//    //Jump to first
//    for (var i=0; i < this.aMsg.length; i++) {
//      if(this.aMsg[i].visible)
//        return i;
//    };
//    return null;

  },

  getPrevVisible: function(s){
    var i;
    if(s >=0 ){
      for (i=s; i >= 0; i--) {
        if(this.aMsg[i].visible) {
          return i;
        }
      }
    }

    for (i=0; i < this.aMsg.length; i++) {
      if(this.aMsg[i].visible) {
        return i;
      }
    }

//    //Jump to last
//    for (var i=this.aMsg.length-1; i >= 0; i--) {
//      if(this.aMsg[i].visible)
//        return i;
//    };
    return null;
  },

  empty_trash: function(){
    var f = document.createElement('FORM');
    f.action='/messages/empty_trash';
    f.method='post';
    document.body.appendChild(f);
    f.submit();
  },
  getById: function(id){
    for (var i=0; i < this.aMsg.length; i++) {
      if(this.aMsg[i].id == id) {
        return i;
      }
    }
    return null;
  },
  count: function(){
    return jQuery(".b-mailbox-list .b-mailbox-item").length - jQuery(".b-mailbox-list .b-mailbox-item-add").length; // Пока поле для ответа считается сообщением
  },
  increase_message_counters: function(delta_showed, delta_total){
    var showed = parseInt(jQuery('#j-messages_on_page_count').text(), 10);
    var total  = parseInt(jQuery('#j-messages_total_count').text(), 10);
    jQuery('#j-messages_on_page_count').text(showed + delta_showed);
    jQuery('#j-messages_total_count').text(total + delta_total);
  },
  update_message_counters: function(showed, total){
    jQuery('#j-messages_on_page_count').text(showed);
    jQuery('#j-messages_total_count').text(total);
  },
  update_main_counters: function(unread_messages_count){
    jQuery('.j-messages-count').html(unread_messages_count);
    var unread_wrap = jQuery('.j-messages-count-wrap');
    unread_messages_count > 0 ? unread_wrap.show() : unread_wrap.hide();
  },
  update_invites_counters: function(unread_invites_count){
    jQuery('.j-invites-count').html(unread_invites_count);
    var unread_wrap = jQuery('.j-invites-count-wrap');
    unread_invites_count > 0 ? unread_wrap.show() : unread_wrap.hide();
  },
  highlight: function(query){
    var messages = jQuery(".b-mailbox-list a,.b-mailbox-list .text");
    var pattern = new RegExp(query, "gi")
    messages.each(function(i){
      var $this = jQuery(this);
      $this.html($this.html().replace(pattern, "<i class='search-highlighted'>" + query + "</i>"));
    });
  }
};

var Correspondences = {
  init: function(){
    this.ms = jQuery(".b-mailbox-list .b-mailbox-item-wrap");
  this.ms.hover(function(){
    jQuery(this).addClass('hover');
  }, function(){
    jQuery(this).removeClass('hover');
  });
    this.checkers = this.ms.find("input[type=checkbox]");
     jQuery("#j-select_all_correspondences").click(function(){Correspondences.select_all();});
    jQuery("#j-deselect_all_correspondences").click(function(){Correspondences.deselect_all();});
    jQuery('#read_correspondences').click(function(){Correspondences.read_selected();});
    jQuery('#restore_correspondences').click(function(){Correspondences.restore(Correspondences.selected_ids());});
    jQuery('#remove_correspondences_to_trash').click(function(){Correspondences.remove_to_trash(Correspondences.selected_ids());});
    jQuery('#remove_correspondences_forever').click(function(){Correspondences.remove_forever(Correspondences.selected_ids());});
    jQuery('#empty_trash').click(function(){Messages.empty_trash();});
  },
  selected_ids: function(){
    var checked = this.checkers.filter(function(i){return Correspondences.checkers[i].checked;});
    var ids = [];
    checked.each(function(i, checker){ids.push(checker.id);});
    return ids;
  },
  showed_correspondences: function(){
    return jQuery(".b-mailbox-item").length - jQuery(".corr-hidden").length;
  },
  read_selected: function(){
    var ids = this.selected_ids();
    if (ids.length < 1) { alert('Выделите сообщения'); return false;}
    jQuery.post("/correspondences/read/", {'ids': ids.join(",")}, function(){}, 'script');
    jQuery.each(ids, function(i, id){
      jQuery("#correspondence_"+id).removeClass("j-unread");
    });
    this.deselect_all();
  },
  action: function(url, ids){
    if (ids.length < 1) { alert('Выделите сообщения'); return false;}
    jQuery.post(url, {'ids': ids.join(",")}, function(){}, 'script');
    jQuery.each(ids, function(i, id){
      jQuery("#correspondence_"+id).addClass('corr-hidden');
      jQuery("#correspondence_"+id).animate({ opacity : 0 }, function(){jQuery(this).hide();});
    });
    this.deselect_all();
    // if(Correspondences.showed_correspondences() == 0){
    //   window.location.reload();
    // }
  },
  remove_to_trash: function(ids){
    this.action("/correspondences/remove/", ids);
  },
  restore: function(ids){
    this.action("/correspondences/restore/", ids);
  },
  remove_forever: function(ids){
    this.action("/correspondences/remove_forever/", ids);
  },
  toggle_select: function(id){
    var was_checked = jQuery('#correspondence_'+id).hasClass("msg-selected");
    if (was_checked){
      jQuery('#'+id).checked = false;
      jQuery('#correspondence_'+id).removeClass("msg-selected");
    }else{
      jQuery('#'+id).checked = true;
      jQuery('#correspondence_'+id).addClass("msg-selected");
    }

  },
  select_all: function(){
    this.checkers.each(function(i, c){c.checked = true});
    // this.ms.addClass("msg-selected");
  },
  deselect_all: function(){
    this.checkers.each(function(i, c){c.checked = false});
    this.ms.removeClass("msg-selected");
  }
}

jQuery(document).ready(function(){
  // jQuery(".clicked").
  //   mousedown(function(){
  //     var $this = jQuery(this);
  //     $this.addClass($this.attr("class").match(/([^ ]+)/)[1] + "-down");
  //   }).
  //   mouseup(function(){
  //     var $this = jQuery(this);
  //     $this.removeClass($this.attr("class").match(/([^ ]+)/)[1] + "-down");
  //   });
  //
  // jQuery(".hovered")
  //   .hover(function(){
  //     var $this = jQuery(this);
  //     $this.addClass($this.attr("class").match(/([^ ]+)/)[1] + "-hover");
  //   }, function(){
  //     var $this = jQuery(this);
  //     $this.removeClass($this.attr("class").match(/([^ ]+)/)[1] + "-hover");
  //   });


  jQuery(document.body).mouseup(function(){
    jQuery(".clicked").each(function(){
      var $this = jQuery(this);
      $this.removeClass($this.attr("class").match(/([^ ]+)/)[1] + "-down");
    });
  });

  Messages.init();
  Correspondences.init();
/*
  jQuery("input").each(function(){
    if(!jQuery(this).parents("div.message").length)
      jQuery(this)
        .focus(function(){
          Messages.s.navigate = false;
        })
        .blur(function(){
          Messages.s.navigate = true;
        })
  })
*/

});

