/**
 * @author: Miroslav Kvasnica - niwi - miradrda@volny.cz, niwiweb.wz.cz
 * @date: 10.9.2010
 */

$(function()
{
  // add new choice
  $(".multichoice-add").click(addChoice);
  // remove previous choice
  $(".multichoice-remove").live('click', removeChoice);
});

var addChoice = function ()
{
  // add remove button?
  var thisItems = $(this).parents('td').find('.multichoice-item');
  if (thisItems.length < 2)
    thisItems.append('<a href="#" title="Odstranit tuto hodnotu" class="multichoice-remove">Odebrat hodnotu</a>');
  $(this).prev().clone().insertBefore(this);

  // unique ID for person-selector
  if ($(this).prev().find('.person-selector-frame').length)
  {
    var hash = Math.ceil(Math.random()*741508741);// TODO hash
    $(this).prev().find('.person-selector-frame').attr('id', hash);
    $(this).prev().find('.person-select').attr('href', '#TB_inline?height=160&width=300&inlineId='+ hash +'&modal=false');
    tb_init('a.thickbox');
    $(".person-selector-frame input").bind('keyup change', waitForSearch);
    $(".person-select").click(setSelectorBox);
  }
  // remove the option selected in previous
  return false;
}

var removeChoice = function ()
{
  // if there is only one item, remove the "remove button"
  var thisItems = $(this).parents('td').find('.multichoice-item');
  var toRemove = $(this).parents('td').find('.multichoice-remove');

  // remove this
  $(this).parent().remove();

  if (thisItems.length < 3) // 3 because this will be removed
    toRemove.remove();

  return false;
}

