// Event portability stuff
function eventCancel(event)
{
  // Portable event cancellation by every known means
  if (window.event) {
    window.event.returnValue = false;
  } else {
    try {
      event.preventDefault();
    } catch (e) {
    }
    try {
      event.stopPropagation();
    } catch (e) {
    }
  }
}

function eventGet(event)
{
  // Portable event fetching
  if (window.event) {
    return window.event;
  } else {
    return event;
  }
}

// IE: keyCode. Others: which

function eventGetKey(event)
{
  if (event.keyCode) {
    return event.keyCode;
  } else {
    return event.which;
  }
}

// Move caret to end of an <input type="text"> or <textarea> field 
function inputSetCaretToEnd (control) {
  if (control.createTextRange) {
    // IE solution
    var range = control.createTextRange();
    range.collapse(false);
    range.select();
  } else if (control.setSelectionRange) {
    // Others
    control.focus();
    var length = control.value.length;
    control.setSelectionRange(length, length);
  }
}

// tagahead-specific stuff

function tagaheadUpdateTags(id, value)
{
  $(id).value = value;
  $(id).focus();
  // Might be necessary somewhere although Firefox seems
  // to do the right thing by default
  inputSetCaretToEnd($(id)); 
}

// Tag module sets this for any given id when there is a suggestion
var tagaheadFirstTagSuggestions = new Array();

function tagaheadKeyUpTags(id, event)
{
  key = eventGetKey(event);
  if (key == 9) {
    if (tagaheadFirstTagSuggestions[id]) {
      $(id).value = tagaheadFirstTagSuggestions[id];
      $(id).focus();
      tagaheadFirstTagSuggestions[id] = false;
      eventCancel(event);
      return false;
    }
  }
  return true;
}

function tagaheadKeyPressTags(id, event)
{
  key = eventGetKey(event);
  // For stubborn browsers that don't allow cancel on keyUp,
  // but do pass tab on keyPress (i.e. Firefox 2.x Mac)
  if (key == 9) {
    if (tagaheadFirstTagSuggestions[id]) {
      // We'll do the real work in tagaheadKeyUpTags, just cancel
      // so we don't leave the field
      eventCancel(event);
      return false;
    }
  }
  return true;
}

