/*
 * $Id: ShowCategoryAction.java,v 1.82 2007/08/14 14:50:02 marbobo Exp $
 *
 * Copyright (c) Siemens AG 2008 
 *           (c) Universität Paderborn 2008 
 * Licensed under EUPL 1.1. 
 *
 * $Log: ShowCategoryAction.java,v $
 * Revision 1.82  2007/08/14 14:50:02  marbobo
 * + Licenseverwaltung komplett umgeschrieben
 * + Kategoriesuche und verlorene Kategorien anzeigen komplett umgeschrieben
 * + Fehler beim Speichern von Beschreibenungsfeldern für Entitäten beseitigt.
 *
 * Revision 1.81  2007/05/29 08:18:30  korowa
 * Suchen nach Kategorien hinzugefügt
 *
 * Revision 1.80  2006/09/18 11:39:41  marbobo
 * + Beim Registrierung einer Kategorie werden auch die Unterkategorien nun brücksichtigt
 *
 * Revision 1.79  2006/08/03 08:06:03  korowa
 * screenIt() in ursprüngliche Form gebracht(wegen Zeitaufwand<-->Nutzen und Standarten)
 *
 * Revision 1.78  2006/08/01 20:58:51  marbobo
 * + Navigiertes Dokument-Hervorheben für alternative Kategoriesicht, Projektsicht und Funktionssicht implementiert
 *
 * Revision 1.77  2006/07/31 11:39:34  korowa
 * Falls Dokument gelockt ist, wird beim Versuch eine neue Version hinzufügen Infomeldung ausgegeben(Zustand+User) und die Aktion wird blockiert
 *
 * Revision 1.76  2006/07/20 21:58:03  marbobo
 * + existCategory erweitert
 * + Bugfix
 *
 * Revision 1.75  2006/07/13 14:50:18  marbobo
 * + Bugfix
 *
 * Revision 1.74  2006/07/13 09:56:26  korowa
 * Bug bei searchRelatedDocuments besetitigt
 *
 * Revision 1.73  2006/07/07 07:57:22  korowa
 * Dokument-und Kategorieaktionen werden jetzt einheitlich in ShowCategorieAction.java definiert und ausgeführt.
 *
 * Revision 1.72  2006/06/29 12:22:15  korowa
 * Dokumentaktionen werden jetzt einheitlich in ShowCategorieAction.java definiert und ausgeführt. Außerdem wird zur Laufzeit überprüft ob ausgewählter Dokument oder Kategorie immer noch vorhanden oder aktuell sind um Nullpointer-Exeptions abzufangen.
 *
 * Revision 1.71  2006/04/29 18:39:46  marbobo
 * + Refactoriengs und eine Ausgaben vereinheitlicht
 *
 * Revision 1.70  2005/09/23 12:48:02  marbobo
 * + In der alternativen Sicht werden alle Dokemnte mit allen Metadaten angezeigt falls noch keine Dokumente geöffnet sind
 *
 * Revision 1.69  2005/09/19 12:50:27  marbobo
 * + Bei Ungültigen Verweisen auf Dokumente und Kategorien wird nun eine Info-Meldung ausgegeben
 *
 * Revision 1.68  2005/09/01 16:31:46  jonyp
 * changes due to new signature of VKCCategory.deleteCategory/VKCDocument.deleteDocument
 *
 * Revision 1.67  2005/09/01 08:31:59  korowa
 * Es werden mehrere URL angeboten, welche direkten Zugriff auf Dateien
 *  und automatisches Anmelden als Gast erlauben.
 *
 * Revision 1.66  2005/08/26 14:56:30  jonyp
 * changes due to new paramter(user) for deleteDocument
 *
 * Revision 1.65  2005/08/08 08:14:15  marbobo
 * + Methoden für Alternativsicht implementiert
 *
 * Revision 1.64  2005/05/31 16:22:35  marbobo
 * + Aktualisierung des Navigators korrigiert
 *
 * Revision 1.63  2005/04/26 00:26:49  marbobo
 * - unnötige Methode entfernt
 *
 * Revision 1.62  2005/02/14 14:01:52  bigmac
 * Applikationsweites CSS konfigurierbar gemacht + Refactorings
 *
 * Revision 1.61  2005/02/14 01:28:49  marbobo
 * + Schnellsuche auf Unicode-Zeichen angepasst
 *
 * Revision 1.60  2005/01/24 18:46:49  marbobo
 * + Bugfix bei der Schnellsuche beseitigt
 *
 * Revision 1.59  2004/11/10 15:02:45  koppy
 * Projektweite Überarbeitung von Error-Logs, Stacktraces,..
 *
 * Revision 1.58  2004/11/03 13:28:03  marbobo
 * + Einige Funktionen für Gast-Benutzer gesperrt
 *
 * Revision 1.57  2004/10/31 18:16:32  marbobo
 * + Verbesserung der Rechte-Überprüfung
 *
 * Revision 1.56  2004/10/31 03:01:31  marbobo
 * + ClipBoard-Funktionen überarbeitet
 *
 * Revision 1.55  2004/10/26 22:29:46  marbobo
 * + Bei CountCatDocs werden nur noch für sichtbare Kategorien und Dokumenten statistiken angezeigt
 *
 * Revision 1.54  2004/10/21 11:56:57  marbobo
 * + kleine Anpassung
 *
 * Revision 1.53  2004/09/15 14:16:05  marbobo
 * + kleine Anpassung wegen der Suche
 *
 * Revision 1.52  2004/08/11 14:23:07  marbobo
 * + Bei nicht mehr vorhandenen Kategorien Warnen und zur Wurzelkategorie weiterleiten
 *
 * Revision 1.51  2004/07/27 14:56:21  jonyp
 * added new parameter for deletion of categories (definite = true)
 *
 * Revision 1.50  2004/07/13 14:30:18  marbobo
 * + Anchor setzen wenn Dokument zur Favoriten hinzugefügt wird
 *
 * Revision 1.49  2004/06/27 17:36:00  marbobo
 * + Quellcode maintenance
 *
 * Revision 1.48  2004/06/24 21:17:58  marbobo
 * + Unterkategorien sortieren
 *
 * Revision 1.47  2004/06/15 15:22:04  jonyp
 * deleted unused import
 * use static methode from BAsicFormAction
 *
 * Revision 1.46  2004/06/09 12:35:43  marbobo
 * Kleine Korrekturen bzgl. Suchdialog
 *
 * Revision 1.45  2004/06/07 20:52:49  marbobo
 * Dokumente löschen -> auf Permission "d" umgestellt
 *
 * Revision 1.44  2004/05/14 18:29:33  marbobo
 * + Sortierung der Dokumente
 *
 * Revision 1.43  2004/05/06 15:11:09  jonyp
 * added support for docfavorites
 *
 * Revision 1.42  2004/05/05 15:03:52  vchris
 * Anpassungen für Favoriten
 *
 * Revision 1.41  2004/04/27 11:01:26  marbobo
 * + Dokumentsicht nochmals erweitert (Details für alle Dokumente ein- und ausblendbar)
 *
 * Revision 1.40  2004/04/26 21:59:26  marbobo
 * + Dokumentsicht erweitert (mit/ohne Details)
 *
 * Revision 1.39  2004/04/21 13:22:17  jonyp
 * bug fix: catch of quota exceeded
 *
 * Revision 1.38  2004/04/21 13:06:44  jonyp
 * minor bug fixes
 *
 * Revision 1.37  2004/04/21 07:58:21  jonyp
 * bug fix: catch of quota exceeded
 *
 * Revision 1.36  2004/04/20 15:26:51  jonyp
 * catch quota exceeed error during copy operation
 *
 * Revision 1.35  2004/04/15 09:43:20  jonyp
 * bug fix: npe when homeCategory does not exist
 *
 * Revision 1.34  2004/04/07 15:48:30  koppy
 * Beim Löschen mehrerer Dokumente nur ein "updateCategory"
 *
 * Revision 1.33  2004/04/01 20:49:46  marbobo
 * Unbenutzte Variablen entfernt
 *
 * Revision 1.32  2004/03/30 13:17:46  jonyp
 * register / go2 home category
 *
 * Revision 1.31  2004/03/15 13:40:01  bigmac
 * Anpassungen an PermissionManager und weitere Refactorings
 *
 * Revision 1.30  2004/03/09 18:40:34  bigmac
 * Anpassungen an VKCSysParameterSerializer
 *
 * Revision 1.29  2004/03/08 18:23:51  bigmac
 * Anpassungen an VKCLanguageSerializer und VKCLanguagePackSerializer
 *
 * Revision 1.28  2004/03/07 20:05:55  bigmac
 * einige Methoden aus der VKCDataBase in die entsprechenden 
 * Serializer verschoben, ein paar Refactorings durchgeführt und 
 * tote Code-Teile entfernt
 *
 * Revision 1.27  2004/03/07 16:53:20  bigmac
 * Anpassungen an VKCAclSerializer
 *
 * Revision 1.26  2004/03/07 13:45:45  bigmac
 * Anpassungen an VKCDocumentTypeSerializer, VKCDocumentClassSerializer, VKCDocumentStatusSerializer
 *
 * Revision 1.25  2004/03/02 23:05:45  bigmac
 * Anpassungen an VKCDocumentSerializer und VKCCategorySerializer
 *
 * Revision 1.24  2004/02/18 14:52:09  marbobo
 * /sysLink.do anpassung
 *
 * Revision 1.23  2004/02/16 10:13:57  bigmac
 * toSet() verlagert nach ArrayUtils
 *
 * Revision 1.22  2004/02/10 15:03:18  bigmac
 * Keine Autoumschaltung auf Projektsicht mehr
 *
 * Revision 1.21  2004/02/09 13:24:26  bigmac
 * Anpassungen an /showCategory.do
 *
 * Revision 1.20  2004/02/04 15:29:06  bigmac
 * Globale Admins werden nicht mehr auf Projektsicht weitergeleitet
 *
 * Revision 1.19  2004/01/31 19:16:16  bigmac
 * *** empty log message ***
 *
 * Revision 1.18  2004/01/29 16:23:28  bigmac
 * Umleitung des Requests falls Kategorie ein Projektordner ist
 *
 * Revision 1.17  2004/01/20 15:49:38  jonyp
 * new show category parameters
 *
 * Revision 1.16  2004/01/12 15:52:03  vchris
 * Änderungen für Dokumentstatusflag
 *
 * Revision 1.15  2003/12/24 10:11:53  bigmac
 * Projektweite Import-Optimierung
 *
 * Revision 1.14  2003/11/29 22:26:16  koppy
 * dieses und jenes
 *
 * Revision 1.13  2003/11/28 15:05:08  jonyp
 * changes due to new schema
 *
 * Revision 1.12  2003/11/11 08:13:33  jonyp
 * some comments
 *
 * Revision 1.11  2003/11/06 15:32:02  koppy
 * Änderungen zwecks optimiertem Navigatorverhalten
 *
 * Revision 1.10  2003/10/20 18:49:25  marbobo
 * sysLink bugfix
 *
 * Revision 1.9  2003/10/09 08:57:42  marbobo
 * bugfix
 *
 * Revision 1.7  2003/10/08 01:05:58  marbobo
 * +berücksichtigung von anchor
 *
 * Revision 1.6  2003/09/08 16:59:04  marbobo
 * *** empty log message ***
 *
 * Revision 1.5  2003/08/29 09:01:43  jonyp
 * auskommentierung getAcl, wird schon von der category selber gemacht
 *
 * Revision 1.4  2003/08/14 15:30:28  marbobo
 * Kategoriepfad wird nun nach Änderung des Kategorienamens richtig angezeigt
 *
 */
