/*
  Moogets - TextboxList + Autocomplete 0.2
  - MooTools version required: 1.2
  - MooTools components required: Element.Event, Element.Style, Selectors, Request.JSON and dependencies.
  
  Credits:
  - Idea: Facebook
  
  Changelog:
  - 0.1: initial release
  - 0.2: added click support, removed $attributes use, code cleanup
*/

/* Copyright: Guillermo Rauch <http://devthought.com/> - Distributed under MIT - Keep this message! */

var GuestbookList = new Class({
  
  Extends: TextboxList,
  
  options: {    
    onBoxDispose: function(item) { this.autoFeed(item.retrieve('text')); },
    onInputFocus: function() { this.autoShow(); },    
    onInputBlur: function(el) { 
      this.lastinput = el;
      this.blurhide = this.autoHide.delay(200, this);
    },
    autocomplete: {
      'opacity': 1,
      'maxresults': 10,
      'minchars': 1
    },
	max_rcpt : 100
  },
  initialize: function(element, autoholder, options) {
	arguments.callee.parent(element, options);
    this.data = [];
		this.autoholder = $(autoholder).set('opacity', this.options.autocomplete.opacity);
		this.autoresults = this.autoholder.getElement('ul');
		var children = this.autoresults.getElements('li');
    children.each(function(el) { this.add(el.innerHTML); }, this); 
  },
  
  autoShow: function(search) {
    this.autoholder.setStyle('display', 'block');
    this.autoholder.getChildren().setStyle('display', 'none');
    if(! search || ! search.trim() || (! search.length || search.length < this.options.autocomplete.minchars) || this.bits.getKeys().length >= this.options.max_rcpt) 
    {
	  this.showMsg();
      this.resultsshown = false;
    } else {
      this.resultsshown = true;
      this.autoresults.setStyle('display', 'block').empty();
      this.data.filter(function(str) {
if(!str) return false;		var a = search.clean().split(" ");
		for(var i=0;i<a.length;i++) {
		  if (!str.test(a[i], 'i')) {
			return false;
		  }
		}	
		return true;
		}).each(function(result, ti) {
        if(ti >= this.options.autocomplete.maxresults) return;
        var that = this;
        var el = new Element('li').addEvents({
          'mouseenter': function() { that.autoFocus(this); },
          'click': function(e) { 
            new Event(e).stop();
            that.autoAdd(this); 
          }
        }).set('html', this.autoHighlight(result, search)).inject(this.autoresults);
        el.store('result', result);
        if(ti == 0) this.autoFocus(el);
      }, this);
    }
    return this;
  },
  
  autoHighlight: function(html, highlight) {
    var a = highlight.clean().split(" ");
    for(var i=0;i<a.length;i++) {
		html = html.replace(new RegExp("<em>", 'gi'),':');
		html = html.replace(new RegExp("</em>", 'gi'),';');
        html = html.replace(new RegExp(a[i], 'gi'), function(match) {
            return '<em>' + match + '</em>';
        });
        html = html.replace(new RegExp(":", 'gi'),'<em>');
        html = html.replace(new RegExp(";", 'gi'),'</em>');
    }
    return html;
  },
  
  autoHide: function() {    
    this.resultsshown = false;
    this.autoholder.setStyle('display', 'none');    
    return this;
  },
  
  autoFocus: function(el) {
    if(! el) return;
    if(this.autocurrent) this.autocurrent.className = '';
    this.autocurrent = el.addClass('auto-focus');
    return this;
  },
  
  autoMove: function(direction) {    
    if(!this.resultsshown) return;
    this.autoFocus(this.autocurrent['get' + (direction == 'up' ? 'Previous' : 'Next')]());
    return this;
  },
  
  autoFeed: function(text) {
    this.data.include(text);    
	this.update();
    return this;
  },
  
  autoAdd: function(el) {
    if(!el || ! el.retrieve('result')) return;
    this.add(el.retrieve('result'));
    delete this.data[this.data.indexOf(el.retrieve('result'))];
    this.autoHide();
    var input = this.lastinput || this.current.retrieve('input');
    input.set('value', '').focus();
	this.update();
    return this;
  },
  
  createInput: function(options) {
    var li = arguments.callee.parent(options);
    var input = li.retrieve('input');
    input.addEvents({
      'keydown': function(e) {
        this.dosearch = false;
        switch(new Event(e).code) {
          case Event.Keys.up: return this.autoMove('up');
          case Event.Keys.down: return this.autoMove('down');        
          case Event.Keys.enter: 
            if(! this.autocurrent) break;
	        this.autoAdd(this.autocurrent);
    	    this.autocurrent = false;
        	this.autoenter = true;
            break;
          case Event.Keys.esc: 
            this.autoHide();
            if(this.current && this.current.retrieve('input'))
              this.current.retrieve('input').set('value', '');
            break;
          default: this.dosearch = true;
        }
      }.bind(this),
      'keyup': function() {
        if(this.dosearch) this.autoShow(input.value);
      }.bind(this)
    });
    input.addEvent(Browser.Engine.trident ? 'keydown' : 'keypress', function(e) { 
      if(this.autoenter) new Event(e).stop()
      this.autoenter = false;
    }.bind(this));
    return li;
  },
	
  showMsg: function() {
	var msg;
	if (this.bits.getKeys().length >= this.options.max_rcpt) {
        msg = ZORPIA_JS_LANG.MESSAGE.MAX_RCPT;
		this.autoholder.getElement('.default').set('html', msg);
	} else {
		msg = ZORPIA_JS_LANG.MESSAGE.AUTO_TIP; 
		this.autoholder.getElement('.default').set('text', msg);
	}	
	this.autoholder.getElement('.default').setStyle('display', 'block');
  },

  createBox: function(text, options) {
    var li = arguments.callee.parent(text, options);
    return li.addEvents({
      'mouseenter': function() { this.addClass('bit-hover') },
      'mouseleave': function() { this.removeClass('bit-hover') }
    }).adopt(new Element('a', {
      'href': '#',
      'class': 'closebutton',
      'events': {
        'click': function(e) {
          new Event(e).stop();
          if(! this.current) this.focus(this.maininput);
          this.dispose(li);
        }.bind(this)
      }
    })).store('text', text);
  }

});
window.addEvent('domready', function() {
  // init
  var tlist2 = new GuestbookList('zorpia-demo', 'auto');

  // fetch and feed
  new Request.JSON({'url': '/messages/getfriends', 'onComplete': function(j) {
    tlist2.options.max_rcpt = j.max_rcpt;
    j.friends.each(tlist2.autoFeed, tlist2);
  }}).send();


  if(typeof(document.form)!='undefined' && typeof(document.form.req_delivery_status)!='undefined')
    setInterval('check_count_rcpts()', 500);

});
function chkFormVal() {
    var f = document.form;
	f.rcpts_username.value = document.rcpt_form.rcpts_list.value;
	//f.rcpts.value = document.rcpt_form.rcpts_list.value;
    if(f.group_code) {
        ;
    }
    else if(f.event_id) {
        var checked = false;
        for(var i=0; i < f.attend_status.length; i++) {
            if(f.attend_status[i].checked) {
                checked = true;
                break;
            }
        }
        if(!checked) {
            alert(ZORPIA_JS_LANG.MESSAGE.NO_EVENT_GUEST);
            return false;
        }
    }
    else if (f.rcpts.value == '' && f.rcpts_username.value == '') {
        alert(ZORPIA_JS_LANG.MESSAGE.NO_RCPT);
        return false;
    }

    if (f.title.value.match(/^\s*$/)) {
        alert(ZORPIA_JS_LANG.MESSAGE.NO_TITLE);
        return false;
    }
    if (f.content.value.match(/^\s*$/)) {
        alert(ZORPIA_JS_LANG.MESSAGE.NO_MSG);
        return false;
    }

    if(!f.msg_submitted) {
        f.msg_submitted = 1;
        f.btSend.value = ZORPIA_JS_LANG.MESSAGE.SENDING;
        f.btSend.disabled = true;
        return true;
    }
}

function check_count_rcpts() {

    var rcpts = document.rcpt_form.rcpts_list.value;
    if(!rcpts) return;
    var rcpts_list = rcpts.split('###');
    if(!rcpts_list) return;

    var rcpts_count = rcpts_list.length;

    var dst = document.form.req_delivery_status;
    if(rcpts_count>1) 
    {
        dst.checked = false;
        dst.disabled = true;
    }
    else 
    {
        dst.disabled = false;
    }
}

