NS_IMETHODIMP
nsXFormsRepeatElement::GetIndex(PRUint32 *aIndex)
{
  NS_ENSURE_ARG(aIndex);
  if (mIsParent) {
    if (!mCurrentRepeat) {
      *aIndex = 0;
      return NS_OK;
    }
    return mCurrentRepeat->GetIndex(aIndex);
  }

  *aIndex = mCurrentIndex;
  return NS_OK;
}
NS_IMETHODIMP
nsXFormsRepeatElement::SetIndex(PRUint32 *aIndex,
                                PRBool    aIsRefresh)
{
  NS_ENSURE_ARG(aIndex);
#ifdef DEBUG_XF_REPEAT
  printf("\tSetindex to %d (current: %d, max: %d), aIsRefresh=%d\n",
         *aIndex, mCurrentIndex, mMaxIndex, aIsRefresh);
#endif

  nsresult rv;

  // Set repeat-index
  if (mIsParent) {
    NS_ASSERTION(mCurrentRepeat,
                 "How can we be a repeat parent without a child?");
    // We're the parent of nested repeats, set through the correct repeat
    return mCurrentRepeat->SetIndex(aIndex, aIsRefresh);
  }
  
  // Do nothing if we are not showing anything
  if (mMaxIndex == 0) {
    SanitizeIndex(aIndex, PR_TRUE);
    mCurrentIndex = *aIndex;
    return NS_OK;
  }

  if (aIsRefresh && !mCurrentIndex) {
    // If we are refreshing, get existing index value from parent
    NS_ASSERTION(mParent,
                 "SetIndex with aIsRefresh == PR_TRUE for a non-nested repeat?!");
    rv = mParent->GetIndex(aIndex);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Check min. and max. value
  SanitizeIndex(aIndex, PR_TRUE);

  // Do nothing if setting to existing value
  if (!aIsRefresh && mCurrentIndex && *aIndex == mCurrentIndex)
    return NS_OK;
  
  
#ifdef DEBUG_XF_REPEAT
  printf("\tWill set index to %d\n",
         *aIndex);
#endif

  // Set the repeat-index
  rv = SetChildIndex(*aIndex, PR_TRUE, aIsRefresh);
  NS_ENSURE_SUCCESS(rv, rv);
  
  // Unset previous repeat-index
  if (mCurrentIndex) {
    // We had the previous selection, unset directly
    SetChildIndex(mCurrentIndex, PR_FALSE, aIsRefresh);
  }
  
  if (mParent) {
    // Selection is in another repeat, inform parent (it will inform the
    // previous owner of its new state)
    rv = mParent->SetCurrentRepeat(this, *aIndex);
    NS_ENSURE_SUCCESS(rv, rv);
  }

  // Set current index to new value
  mCurrentIndex = *aIndex;

  // Inform of index change
  mParent ? mParent->IndexHasChanged() : IndexHasChanged();

  return NS_OK;
}