package vkc.view.action;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.Globals;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.util.MessageResources;

import vkc.exception.DBException;
import vkc.db.VKCDatabase;
import vkc.db.entities.VKCCategory;
import vkc.db.entities.VKCDocument;
import vkc.db.entities.VKCUser;
import vkc.db.serializer.VKCCategoryFavoritesSerializer;
import vkc.db.serializer.VKCDocumentFavoritesSerializer;
import vkc.db.serializer.VKCCategorySerializer;
import vkc.db.serializer.VKCDocumentSerializer;
import vkc.db.serializer.VKCUserSerializer;
import vkc.misc.VKCLogManager;
import vkc.security.PermissionManager;
import vkc.security.VKCAcl;
import vkc.util.ArrayUtils;
import vkc.util.VKCStringUtils;
import vkc.view.ClipBoard;
import vkc.view.WebShare;
import vkc.view.bean.RegisteredCategory;
import vkc.view.bean.RegisteredDocument;
import vkc.view.form.ShowCategoryForm;
import vkc.view.form.SysLinkForm;

/**
 * Action-Klasse für das Anzeigen einer VKC-Kategorie
 *
 * @author koppy
 */
public final class ShowCategoryAction extends Action {
	private ActionForward DEFAULT_FORWARD = new ActionForward("/templates/${template.name}/CategoryView.jsp", false);
	private ActionForward DEFAULT_FORWARD_ANCHORCATEGORYSORTBAR = new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=categorysortbar", false);
	private ActionForward DEFAULT_FORWARD_ANCHORDOCUMENTSORTBAR = new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=documentsortbar", false);

