/**
 * Select assignees
 */
jQuery.fn.selectAssignees = function(s) {
  var settings = jQuery.extend({
    'assignees' : null, 
    
    'choose_responsible' : true,
    'responsible_user_id' : 0,
    
    'choose_subscribers' : false, 
    'subscribers_name' : 'subscribers', 
    'subscribers' : null
  }, s);
  
  var removed_options = [];
  
  return this.each(function() {
  	var wrapper = $(this);
	  var responsible_select = $("select#select_assigned_to");
	  var assignees_select = $("select#multiselect_assignees");
	  
	  wrapper.find('div#multiselect_assignees_wrapper').hide();
	  
	  if(settings['choose_responsible']) {
	    var responsible_user_input = wrapper.find('input.responsible_user_id');
	  } // if
	  
	  if(!settings['choose_subscribers']) {
	    wrapper.find('div#multiselect_assignees_wrapper').show();
	  } // if
	  
	  /**
	   * Set user as responsible
	   * 
	   * @param jQuery user
	   */
	  var set_as_responsible = function(user_id) {
	    var assignee_user_option = assignees_select.find('option.user_option[value='+user_id+']');
	    var responsible_user_option = responsible_select.find('option.user_option[value='+user_id+']');
	    
	    if(assignee_user_option.length == 1) {
	      subscribe_user(user_id);
	    } // if
	    
	    if(!assignee_user_option.attr('selected')) {
	  		assignee_user_option.attr('selected', 'selected');
	    } // if
	    
	    if(!responsible_user_option.attr('selected')) {
	  	  responsible_user_option.attr('selected', 'selected');
	    } // if
	    
	    if(settings['choose_subscribers'] && !assignee_user_option.is('.subscribed')) {
	  		assignee_user_option.addClass('subscribed');
	    } // if
	    
	    assignees_select.find('option.user_option').each(function() {
	  		$(this).removeAttr('disabled');
	    });
	    
	    assignee_user_option.attr('disabled', 'disabled');
	    responsible_user_input.val(user_id);
	    
			if(settings['choose_subscribers']) {
		    responsible_select.selectmenu('refresh', true);
	    	assignees_select.selectmenu('refresh', true);
		  } // if
	    
	    assignees_select.find('option').removeClass('responsible');
	    assignee_user_option.addClass('responsible');
	  }; // set_as_responsible
	  
	  /**
	   * Select given user row
	   * 
	   * @param jQuery user
	   * @param boolean bulk
	   */
	  var select_user = function(user_id) {
	  	
	    var assignee_user_option = assignees_select.find('option.user_option[value='+user_id+']');
	    
	    if(!assignee_user_option.attr('selected')) {
	    	assignee_user_option.attr('selected', 'selected');
	    } // if
	    
	    if(settings['choose_subscribers']) {
		    assignees_select.selectmenu('refresh', true);
		  } // if
	    
	    subscribe_user(user_id);
	  }; // select_user
	  
	  /**
	   * Deselect given user row
	   * 
	   * @param jQuery user
	   */
	  var deselect_user = function(user_id) {
	    var assignee_user_option = assignees_select.find('option.user_option[value='+user_id+']');
	    
	    if(assignee_user_option.attr('selected')) {
	     	assignee_user_option.removeAttr('selected');
	    } // if
	    
	    unsubscribe_user(user_id);
	  }; // deselect_user
	  
	  /**
	   * Mark selected user as subscribed
	   * 
	   * @param jQuery user
	   */
	  var subscribe_user = function(user_id) {
	    var assignee_user_option = assignees_select.find('option.user_option[value='+user_id+']');
	    if(!assignee_user_option.is('.subscribed')) {
	  	  assignee_user_option.addClass('subscribed');
	      
	      if(wrapper.find('input.user_subscription[value=' + user_id + ']').length < 1) {
	        wrapper.append('<input type="hidden" name="' + settings['subscribers_name'] + '[]" value="' + user_id + '" class="user_subscription">');
	        wrapper.append('<input type="hidden" name="' + settings['other_assignees_name'] + '[]" value="' + user_id + '" class="user_other_assignees">');
	      } // if
	    } // if
	  }; // subscribe_user
	  
	  /**
	   * Mark seleted user as not subsscribed
	   * 
	   * @param jQuery user 
	   */
	  var unsubscribe_user = function(user_id) {
	    var assignee_user_option = assignees_select.find('option.user_option[value='+user_id+']');
	    if(assignee_user_option.attr('selected')) {
	      return false;
	    } // if
	    
	    // Mark as no longer subscribed
	    assignee_user_option.removeClass('subscribed');
	    
	    // Remove subscriptions
	    var subscriber = wrapper.find('input.user_subscription[value=' + user_id + ']');
	    if(subscriber.length > 0) {
	      subscriber.remove();
	    } // if
	    
	    // Remove other assignees
	    var other_assignee = wrapper.find('input.user_other_assignees[value=' + user_id + ']');
	    if(other_assignee.length > 0) {
	      other_assignee.remove();
	    } // if
	  }; // unsubscribe_user
	  
	  // Handle responsible select box change
	  responsible_select.change(function() {
	    if($(this).find('option:selected').length == 1) {
	  		wrapper.find('div#multiselect_assignees_wrapper').show();
	      var user_id = $(this).find('option:selected').attr('value');
	    	set_as_responsible(user_id);
	    } else {
	  		assignees_select.parent().hide();
	    } //if
	    
	    assignees_select.selectmenu('refresh', true);
	  });
	  
	  // Handle changes in multibox with assignees
	  assignees_select.change(function() {
		  assignees_select.find('option.user_option:selected').each(function() {
		    var user_id = $(this).attr('value');
		    select_user(user_id);
		  });
		  assignees_select.find('option.user_option:not(:selected)').each(function() {
		    var user_id = $(this).attr('value');
		    deselect_user(user_id);
		  });
	  });
	  
	  // Set responsible
	  if(settings['choose_responsible'] && settings['responsible_user_id']) {
	    var responsible_user = responsible_select.find('option.user_option[value='+settings['responsible_user_id']+']');
	    
	    if(responsible_user.length == 1) {
	      set_as_responsible(settings['responsible_user_id']);
	    } // if
	  } // if
	  
	  if(typeof(settings['assignees']) && settings['assignees']) {
	    for(var i in settings['assignees']) {
	      var assignee = assignees_select.find('option.user_option[value='+settings['assignees'][i]+']');
	      
	      if(assignee.length == 1) {
	        select_user(settings['assignees'][i]);
	      } // if
	    } // for
	  } // if
	  
	  if(settings['choose_subscribers'] && typeof(settings['subscribers']) == 'object' && settings['subscribers']) {
	    for(var i in settings['subscribers']) {
	      var subscriber = assignees_select.find('option.user_option[value='+settings['subscribers'][i]+']');
	      
	      if(subscriber.length == 1) {
	        subscribe_user(settings['subscribers'][i]);
	      } // if
	    } // for
	  } // if
	  
	  /**
	   * filter list by visibility
	   * 
	   * @param integer visibility
	   * @return null
	   */
	  var filter_by_visibility = function (visibility) {
	    var wrapper = $(this);
	    
	    wrapper.find('optgroup').each(function () {
	      var group = $(this);
	      group.show();
	      
	      if(visibility == 1) {
	      	group.find('option').show();
	        
	      	if(removed_options.length) {
	      		$.each(removed_options, function(k, removed_option) {
	      			if(removed_option.group == group.attr('label') && removed_option.parent_id == group.parent().attr('id')) {
	      				group.append($(removed_option.option));
	      				
	      				// Cut removed_option from the array
	      				removed_options = $.grep(removed_options, function(value) {
	      					return value != removed_option;
	      				});
	      			} // if
	      		});
	      	} // if
	      } else {
	      	var options_to_remove = group.find('option[can_see_private="0"]');
	      	
	      	// Collect all removed options
	      	if(options_to_remove.length) {
	      		$.each(options_to_remove, function(k, option_to_remove) {
	      			removed_options.push({
	      				'parent_id' : group.parent().attr('id'),
	      				'group' : group[0].label,
	      				'option' : option_to_remove.outerHTML
	      			});
	      		});
	      	} // if
	        options_to_remove.remove();
	        
	        group.find('option[can_see_private="1"]').show();
	      } // if
	    });
	    
	    // update responsible
      if(assignees_select.parent().parent().is(':visible') && !assignees_select.find('optgroup option').hasClass('responsible')) {
      	var first_user = responsible_select.find('optgroup option:first');
      	
      	first_user.attr('selected', 'selected');
      	set_as_responsible(first_user.val());
      	
      	var subscribed_users = new Array();
      	
      	$.each(assignees_select.find('optgroup option'), function(k, user) {
      		if($(this).hasClass('subscribed')) {
      			subscribed_users.push($(user).val());
      		} // if
      	});
      	
      	$.each($(this).find('input'), function(k, input) {
      		if($(this).hasClass('user_subscription') && $.inArray($(this).val(), subscribed_users) == -1) {
      			unsubscribe_user($(this).val());
      		} // if
      		
      		if($(this).hasClass('user_other_assignees') && $.inArray($(this).val(), subscribed_users) == -1) {
      			unsubscribe_user($(this).val());
      		} // if
      	});
      } // if
	    
	    responsible_select.selectmenu('refresh', true);
	    assignees_select.selectmenu('refresh', true);
	  }; // filter_by_visibility
	  
	  // provide public interface for this function
	  this.filterByVisibility = filter_by_visibility;
  });
  
};