/*
 * jQuery UI Tag Input
 * 
 * @version v1.0.0
 * 
 * Dependencies:
 *  jQuery v1.6.2
 *  jQuery UI v1.8.14       
 */
 
(function($) {
  $.widget('ui.taginput', {
    
    options: {
      minLength  : 3,
      ajaxSource : '/auth/ajax/products.php',
      inputName: 'admin[related]'
    },
    
    _create: function() {
      // For handling static scoping inside callbacks.
      var that = this;
      
      $('span.tagInput-delTag').live('click', function() {
        $(this).parent().remove();        
      });
      
      if (this.element.is('input')) {
        this.tagList = $('ul', $(this.element).parent());
        if (this.tagList.length == 0) {
          this.tagList = $('<ul></ul>').insertAfter(this.element);
        }                                                                         
      } else {
        this._errorHandler('ERROR: Tag input can be use only with text input field.');      
      }
      
      this.element.autocomplete({
        minLength: that.options.minLength,
        source: function(request, response) {
            $.ajax({
                url: that.options.ajaxSource,
                dataType: 'json',                
                data: { 
                  query: request.term,
                  added: function() {
                    // Get id of tags whitch has been already added.
                    var addedTags = new Array();
                    that.tagList.find('li.tagInput-tag input').each(function(index) {
                      addedTags[index] = $(this).val();
                    });                    
                    return addedTags;
                  }
                },
                success: function(data) {               
                  response($.map(data.items, function(item){                    
                    return {
                      id: item.id,
                      label: item.name,
                      name: item.name
                    }
                  }));
                }
            });      
        },  
        select: function(event, ui) {            
            // Add the tag to the tag list.
            hiddenInput = $('<input />')            
              .attr('type', 'hidden')
              .attr('name', that.options.inputName + '[]')
              .val(ui.item.id);
            delButton = $('<span>x</span>')
              .addClass('tagInput-delTag');
            tag = $('<li>'+ui.item.name+'</li>').appendTo(that.tagList)            
              .addClass('tagInput-tag')
              .addClass('ui-widget-content ui-state-default ui-corner-all')
              .append(hiddenInput)
              .append(delButton);           
            // Clean the value of the input.
            $(this).val('');
            // Return false to prevent update of the input.
            return false;
        } 
      }).keypress(function(event) {
        if (event.which == 13) {
          // Prevent submit form with enter.
          return false;
        }
      });
      
      this.tagList
        .addClass('tagInput-tagList')
        .addClass('ui-widget ui-widget-content ui-corner-all');    
    },
    
    _setOption: function() {
    
    },
    
    _errorHandler: function(error) {
      this.error = $('<p>'+error+'</p>').insertAfter(this.element);
      this.error
          .css('color', 'red')
          .css('border', '1px solid red')
          .css('padding', '3px');        
    }                 
  
  });
})(jQuery);