	private ActionForward INFO_FORWARD = new ActionForward("/templates/${template.name}/common/InfoPage.jsp");

	public ActionForward execute(ActionMapping mapping, 
            					 ActionForm f, 
            					 HttpServletRequest request,
            					 HttpServletResponse response)
    throws ServletException {
        try {
            ShowCategoryForm form = (ShowCategoryForm)f;
            
			if (request.getParameter("action.clipboard") != null) {
				return handleClipboardAction(form, request);
			} else if (request.getParameter("action.category.go2home") != null) {
				return handleGo2HomeCategoryAction(form, request);
			} else if (request.getParameter("action.register.document") != null) {
				return handleRegisterDocumentAction(form, request);
			} else if (request.getParameter("action.register.category") != null) {
				return handleRegisterCategoryAction(form, request);
			} else if (request.getParameter("action.register.home-category") != null) {
				return handleRegisterHomeCategoryAction(form, request);
			} else if (request.getParameter("action.delete.document") != null) {
				return handleDeleteDocumentAction(form, request);
			} else if (request.getParameter("action.delete.category") != null) {
				return handleDeleteCategoryAction(form, request);
			} else if (request.getParameter("action.show.documents") != null) {
				return handleShowDocumentsAction(form, request);
			} else if (request.getParameter("action.hide.documents") != null) {
				return handleHideDocumentsAction(form, request);
			} else if (request.getParameter("action.show.all.documents") != null) {
				return handleShowAllDocumentsAction(form, request);
			} else if (request.getParameter("action.hide.all.documents") != null) {
				return handleHideAllDocumentsAction(form, request);
			} else if (request.getParameter("action.show.document.details") != null) {
				return handleShowDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.hide.document.details") != null) {
				return handleHideDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.show.all.document.details") != null) {
				return handleShowAllDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.hide.all.document.details") != null) {
				return handleHideAllDocumentDetailsAction(form, request);
			} else if (request.getParameter("action.addtofavorites-category") != null) {
				return handleAddCategoryToFavorites(form, request);
			} else if (request.getParameter("action.addtofavorites-document") != null) {
				return handleAddDocumentToFavorites(form, request);
			} else if (request.getParameter("action.change.category.sortmode") != null) {
				return handleCategoryChangeSortMode(form, request);
			} else if (request.getParameter("action.change.document.sortmode") != null) {
				return handleDocumentChangeSortMode(form, request);
			} else if (request.getParameter("action.change.document.property") != null) {
				return handleDocumentChangeProperty(form, request);
			} else if (request.getParameter("action.change.document.publisher") != null) {
				return handleDocumentChangePublisher(form, request);
			} else if (request.getParameter("action.search.related-documents") != null) {
				return handleSearchRelatedDocuments(form, request);
			} else if (request.getParameter("action.new.document.version") != null) {
				return handleNewDocumentVersion(form, request);
			} else if (request.getParameter("action.cluster.category") != null) {
				return handleClusterCategory(form, request);
			} else if (request.getParameter("action.archive.category") != null) {
				return handleArchiveCategory(form, request);
			} else if (request.getParameter("action.edit.category") != null) {
				return handleEditCategory(form, request);	
			} else if (request.getParameter("action.edit.category.acl") != null) {
				return handleEditCategoryAcl(form, request);
			} else if (form.isQuickSearchAction(request)) {
		        return handleQuickSearchAction(form, request);
			} else if (form.isQuickSearchCategoryAction(request)) {
                return handleQuickSearchCategoryAction(form, request);
            } else if (request.getParameter("action.refresh") != null) {
				return refresh(form, request);
			} else {
				return handleInitialzeAction(form, request);
			}
        } catch (Exception ex) {
            VKCLogManager.errorLog(this, "1", "Exception while retrieving category!", ex);
            throw new ServletException(ex);
        }
    }	
	
