/**
 * Multiple select - Replaces multiple-select with a stylish list
 * Based on MultipleSelect by Michael Aufreiter (http://www.wollzelle.com)
 * for mootools v1.11
 *
 * @version 1.0
 * @license     GNU General Public License
 * @author      A.G. Gideonse (http://www.xirtcms.com)
 * @copyright   A.G. Gideonse
 */
var MultipleSelect = new Class({

   Implements: [Events, Options], 

   options: {
      className: 'mselect'
   },
   
   // METHOD :: Initializes the list
   initialize: function(el, options) {
      this.setOptions(options);
      this.oEl = $(el);

      // Hide old list
      this.oEl.setStyle('display', 'none');
      var dim = this.oEl.measure(function() {
         return this.getSize();
      });

      // Create replacement list
      this.selectList = new Element('ul', {
        'class': this.options.className + '_list', 'id': el.name+'_choices'
      }).setStyles({
        width: dim.x + 'px', height: dim.y + 'px'
      }).injectAfter(this.oEl);

      this._addOptions(this.oEl);
      this.update(this.oEl);
   },

   // METHOD :: Adds all options from el to the new list
   _addOptions: function(el) {
      
      // Add all options to the list
      for (var i = 0; i < el.length; i++) {
         var cEl = new Element('li', {
            id: el.name + '_' + i,
            text : el.options[i].text
         })

         if (el.options[i].selected) {
            cEl.addClass('selected');
         }

         cEl.inject(this.selectList)
         .addEvent('mousedown', this.choiceSelect.bind(cEl, el));
      }

      // Update selection on change
      el.addEvent('change', this.update);
   },
   
   // METHOD :: Synchronizes selection
   update: function() {

      var oEl = this.oEl;
	  if(oEl != null) {
		  for(i = 0; i < oEl.length; i++) {
			 $(oEl.name + '_' + i).removeClass('selected');
			 if (oEl.options[i].selected) {
				$(oEl.name + '_' + i).addClass('selected');
			 }
		  }
		}
   },

   // METHOD :: Handles changes (onclick)
   choiceSelect: function(oEl) {

      this.toggleClass('selected');
      var cId = this.id.substring(this.id.lastIndexOf('_') + 1);
      oEl.options[cId].selected = oEl.options[cId].selected ? '' : oEl.options[cId].selected = 'selected';

      oEl.fireEvent('change');
   }
});
