/*
 * Created on 2005.05.16.
 *
 * TODO To change the template for this generated file go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
package com.etixpert.evolution.gui.servlets;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.jstl.core.Config;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;

import org.apache.commons.fileupload.DiskFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;

import com.etixpert.evolution.EvolutionException;
import com.etixpert.evolution.HibernateUtil;
import com.etixpert.evolution.LoginException;
import com.etixpert.evolution.ObjectSearch;
import com.etixpert.evolution.PersistableObject;
import com.etixpert.evolution.Tools;
import com.etixpert.evolution.app.bonus.BonusAction;
import com.etixpert.evolution.app.bonus.BonusList;
import com.etixpert.evolution.gui.servlets.pageactions.MultipartPageActionHandler;
import com.etixpert.evolution.gui.servlets.pageactions.PageActionHandler;
import com.etixpert.evolution.ws.WsHelper;
/**
 * @author Peter Albert
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class MainControl extends HttpServlet {
	public static Logger logger = Logger.getLogger("mainControl", new SLoggerFactory());
	//public static Logger logger = Logger.getRootLogger();
	//static Logger logger = Logger.getLogger("mainControl");




	public MainControl() {
        ResourceBundle bundle = ResourceBundle.getBundle("evolution");
        //SimpleLayout layout = new SimpleLayout();
        PatternLayout layout = new PatternLayout("%d{ABSOLUTE} %-p %c{2} %m%n");
        DailyRollingFileAppender appender = null;
        try {
            //appender = new FileAppender(layout, bundle.getString("logpath"), false);
            appender = new DailyRollingFileAppender(layout, bundle.getString("logpath"), "'.'yyyy-MM-dd");
        } catch(Exception e) {
            System.err.println("Couldn't create  appender");
            //throw new ServletException(e);}
        }

        logger.addAppender(appender);
	}


	public void doGet(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
		doPost(req, res);
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res)
	throws ServletException, IOException {
		//if (true) throw new NullPointerException();
		//validation

		JspFactory jspFactory = JspFactory.getDefaultFactory();
		PageContext pageContext = jspFactory.getPageContext(this, req, res,"", true, 0, true);
		req.setAttribute("pageContext", pageContext);

		HttpSession session = req.getSession();

		session.setAttribute("legal_jsp", "yes");

		SLogger.session = session;

		String pageAction = req.getParameter("pageAction");

		logger.info("Request arrived to control servlet");


		try {
			String url = req.getRequestURL().toString();
			String rightURL = url.substring(url.indexOf("/process")+9);

			
			if (pageAction!=null && pageAction.equals("checkuser")) {
				if (checkUser(req)) {
					logger.info("Good user name/password");
					res.setStatus(res.SC_OK);
					return;
				}
				else {
					logger.info("Bad user name/password");
					//res.setStatus(res.SC_BAD_REQUEST);
					res.sendError(res.SC_BAD_REQUEST, "User does not exist!");
					logger.info("Bad user name/password2");
					return;
				}
			}
			else
			if (!req.isRequestedSessionIdValid()) {
				doExpiredPage(req, res);
			} /*else if (!"login".equals(pageAction) && !GUIRightsHelper.isJspAllowed(session, rightURL)) {
				doNotAllowed(req,res, rightURL);
			} */
			else if (FileUpload.isMultipartContent(req)) {
			   doMultipartRequest(req, res);


			}
			else if  (req.getParameter("saveState")!=null) {

				doSaveStateRedirect(req, res);
				//jspFactory.releasePageContext(pageContext);
				return;
			}
			else if (pageAction!=null && pageAction.equals("login")) {
				logger.info("login action starting");
				String b = login(req,req.getSession());
				if (!b.equals("")) {
					Throwable d = new Throwable(b);


					LoginException le = new LoginException(b);
					req.getSession().setAttribute("lastException", le);
					res.sendRedirect("../evolutionErrorPage.jsp");
				}
				else res.sendRedirect("../main.html");
			}
			else  {

				doSimpleRedirect(req, res);
			}
			//jspFactory.releasePageContext(pageContext);
		} catch (Throwable t) {
		    //jspFactory.releasePageContext(pageContext);
			logger.info(t.getMessage());

			if (t instanceof ThreadDeath) {
				throw (ThreadDeath)t;
			}
			//set the exception the same way that jsp does
			  req.getSession().setAttribute("lastException", t);
			  try {
			  	HibernateUtil.closeSession();
			  } catch (Exception e) {
			      logger.error(e.getMessage(), e);
			  }

			  if (t instanceof EvolutionException)
			  	res.sendRedirect("../evolutionErrorPage.jsp");
		      else
		      	res.sendRedirect("../errorPage.jsp");
		    }


		//else throw new ServletException(new Exception("ControlServlet message: important parameters missing "+String.valueOf(c)));
	}

	private void doMultipartRequest(HttpServletRequest req, HttpServletResponse res) throws Exception {
	    logger.info("Request is multiparted");
	    HttpSession session = req.getSession();
	    DiskFileUpload upload = new DiskFileUpload();
        List files = upload.parseRequest(req);
        session.setAttribute("uploaded", files);
        Map jspMap  = fieldsToMap(files);

        //saveState
        String saveState = Tools.getVal(jspMap, "saveState","");
        if (!saveState.equals("") && !saveState.equalsIgnoreCase("nothing")) {
              logger.info("Saving state to "+saveState);
              Map map = (Map) session.getAttribute(saveState);
              if (map==null)
                  session.setAttribute(saveState, jspMap);
              else {
                  List l = (List) map.get("files");
                  if (l!=null) jspMap.put("files", l);
                  session.setAttribute(saveState, jspMap);
              }
        }

        //PageAction

        String pageAction = Tools.getVal(jspMap, "pageAction","");
        if (pageAction!=null && !pageAction.trim().equals("")) {
            logger.info("starting page action "+pageAction);
            if (doPageAction(req,res, pageAction)) return;
            logger.info("page action "+pageAction+" completed");
        } else
            session.removeAttribute("uploaded");

        //link
        String link = Tools.getVal(jspMap, "link", "");
        if (link==null || link.trim().equals(""))

            doSimpleRedirect(req, res);
        else {
            String rightLink = link;
            if (link.indexOf("process")!=-1)
                rightLink = link.substring(link.indexOf("process")+8);
            logger.info("redirect to "+rightLink);
    		res.sendRedirect("../"+rightLink);
        }



	}

	 private Map fieldsToMap(List fileItems) throws Exception {
	    Map map = new HashMap();
	    for (int i=0; i<fileItems.size(); i++) {
	         FileItem fileItem = (FileItem) fileItems.get(i);
	         if (fileItem.isFormField()) {
	             ArrayList l = (ArrayList) map.get(fileItem.getFieldName());
	             if (l==null) l = new ArrayList();
	             l.add(fileItem.getString());
	             map.put(fileItem.getFieldName(), l);
	         }
	    }

	    Iterator it = map.keySet().iterator();
	    HashMap newMap = new HashMap();
	    while (it.hasNext()) {
	        Object key = it.next();
	        ArrayList l = (ArrayList) map.get(key);
	        String[] values = new String[l.size()];
	        for (int i=0; i<l.size(); i++)
	            values[i] = (String) l.get(i);
	        newMap.put(key, values);
	    }

	    return newMap;
	 }

	private void doExpiredPage(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
		logger.warn("Session id is not valid: ");
		res.sendRedirect("../expired.jsp");
	}

	private void doNotAllowed(HttpServletRequest req, HttpServletResponse res, String jsp) throws IOException, ServletException{
		logger.warn("User tried to request a not allowed page: "+jsp);
		res.sendRedirect("../forbidden.jsp");
	}

	private void doSimpleRedirect(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException{
		String url = req.getRequestURL().toString();
		
		String rightURL = url.substring(url.indexOf("/process")+9);

		if (rightURL.equals("article_detail.jsp")) {
			if (req.getSession().getAttribute("CURRENT_ARTICLE_ID")==null) {
				res.sendRedirect("../article_selection.jsp");
				return;
			}
		}

		if (rightURL.equals("user_detail_personal.jsp")) {
			if (req.getSession().getAttribute("CURRENT_DISTRIBUTOR_ID")==null) {
				res.sendRedirect("../user_selection.jsp");
				return;
			}
		}

		if (rightURL.equals("customer_detail_personal.jsp")) {
			if (req.getSession().getAttribute("CURRENT_CUSTOMER_ID")==null) {
				res.sendRedirect("../customer_selection.jsp");
				return;
			}
		}

		if (rightURL.equals("interessent_detail_personal.jsp")) {
			if (req.getSession().getAttribute("CURRENT_INTERESSENT_ID")==null) {
				res.sendRedirect("../interessent_selection.jsp");
				return;
			}
		}		
		
		if (rightURL.equals("order_detail.jsp")) {
			if (req.getSession().getAttribute("CURRENT_ORDER_ID")==null) {
				res.sendRedirect("../order_selection.jsp");
				return;
			}
		}

		logger.info("Simply redirecting new location: "+rightURL);
		res.sendRedirect("../"+rightURL);
	}

	private void doSaveStateRedirect(HttpServletRequest req, HttpServletResponse res) throws IOException, Exception{
		String url = req.getRequestURL().toString();
		String rightURL = url.substring(url.indexOf("/process")+9);
		String name;
		PageContext pageContext = (PageContext) req.getAttribute("pageContext");
		String param = req.getParameter("saveState");

		int i = param.lastIndexOf("/");

		if (i!=-1)
			name = param.substring(param.lastIndexOf("/")+1);
		else
			name = param;



		if (!name.equals("nothing")) {
			logger.info("Saving state of file: "+name);
			saveState(req, name);
			logger.info("Saved state of file: "+name);
		}


		HttpSession session = req.getSession();


		if (req.getParameter("pageAction")!=null && !"".equals(req.getParameter("pageAction"))) {


			String pageAction = req.getParameter("pageAction");
			logger.info("Page action '"+pageAction+"' starting...");



			//simple customer
			if (pageAction.equals("new_customer_add_new_address")) {

				FormHelperC.addCustomerDetailAddressToMap((Map)session.getAttribute("new_customer_detail_address.jsp"),
						(Map)session.getAttribute("new_customer_addresses"), logger);

			}
			else if (pageAction.equals("new_interessent_add_new_address")) {

				FormHelperC.addCustomerDetailAddressToMap((Map)session.getAttribute("new_interessent_detail_address.jsp"),
						(Map)session.getAttribute("new_interessent_addresses"), logger);

			}
			else if (pageAction.equals("customer_add_new_address")) {

				FormHelperC.addCustomerDetailAddressToMap((Map)session.getAttribute("customer_detail_address.jsp"),
						(Map)session.getAttribute("customer_addresses"), logger);

			}
			else if (pageAction.equals("interessent_add_new_address")) {

				FormHelperC.addCustomerDetailAddressToMap((Map)session.getAttribute("interessent_detail_address.jsp"),
						(Map)session.getAttribute("interessent_addresses"), logger);

			}			
			else if (pageAction.equals("new_customer_add_new_bank")) {

				FormHelperC.addCustomerDetailBankToMap((Map)session.getAttribute("new_customer_detail_payment.jsp"),
						(Map)session.getAttribute("new_customer_banks"), logger);


			} else if (pageAction.equals("new_customer_add_new_credit")) {

				FormHelperC.addCustomerDetailCreditToMap((Map)session.getAttribute("new_customer_detail_payment.jsp"),
						(Map)session.getAttribute("new_customer_credits"), logger);


			} else if (pageAction.equals("customer_add_new_bank")) {

				FormHelperC.addCustomerDetailBankToMap((Map)session.getAttribute("customer_detail_payment.jsp"),
						(Map)session.getAttribute("customer_banks"), logger);


			} else if (pageAction.equals("customer_add_new_credit")) {

				FormHelperC.addCustomerDetailCreditToMap((Map)session.getAttribute("customer_detail_payment.jsp"),
						(Map)session.getAttribute("customer_credits"), logger);


			} else if (pageAction.equals("new_customer_cancel")) {

				FormHelperC.cancelNewCustomer(session);


			}else if (pageAction.equals("new_interessent_cancel")) {

				FormHelperC.cancelNewInteressent(session);


			} else if (pageAction.equals("new_customer_add_anyway")) {
				int id = FormHelperC.addDistributor(session, logger);
				logger.info("Distributor added");
				FormHelperC.addAddresses(session, id, logger);
				logger.info("Addresses added");
				FormHelperC.addBanks(session, id, logger);
				FormHelperC.addCredits(session, id, logger);
				logger.info("Page action ended: new_customer_added");
				session.setAttribute("NEW_CUSTOMER_ID", new Integer(id));
				FormHelper.logAcceptProtocol(pageContext, logger, (ArrayList)session.getAttribute("SIMILAR_CUSTOMERS"), new Integer(id));
				session.setAttribute("SIMILAR_CUSTOMERS", null);
				FormHelperC.cancelNewCustomer(session);
			} 
			else if (pageAction.equals("new_customer_add")) {

				boolean can = FormHelperC.checkConstraints(pageContext, logger);
				logger.info("constraint check ok: "+can);
				
				boolean similar = false;
				
			
				if (session.getAttribute("SIMILAR_CUSTOMERS")==null) {
					//pressed first
					similar = FormHelper.hasSimilars(pageContext, logger, false);
					logger.info("similar check ok: "+similar);
				}
				
				if (can && !similar) {
					int id = FormHelperC.addDistributor(session, logger);
					logger.info("Distributor added");
					FormHelperC.addAddresses(session, id, logger);
					logger.info("Addresses added");
					FormHelperC.addBanks(session, id, logger);
					FormHelperC.addCredits(session, id, logger);
					logger.info("Page action ended: new_customer_added");
					session.setAttribute("NEW_CUSTOMER_ID", new Integer(id));
					session.setAttribute("SIMILAR_CUSTOMERS", null);

				}
				if (can && !similar) FormHelperC.cancelNewCustomer(session);
			} else if (pageAction.equals("new_interessent_add")) {

				int id = FormHelperC.addInteressent(session, logger);
				logger.info("Interessent added");
				FormHelperC.addInteressentAddresses(session, id, logger);
				logger.info("Addresses added");
				logger.info("Page action ended: new_interessent_added");
				session.setAttribute("NEW_INTERESSENT_ID", new Integer(id));
				session.setAttribute("SIMILAR_INTERESSENTS", null);

				FormHelperC.cancelNewInteressent(session);
			} else if (pageAction.equals("customer_modify")) {

				int id = -1;
				try {
					id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
				} catch (Exception e) {
					throw e;
				}
				Map problem = FormHelper.checkDisallowBank(pageContext, logger, new Integer(id), "customer_payment_Map");
				if (problem!=null) {
					session.setAttribute("CUSTOMER_ALLOW_BANK_PROBLEM", problem);
				} else {
					FormHelperC.modifyDistributor(session, logger);
					logger.info("Distributor modified");
					FormHelperC.modifyAddresses(session, logger);
					logger.info("Addresses modified");
					FormHelperC.modifyBanks(session, logger);
					FormHelperC.modifyCredits(session, logger);
					logger.info("Page action ended: customer_modify");
					session.setAttribute("CUSTOMER_MODIFIED", "yes");
					logger.info("Page action ended: modify customer");
					session.setAttribute("customer_detail_address.jsp", new Hashtable());
					FormHelperC.loadDistributor(session, logger);
				}
			} else if (pageAction.equals("interessent_modify")) {

				int id = -1;
				try {
					id = Integer.parseInt((String)session.getAttribute("CURRENT_INTERESSENT_ID"));
				} catch (Exception e) {
					throw e;
				}
				FormHelperC.modifyInteressent(session, logger);
				logger.info("Interessent modified");
				FormHelperC.modifyInteressentAddresses(session, logger);
				logger.info("Addresses modified");
				session.setAttribute("INTERESSENT_MODIFIED", "yes");
				logger.info("Page action ended: modify interessent");
				session.setAttribute("interessent_detail_address.jsp", new Hashtable());
				FormHelperC.loadInteressent(session, logger);
			} else if (pageAction.equals("load_customer")) {

				String possibleDistrID = req.getParameter("distr_id");
				if (possibleDistrID!=null) {
					boolean b;
					try {
						b = FormHelperC.isExistingDistributor(session, possibleDistrID);
					} catch (Exception e) {
						throw e;
					}
					if (!b) throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_CUSTOMER"));
					session.setAttribute("CURRENT_CUSTOMER_ID", possibleDistrID);
				}
			   try {

				FormHelperC.loadDistributor(session, logger);
				} catch (Exception e) {
					throw e;
				}

			} else if (pageAction.equals("load_interessent")) {

				String possibleDistrID = req.getParameter("distr_id");
				if (possibleDistrID!=null) {
					boolean b;
					try {
						b = FormHelperC.isExistingInteressent(session, possibleDistrID);
					} catch (Exception e) {
						throw e;
					}
					if (!b) throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_INTERESSENT"));
					session.setAttribute("CURRENT_INTERESSENT_ID", possibleDistrID);
				}
			   try {

				FormHelperC.loadInteressent(session, logger);
				} catch (Exception e) {
					throw e;
				}

			} else if (pageAction.equals("new_customer_delete_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "new_customer_addresses", row, logger, new String[] {"default_delivery", "default_bill"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("customer_delete_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "customer_addresses", row, logger, new String[] {"default_delivery", "default_bill"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("customer_modify_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyAddressRow(session, "customer_addresses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_customer_modify_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyAddressRow(session, "new_customer_addresses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			}  else if (pageAction.equals("new_interessent_delete_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "new_interessent_addresses", row, logger, new String[] {"default_delivery", "default_bill"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("interessent_delete_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "interessent_addresses", row, logger, new String[] {"default_delivery", "default_bill"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("interessent_modify_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyInteressentAddressRow(session, "interessent_addresses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_interessent_modify_address_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyInteressentAddressRow(session, "new_interessent_addresses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			}else if (pageAction.equals("new_customer_delete_bank_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "new_customer_banks", row, logger, new String[] {"default_bill", "default_bonus"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_customer_delete_credit_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "new_customer_credits", row, logger, new String[] {});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("customer_delete_bank_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "customer_banks", row, logger, new String[] {"default_bill", "default_bonus"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("customer_delete_credit_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.deleteRow(session , "customer_credits", row, logger, new String[] {});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("customer_modify_credit_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyCreditRow(session, "customer_credits", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_customer_modify_credit_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyCreditRow(session, "new_customer_credits", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("customer_modify_bank_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyBankRow(session, "customer_banks", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_customer_modify_bank_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelperC.modifyBankRow(session, "new_customer_banks", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("cancel_password_changing")) {
				session.removeAttribute("password_person");
			}




















			//simple distr
			else if (pageAction.equals("new_user_add_new_address")) {

				FormHelper.addUserDetailAddressToMap((Map)session.getAttribute("new_user_detail_address.jsp"),
						(Map)session.getAttribute("new_user_addresses"), logger);

			}
			else if (pageAction.equals("user_add_new_address")) {

				FormHelper.addUserDetailAddressToMap((Map)session.getAttribute("user_detail_address.jsp"),
						(Map)session.getAttribute("user_addresses"), logger);

			}
			else if (pageAction.equals("user_add_bonus")) {

				FormHelper.addUserDetailBonusToMap((Map)session.getAttribute("user_detail_bonus.jsp"),
						(Map)session.getAttribute("user_bonuses"), logger);

			} else if (pageAction.equals("user_modify_bonus_row")) {

				int row = Integer.parseInt((String)req.getParameter("row"));

				try {
					FormHelper.modifyBonusRow(session, "user_bonuses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			}
			else if (pageAction.equals("new_user_add_new_bank")) {

				FormHelper.addUserDetailBankToMap((Map)session.getAttribute("new_user_detail_payment.jsp"),
						(Map)session.getAttribute("new_user_banks"), logger);


			} else if (pageAction.equals("new_user_add_new_credit")) {

				FormHelper.addUserDetailCreditToMap((Map)session.getAttribute("new_user_detail_payment.jsp"),
						(Map)session.getAttribute("new_user_credits"), logger);


			} else if (pageAction.equals("user_add_new_bank")) {

				FormHelper.addUserDetailBankToMap((Map)session.getAttribute("user_detail_payment.jsp"),
						(Map)session.getAttribute("user_banks"), logger);


			} else if (pageAction.equals("user_add_new_credit")) {

				FormHelper.addUserDetailCreditToMap((Map)session.getAttribute("user_detail_payment.jsp"),
						(Map)session.getAttribute("user_credits"), logger);


			}else if (pageAction.equals("new_user_cancel")) {

				FormHelper.cancelNewUser(session);


			} else if (pageAction.equals("start_password_changing")) {


				boolean admin = false;
				boolean distributor = false;
				boolean customer = false;

				boolean specialAgent=false;

				if	(session.getAttribute("admin")!=null) admin = true;
				if  (session.getAttribute("specialAgent")!=null) specialAgent = true;
				if	(session.getAttribute("customer")!=null) customer = true;
				if	(session.getAttribute("distributor")!=null) distributor = true;
				if	(session.getAttribute("specialAgent")!=null) specialAgent = true;

				if (!admin && !specialAgent) {
					String logged = (String)session.getAttribute("USER_LOGGED_ID");
					if (!logged.equalsIgnoreCase(req.getParameter("cnr")))
						throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "WRONG_DISTR_ID"));
				}
				req.getParameter("cnr");

				FormHelper.newPasswordChangeStart(session, req.getParameter("cnr"));


			} else if (pageAction.equals("change_password")) {
				boolean error = false;
				try {
					FormHelper.changePassword(pageContext, req);
				} catch (Exception e) {
					error = true;
					session.setAttribute("password_error", e.getMessage());
				}
				if (!error)
					session.setAttribute("PASSWORD_CHANGED", "yes");
			}
			else if (pageAction.equals("start_new_order")) {


				boolean admin = false;
				boolean distributor = false;
				boolean customer = false;
				boolean specialAgent=false;
				if	(session.getAttribute("admin")!=null) admin = true;
				if  (session.getAttribute("specialAgent")!=null) specialAgent = true;
				if	(session.getAttribute("customer")!=null) customer = true;
				if	(session.getAttribute("distributor")!=null) distributor = true;

				boolean[] rights = OrderHelper.getRights(session, null, req.getParameter("cnr"), OrderHelper.MASK_CREATE);

				if (!rights[OrderHelper.INDEX_CREATE])
						throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "WRONG_DISTR_ID"));



				OrderHelper.newOrderStart(pageContext, req.getParameter("cnr"));

				session.setAttribute("NEW_ORDER_STARTED", "yes");

			}  else if (pageAction.equals("start_new_abo")) {

			    String prefix = AboHelper.getPrefix(req);
			    boolean[] rights = AboHelper.getRights(session, prefix, AboHelper.MASK_CREATE);
			    if (!rights[AboHelper.INDEX_CREATE])
			    	throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "ABO_ERROR_1"));
			    boolean admin = false;
				boolean distributor = false;
				boolean customer = false;
				boolean specialAgent = false;
				if	(session.getAttribute("admin")!=null) admin = true;
				if  (session.getAttribute("specialAgent")!=null) specialAgent = true;
				if	(session.getAttribute("customer")!=null) customer = true;
				if	(session.getAttribute("distributor")!=null) distributor = true;

				/*if (!admin) {
					String logged = (String)session.getAttribute("USER_LOGGED_ID");
					if (!logged.equalsIgnoreCase(req.getParameter("cnr")))
						throw new EvolutionException("Distributor Id ist keine g�?¼ltig!");
				}*/

				String uid = null;
				if (prefix.equals("customer_"))
				    uid = (String)req.getSession().getAttribute("CURRENT_CUSTOMER_ID");
				else
				    uid = (String)req.getSession().getAttribute("CURRENT_DISTRIBUTOR_ID");
				AboHelper.newAboStart(session, uid , prefix, false);

				session.setAttribute(prefix+"NEW_ABO_STARTED", "yes");

			} else if (pageAction.equals("cancel_new_order")) {


				session.setAttribute("new_order.jsp", null);
				Map m = (Map)session.getAttribute("new_order_details");

				session.removeAttribute("NEW_ORDER_STARTED");
				session.removeAttribute("special_discount");
				session.removeAttribute("special_added_discount");
				session.removeAttribute("loaded_special_discount");
				session.removeAttribute("loaded_special_added_discount");
				session.removeAttribute("special_discount_grosshandler");
				session.removeAttribute("special_discount_handler");
				session.removeAttribute("loaded_special_discount_grosshandler");
				session.removeAttribute("loaded_special_discount_handler");
				
				session.removeAttribute("new_sconto_days");
				session.removeAttribute("modify_sconto_days");
				
				
				if (m!=null) {
					m.clear();
					m.put("count", new Integer(0));
				}
				logger.info("Page action ended (spec): cancel_new_order");

				String foStr = "";
				if (session.getAttribute("new_fo")!=null)
					foStr = "?fo=true";
				res.sendRedirect("../new_order_person_select.jsp" + foStr);
				return;


			} else if (pageAction.equals("cancel_new_abo")) {
			    logger.info("Page action: new_abo_cancel");
				String prefix = AboHelper.getPrefix(req);
				session.setAttribute(prefix+"new_abo.jsp", null);
				Map m = (Map)session.getAttribute(prefix+"new_abo_details");

				session.removeAttribute(prefix+"NEW_ABO_STARTED");

				if (m!=null) {
					m.clear();
					m.put("count", new Integer(0));
				}
				logger.info("Page action ended (spec): cancel_new_abo");

				res.sendRedirect("../detail_abo.jsp?prefix="+prefix);
				return;

			}	else if (pageAction.equals("new_user_add_anyway")) {
				int id = FormHelper.addDistributor(session, logger);
				FormHelper.addAddresses(session, id, logger);
				FormHelper.addBanks(session, id, logger);
				FormHelper.addCredits(session, id, logger);
				session.setAttribute("NEW_DISTRIBUTOR_ID", new Integer(id));
				FormHelper.logAcceptProtocol(pageContext, logger, (ArrayList)session.getAttribute("SIMILAR_DISTRIBUTORS"), new Integer(id));
				FormHelper.cancelNewUser(session);
			} else if (pageAction.equals("new_user_add")) {

				boolean can = FormHelper.checkConstraints(pageContext, logger) 
					&& FormHelper.checkDealer(pageContext, logger, false);
				logger.info("constraint check ok: "+can);
				
				boolean similar = false;
				
				similar = FormHelper.hasSimilars(pageContext, logger, true);
				logger.info("similar check ok: "+similar);
				
				if (can && !similar) {
					int id = FormHelper.addDistributor(session, logger);

					FormHelper.addAddresses(session, id, logger);

					FormHelper.addBanks(session, id, logger);
					FormHelper.addCredits(session, id, logger);

					session.setAttribute("NEW_DISTRIBUTOR_ID", new Integer(id));
					
					session.setAttribute("SIMILAR_DISTRIBUTORS", null);
				}
				if (can && !similar) FormHelper.cancelNewUser(session);
			} else if (pageAction.equals("user_modify")) {

				int id = -1;
				try {
					id = Integer.parseInt((String)session.getAttribute("CURRENT_DISTRIBUTOR_ID"));
				} catch (Exception e) {
					throw e;
				}
				
				boolean dealerCheck = FormHelper.checkDealer(pageContext, logger, true);
				Map problem = FormHelper.checkDisallowBank(pageContext, logger, new Integer(id), "user_payment_Map");
				if (problem!=null) {
					session.setAttribute("DISTRIBUTOR_ALLOW_BANK_PROBLEM", problem);
				} else {
					if (dealerCheck) {
						FormHelper.modifyDistributor(session, logger);
						FormHelper.modifyAddresses(session, logger);
						FormHelper.modifyBanks(session, logger);
						FormHelper.modifyCredits(session, logger);

						try {
							FormHelper.modifyIndividualBonus(session, logger);
						} catch (Exception e) {
							throw e;
						}
						session.setAttribute("DISTRIBUTOR_MODIFIED", "yes");
						session.setAttribute("user_detail_address.jsp", new Hashtable());
						session.setAttribute("user_detail_bonus.jsp", new Hashtable());

						FormHelper.loadDistributor(session, logger);
					}
				}
			}
			else if (pageAction.equals("article_supplier_reload")) {
				
			}
			else if (pageAction.equals("load_order")) {

				String possibleOrderID = req.getParameter("order_id");
				if (possibleOrderID==null) possibleOrderID = req.getParameter("order_id0");


				if (OrderHelper.checkOrderID(session, possibleOrderID)) {
					boolean rights[] = OrderHelper.getRights(session, possibleOrderID, null, OrderHelper.MASK_VIEW);
					if (!rights[OrderHelper.INDEX_VIEW])
						throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_RIGHT"));
					logger.debug("Before loadOrder");
					String status = OrderHelper.loadOrder(session, possibleOrderID);

					session.setAttribute("CURRENT_ORDER_ID", possibleOrderID);
					session.setAttribute("CURRENT_MOD_ORDER_STATUS", status);
				} else {
					logger.warn("Order cannot be loaded. Redirecting selection page... (load_order_action ended spec.)");
					session.setAttribute("order_loading_error", LocaleSupport.getLocalizedMessage(pageContext, "ORDER_CANNOT_BE_LOADED"));
					res.sendRedirect("../order_selection.jsp");
					return;
				}

			} else if (pageAction.equals("load_abo")) {

			    String prefix=AboHelper.getPrefix(req);
			    boolean[] rights = AboHelper.getRights(session, prefix, AboHelper.MASK_VIEW);
			    if (!rights[AboHelper.INDEX_VIEW])
			    	throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "ABO_ERROR_2"));


			    logger.info("prefix in load abo: "+prefix);
			    if (req.getParameter("id")==null || req.getParameter("id").equals("")) {

			        session.setAttribute(prefix+"loading_abo_error", LocaleSupport.getLocalizedMessage(pageContext, "ABO_ERROR_3"));
			        res.sendRedirect("../"+prefix+"detail_abo.jsp?prefix="+prefix);
			        return;
			    }

			    AboHelper.loadAbo(session, req.getParameter("id"), "abo_detail.jsp", prefix);
			    session.setAttribute(prefix+"CURRENT_ABO_ID", req.getParameter("id"));
			} else if (pageAction.equals("load_user")) {

				String possibleDistrID = req.getParameter("distr_id");
				if (possibleDistrID!=null) {
					boolean b;
					try {
						b = FormHelper.isExistingDistributor(session, possibleDistrID);
					} catch (Exception e) {
						throw e;
					}

					if (!b) throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_DISTRIBUTOR"));
					session.setAttribute("CURRENT_DISTRIBUTOR_ID", possibleDistrID);
				}

			   try {

				FormHelper.loadDistributor(session, logger);
				} catch (Exception e) {
					throw e;
				}

			} else if (pageAction.equals("distributor_data")) {
				String level_id = req.getParameter("levelID");
				String dist_id = req.getParameter("distID");
				int ilevel = Integer.parseInt(level_id);
				if (ilevel == 100 || ilevel==200 || ilevel==130 || ilevel == 160) {
					session.setAttribute("CURRENT_CUSTOMER_ID", dist_id);
					try {
						FormHelperC.loadDistributor(session, logger);
					} catch (Exception e) {
						throw e;
					}
				} else if (ilevel >= 5000) {
					session.setAttribute("CURRENT_INTERESSENT_ID", dist_id);
					try {
						FormHelperC.loadInteressent(session, logger);
					} catch (Exception e) {
						throw e;
					}
					
				} else {
					session.setAttribute("CURRENT_DISTRIBUTOR_ID", dist_id);
					try {
						FormHelper.loadDistributor(session, logger);
					} catch (Exception e) {
						throw e;
					}

				}


			}
			else if (pageAction.equals("distributor_list")) {

				session.setAttribute("id_from", req.getParameter("id_from"));
				session.setAttribute("id_to", req.getParameter("id_to"));
				session.setAttribute("for_id", "yes");
				session.removeAttribute("for_name");
				session.removeAttribute("for_email");
				session.removeAttribute("for_company");
				session.setAttribute("sorted_by", req.getParameter("sorted_by"));

			}
			else if (pageAction.equals("distributor_list2")) {
				session.setAttribute("name_from", req.getParameter("name_from"));
				session.setAttribute("name_to", req.getParameter("name_to"));
				session.setAttribute("for_name", "yes");
				session.removeAttribute("for_id");
				session.removeAttribute("for_email");
				session.removeAttribute("for_company");
				session.setAttribute("sorted_by", req.getParameter("sorted_by"));
			} 
			else if (pageAction.equals("distributor_list3")) {
				session.setAttribute("email", req.getParameter("email"));
				session.setAttribute("for_email", "yes");
				session.removeAttribute("for_id");
				session.removeAttribute("for_name");
				session.removeAttribute("for_company");
				session.setAttribute("sorted_by", req.getParameter("sorted_by"));
			}
			else if (pageAction.equals("distributor_list4")) {
				session.setAttribute("company", req.getParameter("company"));
				session.setAttribute("for_company", "yes");
				session.removeAttribute("for_id");
				session.removeAttribute("for_name");
				session.removeAttribute("for_email");
				session.setAttribute("sorted_by", req.getParameter("sorted_by"));
			}			
			else if (pageAction.equals("article_list")) {
				session.setAttribute("aid_from", req.getParameter("aid_from"));
				session.setAttribute("aid_to", req.getParameter("aid_to"));
				session.setAttribute("for_id", "yes");
				session.removeAttribute("for_name");
			}
			else if (pageAction.equals("article_supplier_save")) {
				try {
					FormHelper.addSupplierRow(session, req, logger);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());	
				} 
			}
			else if (pageAction.equals("article_list2")) {
				session.setAttribute("descr", req.getParameter("descr"));
				session.setAttribute("for_name", "yes");
				session.removeAttribute("for_id");
			}
			else if (pageAction.equals("new_user_delete_address_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.deleteRow(session , "new_user_addresses", row, logger, new String[] {"default_delivery", "default_bill"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("user_delete_address_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.deleteRow(session , "user_addresses", row, logger, new String[] {"default_delivery", "default_bill"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("user_modify_address_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.modifyAddressRow(session, "user_addresses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_user_modify_address_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.modifyAddressRow(session, "new_user_addresses", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_user_delete_bank_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.deleteRow(session , "new_user_banks", row, logger, new String[] {"default_bill", "default_bonus"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_user_delete_credit_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.deleteRow(session , "new_user_credits", row, logger, new String[] {});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("user_delete_bank_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.deleteRow(session , "user_banks", row, logger, new String[] {"default_bill", "default_bonus"});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("user_delete_credit_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.deleteRow(session , "user_credits", row, logger, new String[] {});
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("user_modify_credit_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.modifyCreditRow(session, "user_credits", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_user_modify_credit_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.modifyCreditRow(session, "new_user_credits", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("user_modify_bank_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.modifyBankRow(session, "user_banks", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("new_user_modify_bank_row")) {
				int row = Integer.parseInt((String)req.getParameter("row"));
				try {
					FormHelper.modifyBankRow(session, "new_user_banks", row, logger);
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("print_downline")) {
				String id = req.getParameter("rootID");
				String[] roles = req.getParameterValues("role");
				String[] pids = req.getParameterValues("pids");
				String countryID = req.getParameter("countryID");
				String orderBy = req.getParameter("sortBy");

				String title1 = req.getParameter("title1");
				String title2 = req.getParameter("title2");
				
				int plength = 0;
				
				if (pids != null) plength = pids.length;
				
				String[] partner_ids = new String[plength+1];
				
				partner_ids[0] = "0";
				
				for (int ttt = 0; ttt<plength; ttt++)
					partner_ids[ttt+1] = pids[ttt];

				boolean email = false;
				boolean email_display = false;
				
				if (req.getParameter("email")!=null) email = true;
				if (req.getParameter("email_display")!=null) email_display = true;
				

				req.removeAttribute("pageAction");
				try {
					//StatHelper.printDownline(id, session, res);
					logger.info("DEBUG: "+id+" "+orderBy+" "+roles+" "+countryID);
					StatHelper.printDownline(id, orderBy, roles, partner_ids, countryID, email, email_display, session, res, title1, title2);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				return;
			} else if (pageAction.equals("print_liefer")) {
				String id = req.getParameter("rootID");
				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");
				try {
					StatHelper.printLiefer(df, dt, id, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../lieferschneinsummen.jsp");
				logger.info("Page action 'print_liefer' (spec) ended.");
				return;
			} else if (pageAction.equals("print_addresses")) {
				logger.info("Page action 'print_addresses' started");
				
				String[] orders = req.getParameterValues("order_id");
				
				try {
					//OrderListHelper.printAddresses(orders, req, res);
					WsHelper.callPostWS(orders, logger, res);
					
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../lieferschneinsummen.jsp");
				logger.info("Page action 'print_addresses' (spec) ended.");
				//session.setAttribute("ws_called", "yes");
				
				return;
			} else if (pageAction.equals("print_da")) {
				String id = req.getParameter("rootID");
				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");

				String[] articles = new String[10];

				for (int h=0; h<10; h++)
					articles[h] = req.getParameter("article"+h);
				try {
					StatHelper.printDA(df, dt, id, articles, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../downline_article.jsp");
				logger.info("Page action 'print_da' (spec) ended.");
				return;
			} else if (pageAction.equals("print_bda")) {

				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");
				String[] roles = req.getParameterValues("role");
				int root = 0;
				
				try {
					root = new Integer(req.getParameter("downline")).intValue();
				} catch (Exception e) {
					root = 0;
				}
				
				String[] articles = new String[10];

				for (int h=0; h<10; h++)
					articles[h] = req.getParameter("article"+h);
				try {
					StatHelper.printBDA(df, dt, articles, new Integer(root), roles, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../bda.jsp");
				logger.info("Page action 'print_bda' (spec) ended.");
				return;
			}else if (pageAction.equals("print_tages")) {
				String d = req.getParameter("date");
				try {
					StatHelper.printTages(d, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../tages_produktion.jsp");
				logger.info("Page action 'print_tages' (spec) ended.");
				return;
			} else if (pageAction.equals("print_umsatz1")) {

				String id = req.getParameter("rootID");
				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");
				String country = req.getParameter("countryID");

				String[] roles = req.getParameterValues("role");
				
				logger.info(id+","+df+","+dt+","+country);

				try {
					StatHelper.printUmsatz1(df,dt, roles, id, country, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../umsatzproduktion.jsp");
				logger.info("Page action 'print_umsatz1' (spec) ended.");
				return;
			} else if (pageAction.equals("print_umsatz2")) {

				String df = req.getParameter("dateFrom");
				String country = req.getParameter("countryID");

				logger.info(df+","+country);

				try {
					StatHelper.printUmsatz2(df,country, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				logger.info("Page action 'print_umsatz2' (spec) ended.");
				//res.sendRedirect("../umsatzsteuervoranmeldung.jsp");
				return;
			} else if (pageAction.equals("print_nq")) {

				String df = req.getParameter("dateFrom");
				String level = req.getParameter("levelID");

				logger.info(df+","+level);

				try {
					StatHelper.printNQ(df,level, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../newqualification.jsp");
				logger.info("Page action 'print_nq' (spec) ended.");
				return;
			} else if (pageAction.equals("print_dwo")) {

				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");

				logger.info(df+","+dt);

				try {
					StatHelper.printDWO(df,dt, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				logger.info("Page action 'print_dwo' (spec) ended.");
				//res.sendRedirect("../dwo.jsp");
				return;
			} else if (pageAction.equals("print_ta")) {
					String df = req.getParameter("dateFrom");
					String dt = req.getParameter("dateTo");
					String downline = req.getParameter("downline");
					String downline_name = req.getParameter("downline_name");
					
					session.setAttribute("downline", downline);
					session.setAttribute("downline_name", downline_name);
					logger.info(df+","+dt + "," + downline + "," + downline_name);

					try {
						StatHelper.printTA(df,dt, downline, downline_name, session, res);
					} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
					}
					logger.info("Page action 'print_ta' (spec) ended.");
					//res.sendRedirect("../toparticles.jsp");
					return;
			}else if (pageAction.equals("print_ta_op")) {
				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");
				String downline = req.getParameter("downline");
				String downline_name = req.getParameter("downline_name");
				
				session.setAttribute("downline", downline);
				session.setAttribute("downline_name", downline_name);
				logger.info(df+","+dt + "," + downline + "," + downline_name);

				try {
					StatHelper.printTA_OP(df,dt, downline, downline_name, session, res);
				} catch (Exception e) {
				throw new EvolutionException(e.getMessage());
				}
				logger.info("Page action 'print_ta' (spec) ended.");
				//res.sendRedirect("../toparticles.jsp");
				return;
		} 
			else if (pageAction.equals("print_nm")) {

				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");
				String sortBy = req.getParameter("sortBy");

				int root = 0;
				
				try {
					root = new Integer(req.getParameter("downline")).intValue();
				} catch (Exception e) {
					root = 0;
				}

				logger.info(df+","+dt+", "+sortBy);

				try {
					StatHelper.printNM(df,dt, sortBy, new Integer(root), session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				logger.info("Page action 'print_nm' (spec) ended.");
				//res.sendRedirect("../new_members.jsp");
				return;
			} else if (pageAction.equals("print_tt")) {

				String df = req.getParameter("dateFrom");
				String dt = req.getParameter("dateTo");
				String sortBy = req.getParameter("sortBy");
				String[] roles = req.getParameterValues("role");

				logger.info(df+","+dt+", "+sortBy);

				try {
					StatHelper.printTT(df,dt, sortBy, roles, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				//res.sendRedirect("../topten.jsp");
				logger.info("Page action 'print_tt' (spec) ended.");
				return;
			} else if (pageAction.equals("print_bl")) {

				String month = req.getParameter("month");
				String sortBy = req.getParameter("sortBy");

				logger.info(month+","+sortBy);

				try {
					StatHelper.printBL(month, sortBy, session, res);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage());
				}
				logger.info("Page action 'print_tt' (spec) ended.");
				//res.sendRedirect("../birthdaylist.jsp");
				return;
			}else if (pageAction.equals("show_liefer")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String id = req.getParameter("rootID");

				session.setAttribute("liefer_dateFrom", dateFrom);
				session.setAttribute("liefer_dateTo", dateTo);
				session.setAttribute("liefer_id", id);

				session.setAttribute("SHOW_LIEFER", "yes");
			} else if (pageAction.equals("show_dl")) {
				String id = req.getParameter("rootID");

				session.setAttribute("dl_id", id);

				session.setAttribute("SHOW_DL", "yes");
			} else if (pageAction.equals("show_da")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String id = req.getParameter("rootID");

				String[] articles = new String[10];

				for (int h=0; h<10; h++)
					articles[h] = req.getParameter("article"+h);

				session.setAttribute("da_dateFrom", dateFrom);
				session.setAttribute("da_dateTo", dateTo);
				session.setAttribute("da_id", id);
				session.setAttribute("da_articles", articles);

				session.setAttribute("SHOW_DA", "yes");
			} else if (pageAction.equals("download_files")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");

				String dfs_dateFrom = "";
				String dfs_dateTo = "";

				try {
					dfs_dateFrom = FormHelper.getDateFormatForDownloadFiles(dateFrom);
				} catch (Exception e) {
					dfs_dateFrom = FormHelper.getDefaultDateForDownloadFiles();
				}

				try {
					dfs_dateTo = FormHelper.getDateFormatForDownloadFiles(dateTo);
				} catch (Exception e) {
					dfs_dateTo = FormHelper.getDateFormatForDownloadFiles(FormHelper.formatSQLDate(new java.sql.Date(System.currentTimeMillis())));
					
				}


				session.setAttribute("dfs_dateFrom", dfs_dateFrom);
				session.setAttribute("dfs_dateTo", dfs_dateTo);				
			} else if (pageAction.equals("show_bda")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String[] roles = req.getParameterValues("role");
				int root = 0;
				
				try {
					root = new Integer(req.getParameter("downline")).intValue();
				} catch (Exception e) {
					root = 0;
				}
				
				
				String[] articles = new String[10];

				for (int h=0; h<10; h++)
					articles[h] = req.getParameter("article"+h);

				session.setAttribute("bda_dateFrom", dateFrom);
				session.setAttribute("bda_dateTo", dateTo);

				session.setAttribute("bda_articles", articles);

				session.setAttribute("bda_root", new Integer(root));
				
				session.setAttribute("bda_roles", roles);
				
				ArrayList checks = new ArrayList();
				if (roles!=null)
					for (int i0=0; i0<roles.length; i0++)
						checks.add(roles[i0]);
				
				String c1 = checks.contains("100")?" checked ":"";
				String c2 = checks.contains("200")?" checked ":"";
				String c3 = checks.contains("300")?" checked ":"";
				
				session.setAttribute("bda_checks", new String[] {c1,c2,c3});
				
				session.setAttribute("SHOW_BDA", "yes");
			} else if (pageAction.equals("show_umsatz1")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String id = req.getParameter("rootID");
				String country = req.getParameter("countryID");

				String[] roles = req.getParameterValues("role");
				
				session.setAttribute("umsatz1_dateFrom", dateFrom);
				session.setAttribute("umsatz1_dateTo", dateTo);
				session.setAttribute("umsatz1_id", id);
				session.setAttribute("umsatz1_country", country);

				session.setAttribute("up_roles", roles);
				
				ArrayList checks = new ArrayList();
				
				if (roles!=null)
					for (int i0=0; i0<roles.length; i0++)
						checks.add(roles[i0]);
				
				String c1 = checks.contains("100:0")?" checked ":"";
				String c2 = checks.contains("130:0")?" checked ":"";
				String c3 = checks.contains("160:0")?" checked ":"";
				String c4 = checks.contains("200:0")?" checked ":"";
				String c5 = checks.contains("300:0")?" checked ":"";
				String c6 = checks.contains("300:1")?" checked ":"";
				String c7 = checks.contains("330:0")?" checked ":"";
				String c8 = checks.contains("350:0")?" checked ":"";
				String c9 = checks.contains("370:0")?" checked ":"";
				String c10 = checks.contains("400:0")?" checked ":"";
				String c11 = checks.contains("400:1")?" checked ":"";
				
				session.setAttribute("up_checks", new String[] {c1,c2,c3, c4, c5, c6, c7, c8, c9, c10, c11});
				
				session.setAttribute("SHOW_UMSATZ1", "yes");
			} else if (pageAction.equals("show_umsatz2")) {
				String dateFrom = req.getParameter("dateFrom");
				String country = req.getParameter("countryID");

				if (country.equals("null")) country = null;

				session.setAttribute("umsatz2_dateFrom", dateFrom);
				session.setAttribute("umsatz2_countryID", country);

				session.setAttribute("SHOW_UMSATZ2", "yes");
			} else if (pageAction.equals("show_nq")) {
				String dateFrom = req.getParameter("dateFrom");
				String level = req.getParameter("levelID");

				session.setAttribute("nq_dateFrom", dateFrom);
				session.setAttribute("nq_levelID", level);

				logger.info("DateFrom: "+dateFrom+", "+level);

				session.setAttribute("SHOW_NQ", "yes");
			} else if (pageAction.equals("show_dwo")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");

				session.setAttribute("dwo_dateFrom", dateFrom);
				session.setAttribute("dwo_dateTo", dateTo);

				logger.info("DateFrom: "+dateFrom+", "+dateTo);

				session.setAttribute("SHOW_DWO", "yes");
			} else if (pageAction.equals("show_ta")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String downline = req.getParameter("downline");
				String downline_name = req.getParameter("downline_name");
				
				session.setAttribute("downline", downline);
				session.setAttribute("downline_name", downline_name);
				session.setAttribute("ta_dateFrom", dateFrom);
				session.setAttribute("ta_dateTo", dateTo);

				logger.info("DateFrom: "+dateFrom+", "+dateTo+ ", " + downline + "," + downline_name);

				session.setAttribute("SHOW_TA", "yes");
			} else if (pageAction.equals("show_ta_op")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String downline = req.getParameter("downline");
				String downline_name = req.getParameter("downline_name");
				
				session.setAttribute("downline", downline);
				session.setAttribute("downline_name", downline_name);
				session.setAttribute("ta_op_dateFrom", dateFrom);
				session.setAttribute("ta_op_dateTo", dateTo);

				logger.info("DateFrom: "+dateFrom+", "+dateTo+ ", " + downline + "," + downline_name);

				session.setAttribute("SHOW_TA_OP", "yes");
			}else if (pageAction.equals("show_nm")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String orderBy = req.getParameter("sortBy");
				int root = 0;
				
				try {
					root = new Integer(req.getParameter("downline")).intValue();
				} catch (Exception e) {
					root = 0;
				}
				session.setAttribute("nm_dateFrom", dateFrom);
				session.setAttribute("nm_dateTo", dateTo);
				session.setAttribute("nm_sortBy", orderBy);
				session.setAttribute("nm_root", new Integer(root));
				logger.info("DateFrom: "+dateFrom+", "+dateTo+", "+orderBy);

				session.setAttribute("SHOW_NM", "yes");
			} else if (pageAction.equals("show_bl")) {

				String month = req.getParameter("month");
				String orderBy = req.getParameter("sortBy");

				session.setAttribute("bl_month", month);
				session.setAttribute("bl_sortBy", orderBy);

				logger.info("Month: "+month+", "+orderBy);

				session.setAttribute("SHOW_BL", "yes");
			}else if (pageAction.equals("show_tt")) {
				String dateFrom = req.getParameter("dateFrom");
				String dateTo = req.getParameter("dateTo");
				String orderBy = req.getParameter("sortBy");

				String[] roles = req.getParameterValues("role");
				
				session.setAttribute("tt_dateFrom", dateFrom);
				session.setAttribute("tt_dateTo", dateTo);
				session.setAttribute("tt_sortBy", orderBy);
				session.setAttribute("tt_roles", roles);

				ArrayList checks = new ArrayList();
				
				if (roles!=null)
					for (int i0=0; i0<roles.length; i0++)
						checks.add(roles[i0]);
				
				String c1 = checks.contains("100")?" checked ":"";
				String c2 = checks.contains("130")?" checked ":"";
				String c3 = checks.contains("160")?" checked ":"";
				String c4 = checks.contains("200")?" checked ":"";
				String c5 = checks.contains("300")?" checked ":"";
				String c6 = checks.contains("330")?" checked ":"";
				String c7 = checks.contains("400")?" checked ":"";
				String c8 = checks.contains("370")?" checked ":"";
				
				session.setAttribute("tt_checks", new String[] {c1,c2,c3, c4, c5, c6, c7, c8});
				
				logger.info("DateFrom: "+dateFrom+", "+dateTo+", "+orderBy);

				session.setAttribute("SHOW_TT", "yes");
			}else if (pageAction.equals("show_tages")) {
				String date = req.getParameter("date");
				session.setAttribute("tages_date", date);
				session.setAttribute("SHOW_TAGES", "yes");
			}else if (pageAction.equals("modify_title")) {
				String which = req.getParameter("whichModify");
				try {
					FormHelper.modifyTitle(which, req.getParameter(which));
				} catch (Exception e) {throw e;}

			} else if (pageAction.equals("new_title")) {
				try {
					FormHelper.newTitle(req.getParameter("new"));
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("modify_language")) {

				String which = req.getParameter("whichModify");
				try {
					FormHelper.modifyLanguage(which, req.getParameter(which));
				} catch (Exception e) {throw e;}

			} else if (pageAction.equals("new_language")) {
				try {
					FormHelper.newLanguage(req.getParameter("new"));
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("modify_level_address")) {

				String which = req.getParameter("whichModify");
				try {
					FormHelper.modifyLevelAddress(which, req.getParameter(which));
				} catch (Exception e) {throw e;}

			} else if (pageAction.equals("new_level_address")) {
				try {
					FormHelper.newLevelAddress(req.getParameter("new"));
				} catch (Exception e) {
					throw e;
				}
			} else if (pageAction.equals("modify_country")) {

				String which = req.getParameter("whichModify");
				try {
					FormHelper.modifyCountry(which, req, logger);
				} catch (Exception e) {
					throw e;
				}

			} else if (pageAction.equals("new_country")) {
				try {
					FormHelper.newCountry(req, logger);
				} catch (Exception e) {
					throw e;
				}

			} else if (pageAction.equals("start_send_data")) {
				
				try {
					Runtime.getRuntime().exec("/home/evolution/bin/export_and_send_full_distributor_view");
					session.setAttribute("send_data_started", "yes");
				} catch (Throwable t) {
					session.setAttribute("send_data_error", "yes");
				}
			} 
			else if (pageAction.equals("download_data")) {
				String id = req.getParameter("id");
				FormHelper.downloadData(id, res);
				//res.sendRedirect("../download_files.jsp");
				logger.info("Page action 'download_data' (spec) ended.");
				return;
				//logger.info("page action ended: download data");
				//return;
			} else if (pageAction.equals("download_pdf")) {
				String id = req.getParameter("id");
				FormHelper.downloadPDF(id, res, false);
				logger.info("Page action 'download_pdf' (spec) ended.");
				return;
			} else if (pageAction.equals("download_ccpdf")) {
				String id = req.getParameter("id");
				FormHelper.downloadPDF(id, res, true);
				logger.info("Page action 'download_pdf' (spec) ended.");
				return;
			}else if (pageAction.equals("add_combi_content")) {
				FormHelper.addCombiToMap((Map)session.getAttribute("combi_articles"),
						req.getParameter("cart_id"),
						req.getParameter("quantity"),
						logger);
			} else if (pageAction.equals("add_new_combi_content")) {
				FormHelper.addCombiToMap((Map)session.getAttribute("new_combi_articles"),
						req.getParameter("art_id"),
						req.getParameter("quantity"),
						logger);
			} else if (pageAction.equals("delete_combi")) {
				FormHelper.deleteCombiFromMap((Map)session.getAttribute("combi_articles"),
						req.getParameter("row"),
						logger);
			} else if (pageAction.equals("new_delete_combi")) {
				FormHelper.deleteCombiFromMap((Map)session.getAttribute("new_combi_articles"),
						req.getParameter("row"),
						logger);
			} else if (pageAction.equals("modify_combi")) {
				FormHelper.modifyCombiFromMap((Map)session.getAttribute("combi_articles"),
						(Map)session.getAttribute("article_detail.jsp"),
						req.getParameter("row"),
						logger);
			} else if (pageAction.equals("new_modify_combi")) {
				FormHelper.modifyCombiFromMap((Map)session.getAttribute("new_combi_articles"),
						(Map)session.getAttribute("new_article.jsp"),
						req.getParameter("row"),
						logger);
			} else if (pageAction.equals("new_article")) {
				FormHelper.newArticle(session, logger);
				session.setAttribute("new_article.jsp", new HashMap());
				Map combiMap = new HashMap();
				combiMap.put("count", new Integer(0));
				session.setAttribute("new_combi_articles", combiMap);
				session.setAttribute("ARTICLE_ADDED", "yes");
			} else if (pageAction.equals("cancel_new_article")) {
				session.setAttribute("new_article.jsp", new HashMap());
				Map combiMap = new HashMap();
				combiMap.put("count", new Integer(0));
				session.setAttribute("new_combi_articles", combiMap);
			} else if (pageAction.equals("load_article")) {
				if (req.getParameter("artId")!=null) {

					String id = req.getParameter("artId");

					logger.info("Page action: load_article: "+id);


					if (!FormHelper.isExistingArticle(session, id)) throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_ARTICLE")+ id+"!");

					FormHelper.loadArticle(session, id,
						logger);
				}

			} 
			else if (pageAction.equals("new_customer_promote")) {
				boolean can = FormHelperC.checkConstraints(pageContext, logger);
				logger.info("constraint check ok: "+can);
				
				boolean similar = false;
				
				int id = -1;
				
				if (session.getAttribute("SIMILAR_CUSTOMERS")==null) {
					//pressed first
					similar = FormHelper.hasSimilars(pageContext, logger, false);
					logger.info("similar check ok: "+similar);
				}
				
				if (can && !similar) {
					id = FormHelperC.addDistributor(session, logger);
					logger.info("Distributor added");
					FormHelperC.addAddresses(session, id, logger);
					logger.info("Addresses added");
					FormHelperC.addBanks(session, id, logger);
					FormHelperC.addCredits(session, id, logger);
					logger.info("Page action ended: new_customer_added");
					session.setAttribute("NEW_CUSTOMER_ID", new Integer(id));
					session.setAttribute("SIMILAR_CUSTOMERS", null);
					int newid = FormHelperC.promoteToDistributor(session, logger, true);
					session.setAttribute("NEW_CUSTOMER_ID", "" + newid);
					logger.info("Customer promoted.");
					FormHelperC.addAddresses(session, newid, false, logger);
					logger.info("Addresses modified");
					FormHelperC.addBanks(session, newid, false, logger);
					FormHelperC.addCredits(session, newid, false, logger);
					//logger.info("Page action ended: customer_modify");
					
					//session.setAttribute("customer_detail_address.jsp", new Hashtable());

					PersistableObject po = new PersistableObject("customer_distributor", new String[] {"customer_id"});
					po.set("customer_id", id);
					po.set("distributor_id", newid);
					
					po.insert();
					
					//AboHelper.newAboStart(session, ""+newid , "user_", true);
					//session.setAttribute("user_NEW_ABO_STARTED", "yes");
					
					boolean wasError = false;
					
					if (false)
					try {
						String totalNetto = "";
						String totalBrutto = "";
						String totalPoints = "";
						String totalBonus = "";
						String totalTradeMargin = "";

						String[] values = AboHelper.countTotals(session, "user_new_abo_details", false);
						totalNetto = values[0];
						totalBrutto = values[1];
						totalBonus = values[2];
						totalTradeMargin = values[3];
						
						Map jspMap = (Map)session.getAttribute("user_new_abo.jsp");
						
						if (jspMap.containsKey("payment_slip"))
							jspMap.remove("payment_slip");
						
						jspMap.put("total_brutto", new String[] {totalBrutto});
						jspMap.put("total_netto", new String[] {totalNetto});
						jspMap.put("total_bonus", new String[] {totalBonus});
						jspMap.put("total_trade_margin", new String[] {totalTradeMargin});
						
						
						PageActionHandler.setBooleanValues((Map) session.getAttribute("user_new_abo_details"), "subscription");
						String orderid = AboHelper.addAbo(session, logger,"user_", true);
//						if (!orderid.equals(""))
		//					session.setAttribute(user_+"ABO_ADDED", orderid);
						session.setAttribute("user_NEW_ABO_STARTED", null);
					} catch (Exception e) {
						session.setAttribute("NEW_PROMOTED_ABO_ERROR", e.getMessage());
						wasError = true;
					}
					
					session.setAttribute("NEW_CUSTOMER_ID", id);
					session.setAttribute("PROMOTED_CUSTOMER_ID", "" + newid);				
					
					
					
					
					
					if (can && !similar) FormHelperC.cancelNewCustomer(session);

				}
				
				
			}
			else if (pageAction.equals("customer_promote")) {
				
				int id = -1;
				
					try {
						id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
					} catch (Exception e) {
						throw e;
					}
					
				Map problem = FormHelper.checkDisallowBank(pageContext, logger, new Integer(id), "customer_payment_Map");
				if (problem!=null) {
					session.setAttribute("CUSTOMER_ALLOW_BANK_PROBLEM", problem);
				} else {
					FormHelperC.modifyDistributor(session, logger);
					logger.info("Distributor modified");
					FormHelperC.modifyAddresses(session, logger);
					logger.info("Addresses modified");
					FormHelperC.modifyBanks(session, logger);
					FormHelperC.modifyCredits(session, logger);
					logger.info("Page action ended: customer_modify");
					session.setAttribute("CUSTOMER_MODIFIED", "yes");
					logger.info("Page action ended: modify customer");
					session.setAttribute("customer_detail_address.jsp", new Hashtable());

					
					//int id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
					int newid = FormHelperC.promoteToDistributor(session, logger, false);
					session.setAttribute("CURRENT_CUSTOMER_ID", "" + newid);
					logger.info("Customer promoted.");
					FormHelperC.addAddresses(session, newid, true, logger);
					logger.info("Addresses modified");
					FormHelperC.addBanks(session, newid, true, logger);
					FormHelperC.addCredits(session, newid, true, logger);
					logger.info("Page action ended: customer_modify");
					session.setAttribute("CUSTOMER_MODIFIED", "yes");
					logger.info("Page action ended: modify customer");
					session.setAttribute("customer_detail_address.jsp", new Hashtable());

					PersistableObject po = new PersistableObject("customer_distributor", new String[] {"customer_id"});
					po.set("customer_id", id);
					po.set("distributor_id", newid);
					
					po.insert();
					
					//AboHelper.newAboStart(session, ""+newid , "user_", true);
					//session.setAttribute("user_NEW_ABO_STARTED", "yes");
					
					boolean wasError = false;
					
					if (false)
					try {
						String totalNetto = "";
						String totalBrutto = "";
						String totalPoints = "";
						String totalBonus = "";
						String totalTradeMargin = "";

						String[] values = AboHelper.countTotals(session, "user_new_abo_details", false);
						totalNetto = values[0];
						totalBrutto = values[1];
						totalPoints = values[2];
						totalBonus = values[3];
						totalTradeMargin = values[4];
						
						Map jspMap = (Map)session.getAttribute("user_new_abo.jsp");
						
						if (jspMap.containsKey("payment_slip"))
							jspMap.remove("payment_slip");
						
						jspMap.put("total_brutto", new String[] {totalBrutto});
						jspMap.put("total_netto", new String[] {totalNetto});
						jspMap.put("total_points", new String[] {totalPoints});
						jspMap.put("total_bonus", new String[] {totalBonus});
						jspMap.put("total_trade_margin", new String[] {totalTradeMargin});
						
						
						PageActionHandler.setBooleanValues((Map) session.getAttribute("user_new_abo_details"), "subscription");
						String orderid = AboHelper.addAbo(session, logger,"user_", true);
//						if (!orderid.equals(""))
		//					session.setAttribute(user_+"ABO_ADDED", orderid);
						session.setAttribute("user_NEW_ABO_STARTED", null);
					} catch (Exception e) {
						session.setAttribute("PROMOTED_ABO_ERROR", e.getMessage());
						wasError = true;
					}
					
					
					session.setAttribute("CURRENT_CUSTOMER_ID", "" + id);
					session.setAttribute("PROMOTED_CUSTOMER_ID", "" + newid);				
					
					FormHelperC.loadDistributor(session, logger);
				}
				
			}
			
			else if (pageAction.equals("article_modify")) {

				try {
					FormHelper.modifyArticle(session, logger);
					session.setAttribute("ARTICLE_MODIFIED", "yes");
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage(), e);
				}

			} else if (pageAction.equals("modify_order") || pageAction.equals("order_add_mail")) { 
				try {
					boolean[] rights = OrderHelper.getRights(session, (String)session.getAttribute("CURRENT_ORDER_ID"), null, OrderHelper.MASK_MODIFY);
					if (!rights[OrderHelper.INDEX_MODIFY]) {
						session.setAttribute("ORDER_MODIFIED", "yes");
						throw new EvolutionException(LocaleSupport.getLocalizedMessage(pageContext, "NO_RIGHT"));
					}

					boolean mail = pageAction.equals("order_add_mail"); 
					
					String old_status = (String)session.getAttribute("CURRENT_MOD_ORDER_STATUS");
					String new_status = OrderHelper.getStatus((String)session.getAttribute("CURRENT_ORDER_ID"));
					
					if (!old_status.equals(new_status)) {
						session.setAttribute("ORDER_STATUS_CHANGED_IN_THE_BACKGROUND", "lklk");
						session.setAttribute("ORDER_MODIFIED", "yes");
					}
					else {
						OrderHelper.modifyOrder(pageContext, logger, mail);
						OrderHelper.loadOrder(session, (String)session.getAttribute("CURRENT_ORDER_ID"));
						session.setAttribute("ORDER_MODIFIED", "yes");
					}
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage(), e);
				}
			} else if (pageAction.equals("modify_abo")) {
			    String prefix = AboHelper.getPrefix(req);
			    try {
			    	PageActionHandler.changeBooleanValues(req, (Map) session.getAttribute(prefix+"abo_details"), "subscription");
			        AboHelper.modifyAbo(session, logger, prefix);
			        AboHelper.loadAbo(session, (String) session.getAttribute(prefix+"CURRENT_ABO_ID"),"abo_detail.jsp", prefix);
			        session.setAttribute(prefix+"ABO_MODIFIED", "yes");
			    } catch (Exception e) {
			        throw new EvolutionException(e.getMessage(), e);
			    }

			} else if (pageAction.equals("new_order_add") || pageAction.equals("new_order_add_mail")) { 
				try {
					boolean mail = pageAction.equals("new_order_add_mail"); 
					String orderid = OrderHelper.addOrder(pageContext, logger, mail);
					session.setAttribute("ORDER_ADDED", orderid);
					ObjectSearch os = new ObjectSearch();
					List l = os.search("select level_id, order_create from distributor d, general_rights r where d.level_id=r.role_id and d.id=?",
									new Object[]{new Integer((String)session.getAttribute("USER_LOGGED_ID"))});
					if (l.size()>0) {
						PersistableObject po = (PersistableObject) l.get(0);
						String right = (String) po.get("order_create");
						if (right.equalsIgnoreCase("s")) {

							OrderHelper.loadOrderStatic(orderid, session, logger);

							session.setAttribute("SELF_REDIRECT_STATIC", "yes");
						}
					}
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage(), e);
				}

			}    else if (pageAction.equals("new_abo_add")) {
			    String prefix = AboHelper.getPrefix(req);
				try {
					PageActionHandler.changeBooleanValues(req, (Map) session.getAttribute(prefix+"new_abo_details"), "subscription");
					String orderid = AboHelper.addAbo(session, logger,prefix, false);
					if (!orderid.equals(""))
						session.setAttribute(prefix+"ABO_ADDED", orderid);
				} catch (Exception e) {
					throw new EvolutionException(e.getMessage(), e);
				}

			}  else if (pageAction.equals("bonus_count")) {
				String id    = req.getParameter("distr_id");
				Integer iid  = null;
				try {
					iid = new Integer(id);
				} catch (Exception e) {
				}
				
				String details = req.getParameter("details");
				session.setAttribute("DETAILS", details != null ? details : "");
				
				session.setAttribute("BONUS_DISTRIBUTOR_INTEGER", iid != null ? iid :
					new Integer((String) session.getAttribute("USER_LOGGED_ID")));

				String sdate = req.getParameter("date");
				Calendar date = Calendar.getInstance();
				try {
				    String[] month_year = sdate.split("\\.");
				    date.set(Calendar.MONTH, Integer.parseInt(month_year[0]) - 1);
				    date.set(Calendar.YEAR, Integer.parseInt(month_year[1]));
				    date.set(Calendar.DAY_OF_MONTH, 1);
				    date = BonusList.getMonthBegin(date.getTime());
				} catch (Exception e) {
					logger.info(e.toString());
				}
				session.setAttribute("BONUS_DATE", date);
			}  else if (pageAction.equals("bonus_details")) {
				String id    = req.getParameter("distr_id");
				Integer iid  = null;
				try {
					iid = new Integer(id);
				} catch (Exception e) {
				}
				session.setAttribute("BONUSDETAILS_DISTRIBUTOR_INTEGER", iid != null ? iid :
					new Integer((String) session.getAttribute("USER_LOGGED_ID")));

				String sdate = req.getParameter("date");
				Calendar date = Calendar.getInstance();
				try {
				    String[] month_year = sdate.split("\\.");
				    date.set(Calendar.MONTH, Integer.parseInt(month_year[0]) - 1);
				    date.set(Calendar.YEAR, Integer.parseInt(month_year[1]));
				    date.set(Calendar.DAY_OF_MONTH, 1);
				    date = BonusList.getMonthBegin(date.getTime());
				} catch (Exception e) {
					logger.error(e.toString());
				}
				session.setAttribute("BONUS_DATE", date);
			} else if (pageAction.equals("bonus_print")) {

				String  id  = req.getParameter("distr_id");
				Integer uid = null;
				try {uid = new Integer((String) session.getAttribute("USER_LOGGED_ID"));} catch (Exception e) {	}

				Integer iid = null;
				try {iid = new Integer(id);} catch (Exception e) {}

				if (iid == null) {
					iid = uid;
				}

				String sdate = req.getParameter("date");
				Calendar date = Calendar.getInstance();
				try {
				    String[] month_year = sdate.split("\\.");
				    date.set(Calendar.MONTH, Integer.parseInt(month_year[0]) - 1);
				    date.set(Calendar.YEAR, Integer.parseInt(month_year[1]));
				    date.set(Calendar.DAY_OF_MONTH, 1);
				    date = BonusList.getMonthBegin(date.getTime());
				} catch (Exception e) {
					logger.error(e.toString());
				}
				byte[] data = uid != null ? BonusList.generatePDF(iid, uid, date.getTime(), BonusList.TYPE_BONUSDETAIL, getServletContext().getRealPath("WEB-INF")) : null;
				FormHelper.downloadPDF(data, "bonus", res);
				return;
			} else if (pageAction.equals("org_count")) {
				String id = req.getParameter("distr_id");
				Integer iid = null;
				try {
					iid = new Integer(id);
				} catch (Exception e) {
				}
				session.setAttribute("ORG_DISTRIBUTOR_INTEGER", iid != null ? iid :
					new Integer((String) session.getAttribute("USER_LOGGED_ID")));

				String sdate = req.getParameter("date");
				Calendar date = Calendar.getInstance();
				try {
				    String[] month_year = sdate.split("\\.");
				    date.set(Calendar.MONTH, Integer.parseInt(month_year[0]) - 1);
				    date.set(Calendar.YEAR, Integer.parseInt(month_year[1]));
				    date.set(Calendar.DAY_OF_MONTH, 1);
				    date = BonusList.getMonthBegin(date.getTime());
				} catch (Exception e) {
					logger.error(e.toString());
				}
				session.setAttribute("ORG_DATE", date);
			}
			else if (pageAction.equals("bonus_accept")) {
				String sdate = req.getParameter("date");
				Calendar date = Calendar.getInstance();
				try {
				    String[] month_year = sdate.split("\\.");
				    date.set(Calendar.MONTH, Integer.parseInt(month_year[0]) - 1);
				    date.set(Calendar.YEAR, Integer.parseInt(month_year[1]));
				    date.set(Calendar.DAY_OF_MONTH, 1);
				    date = BonusList.getMonthBegin(date.getTime());
				} catch (Exception e) {
					logger.error(e.toString());
				}
				String ret = BonusAction.accept(date.getTime(), getServletContext().getRealPath("WEB-INF"));
				StringBuffer message = ret != null ? new StringBuffer(ret) : null;
				session.setAttribute("BONUS_MESSAGE", message);
			}
			else if (pageAction.equals("bonus_generate")) {
				String sdate = req.getParameter("date");
				Calendar date = Calendar.getInstance();
				try {
				    String[] month_year = sdate.split("\\.");
				    date.set(Calendar.MONTH, Integer.parseInt(month_year[0]) - 1);
				    date.set(Calendar.YEAR, Integer.parseInt(month_year[1]));
				    date.set(Calendar.DAY_OF_MONTH, 1);
				    date = BonusList.getMonthBegin(date.getTime());
				} catch (Exception e) {
					logger.error(e.toString());
				}
				Date now = Calendar.getInstance().getTime();
				StringBuffer message = new StringBuffer();
				Object[] ret = BonusAction.generate(date.getTime(), now, getServletContext().getRealPath("WEB-INF"), message);
				BonusAction.storeAll(ret, now);
				session.setAttribute("BONUS_MESSAGE", message.append(LocaleSupport.getLocalizedMessage(pageContext, "BONUS_MESSAGE")));
			}
			else if (pageAction.equals("download_bill")) {
			    OrderListHelper.downloadBill(req, res);
			    logger.info("Page action 'download_bill' (spec) ended.");
			    return;
			}
			else if (!pageAction.equals("")) {
			    if (doPageAction(req,res, pageAction)) return;



			}

	        logger.info("page action ended: "+pageAction);

		}



		String link = req.getParameter("link");
		String rightLink = link;
		if (link.indexOf("process")!=-1)
			rightLink = link.substring(link.indexOf("process")+8);
		if (link==null) {
			logger.info("link parameter is null, unconsistent form!");
			return;
		}
		logger.info("Trying to redirect new location: "+rightLink);



		if (rightLink.equals("article_detail.jsp")) {
			logger.info("examine: article_detail.jsp");
			if (req.getSession().getAttribute("CURRENT_ARTICLE_ID")==null) {
				logger.info("Redirecting ../article_selection.jsp");
				res.sendRedirect("../article_selection.jsp");
				return;
			}
		}

		if (rightLink.equals("user_detail_personal.jsp")) {
			if (req.getSession().getAttribute("CURRENT_DISTRIBUTOR_ID")==null) {
				logger.info("Redirecting ../user_selection.jsp");
				res.sendRedirect("../user_selection.jsp");
				return;
			}
		}

		if (rightLink.equals("customer_detail_personal.jsp")) {
			if (req.getSession().getAttribute("CURRENT_CUSTOMER_ID")==null) {
				logger.info("Redirecting ../customer_selection.jsp");
				res.sendRedirect("../customer_selection.jsp");
				return;
			}
		}

		if (rightLink.equals("order_detail.jsp")) {
			logger.info("How can i get here?");
			if (req.getSession().getAttribute("CURRENT_ORDER_ID")==null) {
				logger.info("Redirecting ../order_selection.jsp");
				res.sendRedirect("../order_selection.jsp");
				return;
			}
		}

		logger.info("really redirect: "+rightLink);
		res.sendRedirect("../"+rightLink);
	}

	private boolean doPageAction(HttpServletRequest req, HttpServletResponse res, String pageAction) throws ServletException{
	    PageActionHandler pageActionHandler = null;
	    PageContext pageContext = (PageContext) req.getAttribute("pageContext");
	    try {
	      if (!FileUpload.isMultipartContent(req))
	        pageActionHandler = (PageActionHandler)  Class.forName("com.etixpert.evolution.gui.servlets.pageactions."+pageAction.toLowerCase()).newInstance();
	      else
	        pageActionHandler = (MultipartPageActionHandler) Class.forName("com.etixpert.evolution.gui.servlets.pageactions."+pageAction.toLowerCase()).newInstance();

	    } catch (Exception e) {
	        logger.warn("Cannot find page action: "+pageAction, e);
	    }

	    if (pageActionHandler!=null) {
	        pageActionHandler.setPageContext(pageContext);
	        pageActionHandler.handleRequest(req, res);
	        if (pageActionHandler.sentToResponse())
	            return true;

	    }
	    return false;

	}
	
	private boolean checkUser(HttpServletRequest request) {
		boolean ret = false;
		
		ResourceBundle bundle = ResourceBundle.getBundle("evolution" );
		
		String ips = bundle.getString("allowed_ips");
		
		
		String ip = request.getRemoteAddr();

		logger.info("IP: " + ip);
		
		String[] arr = ips.split(";");
		
		boolean hasIP = false;
		
		for (int i = 0; i<arr.length; i++)
			if (arr[i].equals(ip)) hasIP = true;
		
		if (!hasIP) {
			logger.info("IP not authenticated: "+request.getRemoteAddr()+", "+request.getRemoteHost());
			return false;
		}
		
		ObjectSearch os = new ObjectSearch("distributor", (List)null);
		os.setCondition("id = ? AND password = ? AND active = ? and (level_id > 290 or level_id < 50)");

		List result;

		String userID = (String)request.getParameter("user");
		String password = (String)request.getParameter("pw");
		
		boolean isInteger = false;
		try {
			Integer.valueOf(userID);
			isInteger = true;
		}
		catch (NumberFormatException e) {
		}		
		
		
		// parameter is the USERID
		if (isInteger) {
			os.setCondition("id = ? AND password = ? AND active = ? and (level_id > 290 or level_id < 50)");
			try {
				logger.info("Searching for user id: "+userID+", password: "+password);
				result = os.search(new Object[] {new Integer(userID), password, new Boolean(true)});
				logger.info("Result: "+result.size());
			}
			catch (Exception e) {
				logger.error("Database error ",e);
				return false;
			}
		}
		// parameter is the NICKNAME
		else {
			os.setCondition("nickname = ? AND password = ? AND active = ? and (level_id > 290 or level_id < 50)");
			try {
				logger.info("Searching for user nickname: "+userID+", password: "+password);
				result = os.search(new Object[] {userID, password, new Boolean(true)});
				logger.info("Result: "+result.size());
			}
			catch (Exception e) {
				logger.error("Database error ",e);
				return false;
			}
		}
		
		
		
//		try {
//			logger.info("Searching for user: "+userID+", password: "+password);
//			result = os.search(new Object[] {new Integer(userID), password, new Boolean(true)});
//			logger.info("Result: "+result.size());
//			
//		} catch (Exception e) {
//			logger.error("Database error ",e);
//			return false;
//		}

		if (result.size()>0) return true;

		//PersistableObject po = (PersistableObject)result.get(0);
		return ret;
	}
	
	private String login(HttpServletRequest req, HttpSession session) {
	    session.removeAttribute("admin"); 
	    session.removeAttribute("distributor"); 
	    session.removeAttribute("customer");
		session.removeAttribute("specialAgent");
		session.removeAttribute("dealer");
		String ret = "";
		PageContext pageContext = (PageContext) req.getAttribute("pageContext");
		String userId = req.getParameter("user");

		logger.info("login process started");

		if (userId == null || userId.equals("")) return LocaleSupport.getLocalizedMessage(pageContext, "USER_NAME_INVALID");

		int userIdi;



		try {
			userIdi = Integer.parseInt(userId);
		} catch (NumberFormatException nfe) {
			userIdi = -1;
		}



		String password = req.getParameter("password");


		if (password == null) return "password null";



		if ("".equals(password)) return LocaleSupport.getLocalizedMessage(pageContext, "PASSWORD_EMPTY");


		ObjectSearch os = new ObjectSearch("distributor", (List)null);

		os.setCondition("id = ? OR nickname = ?");


		List result;

		try {
			result = os.search(new Object[] {new Integer(userIdi), userId});
		} catch (Exception e) {
			logger.error("Database error ",e);
			return "Database error: "+e.getMessage();
		}


		if (result.size()==0) return LocaleSupport.getLocalizedMessage(pageContext, "NON_EXISTING_USER");

		PersistableObject po = (PersistableObject)result.get(0);


		String po_passwd = (String)po.get("password");

		if (!password.equals(po_passwd)) return LocaleSupport.getLocalizedMessage(pageContext, "INCORRECT_PASSWORD");

		if (po.get("active")!=null) {
			Boolean bol = (Boolean)po.get("active");
			if (!bol.booleanValue())
			return LocaleSupport.getLocalizedMessage(pageContext, "DEACTIVED_USER");
		}

		int level_id = 100;

		Object o = po.get("level_id");

		if (o instanceof Integer)
		   level_id = ((Integer)o).intValue();

		if (level_id == 3) session.setAttribute("specialAgent", "yes");

		String userLoggedIn = po.getString("id", "");
		String userLoggedLastName = po.getString("lastname", "");

		os = new ObjectSearch("user_roles", (List)null);
		os.setCondition("id = ?");
		try {
			result = os.search(new Object[] {new Integer(level_id)});
		} catch (Exception e) {
			return "Database error";
		}

		String type = "c";

		if (result.size()>0) {
			po = (PersistableObject)result.get(0);
			type = (String)po.get("dist_type");
		}


		logger.info("--------- Request IP: "+req.getRemoteAddr()+" -------------");
		logger.info("--------- User id: "+userLoggedIn+", "+userLoggedLastName+" -------------");
		logger.info("--------- Level id: "+level_id+" -------------");

		session.setAttribute("USER_LOGGED_REMOTE_ADDRESS", req.getRemoteAddr());
		session.setAttribute("USER_LOGGED_ID", userLoggedIn);
		session.setAttribute("USER_LOGGED_LEVEL_ID", new Integer(level_id).toString());
		session.setAttribute("USER_LOGGED_LASTNAME", userLoggedLastName);
		Config.set(session, Config.FMT_LOCALE, Locale.GERMANY);


		int intId = new Integer(userLoggedIn).intValue();

		if (intId < 100) session.setMaxInactiveInterval(14400);
		else session.setMaxInactiveInterval(1800);

		//impossible
		if (type!=null)
			{

				session.setAttribute("USER_LOGGED_TYPE", type);
				if (level_id == 300 || level_id == 350 || level_id == 330 || level_id == 370)
					session.setAttribute("USER_LOGGED_TYPE", "t");

				if (type.equals("e") && (level_id!=3)) {
					session.setAttribute("admin", "yes");

				}
				else if (type.equals("d") || type.equals("m") || type.equals("t")) 
					session.setAttribute("distributor", "yes");
				else if (type.equals("c")) {

					session.setAttribute("customer", "yes");
					if (level_id == 200) session.setAttribute("vip_customer", "too");
					
				}

				logger.info(level_id+ " "+type);
			}
		else session.setAttribute("USER_LOGGED_TYPE", "c");




		return ret;
	}

	private void saveState(HttpServletRequest req, String jspName) throws ServletException {
		HttpSession session = req.getSession();
		Map params = new Hashtable();
		//if (req.getParameter("comment")!=null)
		params.putAll(req.getParameterMap());

		if (jspName.equals("new_order.jsp") || jspName.equals("order_detail.jsp") || jspName.contains("address")) {
			logger.info("Encoding utf8 to iso8859-2 for page: " + jspName);
			for (Object keyObj : params.keySet()) {
				String keyStr = (String)keyObj;
				Object valueObj = params.get(keyStr);
				if (valueObj instanceof String[]) {
					String[] values = (String[])valueObj;
					String valueStr = "";
					try {
						valueStr = new String(values[0].getBytes(), "ISO-8859-2");
					} catch (Exception e) {
						valueStr = "encoding not supported!";
					}
					params.put(keyStr, new String[] {valueStr});
				}
			}
		}

		logger.debug("jspName: "+jspName);
		if (jspName.startsWith("list_orders.jsp") && req.getParameter("status")!=null) {
			String status = req.getParameter("status");
			//String statusTo = req.getParameter("toStatus");
		   logger.info("Storing  infos for listing orders. Status: "+status);
		  //String[] ids = req.getParameterValues("order_id");

		  //ez valamiert nem ment el semmmi olyat, amire az ordersearchacceptnek szuksege lett volna: Peter
		  //session.setAttribute(jspName+status, params);

		  session.setAttribute("orderstatus", status);

		  //ezt a kettot en tettem hozza
		  //session.setAttribute("orderTostatus", statusTo);
		  //session.setAttribute("orderids", ids);
		}

		session.setAttribute(jspName, params);

		if (jspName.equals("new_user_detail_add.jsp")) {
			if (!"new_user_add_anyway".equals(req.getParameter("pageAction")) &&
					!"new_user_add".equals(req.getParameter("pageAction"))) {
				session.setAttribute("SIMILAR_DISTRIBUTORS", null);
			} 
		}
		
		if (jspName.equals("new_user_detail_address.jsp")) {
			Map addressMap = (Map)session.getAttribute("new_user_addresses");
			if (req.getParameter("default_delivery")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_delivery"));
					addressMap.put("default_delivery", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					addressMap.put("default_bill", new Integer(i));
				}
			}
		}

		if (jspName.equals("user_detail_address.jsp")) {
			Map addressMap = (Map)session.getAttribute("user_addresses");
			if (req.getParameter("default_delivery")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_delivery"));
					addressMap.put("default_delivery", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					addressMap.put("default_bill", new Integer(i));
				}
			}
		}

		if (jspName.equals("new_user_detail_payment.jsp")) {
			Map banksMap = (Map)session.getAttribute("new_user_banks");
			if (req.getParameter("default_bonus")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bonus"));
					banksMap.put("default_bonus", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					banksMap.put("default_bill", new Integer(i));
				}
			}

			Map paymentMap = FormHelper.userDetailPaymentToMap((Map)session.getAttribute("new_user_detail_payment.jsp"));
			session.setAttribute("new_user_payment_Map", paymentMap);
		}

		if (jspName.equals("user_detail_payment.jsp")) {
			Map banksMap = (Map)session.getAttribute("user_banks");
			if (req.getParameter("default_bonus")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bonus"));
					banksMap.put("default_bonus", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					banksMap.put("default_bill", new Integer(i));
				}
			}

			Map paymentMap = FormHelper.userDetailPaymentToMap((Map)session.getAttribute("user_detail_payment.jsp"));
			session.setAttribute("user_payment_Map", paymentMap);
		}

		if (jspName.equals("user_detail_bonus.jsp")) {

		}

		if (jspName.equals("new_user_detail_personal.jsp")) {
			Map personalMap = FormHelper.userDetailPersonalToMap((Map)session.getAttribute("new_user_detail_personal.jsp"), logger);
			session.setAttribute("new_user_personal_Map", personalMap);
		}

		if (jspName.equals("new_user_detail_int.jsp")) {
			Map intMap = FormHelper.userDetailIntToMap((Map)session.getAttribute("new_user_detail_int.jsp"), logger);
			session.setAttribute("new_user_int_Map", intMap);
		}


		if (jspName.equals("user_detail_personal.jsp")) {
			Map personalMap = FormHelper.userDetailPersonalToMap((Map)session.getAttribute("user_detail_personal.jsp"), logger);
			session.setAttribute("user_personal_Map", personalMap);
		}

		if (jspName.equals("user_detail_int.jsp")) {
			Map intMap = FormHelper.userDetailIntToMap((Map)session.getAttribute("user_detail_int.jsp"), logger);
			session.setAttribute("user_int_Map", intMap);
		}














		//customers

		if (jspName.equals("new_customer_detail_add.jsp")) {
			if (!"new_customer_add_anyway".equals(req.getParameter("pageAction")) &&
					!"new_customer_add".equals(req.getParameter("pageAction"))) 
				session.setAttribute("SIMILAR_CUSTOMERS", null);
		}
		
		if (jspName.equals("new_customer_detail_address.jsp")) {
			Map addressMap = (Map)session.getAttribute("new_customer_addresses");
			if (req.getParameter("default_delivery")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_delivery"));
					addressMap.put("default_delivery", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					addressMap.put("default_bill", new Integer(i));
				}
			}
		}

		if (jspName.equals("new_interessent_detail_address.jsp")) {
			Map addressMap = (Map)session.getAttribute("new_interessent_addresses");
			if (req.getParameter("default_delivery")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_delivery"));
					addressMap.put("default_delivery", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					addressMap.put("default_bill", new Integer(i));
				}
			}
		}
		
		
		if (jspName.equals("customer_detail_address.jsp")) {
			Map addressMap = (Map)session.getAttribute("customer_addresses");
			if (req.getParameter("default_delivery")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_delivery"));
					addressMap.put("default_delivery", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					addressMap.put("default_bill", new Integer(i));
				}
			}
		}
		
		if (jspName.equals("interessent_detail_address.jsp")) {
			Map addressMap = (Map)session.getAttribute("interessent_addresses");
			if (req.getParameter("default_delivery")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_delivery"));
					addressMap.put("default_delivery", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (addressMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					addressMap.put("default_bill", new Integer(i));
				}
			}
		}

		if (jspName.equals("new_customer_detail_payment.jsp")) {
			Map banksMap = (Map)session.getAttribute("new_customer_banks");
			if (req.getParameter("default_bonus")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bonus"));
					banksMap.put("default_bonus", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					banksMap.put("default_bill", new Integer(i));
				}
			}

			Map paymentMap = FormHelperC.customerDetailPaymentToMap((Map)session.getAttribute("new_customer_detail_payment.jsp"));
			session.setAttribute("new_customer_payment_Map", paymentMap);
		}

		if (jspName.equals("customer_detail_payment.jsp")) {
			Map banksMap = (Map)session.getAttribute("customer_banks");
			if (req.getParameter("default_bonus")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bonus"));
					banksMap.put("default_bonus", new Integer(i));
				}
			}
			if (req.getParameter("default_bill")!=null) {
				if (banksMap!=null) {
					int i = Integer.parseInt(req.getParameter("default_bill"));
					banksMap.put("default_bill", new Integer(i));
				}
			}

			Map paymentMap = FormHelperC.customerDetailPaymentToMap((Map)session.getAttribute("customer_detail_payment.jsp"));
			session.setAttribute("customer_payment_Map", paymentMap);
		}


		if (jspName.equals("new_customer_detail_personal.jsp")) {
			Map personalMap = FormHelperC.customerDetailPersonalToMap((Map)session.getAttribute("new_customer_detail_personal.jsp"), logger);
			session.setAttribute("new_customer_personal_Map", personalMap);
		}

		if (jspName.equals("new_interessent_detail_personal.jsp")) {
			Map personalMap = FormHelperC.customerDetailPersonalToMap((Map)session.getAttribute("new_interessent_detail_personal.jsp"), logger);
			session.setAttribute("new_interessent_personal_Map", personalMap);
		}
		
		
		if (jspName.equals("new_customer_detail_int.jsp")) {
			logger.info("DEBUG: CKCKCKC");
			Map intMap = FormHelperC.customerDetailIntToMap((Map)session.getAttribute("new_customer_detail_int.jsp"), logger);
			session.setAttribute("new_customer_int_Map", intMap);
		}
		if (jspName.equals("new_interessent_detail_int.jsp")) {
			logger.info("DEBUG: CKCKCKC");
			Map intMap = FormHelperC.interessentDetailIntToMap((Map)session.getAttribute("new_interessent_detail_int.jsp"), logger);
			session.setAttribute("new_interessent_int_Map", intMap);
		}


		if (jspName.equals("customer_detail_personal.jsp")) {
			Map personalMap = FormHelperC.customerDetailPersonalToMap((Map)session.getAttribute("customer_detail_personal.jsp"), logger);
			session.setAttribute("customer_personal_Map", personalMap);
		}

		if (jspName.equals("customer_detail_int.jsp")) {
			Map intMap = FormHelperC.customerDetailIntToMap((Map)session.getAttribute("customer_detail_int.jsp"), logger);
			session.setAttribute("customer_int_Map", intMap);
		}
		if (jspName.equals("interessent_detail_personal.jsp")) {
			Map personalMap = FormHelperC.customerDetailPersonalToMap((Map)session.getAttribute("interessent_detail_personal.jsp"), logger);
			session.setAttribute("interessent_personal_Map", personalMap);
		}

		if (jspName.equals("interessent_detail_int.jsp")) {
			Map intMap = FormHelperC.interessentDetailIntToMap((Map)session.getAttribute("interessent_detail_int.jsp"), logger);
			session.setAttribute("interessent_int_Map", intMap);
		}

	}

}