	private ActionForward refresh(ShowCategoryForm form, HttpServletRequest request) {		
		return this.DEFAULT_FORWARD;
	}
	
	private ActionForward handleEditCategoryAcl(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/editCategoryAcl.do?init=true&categoryId=" + form.getCategoryId(), true);
	}

	private ActionForward handleEditCategory(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/editCategory.do?validate=false&categoryId=" + form.getCategoryId(), true);
	}

	private ActionForward handleClusterCategory(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/clusterCategory.do?initialize=true&categoryId=" + form.getCategoryId(), true);
	}

	private ActionForward handleArchiveCategory(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/archiveCategory.do?categoryId=" + form.getCategoryId(), true);
	}

	private ActionForward handleSearchRelatedDocuments(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/searchRelatedDocuments.do?documentId=" + form.getDocumentId() + "&categoryId=" + form.getCategoryId(), true);
	}

	private ActionForward handleNewDocumentVersion(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}		
		String lockUser = vkc.webdav.WebDavServlet.getLockUserName(form.getDocumentId());		
		if(lockUser!=null){	
			request.setAttribute(WebShare.MESSAGE_KEY,form.getResources().getMessage(form.getLocale(), "vkc.string.lockUserInfo", lockUser));
			return DEFAULT_FORWARD;
		}			
		return new ActionForward("/newDocumentVersion.do"+
				"?newDocumentPreDocId=" + form.getDocumentId() + 
				"&categoryId=" + form.getCategoryId(), true);
	}

	private ActionForward handleDocumentChangePublisher(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/changeDocumentPublisher.do?documentId=" + form.getDocumentId(), true);
	}

	private ActionForward handleDocumentChangeProperty(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		return new ActionForward("/editDocument.do?documentId=" + form.getDocumentId(), true);
	}

	private ActionForward handleCategoryChangeSortMode(ShowCategoryForm form, HttpServletRequest request) {
		return DEFAULT_FORWARD_ANCHORCATEGORYSORTBAR;
	}

	private ActionForward handleDocumentChangeSortMode(ShowCategoryForm form, HttpServletRequest request) {
		return DEFAULT_FORWARD_ANCHORDOCUMENTSORTBAR;
	}

	private ActionForward handleHideAllDocumentsAction(ShowCategoryForm form, HttpServletRequest request) {
		form.setShowDocuments(new Integer[0]);

		return DEFAULT_FORWARD;
	}

	private ActionForward handleShowAllDocumentsAction(ShowCategoryForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList();		
		
		for (int i = 0; i < form.getCategory().getDocuments().size(); i++) {
			VKCDocument doc = (VKCDocument)form.getCategory().getDocuments().get(i);
			ids.add(doc.getDocumentId());
		}
		
		for (int i = 0; i < form.getVirtualDocuments().size(); i++) {
			VKCDocument doc = (VKCDocument)form.getVirtualDocuments().get(i);
			ids.add(doc.getDocumentId());
		}
		
		for (int i = 0; i < form.getToBePublishedDocuments().size(); i++) {
			VKCDocument doc = (VKCDocument)form.getToBePublishedDocuments().get(i);
			ids.add(doc.getDocumentId());
		}
		
		form.setShowDocuments((Integer[])ids.toArray(new Integer[0]));
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleHideDocumentsAction(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		List ids = new ArrayList(Arrays.asList(form.getShowDocuments()));
		ids.remove(form.getSelectedId());
		form.setShowDocuments((Integer[])ids.toArray(new Integer[0]));
        
		return new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleShowDocumentsAction(ShowCategoryForm form, HttpServletRequest request) {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		List ids = new ArrayList(Arrays.asList(form.getShowDocuments()));
		ids.add(form.getSelectedId());
		form.setShowDocuments((Integer[])ids.toArray(new Integer[0]));
        
		return new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleHideAllDocumentDetailsAction(ShowCategoryForm form, HttpServletRequest request) {
		form.setShowDocumentDetails(new Integer[0]);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleShowAllDocumentDetailsAction(ShowCategoryForm form, HttpServletRequest request) throws DBException {
		List ids = new ArrayList();
		
		for (int i = 0; i < form.getCategory().getDocuments().size(); i++) {
			VKCDocument doc = (VKCDocument)form.getCategory().getDocuments().get(i);
			ids.add(doc.getDocumentId());
		}
		
		for (int i = 0; i < form.getVirtualDocuments().size(); i++) {
			VKCDocument doc = (VKCDocument)form.getVirtualDocuments().get(i);
			ids.add(doc.getDocumentId());
		}
		
		for (int i = 0; i < form.getToBePublishedDocuments().size(); i++) {
			VKCDocument doc = (VKCDocument)form.getToBePublishedDocuments().get(i);
			ids.add(doc.getDocumentId());
		}
		
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));
		
		if (form.getShowDocuments().length == 0) {
			form.setShowDocuments((Integer[])ids.toArray(new Integer[0]));
		}
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleHideDocumentDetailsAction(ShowCategoryForm form, HttpServletRequest request) {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.remove(form.getSelectedId());
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));
		
		return new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleShowDocumentDetailsAction(ShowCategoryForm form, HttpServletRequest request) {
		List ids = new ArrayList(Arrays.asList(form.getShowDocumentDetails()));
		ids.add(form.getSelectedId());
		form.setShowDocumentDetails((Integer[])ids.toArray(new Integer[0]));

		return new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=doc" + form.getSelectedId(), false);
	}

	private ActionForward handleQuickSearchAction(ShowCategoryForm form, HttpServletRequest request) {
        if (form.getSearchFromHere() != null) {
			return new ActionForward("/searchDocuments.do?searchFromHere=" + form.getSearchFromHere() + "&searchFromHereText=" + VKCStringUtils.base64Encode(form.getSearchFromHereText()), true);
		} 

		return new ActionForward("/searchDocuments.do?searchFromHereText=" + VKCStringUtils.base64Encode(form.getSearchFromHereText()), true);
	}

    private ActionForward handleQuickSearchCategoryAction(ShowCategoryForm form, HttpServletRequest request) {
        String params = "?openSearchCategoriesView=true";
        
        if (form.getSearchFromHere() != null) {
            params += "&searchCategoryId=" + form.getSearchFromHere();
        } 
        
        return new ActionForward("/templates/${template.name}/CategoryView.jsp" + params, false);
    }

	/**
	 * Method deletes the selected category
	 */
	private ActionForward handleDeleteCategoryAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		
		if (form.getCategoryId().intValue() == VKCCategory.ROOT_CATEGORY_ID) {
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.root.not.deletable");
			
			return DEFAULT_FORWARD;
		} else if (form.getUser().isGuestUser() || !PermissionManager.hasPermissionsRecursiv(form.getCategoryId(), form.getUser(), "D")) {
			// User hat nicht die Berechtigung zum Löschen
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");
			
			return DEFAULT_FORWARD;
		} else {
            Integer parentCategoryId = form.getCategory().getParentCategoryId();
            VKCUser user = form.getUser();
		    VKCCategorySerializer.deleteCategory( user, form.getCategoryId(), !WebShare.isTrashEnabled(), null );
			request.setAttribute(WebShare.INFO_KEY, "category.deleted");
			
			return new ActionForward("/showCategory.do?categoryId=" + parentCategoryId + "&refreshTreeView=true", true);
		}
	}

	/**
	 * Method give the path of the home category  
	 */
	private ActionForward handleGo2HomeCategoryAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		VKCUser user = form.getUser();
		
		// by default: stay on this page
		Integer homeCategoryId = new Integer(request.getParameter("prevCategoryId"));
		
		if (user.getHomeCategoryId() != null && user.getHomeCategoryId().intValue() > 0) {		
		    // check, if homecategory still exists 
		    if (VKCCategorySerializer.retrieveCategory(user.getHomeCategoryId()) != null) {
				homeCategoryId = user.getHomeCategoryId();	 
		    }
		} 
		
		// give the path to the home category
	    return new ActionForward("/showCategory.do?categoryId=" + homeCategoryId, true);
	}
	
	/**
	 * Method adds the selected document to the the user's registration list
	 */
	private ActionForward handleRegisterDocumentAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		VKCUser user = form.getUser();
		
		if (!user.isGuestUser()) {
			if (user.isDedicatedAdmin() || user.hasAdminPrivileges()) {
				return new ActionForward("/registerGroup.do?initialize=true&categoryId=" + form.getCategoryId() + "&documentId=" + form.getDocumentId(), true);
			}

			user.retrieveRegisteredDocuments();

			if (user.isRegisteredDocument(form.getDocumentId())) {
				// Dokument schon registriert
				request.setAttribute(WebShare.INFO_KEY, "vkc.document.allreadyRegistered");
			} else {
				// Document registrieren
				RegisteredDocument document = new RegisteredDocument();
				document.setDocumentId(form.getDocumentId());
				document.setThreshold(new Integer(10));
				user.addRegisteredDocument(document);
				user.saveRegisteredDocuments();
				request.setAttribute(WebShare.INFO_KEY, "vkc.document.registered");
			}
		}
		
		// Weiterleiten zur Kategorieansicht
		return new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=doc" + form.getDocumentId(), false);
	}
	
	/**
	 * Method adds the selected category to the the user's registration list
	 */
	private ActionForward handleRegisterCategoryAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		VKCUser user = form.getUser();

		if (!user.isGuestUser()) {
			if (user.isDedicatedAdmin() || user.hasAdminPrivileges()) {
				return new ActionForward("/registerGroup.do?initialize=true&categoryId=" + form.getCategoryId(), true);
			}

			user.retrieveRegisteredCategories();			

			if (user.isRegisteredCategory(form.getCategoryId())) {
				//Kategorie schon registriert
				request.setAttribute(WebShare.INFO_KEY, "vkc.category.allreadyRegistered");
			} else {
				//Kategorie registrieren
				RegisteredCategory category = new RegisteredCategory();
				category.setCategoryId(form.getCategoryId());
				category.setIncludeSubDirs(Boolean.TRUE);
				user.addRegisteredCategory(category);
				user.saveRegisteredCategories();
				request.setAttribute(WebShare.INFO_KEY, "vkc.category.registered");
			}
		}

		return DEFAULT_FORWARD;
	}

	/**
	 * Method adds the selected category to the the user's registration list
	 */
	private ActionForward handleRegisterHomeCategoryAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		VKCUser user = form.getUser();		

		if (!user.isGuestUser()) {			
			user.setHomeCategoryId(form.getCategoryId());
			VKCUserSerializer.saveUser(user);			
			request.setAttribute(WebShare.INFO_KEY, "vkc.category.home.registered");
		}

		return DEFAULT_FORWARD;
	}

	/**
	 * Method deletes a single document from the selected category.
	 */
	private ActionForward handleDeleteDocumentAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		// überprüfen, ob der Benutzer die Berechtigung zum Löschen des angeforderten Dokuments hat
		VKCCategory category = form.getCategory();
		VKCAcl acl = category.getAcl();
		VKCUser user = form.getUser();

		if (!form.getUser().isGuestUser() && PermissionManager.hasPermission(acl, form.getUser(), 'd')) {
			VKCDocumentSerializer.deleteDocument(user, form.getDocumentId(), !WebShare.isTrashEnabled(), null);
			form.reloadCategory();        
		} else {
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");
		}
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleClipboardAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		ActionErrors errors = new ActionErrors();
		
		try {
			VKCUser user = form.getUser();
			VKCCategory category = form.getCategory();
			
			if (form.getClipboardAction().equals("noaction")) {
				errors.add("error.noaction_choosen", new ActionError("error.noaction_choosen"));
			}
			
			if (form.getSelectedCategoryIds().length + form.getSelectedDocumentIds().length == 0 &&
				!(form.getClipboardAction().equals("paste") || form.getClipboardAction().equals("pasteAsProject"))) {
				errors.add("error.noitem_checked", new ActionError("error.noitem_checked"));
			}
		
			if (errors.size() > 0) {
				request.setAttribute(Globals.ERROR_KEY, errors);
				
				return DEFAULT_FORWARD;
			}
	
			String action = form.getClipboardAction();
			VKCAcl acl = category.getAcl();
	
			HttpSession session = request.getSession();
			String[] categoryIds = form.getSelectedCategoryIds();
			String[] documentIds = form.getSelectedDocumentIds();
	        
			MessageResources resources = getResources(request);
	
			if (action.equals("copy") || action.equals("cut")) {
				// COPY/CUT - Action			
				Set catIdsSet = ArrayUtils.toIntegerSet(categoryIds);
				Set docIdsSet = ArrayUtils.toIntegerSet(documentIds);
	
				ClipBoard clipBoard = new ClipBoard();
				clipBoard.setCategoryIds(catIdsSet);
				clipBoard.setDocumentIds(docIdsSet);
				clipBoard.setSourceCategoryId(form.getCategoryId());
				clipBoard.setUser(form.getUser());
				clipBoard.setOperation(action.equals("cut") 
				        			   ? ClipBoard.CUT_OPERATION 
				        		       : ClipBoard.COPY_OPERATION);

				if (clipBoard.execute()) {
					session.setAttribute(WebShare.CLIPBOARD_KEY, clipBoard);
				} else {
					errors.add("cutfailed", new ActionError("error.cut.selection"));
				}
			} else if (action.equals("delete")) {
				// DELETE - Action			
				Set catIdsSet = ArrayUtils.toIntegerSet(categoryIds);
				Set docIdsSet = ArrayUtils.toIntegerSet(documentIds);
	
				ClipBoard clipBoard = new ClipBoard();
				clipBoard.setCategoryIds(catIdsSet);
				clipBoard.setDocumentIds(docIdsSet);
				clipBoard.setSourceCategoryId(form.getCategoryId());
				clipBoard.setUser(form.getUser());
				clipBoard.setOperation(ClipBoard.DELETE_OPERATION);

				if (clipBoard.execute()) {
					return new ActionForward("/templates/${template.name}/CategoryView.jsp?refreshTreeView=true");
				}

				errors.add("deletefailed", new ActionError("error.delete.selection"));
			} else if (action.equals("paste")) {
				// PASTE - Action
				ClipBoard clipBoard = (ClipBoard) session.getAttribute(WebShare.CLIPBOARD_KEY);
	
				if (clipBoard != null) {
					switch (clipBoard.getOperation()) {
						case ClipBoard.CUT_OPERATION: {
						    clipBoard.setTargetCategoryId(form.getCategoryId());
							clipBoard.setUser(form.getUser());
						    clipBoard.setOperation(ClipBoard.MOVE_OPERATION);
							
						    if (clipBoard.execute()) {
							    session.removeAttribute(WebShare.CLIPBOARD_KEY);
								
							    return new ActionForward("/templates/${template.name}/CategoryView.jsp?refreshTreeView=true");
						    } 
						    
						    clipBoard.setOperation(ClipBoard.CUT_OPERATION);
						    errors.add("movefailed", new ActionError("error.move.selection"));
	
							break;
						}
	
						case ClipBoard.COPY_OPERATION: {
							try {
							    clipBoard.setTargetCategoryId(form.getCategoryId());
								clipBoard.setUser(form.getUser());
							    clipBoard.setOperation(ClipBoard.PASTE_OPERATION);
							    
							    if (clipBoard.execute()) {
									return new ActionForward("/templates/${template.name}/CategoryView.jsp?refreshTreeView=true");
							    }

							    clipBoard.setOperation(ClipBoard.COPY_OPERATION);
								errors.add("pastefailed", new ActionError("error.paste.selection"));
							} catch (DBException e) {
                                // catch quota exceed message !!!
								if (VKCDatabase.QUOTA_EXCEEDED.equals(e.getMessage())) {
                                    errors.add("vkc.document.paste.quota.exceeded", new ActionError("vkc.document.paste.quota.exceeded", user.getQuota()));
								} else {
									throw new DBException(e);
								}
							}
	
							break;
						}

				    	default: {
				    		break;
				    	}
					}
				}
			} else if (action.equals("pasteAsProject")) {
				// PASTE AS PROJECT
				ClipBoard clipBoard = (ClipBoard) session.getAttribute(WebShare.CLIPBOARD_KEY);
	
				if (clipBoard != null && PermissionManager.hasPermission(acl, user, 'w')) {
					VKCCategory projectCategory = 
                        WebShare.database.copyCategory( 
							category, 
                            clipBoard.getFirstCategoryId(),
							resources.getMessage(user.getLanguage().getLocale(), "vkc.projectmgmt.newProject"), 
                            true,
                            form.getUser());
	
					return new ActionForward("/createProject.do?categoryId=" + projectCategory.getCategoryId(), false);
				}
			}
	        
			return DEFAULT_FORWARD;
		} finally {
			if(!errors.isEmpty()) {
				saveErrors(request, errors);
			}
			
			form.setClipboardAction("noaction");
			form.reloadCategory();
		}
	}

	private ActionForward handleInitialzeAction(ShowCategoryForm form, HttpServletRequest request) throws Exception {
		if (form.getCategoryId() == null) {
			form.setCategoryId(new Integer(VKCCategory.ROOT_CATEGORY_ID));
		}

		VKCCategory category = form.getCategory();
		
		//Kategorie existiert nicht mehr
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		if (category != null && !PermissionManager.hasPermission(category.getAcl(), form.getUser(), 'r')) {
			request.setAttribute(WebShare.INFO_KEY, "vkc.info.access_denied");
			VKCLogManager.accessLog(request.getRemoteHost(), null, form.getUser().getUser(), 
			request.getContextPath() + SysLinkForm.getCategorySysLink(category.getCategoryId(), SysLinkForm.LOGINTYPE_NORMAL_USER), 403, 0);
			
			return INFO_FORWARD;
		}
		
		if (request.getParameter("sysLinkMessageKey") != null) {
			request.setAttribute(WebShare.INFO_KEY, request.getParameter("sysLinkMessageKey"));
		}
		
		VKCLogManager.accessLog(request.getRemoteHost(), null, form.getUser().getUser(), 
		request.getContextPath() + SysLinkForm.getCategorySysLink(category.getCategoryId(), SysLinkForm.LOGINTYPE_NORMAL_USER), 200, 0);
		
		return DEFAULT_FORWARD;
	}

	private ActionForward handleAddCategoryToFavorites(ShowCategoryForm form, HttpServletRequest request) throws DBException {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		if (!form.getUser().isGuestUser()) {
		    VKCCategoryFavoritesSerializer.addCategoryFavorites(form.getUser().getUserId(), form.getCategoryId());
			request.setAttribute(WebShare.INFO_KEY, "vkc.favorites.category.registered");
		}

		return DEFAULT_FORWARD;
	}

	private ActionForward handleAddDocumentToFavorites(ShowCategoryForm form, HttpServletRequest request) throws DBException {
		if (form.isNotuptodate()) {
			return DEFAULT_FORWARD;
		}

		VKCUser user = form.getUser();
		
		if (!user.isGuestUser()) {
			VKCDocumentFavoritesSerializer.addDocumentFavorites(form.getUser().getUserId(), form.getDocumentId());
			request.setAttribute(WebShare.INFO_KEY, "vkc.favorites.document.registered");
		}
	
		return new ActionForward("/templates/${template.name}/CategoryView.jsp?anchor=doc" + form.getDocumentId(), false);				
	}
}