/**
   * Import book exemplars
   *
   * @param nodes
   * @return
   */
  private Boolean processExemplars(NodeList nodes) {
    NodeList exemplars = nodes.item(0).getChildNodes();

    for (int i = 0; i < exemplars.getLength(); i++) {
      if (exemplars.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element exemplarNode = (Element) exemplars.item(i);

        Exemplar exemplar = new Exemplar();

        exemplar.setIdexemplar(Integer.parseInt(getTagValue("idexemplar", exemplarNode)));
        exemplar.setAquired(
            DatatypeConverter.parseDateTime(getTagValue("aquired", exemplarNode)).getTime());
        exemplar.setState(Integer.parseInt(getTagValue("state", exemplarNode)));

        Book book = bookMgr.findByIdbook(Integer.parseInt(getTagValue("book", exemplarNode)));
        if (book == null) {
          continue;
        }

        exemplar.setBook(book);

        try {
          exemplarMgr.save(exemplar);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import users
   *
   * @param nodes list of users nodes (wrapper node, thus only one)
   * @return
   */
  private Boolean processUsers(NodeList nodes) {
    NodeList users = nodes.item(0).getChildNodes();

    for (int i = 0; i < users.getLength(); i++) {
      if (users.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element userNode = (Element) users.item(i);

        User user = new User();

        user.setIduser(Integer.parseInt(getTagValue("iduser", userNode)));
        user.setForename(getTagValue("forename", userNode));
        user.setSurname(getTagValue("surname", userNode));
        user.setPermitNumber(getTagValue("permitNumber", userNode));
        user.setAddress(getTagValue("address", userNode));
        user.setEmail(getTagValue("email", userNode));
        user.setRegistered(
            DatatypeConverter.parseDateTime(getTagValue("registered", userNode)).getTime());
        user.setExpire(DatatypeConverter.parseDateTime(getTagValue("expire", userNode)).getTime());
        user.setPassword(getTagValue("password", userNode));
        user.setLevel(getTagValue("level", userNode));

        try {
          userMgr.Save(user);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import books
   *
   * @param nodes
   * @return
   */
  private Boolean processBooks(NodeList nodes) {
    NodeList books = nodes.item(0).getChildNodes();

    for (int i = 0; i < books.getLength(); i++) {
      if (books.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element bookNode = (Element) books.item(i);

        Book book = new Book();

        book.setIdbook(Integer.parseInt(getTagValue("idbook", bookNode)));
        book.setCode(getTagValue("code", bookNode));
        book.setEdition(Integer.parseInt(getTagValue("edition", bookNode)));
        book.setPages(Integer.parseInt(getTagValue("pages", bookNode)));
        book.setPlace(getTagValue("place", bookNode));
        book.setYear(DatatypeConverter.parseDateTime(getTagValue("year", bookNode)).getTime());
        book.setType(getTagValue("type", bookNode));
        book.setName(getTagValue("name", bookNode));

        // find and set publisher
        Publisher publisher =
            publisherMgr.findByIdpublisher(Integer.parseInt(getTagValue("publisher", bookNode)));
        if (publisher == null) {
          continue;
        }

        book.setPublisher(publisher);

        // find and set genre
        Genre genre = genreMgr.findByIdgenre(Integer.parseInt(getTagValue("genre", bookNode)));
        if (genre == null) {
          continue;
        }

        book.setGenre(genre);

        // setup book authors
        List<String> authors = getTagsValues("authorCollection", bookNode);

        if (book.getAuthorCollection() == null) {
          book.setAuthorCollection(new ArrayList<Author>());
        }

        for (String authorId : authors) {
          Author author = authorMgr.findByIdauthor(Integer.parseInt(authorId));
          if (author != null) {
            //						book.getAuthorCollection().add(author);
            author.getBooksCollection().add(book);
            authorMgr.save(author);
          }
        }

        try {
          bookMgr.save(book);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import borrows
   *
   * @param nodes
   * @return
   */
  public Boolean processBorrows(NodeList nodes) {
    NodeList borrows = nodes.item(0).getChildNodes();

    for (int i = 0; i < borrows.getLength(); i++) {
      if (borrows.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element borrowNode = (Element) borrows.item(i);

        Borrow borrow = new Borrow();

        borrow.setIdborrow(Integer.parseInt(getTagValue("idborrow", borrowNode)));
        borrow.setProlongations(Integer.parseInt(getTagValue("prolongations", borrowNode)));
        borrow.setBorrowed(
            DatatypeConverter.parseDateTime(getTagValue("borrowed", borrowNode)).getTime());

        // set returned date (can be null)
        try {
          if (getTagValue("returned", borrowNode) != null) {
            borrow.setReturned(
                DatatypeConverter.parseDateTime(getTagValue("returned", borrowNode)).getTime());
          }
        } catch (NullPointerException e) {
        }

        User user = userMgr.findByIduser(Integer.parseInt(getTagValue("user", borrowNode)));
        if (user == null) {
          continue;
        }

        borrow.setUser(user);

        Exemplar exemplar =
            exemplarMgr.findByIdexemplar(Integer.parseInt(getTagValue("exemplar", borrowNode)));
        if (exemplar == null) {
          continue;
        }

        borrow.setExemplar(exemplar);

        try {
          borrowMgr.Save(borrow);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import genres
   *
   * @param nodes
   * @return
   */
  private Boolean processGenres(NodeList nodes) {
    NodeList genres = nodes.item(0).getChildNodes();

    for (int i = 0; i < genres.getLength(); i++) {
      if (genres.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element genreNode = (Element) genres.item(i);

        Genre genre = new Genre();

        genre.setIdgenre(Integer.parseInt(getTagValue("idgenre", genreNode)));
        genre.setName(getTagValue("name", genreNode));

        try {
          genreMgr.save(genre);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import authors
   *
   * @param nodes
   * @return
   */
  private Boolean processAuthors(NodeList nodes) {
    NodeList authors = nodes.item(0).getChildNodes();

    for (int i = 0; i < authors.getLength(); i++) {
      if (authors.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element authorNode = (Element) authors.item(i);

        Author author = new Author();

        author.setIdauthor(Integer.parseInt(getTagValue("idauthor", authorNode)));
        author.setName(getTagValue("name", authorNode));

        try {
          authorMgr.save(author);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import publishers
   *
   * @param nodes
   * @return
   */
  private Boolean processPublishers(NodeList nodes) {
    NodeList publishers = nodes.item(0).getChildNodes();

    for (int i = 0; i < publishers.getLength(); i++) {
      if (publishers.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element publisherNode = (Element) publishers.item(i);

        Publisher publisher = new Publisher();

        publisher.setIdpublisher(Integer.parseInt(getTagValue("idpublisher", publisherNode)));
        publisher.setName(getTagValue("name", publisherNode));
        publisher.setAddress(getTagValue("address", publisherNode));

        try {
          publisherMgr.save(publisher);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  /**
   * Import bookings
   *
   * @param nodes
   * @return
   */
  private Boolean processBookings(NodeList nodes) {
    NodeList bookings = nodes.item(0).getChildNodes();

    for (int i = 0; i < bookings.getLength(); i++) {
      if (bookings.item(i).getNodeType() == Node.ELEMENT_NODE) {
        Element bookingNode = (Element) bookings.item(i);

        Booking booking = new Booking();

        booking.setIdbooking(Integer.parseInt(getTagValue("idbooking", bookingNode)));
        booking.setState(Integer.parseInt(getTagValue("state", bookingNode)));
        booking.setDate(
            DatatypeConverter.parseDateTime(getTagValue("date", bookingNode)).getTime());

        Book book = bookMgr.findByIdbook(Integer.parseInt(getTagValue("book", bookingNode)));
        if (book == null) {
          continue;
        }

        booking.setBook(book);

        User user = userMgr.findByIduser(Integer.parseInt(getTagValue("user", bookingNode)));
        if (user == null) {
          continue;
        }

        booking.setUser(user);

        try {
          bookingMgr.Save(booking);
        } catch (EJBException ex) {
          ex.printStackTrace(System.out);
        }
      }
    }
    return true;
  }
  public void main(IWContext iwc) throws Exception {
    // TODO eiki cache countries
    // some caching made by aron
    super.main(iwc);
    // System.out.println( "country dropdown main start "+
    // com.idega.util.IWTimestamp.RightNow().toString());
    List localeCountries = Arrays.asList(Locale.getISOCountries());

    // List locales = Arrays.asList( java.util.Locale.getAvailableLocales());
    // List locales = ICLocaleBusiness.listOfAllLocalesJAVA();
    Locale currentLocale = iwc.getCurrentLocale();

    // Iterator iter = locales.iterator();
    Iterator iter = localeCountries.iterator();

    Country country = null;
    String countryDisplayName = null;
    Map countries = new HashMap();
    String lang = currentLocale.getISO3Language();
    Locale locale;
    List smallCountries = new Vector();
    // CountryHome countryHome = getAddressBusiness(iwc).getCountryHome();
    while (iter.hasNext()) {
      // Locale locale = (Locale) iter.next();

      String ISOCountry = (String) iter.next();
      try {
        locale = new Locale(lang, ISOCountry);

        countryDisplayName = locale.getDisplayCountry(currentLocale);
        // country = countryHome.findByIsoAbbreviation(locale.getCountry());
        country = getCountryByISO(locale.getCountry());

        if (countryDisplayName != null
            && country != null
            && !countries.containsKey(country.getPrimaryKey())) {
          countries.put(country.getPrimaryKey(), country); // cache
          SmallCountry sCountry =
              new SmallCountry(
                  (Integer) country.getPrimaryKey(), countryDisplayName, ISOCountry, currentLocale);
          smallCountries.add(sCountry);
          // addMenuElement(((Integer)country.getPrimaryKey()).intValue(),countryDisplayName);
        }
      } catch (Exception e1) {
        // e1.printStackTrace();
      }
    }
    Collections.sort(smallCountries);

    for (Iterator iterator = smallCountries.iterator(); iterator.hasNext(); ) {
      SmallCountry sCountry = (SmallCountry) iterator.next();
      // we dont want the ISO code into the list
      if (!sCountry.name.equalsIgnoreCase(sCountry.code)) {
        addMenuElement(sCountry.getID().intValue(), sCountry.getName());
      }
    }

    try {
      if (!StringUtil.isEmpty(this.selectedCountryName)) {
        this.selectedCountry =
            getAddressBusiness(iwc).getCountryHome().findByCountryName(this.selectedCountryName);
      }
      // we must ensure no external selected country is set
      else if (this.selectedCountry == null && !StringUtil.isEmpty(currentLocale.getCountry())) {
        this.selectedCountry =
            getAddressBusiness(iwc)
                .getCountryHome()
                .findByIsoAbbreviation(currentLocale.getCountry());
      }
    } catch (RemoteException e) {
      e.printStackTrace();
    } catch (EJBException e) {
      e.printStackTrace();
    } catch (FinderException e) {
      e.printStackTrace();
    }

    if (this.selectedCountry != null) {
      setSelectedElement(((Integer) this.selectedCountry.getPrimaryKey()).intValue());
    }
    // System.out.println( "country dropdown main end "+
    // com.idega.util.IWTimestamp.RightNow().toString());
  }
  /*
   * (non-Javadoc)
   *
   * @see is.idega.idegaweb.member.presentation.UserEditor#presentateUserRelations(com.idega.presentation.IWContext)
   */
  protected void editUserRelations(IWContext iwc) throws RemoteException {
    Table relationsTable = new Table();
    relationsTable.setWidth(Table.HUNDRED_PERCENT);
    relationsTable.setCellspacing(4);
    int row = 1;

    if (user != null) {
      addSeperator(iwrb.getLocalizedString("mbe.user_relations", "User relations"));
      CommuneFamilyService familyService = getFamilyService(iwc);
      // partner handling
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.spouse", "Spouse")), 1, row);
      User partner = null;
      try {
        partner = familyService.getSpouseFor(this.user);
      } catch (NoSpouseFound e) {
      } catch (Exception e) {
      }
      if (partner != null) {
        relationsTable.add(getRelatedUserLink(partner), 2, row);
        relationsTable.add(
            getDisconnectorLink(
                familyService.getSpouseRelationType(),
                null,
                (Integer) user.getPrimaryKey(),
                (Integer) partner.getPrimaryKey(),
                getDeleteIcon(
                    iwrb.getLocalizedString(
                        "mbe.remove_spouse_relation", "Remove spouse relationship"))),
            3,
            row);
      }

      // cohabitant handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.cohabitant", "Cohabitant")), 5, row);
      User cohabitant = null;
      try {
        cohabitant = familyService.getCohabitantFor(this.user);
      } catch (NoCohabitantFound e) {
      }
      if (cohabitant != null) {
        relationsTable.add(getRelatedUserLink(cohabitant), 6, row);
        relationsTable.add(
            getDisconnectorLink(
                familyService.getCohabitantRelationType(),
                null,
                (Integer) user.getPrimaryKey(),
                (Integer) cohabitant.getPrimaryKey(),
                getDeleteIcon(
                    iwrb.getLocalizedString(
                        "mbe.remove_cohabitant_relation", "Remove cohabitant relationship"))),
            7,
            row);
      }
      row++;

      // parent handling
      int parentStartRow = row, custodianStartRow = row;
      relationsTable.add(getHeader(iwrb.getLocalizedString("mbe.parents", "Parents")), 1, row);
      Collection parents = null;
      try {
        parents = familyService.getParentsFor(user);
        if (parents != null && !parents.isEmpty()) {
          for (Iterator iter = parents.iterator(); iter.hasNext(); ) {
            User parent = (User) iter.next();
            relationsTable.add(getRelatedUserLink(parent), 2, parentStartRow);
            String relationType = familyService.getParentRelationType();
            relationsTable.add(
                getDisconnectorLink(
                    null,
                    relationType,
                    (Integer) user.getPrimaryKey(),
                    (Integer) parent.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_parent_relation", "Remove parent relationship"))),
                3,
                parentStartRow);
            parentStartRow++;
          }
        }
      } catch (Exception e1) {
      }

      // custodians handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.custodians", "Custodians")), 5, custodianStartRow);
      Collection custodians = null;
      try {
        custodians = familyService.getCustodiansFor(user, false);
        if (custodians != null && !custodians.isEmpty()) {
          for (Iterator iter = custodians.iterator(); iter.hasNext(); ) {
            User custodian = (User) iter.next();
            relationsTable.add(getRelatedUserLink(custodian), 6, custodianStartRow);
            String relationType = familyService.getCustodianRelationType();
            relationsTable.add(
                getDisconnectorLink(
                    null,
                    relationType,
                    (Integer) user.getPrimaryKey(),
                    (Integer) custodian.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_custodian_relation", "Remove custodian relationship"))),
                7,
                custodianStartRow);
            custodianStartRow++;
          }
        }
      } catch (Exception e1) {
      }
      row = Math.max(custodianStartRow, parentStartRow) + 1;

      // biological children handling
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.parential_children", "Parential children")),
          1,
          row);
      Collection children = null;
      int childrowstart = row;
      try {
        children = familyService.getChildrenFor(user);
        if (children != null && !children.isEmpty()) {
          for (Iterator iter = children.iterator(); iter.hasNext(); ) {
            User child = (User) iter.next();
            relationsTable.add(getRelatedUserLink(child), 2, row);
            relationsTable.add(
                getDisconnectorLink(
                    familyService.getParentRelationType(),
                    null,
                    (Integer) user.getPrimaryKey(),
                    (Integer) child.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_child_relation", "Remove child relationship"))),
                3,
                row);
            row++;
          }
        }
      } catch (Exception e2) {
      }
      // custody children handling
      row = childrowstart;
      relationsTable.add(
          getHeader(iwrb.getLocalizedString("mbe.custody_children", "Custody children")), 5, row);
      try {
        children = familyService.getChildrenInCustodyOf(user);
        if (children != null && !children.isEmpty()) {
          for (Iterator iter = children.iterator(); iter.hasNext(); ) {
            User child = (User) iter.next();
            relationsTable.add(getRelatedUserLink(child), 6, row);
            relationsTable.add(
                getDisconnectorLink(
                    familyService.getCustodianRelationType(),
                    null,
                    (Integer) user.getPrimaryKey(),
                    (Integer) child.getPrimaryKey(),
                    getDeleteIcon(
                        iwrb.getLocalizedString(
                            "mbe.remove_child_relation", "Remove child relationship"))),
                7,
                row);
            row++;
          }
        }
      } catch (NoChildrenFound e3) {
        // e3.printStackTrace();
      } catch (RemoteException e3) {
        e3.printStackTrace();
      } catch (EJBException e3) {
        e3.printStackTrace();
      }
    }
    relationsTable.setWidth(2, "150");
    relationsTable.setWidth(6, "150");

    row++;
    relationsTable.mergeCells(1, row, relationsTable.getColumns(), row);
    relationsTable.setAlignment(1, row, Table.HORIZONTAL_ALIGN_RIGHT);
    relationsTable.add(getCancelButton(iwc), 1, row);

    addToMainPart(relationsTable);

    presentButtons(iwc);
    presentButtonRegister(iwc);
  }