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

/**
 * @author Peter Albert
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletException;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.jstl.fmt.LocaleSupport;

import org.apache.log4j.Logger;
import org.hibernate.Transaction;

import com.etixpert.evolution.Distributor;
import com.etixpert.evolution.HibernateUtil;
import com.etixpert.evolution.Interessent;
import com.etixpert.evolution.ObjectSearch;
import com.etixpert.evolution.PersistableObject;

public class FormHelperC {
	
	public static int promoteToDistributor(HttpSession session, Logger logger, boolean new_) throws ServletException {
		int newID = -1;
		String password = new_?(String)session.getAttribute("LAST_GENERATED_CUSTOMER_PASSWORD"):
				(String)session.getAttribute("CURRENT_CUSTOMER_PASSWORD");
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute(new_?"new_customer_personal_Map":"customer_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute(new_?"new_customer_personal_Map":"customer_personal_Map"));
			if (session.getAttribute(new_?"new_customer_int_Map":"customer_int_Map")!=null)
			complex.putAll((Map)session.getAttribute(new_?"new_customer_int_Map":"customer_int_Map"));
			if (session.getAttribute(new_?"new_customer_payment_Map":"customer_payment_Map")!=null)
			complex.putAll((Map)session.getAttribute(new_?"new_customer_payment_Map":"customer_payment_Map"));
		
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			
			if (complex.get("pay_method_id")==null) complex.put("pay_method_id", new Integer(3));
			if (complex.get("shipping_id")==null) complex.put("shipping_id", new Integer(1));
			
			complex.remove("sponsor_name");
			complex.remove("customer_sponsor_name");
			complex.remove("row");
			
			int id = new_?((Integer)session.getAttribute("NEW_CUSTOMER_ID")).intValue():
					Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
			
			//complex.put("id", new Integer(newID));
			complex.put("password", password);
			
			
			
			java.sql.Date cd = new java.sql.Date(System.currentTimeMillis());
			
			complex.put("creation_date", cd);
			complex.put("created_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
			
			complex.put("level_id", new Integer(300));
			
			Distributor d = new Distributor(complex);
		
			newID = d.generateID();
			
			d.insert();
			
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
		
		return newID;
	}	
	
	public static boolean checkCCanBeDeleted(Integer id) throws Exception {
		ObjectSearch os = new ObjectSearch("order_header", "id");
		os.setCondition("account_id = ? AND pay_method_id = ? AND (order_status_id = ? OR order_status_id = ?)");
		
		List result = os.search(new Object[] {id, new Integer(2), new Integer(10), new Integer(20)});
		
		if (result.size()>0) return false;
		
		ObjectSearch os2 = new ObjectSearch("subscription_header", "id");
		os2.setCondition("account_id = ? AND pay_method_id = ?");
		
		List result2 = os2.search(new Object[] {id, new Integer(2)});
		
		if (result2.size()>0) return false;
		
		
		return true;
		
	}
	
	public static boolean checkBCanBeDeleted(Integer id) throws Exception {
		ObjectSearch os = new ObjectSearch("order_header", "id");
		os.setCondition("account_id = ? AND pay_method_id = ? AND (order_status_id = ? OR order_status_id = ?)");
		
		List result = os.search(new Object[] {id, new Integer(1), new Integer(10), new Integer(20)});
		
		if (result.size()>0) return false;
		
		ObjectSearch os2 = new ObjectSearch("subscription_header", "id");
		os2.setCondition("account_id = ? AND pay_method_id = ?");
		
		List result2 = os2.search(new Object[] {id, new Integer(1)});
		
		if (result2.size()>0) return false;

		
		return true;
		
	}	
	
	public static boolean checkConstraints(PageContext pc, Logger logger) {
		HttpSession session = pc.getSession();
		Map pMap = (Map)session.getAttribute("new_customer_payment_Map");
		Map iMap = (Map)session.getAttribute("new_customer_int_Map");
		try {
			int sponsor = ((Integer)iMap.get("sponsor")).intValue();
		} catch (Exception e) {
			session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "C_NO_SPONSOR"));
			return false;		
		}
		try {
			int level_id = ((Integer)iMap.get("level_id")).intValue();
		} catch (Exception e) {
			session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "C_NO_DIST_TYPE"));
			return false;		
		}
			 
		int pmethod = -1;
		try {
			pmethod = ((Integer)pMap.get("pay_method_id")).intValue();
		} catch (Exception e) {
			session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "C_NO_STANDARD_PAYMENT_METHOD"));
			return false;
		}
		if (pmethod == 2) {
			Map creditMap = (Map)session.getAttribute("new_customer_credits");
			if (creditMap == null) return false;
			int count = ((Integer)creditMap.get("count")).intValue();
			if (count == 0) {
				session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "C_NO_CREDITCARD"));
				return false;
			}
			
		} else if (pmethod == 1) {
			Map bankMap = (Map)session.getAttribute("new_customer_banks");
			if (bankMap == null) return false;
			int count = ((Integer)bankMap.get("count")).intValue();
			if (count == 0) {
				session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "C_NO_BANK_ACCOUNT"));
				return false;
			}
			if (pMap.get("allow_bank")!=null) {
				Boolean b = (Boolean)pMap.get("allow_bank");
				if (!b.booleanValue()) {
					session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "WARNING_ALLOW_BANK"));
					return false;
				}
			}

						
		} else if (pmethod == 6) {
			if (pMap.get("payment_slip")!=null) {
				Boolean b = (Boolean)pMap.get("payment_slip");
				if (!b.booleanValue()) {
					session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "WARNING_PAYMENT_SLIP"));
					return false;					
				}
			} else {
				session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "WARNING_PAYMENT_SLIP"));
				return false;									
			}
		}
				
		if (iMap.get("transferbonus")!=null) {
			Boolean b = (Boolean)iMap.get("transferbonus");
			if (b.booleanValue() && !hasAccount(session)) {
				session.setAttribute("CANNOT_ADD_CUSTOMER", LocaleSupport.getLocalizedMessage(pc, "C_NO_TRANSFERABLE_ACCOUNT"));
				return false;
			}
		}				
				
		return true;
	}
	
	
	public static boolean hasAccount(HttpSession session) {
		Map bankMap = (Map)session.getAttribute("new_customer_banks");
		Map creditMap = (Map)session.getAttribute("new_customer_credits");
	
		if (bankMap!=null) {
			int count = ((Integer)bankMap.get("count")).intValue();
			if (count!=0) return true;
		}

		if (creditMap!=null) {
			int count = ((Integer)creditMap.get("count")).intValue();
			if (count!=0) return true;
		}

	
		return false;
	
	}

	public static void modifyInteressentAddressRow(HttpSession session, String where, int row, Logger logger) throws Exception{
		
		Map m = (Map)session.getAttribute(where);
		Map address = (Map)m.get(String.valueOf(row));
		
		if (address==null) return;
		
		String jsplink;
		
		if (where.startsWith("new")) jsplink = "new_interessent_detail_address.jsp";
		else jsplink = "interessent_detail_address.jsp";
		
		Map jspMap = (Map)session.getAttribute(jsplink);
		
		
		
		
		
		Set keys = address.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = address.get(actualName);
			
			boolean shouldPutIn = true;
			
			
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
				
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
				
				if (actualName.equals("private")) {
					shouldPutIn = true;
					actualName="address_type";
					actualValue=bactVal.booleanValue()?"1":"0";
				}
				
			}
			
			String jspPut = actualValue.toString();
			
			
			if (actualValue instanceof java.sql.Date) {
				
				jspPut = formatSQLDate((java.sql.Date)actualValue);
				
			}
			
			//jspMap.put(actualName, actualValue);
				if (shouldPutIn) {
					jspMap.put(actualName, new String[] {jspPut});
				}
		}
		
		session.setAttribute(jsplink, jspMap);
		
		m.put("modify", new Integer(row));
		
	}

	
	public static void modifyAddressRow(HttpSession session, String where, int row, Logger logger) throws Exception{
		
		Map m = (Map)session.getAttribute(where);
		Map address = (Map)m.get(String.valueOf(row));
		
		if (address==null) return;
		
		String jsplink;
		
		if (where.startsWith("new")) jsplink = "new_customer_detail_address.jsp";
		else jsplink = "customer_detail_address.jsp";
		
		Map jspMap = (Map)session.getAttribute(jsplink);
		
		
		
		
		
		Set keys = address.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = address.get(actualName);
			
			boolean shouldPutIn = true;
			
			
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
				
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
				
				if (actualName.equals("private")) {
					shouldPutIn = true;
					actualName="address_type";
					actualValue=bactVal.booleanValue()?"1":"0";
				}
				
			}
			
			String jspPut = actualValue.toString();
			
			
			if (actualValue instanceof java.sql.Date) {
				
				jspPut = formatSQLDate((java.sql.Date)actualValue);
				
			}
			
			//jspMap.put(actualName, actualValue);
				if (shouldPutIn) {
					jspMap.put(actualName, new String[] {jspPut});
				}
		}
		
		
		session.setAttribute(jsplink, jspMap);
		
		
		
		
		
		
		
		
		
		
		
		m.put("modify", new Integer(row));
		
	}

	
	public static void modifyBankRow(HttpSession session, String where, int row, Logger logger) throws Exception{
		
		Map m = (Map)session.getAttribute(where);
		Map bank = (Map)m.get(String.valueOf(row));
		
		if (bank==null) return;
		
		String jsplink;
		
		if (where.startsWith("new")) jsplink = "new_customer_detail_payment.jsp";
		else jsplink = "customer_detail_payment.jsp";
		
		Map jspMap = (Map)session.getAttribute(jsplink);
		
		
		
		
		
		Set keys = bank.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = bank.get(actualName);
			
			boolean shouldPutIn = true;
			
			
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
			
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
								
			}
			
			String jspPut = actualValue.toString();
			
			
			if (actualValue instanceof java.sql.Date) {
				logger.info("Date: "+shouldPutIn);
				jspPut = formatSQLDate((java.sql.Date)actualValue);
			}
			
			//jspMap.put(actualName, actualValue);
				if (shouldPutIn) {
					jspMap.put(actualName, new String[] {jspPut});
				}
		}
		
		
		session.setAttribute(jsplink, jspMap);
		m.put("modify", new Integer(row));
		
	}	
	//public static boolean

	public static void modifyCreditRow(HttpSession session, String where, int row, Logger logger) throws Exception{
		
		Map m = (Map)session.getAttribute(where);
		Map bank = (Map)m.get(String.valueOf(row));
		
		if (bank==null) return;
		
		String jsplink;
		
		if (where.startsWith("new")) jsplink = "new_customer_detail_payment.jsp";
		else jsplink = "customer_detail_payment.jsp";
		
		Map jspMap = (Map)session.getAttribute(jsplink);
		
		
		
		
		
		Set keys = bank.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = bank.get(actualName);
			
			boolean shouldPutIn = true;
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
				
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
								
			}
			
			String jspPut = actualValue.toString();
			
			
			if (actualValue instanceof java.sql.Date) {
				
				//formatback(formatSQLDate(valFromD)
				jspPut = formatback(formatSQLDate((java.sql.Date)actualValue));
				
			}
			
			//jspMap.put(actualName, actualValue);
				if (shouldPutIn) {
					
					if (actualName.equals("comment")) jspMap.put("fully", new String[] {jspPut});
					else jspMap.put(actualName, new String[] {jspPut});
				}
		}
			
		session.setAttribute(jsplink, jspMap);
		m.put("modify", new Integer(row));
		
	}	
	
	
	public static void deleteRow(HttpSession session , String where, int row, Logger logger, String[] toNull) throws Exception {
		
		Map m = (Map)session.getAttribute(where);
		List deleteList;
		
		if (m.get("deleteList")!=null) deleteList = (List)m.get("deleteList");
		else deleteList = new ArrayList();
		
		//impossible
		if (deleteList.contains(new Integer(row))) return;
		
		boolean canc = true;
		boolean canb = true;
		
		if (where.indexOf("credit")!=-1) {
			Map d = (Map)m.get(String.valueOf(row));
			Integer id = (Integer)d.get("id");
			if (id!=null) canc = checkCCanBeDeleted(id);
		} else if (where.indexOf("bank")!=-1) {
			Map d = (Map)m.get(String.valueOf(row));
			Integer id = (Integer)d.get("id");
			if (id!=null) canb = checkBCanBeDeleted(id);			
		}
		
		
		if (!canc || !canb) {
			session.setAttribute(canb?"CREDITCARD_CANNOT_BE_DELETED":"BANK_ACCOUNT_CANNOT_BE_DELETED", "yes");
		} else {
			deleteList.add(new Integer(row));
			m.put("deleteList", deleteList);
			
			for (int z=0; z<toNull.length; z++)
				m.put(toNull[z], new Integer(0));
		}
		
	}
	
	public static boolean isExistingDistributor(HttpSession session, String distr_id) throws Exception {
		
		//for rights checking
		String user_logged_id = (String)session.getAttribute("USER_LOGGED_ID");
		
		ObjectSearch os = new ObjectSearch("distributor", (List) null);
		os.setCondition("id = ?");
		
		Integer intObj;
		
		int intern;
		try {
		    intern = Integer.parseInt(distr_id);
		} catch (Exception e) {
			return false;
		}
		
		intObj = new Integer(intern);
		
		List result;
		
		
		result = os.search(new Object[] {intObj});
		
		if (result.size()==0) return false;	
		
		PersistableObject po = (PersistableObject)result.get(0);
		
		Integer it = (Integer)po.get("level_id");
		
		int h = it.intValue();
		
		if (h==100 || h == 130 || h == 160 || h == 200) return true;
		
		return false;
	
	}
	
	public static boolean isExistingInteressent(HttpSession session, String distr_id) throws Exception {
		
		//for rights checking
		String user_logged_id = (String)session.getAttribute("USER_LOGGED_ID");
		
		ObjectSearch os = new ObjectSearch("interessent", (List) null);
		os.setCondition("id = ?");
		
		Integer intObj;
		
		int intern;
		try {
		    intern = Integer.parseInt(distr_id);
		} catch (Exception e) {
			return false;
		}
		
		intObj = new Integer(intern);
		
		List result;
		
		
		result = os.search(new Object[] {intObj});
		
		if (result.size()==0) return false;	
		
		return true;
	
	}	
	
	
	public static String generateCustomerDataHeaderString(PageContext pc) {
		HttpSession session = pc.getSession();
		StringBuffer sb = new StringBuffer();
		
		String s1 = "";
		String s2 = "";
		
		String deact = "";
		
		if (session.getAttribute("CURRENT_CUSTOMER_DEACTIVATED")!=null) {
			s1 = "<span class=\"deactivated\">";
			s2 = "</span>";
			deact = LocaleSupport.getLocalizedMessage(pc,"DEACTIVED")+", ";
		}

		
		
		sb.append("<span style=\"font-size: 16px;color: #990000;\"><b>");
		
		sb.append(deact);
		
		sb.append(session.getAttribute("CURRENT_CUSTOMER_ID")!=null?(String)session.getAttribute("CURRENT_CUSTOMER_ID"):"n/a");
		sb.append(", ");
		sb.append(session.getAttribute("CURRENT_CUSTOMER_NAME")!=null?(String)session.getAttribute("CURRENT_CUSTOMER_NAME"):"n/a");
		sb.append("</b>"+"</span>");
		return sb.toString();
	}
	
	public static String generateInteressentDataHeaderString(PageContext pc) {
		HttpSession session = pc.getSession();
		StringBuffer sb = new StringBuffer();
		
		String s1 = "";
		String s2 = "";
		
		String deact = "";
		
		if (session.getAttribute("CURRENT_INTERESSENT_DEACTIVATED")!=null) {
			s1 = "<span class=\"deactivated\">";
			s2 = "</span>";
			deact = LocaleSupport.getLocalizedMessage(pc,"DEACTIVED")+", ";
		}

		
		
		sb.append("<span style=\"font-size: 16px;color: #990000;\"><b>");
		
		sb.append(deact);
		
		sb.append(session.getAttribute("CURRENT_INTERESSENT_ID")!=null?(String)session.getAttribute("CURRENT_INTERESSENT_ID"):"n/a");
		sb.append(", ");
		sb.append(session.getAttribute("CURRENT_INTERESSENT_NAME")!=null?(String)session.getAttribute("CURRENT_INTERESSENT_NAME"):"n/a");
		sb.append("</b>"+"</span>");
		return sb.toString();
	}
	
	public static Title[] getTitles() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("title", l);
		
		os.setOrderBy(new String[] {"id"});
		
		List res = os.search();
		Title[] titles = new Title[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			titles[t] = new Title(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return titles;
	}

	public static DistributorMin[] getDistMin() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("distributor", l);
		os.setOrderBy(new String[] {"lastname"});
		List res = os.search();
		DistributorMin[] dm = new DistributorMin[res.size()];
		
		HashMap levels = new HashMap();
		com.etixpert.evolution.gui.servlets.Level[] pms = FormHelper.getLevels();
		for (int i = 0; i<pms.length; i++) {
			levels.put(pms[i].id, pms[i].value);
		}
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			String level_id = po.getString("level_id", "");
			String val = (String)levels.get(level_id);
		
			dm[t] = new DistributorMin(String.valueOf(po.get("id")), (String)po.get("lastname")+", "+(String)po.get("firstname"), val); 
		}
		
		//"<option>A</option>";
		
		return dm;
		
	}
	
	public static DistributorMin[] getDistMin_od() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("distributor", l);
		os.setOrderBy(new String[] {"lastname"});
		os.setCondition("level_id<>100 AND level_id<>200");
		List res = os.search();
		DistributorMin[] dm = new DistributorMin[res.size()];
		
		HashMap levels = new HashMap();
		com.etixpert.evolution.gui.servlets.Level[] pms = FormHelper.getLevels();
		for (int i = 0; i<pms.length; i++) {
			levels.put(pms[i].id, pms[i].value);
		}
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			String level_id = po.getString("level_id", "");
			String val = (String)levels.get(level_id);
		
			dm[t] = new DistributorMin(String.valueOf(po.get("id")), (String)po.get("lastname")+", "+(String)po.get("firstname"), val); 
		}
		
		//"<option>A</option>";
		
		return dm;
		
	}	

	public static DistributorMin[] getDistMin_oc() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("distributor", l);
		os.setOrderBy(new String[] {"lastname"});
		os.setCondition("level_id in (100, 130, 160, 200)");
		List res = os.search();
		DistributorMin[] dm = new DistributorMin[res.size()];
		
		HashMap levels = new HashMap();
		com.etixpert.evolution.gui.servlets.Level[] pms = FormHelper.getLevels();
		for (int i = 0; i<pms.length; i++) {
			levels.put(pms[i].id, pms[i].value);
		}
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			String level_id = po.getString("level_id", "");
			String val = (String)levels.get(level_id);
		
			dm[t] = new DistributorMin(String.valueOf(po.get("id")), (String)po.get("lastname")+", "+(String)po.get("firstname"), val); 
		}
		
		//"<option>A</option>";
		
		return dm;
		
	}		
	
	public static LevelAddress[] getLevelAddresses() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("level_address", l);
		
		os.setOrderBy(new String[] {"id"});
		
		List res = os.search();
		LevelAddress[] levelAddresses = new LevelAddress[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			levelAddresses[t] = new LevelAddress(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return levelAddresses;
	}

	public static Language[] getLanguages() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("language", l);
		List res = os.search();
		Language[] languages = new Language[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			languages[t] = new Language(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return languages;
	}

	public static PM[] getPMs() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("payment_method", l);
		os.setCondition("id <> 5 and id<>6");
		List res = os.search();
		PM[] pms = new PM[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pms[t] = new PM(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return pms;
	}	

	public static PM[] getPMsAll() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("payment_method", l);
		os.setCondition("id <> 5");
		List res = os.search();
		PM[] pms = new PM[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pms[t] = new PM(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return pms;
	}	
	public static Shipping[] getShippings() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("shipping", l);
		List res = os.search();
		Shipping[] pms = new Shipping[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pms[t] = new Shipping(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return pms;
	}	

	public static CCC[] getCCCs() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("cc_org", l);
		List res = os.search();
		CCC[] pms = new CCC[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pms[t] = new CCC(String.valueOf(po.get("id")), (String)po.get("org")); 
		}
		
		//"<option>A</option>";
		
		return pms;
	}	
	
	public static Level[] getLevels() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("user_roles", l);
		os.setCondition("dist_type = 'c'");
		os.setOrderBy(new String[] {"id"});
		List res = os.search();
		Level[] pms = new Level[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pms[t] = new Level(String.valueOf(po.get("id")), "0", (String)po.get("descr"), (String)po.get("dist_type")); 
		}
		
		//"<option>A</option>";
		
		return pms;
	}
	
	public static Level[] getInteressentLevels() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("interessent_roles", l);
		os.setOrderBy(new String[] {"id"});
		List res = os.search();
		Level[] pms = new Level[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pms[t] = new Level(String.valueOf(po.get("id")), "0", (String)po.get("descr"), ""); 
		}
		
		//"<option>A</option>";
		
		return pms;
	}	
	
	
	public static Country[] getCountries() throws SQLException {
		List l = new ArrayList();
		l.add("country_code");
		
		ObjectSearch os = new ObjectSearch("country", l);
		List res = os.search();
		Country[] countries = new Country[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			countries[t] = new Country((String)po.get("country_code"), (String)po.get("country_post_code"),(String)po.get("name")); 
		}
		
		//"<option>A</option>";
		
		return countries;
	}
	
	
	
	public static Map customerDetailPersonalToMap(Map orig, Logger logger) throws ServletException{
		Map ret = new HashMap();
		
		try {
		
		Set names = orig.keySet();
		Iterator i = names.iterator();
		
		while (i.hasNext()) {
			String name = (String)i.next();
			String values[] = (String[])orig.get(name);
			String value = values[0];
			if (name.equals("birthdate")) {
				java.util.Date formatted = formatDate(value);
				if (formatted!=null)
					ret.put(name, formatted);
			} else if (name.indexOf("_id")!=-1){
				int iVal = 0;
				try {
					iVal = Integer.parseInt(value);
				} catch (NumberFormatException nfe) {
					iVal = -1;
					
				}
				if (iVal!=-1)
				ret.put(name, new Integer(iVal));
			} else {
				ret.put(name, value);
			}
			
		}	
		} catch (Exception e) {
			throw new ServletException(e);
				
		}
		return ret;
		
	}

	public static Map customerDetailPaymentToMap(Map orig) {
		Map ret = new HashMap();
		
		Set names = orig.keySet();
		Iterator i = names.iterator();
		
		//ret.put("transferbonus", new Boolean(false));
		ret.put("payment_slip", new Boolean(false));
		ret.put("allow_bank", new Boolean(false));
		while (i.hasNext()) {
			String name = (String)i.next();
			String[] values = (String[])orig.get(name);
			String value = values[0];
			if (name.equals("transferbonus")) {
				ret.put(name, new Boolean(true));
			} else if (name.equals("pay_method_id") || name.equals("vat_id")) {
				int iVal = 0;
				try {
					iVal = Integer.parseInt(value);
				} catch (NumberFormatException nfe) {
					iVal = -1;
					
				}
				if (iVal!=-1)
					ret.put(name, new Integer(iVal));
				
			}else if (name.equals("payment_slip")) {
				ret.put(name, new Boolean(true));
			}else if (name.equals("allow_bank")) {
				ret.put(name, new Boolean(true));
			}
			
		}	
		return ret;
		
	}

	public static Map interessentDetailIntToMap(Map orig, Logger logger) throws ServletException {
		Map ret = new HashMap();
		
		try {
		
		
		
		Set names = orig.keySet();
		Iterator i = names.iterator();
		
		
		ret.put("active", new Boolean(true));
		
		while (i.hasNext()) {
			String name = (String)i.next();
			
			logger.info("DEBUG: NAME: "+name);
			
			String[] values = (String[])orig.get(name);
			String value = null; 
				if (values != null && values.length>0) value = values[0];
			
				
			if (name.equals("active")) {
				ret.put("active", new Boolean(false));
			}
			else if (name.indexOf("_id")!=-1) {
				int iVal = 0;
				try {
					iVal = Integer.parseInt(value);
				} catch (NumberFormatException nfe) {
					logger.info("DEBUG number errr: "+nfe.getMessage());
					iVal = -1;
				}
				if (iVal!=-1) {
					ret.put(name, new Integer(iVal));
					logger.info("DEBUG: "+iVal);
				} else if ("no_sel".equals(value)) {
					ret.put(name, null);
				}
			}
			else {
				ret.put(name, value);
			}
			
		}	
		} catch (Exception e) {
			throw new ServletException(e);
		}
		return ret;
		
	}	
	
	public static Map customerDetailIntToMap(Map orig, Logger logger) throws ServletException {
		Map ret = new HashMap();
		
		try {
		
		
		
		Set names = orig.keySet();
		Iterator i = names.iterator();
		
		
		ret.put("active", new Boolean(true));
		ret.put("deleted", new Boolean(false));
		ret.put("newsletter", new Boolean(false));
		ret.put("printlock", new Boolean(false));
		ret.put("customer_service", new Boolean(false));
		ret.put("transferbonus", new Boolean(false));
		
		while (i.hasNext()) {
			String name = (String)i.next();
			
			logger.info("DEBUG: NAME: "+name);
			
			String[] values = (String[])orig.get(name);
			String value = null; 
				if (values != null && values.length>0) value = values[0];
			
				
			if (name.equals("homepage") || name.equals("last_order_date") || name.equals("statusdate")) {
				java.util.Date formatted = formatDate(value);
				if (formatted != null)
					ret.put(name, formatted);
			} 
			else if (name.equals("active")) {
				ret.put("active", new Boolean(false));
			}
			else if (name.equals("vat_id")) {
				ret.put(name, value);
			}
			else if (name.equals("sponsor") || name.equals("customer_sponsor") || name.indexOf("_id")!=-1) {
				int iVal = 0;
				try {
					iVal = Integer.parseInt(value);
				} catch (NumberFormatException nfe) {
					logger.info("DEBUG sponsor errr: "+nfe.getMessage());
					iVal = -1;
				}
				if (iVal!=-1) {
					ret.put(name, new Integer(iVal));
					logger.info("DEBUG sponsor: "+iVal);
				} else if ("no_sel".equals(value)) {
					ret.put(name, null);
				}
			}
			else if (name.equals("deleted") || name.equals("newsletter") || name.equals("printlock") || name.equals("customer_service") || name.equals("transferbonus")) {
				ret.put(name, new Boolean(true));
			}
			else {
				ret.put(name, value);
			}
			
		}	
		} catch (Exception e) {
			throw new ServletException(e);
		}
		return ret;
		
	}	
	
	public static String getCCCName(String id) {
		List l = new ArrayList();
		l.add("id");
		ObjectSearch os = new ObjectSearch("cc_org", l);
		os.setCondition("id = ?");
		List resultList;
		try {
			resultList = os.search(new Object[] {new Integer(id)});
		} catch (Exception e) {
			return e.getMessage();
		}
		if (resultList.size()>0)
		return  (String)((PersistableObject)resultList.get(0)).get("org");
		else return "";
	
	}
	
	public static void addCustomerDetailCreditToMap(Map origBank, Map addressMap, Logger log) {
		Map ret = new HashMap();
		
		Set names = origBank.keySet();
		Iterator i = names.iterator();
		while (i.hasNext()) {
			String name = (String)i.next();
			String[] values = (String[])origBank.get(name);
			String value = values[0];

			if (value != null)
				value = value.trim();

			
			if (name.equals("comment")) {
				}
			else if (name.equals("fully")) {
				ret.put("comment", value);
				
			}
			else if (name.indexOf("valid_")!=-1) {
				
				String[] sa = value.split("/");
				if (sa.length!=2) continue;
				
				String day = "01";
				
				/*try {
					int g = Integer.parseInt(sa[0]);
					day = FormHelper.months_last_days[g];
				}
				catch (Exception e) {}
				*/
				java.util.Date formatted = formatDate(day+"."+sa[0]+".20"+sa[1]);
				if (formatted!=null)
					ret.put(name, formatted);
			}
			else if (name.equals("cc_org_id")) {
				int iVal = 0;
				try {
					iVal = Integer.parseInt(value);
				} catch (NumberFormatException nfe) {
					iVal = -1;
				}
				if (iVal!=-1)
					ret.put(name, new Integer(iVal));				
			}
			else
				ret.put(name, value);
		}	
		boolean modify = false;
		
		if (addressMap.get("modify")!=null) modify = true;
		if (!modify) {
			log.info("ok6");
			Integer integer = (Integer)addressMap.get("count");
			int ii = integer.intValue();
			addressMap.put(String.valueOf(ii), ret);
			addressMap.put("count", new Integer(ii+1));
		} else {
			Integer integer = (Integer)addressMap.get("modify");
			Map old = (Map)addressMap.get(new String(String.valueOf(integer)));
			Integer id = (Integer)old.get("id");
			
			if (id!=null) ret.put("id", id);
			addressMap.put(String.valueOf(integer.intValue()), ret);
			addressMap.remove("modify");
		}
	}

	
	public static void addCustomerDetailBankToMap(Map origBank, Map addressMap, Logger log) {
		Map ret = new HashMap();
		
		Set names = origBank.keySet();
		Iterator i = names.iterator();
		while (i.hasNext()) {
			String name = (String)i.next();
			String[] values = (String[])origBank.get(name);
			String value = values[0];
			
			if (value != null)
				value = value.trim();

			if ("iban".equals(name)) {
				if (value != null)
					value = value.replaceAll(" ", "");
				ret.put(name, value);
			}
			
			if ("debit_date".equals(name)) {
				java.util.Date formatted = formatDate(value);
				//if (formatted!=null)
				ret.put(name, formatted);
			} else ret.put(name, value);
		}	
		
		//Boolean b = (Boolean)addressMap.get("new");
		boolean modify = false;
		
		if (addressMap.get("modify")!=null) modify = true;
		//if (b.booleanValue()) {
		if (!modify) {
			Integer integer = (Integer)addressMap.get("count");
			int ii = integer.intValue();
			if (ii==0) {
				addressMap.put("default_bonus", new Integer(0));
				addressMap.put("default_bill", new Integer(0));
			}
			addressMap.put(String.valueOf(ii), ret);
			addressMap.put("count", new Integer(ii+1));
		} else {
			Integer integer = (Integer)addressMap.get("modify");
			Map old = (Map)addressMap.get(new String(String.valueOf(integer)));
			Integer id = (Integer)old.get("id");
			
			if (id!=null) ret.put("id", id);
			addressMap.put(String.valueOf(integer.intValue()), ret);
			addressMap.remove("modify");
		}
	}
	
	public static boolean underMod(HttpSession session, String map) {
		Map m = (Map)session.getAttribute(map);
		if (m.get("modify")!=null) return true;
		else return false;
		
	}
	
	
	
	public static void addCustomerDetailAddressToMap(Map origAddress, Map addressMap, Logger log) {
		Map ret = new HashMap();
		
		Set names = origAddress.keySet();
		Iterator i = names.iterator();
		while (i.hasNext()) {
			String name = (String)i.next();
			String[] values = (String[])origAddress.get(name);
			String value = values[0];
			if (name.equals("address_type")) {
				ret.put("private", value.equals("1")?new Boolean(true):new Boolean(false));
			}
			/*else if (name.equals("postcode")) {
				int iVal = 0;
				try {
					iVal = Integer.parseInt(value);
				} catch (NumberFormatException nfe) {
					iVal = -1;
				}
				if (iVal!=-1)
					ret.put(name, new Integer(iVal));								
			}*/
			else {
				ret.put(name, value);
			}
		}	
		
		
		boolean modify = false;
		
		if (addressMap.get("modify")!=null) modify = true;
		
		//if (b.booleanValue()) {
		if (!modify) {
			Integer integer = (Integer)addressMap.get("count");
			int ii = integer.intValue();
			if (ii==0) {
				addressMap.put("default_delivery", new Integer(0));
				addressMap.put("default_bill", new Integer(0));
			}
			addressMap.put(String.valueOf(ii), ret);
			addressMap.put("count", new Integer(ii+1));
		} else {
			Integer integer = (Integer)addressMap.get("modify");
			Map old = (Map)addressMap.get(new String(String.valueOf(integer)));
			Integer id = (Integer)old.get("id");
			
			if (id!=null) ret.put("id", id);
			addressMap.put(String.valueOf(integer.intValue()), ret);
			addressMap.remove("modify");
		}
	}

	public static void newTitle(String descr) throws Exception {
		List l = new ArrayList();
		l.add("id");
		Map m = new HashMap();
		m.put("descr", descr);
		PersistableObject po = new PersistableObject("title", l, m);
		
		po.insert();
	}
	
	public static void modifyTitle(String id, String descr) throws Exception {
		int i;
		
		try {
			i = Integer.parseInt(id);
		} catch (Exception e) {
			return;
		}
		
		
		
		ObjectSearch os = new ObjectSearch("title", "id");
		os.setCondition("id = ?");
		
		List l = os.search(new Object[] {new Integer(i)});
		
		if (l.size()!=1) return;
		
		PersistableObject po = (PersistableObject)l.get(0);
		
		
		
		po.set("descr", descr);
		
		po.update();
		
	}
	

	
	public static String generateBankTableRows(HttpSession session, String where) {
		Map bankMap = (Map)session.getAttribute(where);
		//if (addressMap == null) return "<tr></tr>";
		String deleteLink;
		String deleteLink0;
		
		String modifyLink0;
				
		if (where.startsWith("new")) {
			deleteLink = "new_customer_detail_payment.jsp";
			deleteLink0 = "new_customer_delete_bank_row";
			modifyLink0 = "new_customer_modify_bank_row";
		}
		else {
			deleteLink = "customer_detail_payment.jsp";
			deleteLink0 = "customer_delete_bank_row";
			modifyLink0 = "customer_modify_bank_row";
		}
		
		
		int i = ((Integer)bankMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";
		
		StringBuffer sb = new StringBuffer();
		
		for (int j = 0; j<i; j++) {
			Map bank = (Map)bankMap.get(String.valueOf(j));
			
			List deleteList = (List)bankMap.get("deleteList");
			if (deleteList!=null)
				if (deleteList.contains(new Integer(j))) continue;
			
			String selectedBill = "";
			if (((Integer)bankMap.get("default_bill")).intValue()==j) selectedBill = " checked";

			String selectedBonus = "";
			if (((Integer)bankMap.get("default_bonus")).intValue()==j) selectedBonus = " checked";
			
//			sb.append("<tr>" +					
//			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
//			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ deleteLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/delete.gif\"/></a></td>"+
//			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_bill\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedBill+"></td>" +
//			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_bonus\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedBonus+"></td>" +
//            "<td id=\"accountTableDataContent\">"+ bank.get("bank_code") +"</td>"+
//		  	"<td id=\"accountTableDataContent\">"+ bank.get("account_number") + "</td>"+
//			"<td id=\"accountTableDataContent\">"+bank.get("bank")+"</td>"+
//	    	"<td id=\"accountTableDataContent\">"+bank.get("iban")+"</td>"+
//			"<td id=\"accountTableDataContent\">"+bank.get("comment")+"</td>"+
//			"</tr>");
			
			
			sb.append("<tr>" +					
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ deleteLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/delete.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_bill\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedBill+"></td>" +
			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_bonus\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedBonus+"></td>" +
		  	"<td id=\"accountTableDataContent\">"+bank.get("iban")+"</td>"+
		  	"<td id=\"accountTableDataContent\">"+bank.get("bic")+"</td>"+
			"<td id=\"accountTableDataContent\">"+bank.get("bank")+"</td>"+
			"<td id=\"accountTableDataContent\">"+bank.get("comment")+"</td>"+
			"</tr>");
			
			
		}
		
		return sb.toString();		
	}

	public static String formatback(String orig) {
		//dd.mm.yyyy  =>  mm/yy
		StringBuffer sb = new StringBuffer();
		sb.append(orig.substring(3,5)+"/"+orig.substring(8,10));
		
		return sb.toString();
		
	}
	
	public static String generateCreditTableRows(HttpSession session, String MapName) {
		Map creditMap = (Map)session.getAttribute(MapName);
		//if (addressMap == null) return "<tr></tr>";
		String deleteLink;
		String deleteLink0;
		
		String modifyLink0;
				
		if (MapName.startsWith("new")) {
			deleteLink = "new_customer_detail_payment.jsp";
			deleteLink0 = "new_customer_delete_credit_row";
			modifyLink0 = "new_customer_modify_credit_row";
		}
		else {
			deleteLink = "customer_detail_payment.jsp";
			deleteLink0 = "customer_delete_credit_row";
			modifyLink0 = "customer_modify_credit_row";
		}
		
		int i = ((Integer)creditMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";

		StringBuffer sb = new StringBuffer();
		
		for (int j = 0; j<i; j++) {
			Map credit = (Map)creditMap.get(String.valueOf(j));
			List deleteList = (List)creditMap.get("deleteList");
			if (deleteList!=null)
				if (deleteList.contains(new Integer(j))) continue;					
			java.sql.Date valFromD = ((java.sql.Date)credit.get("valid_from")); 
			String valFrom; 
			if (valFromD == null) valFrom = ""; else valFrom = formatback(formatSQLDate(valFromD)); 
			
			java.sql.Date valToD = ((java.sql.Date)credit.get("valid_to")); 
			String valTo; 
			if (valToD == null) valTo = ""; else valTo = formatback(formatSQLDate(valToD)); 
			
			sb.append("<tr>" +
					"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
					"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ deleteLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/delete.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\">"+getCCCName(credit.get("cc_org_id").toString())+"</td>"+
            "<td id=\"accountTableDataContent\">"+ credit.get("cc_number") +"</td>"+
		  	"<td id=\"accountTableDataContent\">"+ valFrom + "</td>"+
	    	"<td id=\"accountTableDataContent\">"+valTo+"</td>"+
			"<td id=\"accountTableDataContent\">"+credit.get("comment")+"</td>"+
			"</tr>");
		}
		
		return sb.toString();		
	}	

	public static int addInteressent(HttpSession session, Logger logger) throws ServletException {
		int newID = -1;
		String password = "";
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute("new_interessent_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_interessent_personal_Map"));
			if (session.getAttribute("new_interessent_int_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_interessent_int_Map"));
		
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			
			complex.remove("sponsor_name");
			complex.remove("customer_sponsor_name");
			complex.remove("row");
			
			password = generatePassword();
			
			logger.info("Generated password: ----------------------------------- "+password);
			
			complex.put("password", password);
			
			java.sql.Date cd = new java.sql.Date(System.currentTimeMillis());
			
			complex.put("creation_date", cd);
			complex.put("created_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
			Interessent d = new Interessent(complex);
		
			//newID = d.generateID();
			
			d.insert();
//			ObjectSearch last = new ObjectSearch();
//			List l = last.search("select {fn currval('seq_interessent')}");
//			PersistableObject currvalRow = (PersistableObject) l.get(0);
//
//			Long newid = (Long) currvalRow.get("currval");
			newID = ((Integer)d.get("id")).intValue();
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
		session.setAttribute("LAST_GENERATED_INTERESSENT_PASSWORD", password);
		return newID;
	}	
	
	public static int addDistributor(HttpSession session, Logger logger) throws ServletException {
		int newID = -1;
		String password = "";
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute("new_customer_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_customer_personal_Map"));
			if (session.getAttribute("new_customer_int_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_customer_int_Map"));
			if (session.getAttribute("new_customer_payment_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_customer_payment_Map"));
		
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			
			if (complex.get("pay_method_id")==null) complex.put("pay_method_id", new Integer(3));
			if (complex.get("shipping_id")==null) complex.put("shipping_id", new Integer(1));
			
			complex.remove("sponsor_name");
			complex.remove("customer_sponsor_name");
			complex.remove("row");
			
			password = generatePassword();
			
			logger.info("Generated password: ----------------------------------- "+password);
			
			complex.put("password", password);
			
			java.sql.Date cd = new java.sql.Date(System.currentTimeMillis());
			
			complex.put("creation_date", cd);
			complex.put("created_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
			Distributor d = new Distributor(complex);
		
			newID = d.generateID();
			
			d.insert();
			
			
			
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
		session.setAttribute("LAST_GENERATED_CUSTOMER_PASSWORD", password);
		return newID;
	}
	
	public static boolean addInteressentAddresses(HttpSession session, int dist_id, Logger logger) throws ServletException {
		return addInteressentAddresses(session, dist_id, false, logger);
	}	
	
	public static boolean addInteressentAddresses(HttpSession session, int dist_id, boolean promote, Logger logger) throws ServletException{
		try {
		Map addressMap = (Map)session.getAttribute(promote?"interessent_addresses":"new_interessent_addresses");
		//Map addressMap = (Map)session.getAttribute("new_customer_addresses");
		if (addressMap == null) return true;
		Integer iCount = (Integer)addressMap.get("count");
		if (iCount == null) return true;
		int count = iCount.intValue();
		Integer iDefBill = (Integer)addressMap.get("default_bill");
		Integer iDefDelivery = (Integer)addressMap.get("default_delivery");
		int defBill = 0;
		int defDelivery = 0;
		
		
		
		if (iDefBill != null) defBill = iDefBill.intValue();
		if (iDefDelivery != null) defDelivery = iDefDelivery.intValue();
		for (int i = 0; i<count; i++) {
			Map address = (Map)addressMap.get(String.valueOf(i));
			
			List deleteList = (List)addressMap.get("deleteList");
			
			if (deleteList!=null) {
				if (deleteList.contains(new Integer(i))) continue;
			}
			
			if (promote) address.remove("id");
			
			address.put("distr_id", new Integer(dist_id));
			if (i==defBill) address.put("default_bill", new Boolean(true));
			else address.put("default_bill", new Boolean(false));
			
			if (i==defDelivery) address.put("default_delivery", new Boolean(true));
			else address.put("default_delivery", new Boolean(false));
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (address.get("link")!=null)
				address.remove("link");
			if (address.get("saveState")!=null)
				address.remove("saveState");
			if (address.get("pageAction")!=null)
				address.remove("pageAction");
			if (address.get("row")!=null)
				address.remove("row");
			
			
			PersistableObject po = new PersistableObject("interessent_address", l, address);
			
			try {
				po.insert();
			} catch (Exception ex) {
				logger.info(ex.getMessage());
				throw new ServletException(ex);
			}
			
			}
			}catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		
		}
		return true;
		
	}	
	
	public static boolean addAddresses(HttpSession session, int dist_id, Logger logger) throws ServletException {
		return addAddresses(session, dist_id, false, logger);
	}	
	
	public static boolean addAddresses(HttpSession session, int dist_id, boolean promote, Logger logger) throws ServletException{
		try {
		Map addressMap = (Map)session.getAttribute(promote?"customer_addresses":"new_customer_addresses");
		//Map addressMap = (Map)session.getAttribute("new_customer_addresses");
		if (addressMap == null) return true;
		Integer iCount = (Integer)addressMap.get("count");
		if (iCount == null) return true;
		int count = iCount.intValue();
		Integer iDefBill = (Integer)addressMap.get("default_bill");
		Integer iDefDelivery = (Integer)addressMap.get("default_delivery");
		int defBill = 0;
		int defDelivery = 0;
		
		
		
		if (iDefBill != null) defBill = iDefBill.intValue();
		if (iDefDelivery != null) defDelivery = iDefDelivery.intValue();
		for (int i = 0; i<count; i++) {
			Map address = (Map)addressMap.get(String.valueOf(i));
			
			List deleteList = (List)addressMap.get("deleteList");
			
			if (deleteList!=null) {
				if (deleteList.contains(new Integer(i))) continue;
			}
			
			if (promote) address.remove("id");
			
			address.put("distr_id", new Integer(dist_id));
			if (i==defBill) address.put("default_bill", new Boolean(true));
			else address.put("default_bill", new Boolean(false));
			
			if (i==defDelivery) address.put("default_delivery", new Boolean(true));
			else address.put("default_delivery", new Boolean(false));
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (address.get("link")!=null)
				address.remove("link");
			if (address.get("saveState")!=null)
				address.remove("saveState");
			if (address.get("pageAction")!=null)
				address.remove("pageAction");
			if (address.get("row")!=null)
				address.remove("row");
			
			
			PersistableObject po = new PersistableObject("address", l, address);
			
			try {
				po.insert();
			} catch (Exception ex) {
				logger.info(ex.getMessage());
				throw new ServletException(ex);
			}
			
			}
			}catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		
		}
		return true;
		
	}

	public static boolean addBanks(HttpSession session, int dist_id, Logger logger) throws ServletException{
		return addBanks(session, dist_id, false, logger);
	}
	
	public static boolean addBanks(HttpSession session, int dist_id, boolean promote, Logger logger) throws ServletException{
		Map banksMap = (Map)session.getAttribute(promote?"customer_banks":"new_customer_banks");
		//Map banksMap = (Map)session.getAttribute("new_customer_banks");
		if (banksMap == null) return true;
		Integer iCount = (Integer)banksMap.get("count");
		if (iCount == null) return true;
		int count = iCount.intValue();
		Integer iDefBill = (Integer)banksMap.get("default_bill");
		Integer iDefBonus = (Integer)banksMap.get("default_bonus");
		int defBill = 0;
		int defBonus = 0;
		
		if (iDefBill != null) defBill = iDefBill.intValue();
		if (iDefBonus != null) defBonus = iDefBonus.intValue();
		for (int i = 0; i<count; i++) {
			Map bank = (Map)banksMap.get(String.valueOf(i));
			
			List deleteList = (List)banksMap.get("deleteList");
			
			if (deleteList!=null) {
				if (deleteList.contains(new Integer(i))) continue;
			}
			
			bank.put("distr_id", new Integer(dist_id));
			if (i==defBill) bank.put("default_bill", new Boolean(true));
			else bank.put("default_bill", new Boolean(false));
			
			if (i==defBonus) bank.put("default_bonus", new Boolean(true));
			else bank.put("default_bonus", new Boolean(false));
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (bank.get("link")!=null)
				bank.remove("link");
			if (bank.get("saveState")!=null)
				bank.remove("saveState");
			if (bank.get("pageAction")!=null)
				bank.remove("pageAction");
			if (bank.get("cc_number")!=null)
				bank.remove("cc_number");
			if (bank.get("cc_org_id")!=null)
				bank.remove("cc_org_id");
			if (bank.get("valid_from")!=null)
				bank.remove("valid_from");
			if (bank.get("valid_to")!=null)
				bank.remove("valid_to");
			if (bank.get("fully")!=null)
				bank.remove("fully");
			
			if (bank.get("pay_method_id")!=null)
				bank.remove("pay_method_id");
			
			if (bank.get("vat_id")!=null)
				bank.remove("vat_id");
			
			if (bank.get("transferbonus")!=null)
				bank.remove("transferbonus");
			if (bank.get("row")!=null)
				bank.remove("row");
			
			if (bank.get("payment_slip")!=null)
				bank.remove("payment_slip");
			
			if (bank.get("allow_bank")!=null)
				bank.remove("allow_bank");
			
			if (promote) bank.remove("id");
			
			PersistableObject po = new PersistableObject("bank_account", l, bank);
			
			try {
				po.insert();
			} catch (Exception ex) {
				logger.info(ex.getMessage());
				throw new ServletException(ex);
			}
			
		}
		
		return true;
		
	}	

	public static boolean isCustomerPromoted(HttpSession session) {

		int cust_id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));

		PersistableObject po = new PersistableObject("customer_distributor", new String[] {"customer_id"});
		po.set("customer_id", cust_id);
		
		try {
			po.load();
			
		} catch (Exception e) {
			return false;
		}
		
		return true;
	}
	
	public static boolean addCredits(HttpSession session, int dist_id, Logger logger) throws ServletException{
		return addCredits(session, dist_id, false, logger);
	}
	
	public static boolean addCredits(HttpSession session, int dist_id, boolean promote, Logger logger) throws ServletException{
		Map creditsMap = (Map)session.getAttribute(promote?"customer_credits":"new_customer_credits");
		//Map creditsMap = (Map)session.getAttribute("new_customer_credits");
		if (creditsMap == null) return true;
		Integer iCount = (Integer)creditsMap.get("count");
		if (iCount == null) return true;
		int count = iCount.intValue();
		
		for (int i = 0; i<count; i++) {
			Map credit = (Map)creditsMap.get(String.valueOf(i));
			credit.put("distr_id", new Integer(dist_id));
			
			List deleteList = (List)creditsMap.get("deleteList");
			
			if (deleteList!=null) {
				if (deleteList.contains(new Integer(i))) continue;
			}
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (credit.get("link")!=null)
				credit.remove("link");
			if (credit.get("saveState")!=null)
				credit.remove("saveState");
			if (credit.get("pageAction")!=null)
				credit.remove("pageAction");
			if (credit.get("iban")!=null)
				credit.remove("iban");
			if (credit.get("account_number")!=null)
				credit.remove("account_number");
			if (credit.get("bank")!=null)
				credit.remove("bank");
			if (credit.get("default_bill")!=null)
				credit.remove("default_bill");
			if (credit.get("default_bonus")!=null)
				credit.remove("default_bonus");
			if (credit.get("bank_code")!=null)
				credit.remove("bank_code");
			if (credit.get("bic")!=null)
				credit.remove("bic");
			if (credit.get("debit_date")!=null)
				credit.remove("debit_date");
			
			if (credit.get("pay_method_id")!=null)
				credit.remove("pay_method_id");
			
			if (credit.get("vat_id")!=null)
				credit.remove("vat_id");
			
			if (credit.get("transferbonus")!=null)
				credit.remove("transferbonus");
			if (credit.get("row")!=null)
				credit.remove("row");
			
			if (credit.get("payment_slip")!=null)
				credit.remove("payment_slip");

			if (credit.get("allow_bank")!=null)
				credit.remove("allow_bank");
			
			if (promote) credit.remove("id");
			
			PersistableObject po = new PersistableObject("creditcard", l, credit);
			
			try {
				po.insert();
			} catch (Exception ex) {
				logger.error(ex.getMessage());
				throw new ServletException(ex);
			}
			
		}
		
		return true;
		
	}	

	
	public static void cancelNewCustomer(HttpSession session) throws javax.servlet.ServletException {
		try {
		session.setAttribute("new_customer_detail_personal.jsp", null);
		session.setAttribute("new_customer_detail_address.jsp", null);
		
		Map payment = new HashMap();
		
		payment.put("pay_method_id", new String[] {"4"});
		//payment.put("allow_bank", new String[] {"yes"});
		session.setAttribute("new_customer_detail_payment.jsp", payment);
		
		Map inte = new HashMap();
		inte.put("sponsor", new String[] {"0"});
		inte.put("newsletter", new String[] {"yes"});
		inte.put("customer_service", new String[] {"yes"});
		//inte.put("transferbonus", new String[] {"yes"});
		inte.put("shipping_id", new String[] {"1"});
		
		session.setAttribute("new_customer_detail_int.jsp", inte);
		
		session.setAttribute("new_customer_personal_Map", null);
		session.setAttribute("new_customer_payment_Map", null);
		session.setAttribute("new_customer_int_Map", null);
		
		Map addressMap = new HashMap();
		Map bankMap = new HashMap();
		Map creditMap = new HashMap();		
		
		addressMap.put("count", new Integer("0"));
		addressMap.put("default_delivery", new Integer("0"));
		addressMap.put("default_bill", new Integer("0"));
		session.setAttribute("new_customer_addresses", addressMap);
		
		bankMap.put("count", new Integer("0"));
		bankMap.put("default_bill", new Integer("0"));
		bankMap.put("defaul_bonus", new Integer("0"));
		session.setAttribute("new_customer_banks", bankMap);
		
		creditMap.put("count", new Integer("0"));
		session.setAttribute("new_customer_credits", creditMap);
		
		session.setAttribute("SIMILAR_CUSTOMERS", null);
		} catch (Exception e) {
			throw new javax.servlet.ServletException(e);
		}
	}
	
	public static void cancelNewInteressent(HttpSession session) throws javax.servlet.ServletException {
		try {
		session.setAttribute("new_interessent_detail_personal.jsp", null);
		session.setAttribute("new_interessent_detail_address.jsp", null);
		
		Map inte = new HashMap();
		session.setAttribute("new_interessent_detail_int.jsp", inte);
		
		session.setAttribute("new_interessent_personal_Map", null);
		session.setAttribute("new_interessent_int_Map", null);
		
		Map addressMap = new HashMap();
		
		addressMap.put("count", new Integer("0"));
		addressMap.put("default_delivery", new Integer("0"));
		addressMap.put("default_bill", new Integer("0"));
		session.setAttribute("new_interessent_addresses", addressMap);
		
		
		session.setAttribute("SIMILAR_INTERESSENTS", null);
		} catch (Exception e) {
			throw new javax.servlet.ServletException(e);
		}
	}
	
	public static String generateInteressentAddressTableRows(HttpSession session, String where) {
		Map addressMap = (Map)session.getAttribute(where);
		
		String deleteLink;
		String deleteLink0;
		
		String modifyLink0;
				
		if (where.startsWith("new")) {
			deleteLink = "new_interessent_detail_address.jsp";
			deleteLink0 = "new_interessent_delete_address_row";
			modifyLink0 = "new_interessent_modify_address_row";
		}
		else {
			deleteLink = "interessent_detail_address.jsp";
			deleteLink0 = "interessent_delete_address_row";
			modifyLink0 = "interessent_modify_address_row";
		}
		
		
		//if (addressMap == null) return "<tr></tr>";
		int i = ((Integer)addressMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";
		
		StringBuffer sb = new StringBuffer();
		
		for (int j = 0; j<i; j++) {
			Map address = (Map)addressMap.get(String.valueOf(j));
			
			List deleteList = (List)addressMap.get("deleteList");
			
			if (deleteList!=null)
				if (deleteList.contains(new Integer(j))) continue;
			
			String type = ((Boolean)address.get("private")).booleanValue()?"Privat":"Firma";
			
			String ad = address.get("postcode")+", "+address.get("city")+", "+address.get("street");
			
			String selectedBill = "";
			if (((Integer)addressMap.get("default_bill")).intValue()==j) selectedBill = " checked";

			String selectedDelivery = "";
			if (((Integer)addressMap.get("default_delivery")).intValue()==j) selectedDelivery = " checked";
			
			sb.append("<tr>" +
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ deleteLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/delete.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_bill\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedBill+"></td>" +
			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_delivery\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedDelivery+"></td>" +
			"<td id=\"accountTableDataContent\">"+address.get("country_post_code")+"</td>"+
            "<td id=\"accountTableDataContent\">"+ ad +"</td>"+
		  	"<td id=\"accountTableDataContent\">"+ type + "</td>"+
	    	"<td id=\"accountTableDataContent\">"+address.get("delivery_name")+"</td>"+
			"<td id=\"accountTableDataContent\">"+address.get("comment")+"</td>"+
			"</tr>");
		}
		
		return sb.toString();
	}	
	
	
	public static String generateAddressTableRows(HttpSession session, String where) {
		Map addressMap = (Map)session.getAttribute(where);
		
		String deleteLink;
		String deleteLink0;
		
		String modifyLink0;
				
		if (where.startsWith("new")) {
			deleteLink = "new_customer_detail_address.jsp";
			deleteLink0 = "new_customer_delete_address_row";
			modifyLink0 = "new_customer_modify_address_row";
		}
		else {
			deleteLink = "customer_detail_address.jsp";
			deleteLink0 = "customer_delete_address_row";
			modifyLink0 = "customer_modify_address_row";
		}
		
		
		//if (addressMap == null) return "<tr></tr>";
		int i = ((Integer)addressMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";
		
		StringBuffer sb = new StringBuffer();
		
		for (int j = 0; j<i; j++) {
			Map address = (Map)addressMap.get(String.valueOf(j));
			
			List deleteList = (List)addressMap.get("deleteList");
			
			if (deleteList!=null)
				if (deleteList.contains(new Integer(j))) continue;
			
			String type = ((Boolean)address.get("private")).booleanValue()?"Privat":"Firma";
			
			String ad = address.get("postcode")+", "+address.get("city")+", "+address.get("street");
			
			String selectedBill = "";
			if (((Integer)addressMap.get("default_bill")).intValue()==j) selectedBill = " checked";

			String selectedDelivery = "";
			if (((Integer)addressMap.get("default_delivery")).intValue()==j) selectedDelivery = " checked";
			
			sb.append("<tr>" +
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ deleteLink0+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ deleteLink +"');\"><img border=\"0\" src=\"img/delete.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_bill\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedBill+"></td>" +
			"<td id=\"accountTableDataContent\"><input type=\"radio\" name=\"default_delivery\" value=\""+ String.valueOf(j)+ "\"/ "+ selectedDelivery+"></td>" +
			"<td id=\"accountTableDataContent\">"+address.get("country_post_code")+"</td>"+
            "<td id=\"accountTableDataContent\">"+ ad +"</td>"+
		  	"<td id=\"accountTableDataContent\">"+ type + "</td>"+
	    	"<td id=\"accountTableDataContent\">"+address.get("delivery_name")+"</td>"+
			"<td id=\"accountTableDataContent\">"+address.get("comment")+"</td>"+
			"</tr>");
		}
		
		return sb.toString();
	}
	
	public static String generatePassword() {
		StringBuffer sb = new StringBuffer();
		for (int i=0; i<6; i++) {
				sb.append(randomLowercase());
		}
		sb.append(randomNumber());
		sb.append(randomNumber());
		return sb.toString();
	}

	private static char randomLowercase() {
		char ch = (char) (97 + (int) (Math.random() * 26));
		if (ch == 'o') ch = 'p';
		if (ch == 'i') ch ='j';
		if (ch == 'l') ch = 'k';
		return ch;
	}

	/**
	 * @return a random uppercase character from 'A' to 'Z'
	 */
	private static char randomUppercase() {
		char ch = (char) (65 + (int) (Math.random() * 26));
		if (ch == 'O') ch = 'P';
		if (ch == 'I') ch ='J';
		return ch;
	}

	/**
	 * @return a random character from '0' to '9'
	 */
	private static char randomNumber() {
		char ch =(char) (48 + (int) (Math.random() * 10)); 
		if (ch == '1') ch = '2';
		if (ch == '0') ch = '9';
		return ch;
	}	
	
	public static void loadInteressent(HttpSession session, Logger logger) throws Exception {
		String dist_id = (String)session.getAttribute("CURRENT_INTERESSENT_ID");

		
		if (dist_id == null) return;
		
		int id = 0;
		try {	
			id = Integer.parseInt(dist_id);
		} catch (NumberFormatException nfe) {
			//impossible
			id = 0;
		}
		
		ObjectSearch os = new ObjectSearch("Interessent", (List) null);
		os.setCondition("id = ?");
		
		List ResultList;
		
		try {
			ResultList = os.search(new Object[] {new Integer(id)});
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
		if (ResultList.size()<=0) return;
		PersistableObject po = (PersistableObject)ResultList.get(0);
		
		Map all = po.getValues();
		
		Map personal = new HashMap();
		Map payment = new HashMap();
		Map internal = new HashMap();
		
		
		
		String[] needPersonal = new String[] {"firstname", "password", "lastname","birthdate", "country_code","tel1", "tel2","level_address_id", 
				"titel_id","mobil", "email","fax", "www","language_id", "couple_partner","company", "comment","creation_date", "id"};
		
		
		String[] needInt = new String[] {"active",  "level_id", "advertised"};
		
		String[] needAddress = new String[] {"id", "private" , "comment", "country_post_code", "postcode", "city", "street", "delivery_name"};
		
		List lpersonal = getList(needPersonal);
		
		List linternal = getList(needInt);
		
		List laddress = getList(needAddress);
		

		Map jspPersonal = new HashMap();
		Map jspPayment = new HashMap();
		Map jspInternal = new HashMap();		
		
		Set keys = all.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = all.get(actualName);
			
			boolean shouldPutIn = true;
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
				
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
				
				if (actualName.equals("active")) {
					shouldPutIn = !shouldPutIn;
					logger.info("active was: "+shouldPutIn);
				} 
			}
			
			String jspPut = actualValue.toString();
			
			if (actualValue instanceof java.sql.Date) {
			
				jspPut = formatSQLDate((java.sql.Date)actualValue);
				logger.info(jspPut);
			}
			
			if (lpersonal.contains(actualName)) {
			
				personal.put(actualName, actualValue);
				if (shouldPutIn) {
					jspPersonal.put(actualName, new String[] {jspPut});
				}
			}
			if (linternal.contains(actualName)) {
				internal.put(actualName, actualValue);
				if (shouldPutIn) {
					jspInternal.put(actualName, new String[] {jspPut});
				}

			}
		}
		String name = "";
		if (personal.containsKey("lastname")) name = (String)personal.get("lastname");
		if (personal.containsKey("firstname")) name = name + ", "+(String)personal.get("firstname");
		
		session.setAttribute("CURRENT_INTERESSENT_NAME", name);

		session.removeAttribute("CURRENT_INTERESSENT_DEACTIVATED");

		if (po.get("active")!=null) {
			Boolean bactive = (Boolean)po.get("active");
			boolean active = bactive.booleanValue();
			if (!active) session.setAttribute("CURRENT_INTERESSENT_DEACTIVATED", "yes");
		}

		
		
		session.setAttribute("interessent_detail_personal.jsp", jspPersonal);
		session.setAttribute("interessent_detail_int.jsp", jspInternal);
		
		session.setAttribute("interessent_detail_address.jsp", new HashMap());
		
		session.setAttribute("interessent_personal_Map", personal);
		session.setAttribute("interessent_int_Map", internal);
		
		ObjectSearch os4 = new ObjectSearch("interessent_address", (List) null);
		os4.setCondition("distr_id = ?");
		
		try {
			ResultList = os4.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it4 = ResultList.iterator();
		
		//Map userAddressMap = (Map)session.getAttribute("user_addresses");
		Map userAddressMap = new HashMap();
		
		int addressNumber = 0;
		
		int _defaultBill = 0;
		int _defaultDelivery = 0;
		
		while (it4.hasNext()) {
			
			addressNumber++;
			Map address = new HashMap();
			PersistableObject po4 = (PersistableObject)it4.next();
			
			Map m = po4.getValues();
			
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
				
				String nn = (String)ni.next();
				
				if (nn.equals("default_delivery")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) _defaultDelivery = addressNumber - 1;
					}
				}

				if (nn.equals("default_bill")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) _defaultBill = addressNumber - 1;
					}
				}
				
				
				if (laddress.contains(nn)) {
					if (m.get(nn) != null) {
						address.put(nn, m.get(nn));
					}
				}
			}
			
			userAddressMap.put(String.valueOf(addressNumber-1), address);
			
		}
		
		userAddressMap.put("count", new Integer(addressNumber));
		userAddressMap.put("default_bill", new Integer(_defaultBill));
		userAddressMap.put("default_delivery", new Integer(_defaultDelivery));
		
		session.setAttribute("interessent_addresses", userAddressMap);
		
	}	
	
	
	public static void loadDistributor(HttpSession session, Logger logger) throws Exception {
		String dist_id = (String)session.getAttribute("CURRENT_CUSTOMER_ID");

		
		if (dist_id == null) return;
		
		int id = 0;
		try {	
			id = Integer.parseInt(dist_id);
		} catch (NumberFormatException nfe) {
			//impossible
			id = 0;
		}
		
		ObjectSearch os = new ObjectSearch("Distributor", (List) null);
		os.setCondition("id = ?");
		
		List ResultList;
		
		try {
			ResultList = os.search(new Object[] {new Integer(id)});
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
		if (ResultList.size()<=0) return;
		PersistableObject po = (PersistableObject)ResultList.get(0);
		
		Map all = po.getValues();
		
		Map personal = new HashMap();
		Map payment = new HashMap();
		Map internal = new HashMap();
		
		
		
		String[] needPersonal = new String[] {"firstname", "password", "lastname","birthdate", "country_code","tel1", "tel2","level_address_id", 
				"titel_id","mobil", "email","fax", "www","language_id", "couple_partner","company", "comment","creation_date", "id"};
		
		String[] needPayment = new String[] {"pay_method_id", "payment_slip", "allow_bank"};
		
		String[] needInt = new String[] {"vat_id", "transferbonus", "active", "deleted","printlock", "customer_service","newsletter", 
				"shipping_id","status_date", "last_order_date","statusdate", "sponsor", "customer_sponsor", "level_id", "homepage"};
		
		String[] needCredit = new String[] {"id", "cc_org_id", "cc_number", "valid_from", "valid_to", "comment"};
		
		String[] needBank = new String[] {"id", "bank_code", "iban", "account_number", "bank", "comment", "bic", "debit_date"};
		
		String[] needAddress = new String[] {"id", "private" , "comment", "country_post_code", "postcode", "city", "street", "delivery_name"};
		
		List lpersonal = getList(needPersonal);
		
		List lpayment = getList(needPayment);
		
		List linternal = getList(needInt);

		List lcredit = getList(needCredit);
		
		List laddress = getList(needAddress);
		
		List lbank = getList(needBank);

		Map jspPersonal = new HashMap();
		Map jspPayment = new HashMap();
		Map jspInternal = new HashMap();		
		
		Set keys = all.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = all.get(actualName);
			
			boolean shouldPutIn = true;
			
			
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
				
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
				
				if (actualName.equals("active")) {
					shouldPutIn = !shouldPutIn;
					logger.info("active was: "+shouldPutIn);
				} 
			}
			
			String jspPut = actualValue.toString();
			
			if (actualValue instanceof java.sql.Date) {
			
				jspPut = formatSQLDate((java.sql.Date)actualValue);
				logger.info(jspPut);
			}
			
			if (lpersonal.contains(actualName)) {
			
				personal.put(actualName, actualValue);
				if (shouldPutIn) {
					jspPersonal.put(actualName, new String[] {jspPut});
				}
			}
			if (lpayment.contains(actualName)) {
			
				payment.put(actualName, actualValue);
				if (shouldPutIn) {
					jspPayment.put(actualName, new String[] {jspPut});
				}

			}
			if (linternal.contains(actualName)) {
				internal.put(actualName, actualValue);
				if (shouldPutIn) {
					jspInternal.put(actualName, new String[] {jspPut});
				}

			}
		}
		String name = "";
		if (personal.containsKey("lastname")) name = (String)personal.get("lastname");
		if (personal.containsKey("firstname")) name = name + ", "+(String)personal.get("firstname");
		
		
		
		session.setAttribute("CURRENT_CUSTOMER_NAME", name);

		session.removeAttribute("CURRENT_CUSTOMER_DEACTIVATED");

		if (po.get("active")!=null) {
			Boolean bactive = (Boolean)po.get("active");
			boolean active = bactive.booleanValue();
			if (!active) session.setAttribute("CURRENT_CUSTOMER_DEACTIVATED", "yes");
		}

		
		
		session.setAttribute("customer_detail_personal.jsp", jspPersonal);
		session.setAttribute("customer_detail_payment.jsp", jspPayment);
		session.setAttribute("customer_detail_int.jsp", jspInternal);
		
		session.setAttribute("customer_detail_address.jsp", new HashMap());
		
		session.setAttribute("customer_personal_Map", personal);
		session.setAttribute("customer_payment_Map", payment);
		session.setAttribute("customer_int_Map", internal);
		
		ObjectSearch os2 = new ObjectSearch("creditcard", (List) null);
		os2.setCondition("distr_id = ?");
		
		try {
			ResultList = os2.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it2 = ResultList.iterator();
		
		//Map userCreditMap = (Map)session.getAttribute("user_credits");
		Map userCreditMap = new HashMap();
		
		int creditNumber = 0;
		
		while (it2.hasNext()) {
			
			creditNumber++;
			Map credit = new HashMap();
			PersistableObject po2 = (PersistableObject)it2.next();
			
			Map m = po2.getValues();
			
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
			
				String nn = (String)ni.next();
			
				if (lcredit.contains(nn)) {
					if (m.get(nn) != null) {
						if (nn.equals("comment")) credit.put("comment", m.get(nn));
						else
						credit.put(nn, m.get(nn));
					}
				}
			
			}
			
			userCreditMap.put(String.valueOf(creditNumber-1), credit);
			
		}
		
		userCreditMap.put("count", new Integer(creditNumber));

		session.setAttribute("customer_credits", userCreditMap);
		
		ObjectSearch os3 = new ObjectSearch("bank_account", (List) null);
		os3.setCondition("distr_id = ?");
		
		try {
			ResultList = os3.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it3 = ResultList.iterator();
		
		
		
		//Map userBankMap = (Map)session.getAttribute("user_banks");
		Map userBankMap = new HashMap();
		
		
		
		int bankNumber = 0;
		
		int defaultBill = 0;
		
		int defaultBonus = 0;
		
		while (it3.hasNext()) {
		
			bankNumber++;
			Map bank = new HashMap();
			PersistableObject po3 = (PersistableObject)it3.next();
		
			Map m = po3.getValues();
		
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
				
				String nn = (String)ni.next();
				
				if (nn.equals("default_bill")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) defaultBill = bankNumber - 1;
					}
				}

				if (nn.equals("default_bonus")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) defaultBonus = bankNumber - 1;
					}
				}
				
				
				if (lbank.contains(nn)) {
					if (m.get(nn) != null) {
						bank.put(nn, m.get(nn));
					}
				}
			}
			
			userBankMap.put(String.valueOf(bankNumber-1), bank);
			
		}
		
		userBankMap.put("count", new Integer(bankNumber));
		userBankMap.put("default_bonus", new Integer(defaultBonus));
		userBankMap.put("default_bill", new Integer(defaultBill));

		session.setAttribute("customer_banks", userBankMap);
		
		
		ObjectSearch os4 = new ObjectSearch("address", (List) null);
		os4.setCondition("distr_id = ?");
		
		try {
			ResultList = os4.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it4 = ResultList.iterator();
		
		
		
		//Map userAddressMap = (Map)session.getAttribute("user_addresses");
		Map userAddressMap = new HashMap();
		
		
		int addressNumber = 0;
		
		int _defaultBill = 0;
		
		int _defaultDelivery = 0;
		
		while (it4.hasNext()) {
			
			addressNumber++;
			Map address = new HashMap();
			PersistableObject po4 = (PersistableObject)it4.next();
			
			Map m = po4.getValues();
			
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
				
				String nn = (String)ni.next();
				
				if (nn.equals("default_delivery")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) _defaultDelivery = addressNumber - 1;
					}
				}

				if (nn.equals("default_bill")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) _defaultBill = addressNumber - 1;
					}
				}
				
				
				if (laddress.contains(nn)) {
					if (m.get(nn) != null) {
						address.put(nn, m.get(nn));
					}
				}
			}
			
			userAddressMap.put(String.valueOf(addressNumber-1), address);
			
		}
		
		userAddressMap.put("count", new Integer(addressNumber));
		userAddressMap.put("default_bill", new Integer(_defaultBill));
		userAddressMap.put("default_delivery", new Integer(_defaultDelivery));
		
		session.setAttribute("customer_addresses", userAddressMap);
		
	}	
	
	
	public static void loadDistributor_old(HttpSession session, Logger logger) throws Exception {
		
		String dist_id = (String)session.getAttribute("CURRENT_CUSTOMER_ID");

		
		
		if (dist_id == null) return;
		
		int id = 0;
		try {	
			id = Integer.parseInt(dist_id);
		} catch (NumberFormatException nfe) {
			//impossible
			id = 0;
		}
		
		ObjectSearch os = new ObjectSearch("Distributor", (List) null);
		os.setCondition("id = ?");
		
		List ResultList;
		
		try {
			ResultList = os.search(new Object[] {new Integer(id)});
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
		
		if (ResultList.size()<=0) return;
		
		PersistableObject po = (PersistableObject)ResultList.get(0);
		
		Map all = po.getValues();
		
		Map personal = new HashMap();
		Map payment = new HashMap();
		Map internal = new HashMap();
		
		
		
		String[] needPersonal = new String[] {"firstname", "password", "lastname","birthdate", "country_code","tel1", "tel2","level_address_id", 
				"titel_id","mobil", "email","fax", "www","language_id", "couple_partner","company", "comment","creation_date", "id"};
		
		String[] needPayment = new String[] {"pay_method_id"};
		
		String[] needInt = new String[] {"vat_id", "transferbonus", "active", "deleted","printlock", "customer_service","newsletter", 
				"shipping_id","status_date", "last_order_date","statusdate", "sponsor", "customer_sponsor", "level_id", "homepage"};
		
		String[] needCredit = new String[] {"id", "cc_org_id", "cc_number", "valid_from", "valid_to", "comment"};
		
		String[] needBank = new String[] {"id", "bank_code", "iban", "account_number", "bank", "comment", "bic"};
		
		String[] needAddress = new String[] {"id", "private" , "comment", "country_post_code", "postcode", "city", "street", "delivery_name"};
		
		List lpersonal = getList(needPersonal);
		
		List lpayment = getList(needPayment);
		
		List linternal = getList(needInt);

		List lcredit = getList(needCredit);
		
		List laddress = getList(needAddress);
		
		List lbank = getList(needBank);

		Map jspPersonal = new HashMap();
		Map jspPayment = new HashMap();
		Map jspInternal = new HashMap();		
		
		Set keys = all.keySet();
		
		Iterator it = keys.iterator();
		
		
		while (it.hasNext()) {
			String actualName = (String)it.next();
			Object actualValue = all.get(actualName);
			
			boolean shouldPutIn = true;
			
			if (actualValue==null) continue;
			
			if (actualValue instanceof Boolean) {
				Boolean bactVal = (Boolean)actualValue;
				if (!bactVal.booleanValue()) shouldPutIn = false; else shouldPutIn = true;
				
				if (actualName.equals("active")) {
					shouldPutIn = !shouldPutIn;
				} 
			}
			
			String jspPut = actualValue.toString();
			if (actualValue instanceof java.sql.Date) {
				jspPut = formatSQLDate((java.sql.Date)actualValue);
				logger.info(jspPut);
			}
			
			if (lpersonal.contains(actualName)) {
				personal.put(actualName, actualValue);
				if (shouldPutIn) {
					jspPersonal.put(actualName, new String[] {jspPut});
				}
			}
			if (lpayment.contains(actualName)) {
				payment.put(actualName, actualValue);
				if (shouldPutIn) {
					jspPayment.put(actualName, new String[] {jspPut});
				}

			}
			if (linternal.contains(actualName)) {
				internal.put(actualName, actualValue);
				if (shouldPutIn) {
					jspInternal.put(actualName, new String[] {jspPut});
				}

			}
		}
		String name = "";
		if (personal.containsKey("lastname")) name = (String)personal.get("lastname");
		if (personal.containsKey("firstname")) name = name + ", "+(String)personal.get("firstname");
		
		
		
		session.setAttribute("CURRENT_CUSTOMER_NAME", name);
		
		
		session.setAttribute("customer_detail_personal.jsp", jspPersonal);
		session.setAttribute("customer_detail_payment.jsp", jspPayment);
		session.setAttribute("customer_detail_int.jsp", jspInternal);
		
		session.setAttribute("customer_detail_address.jsp", new HashMap());

		session.setAttribute("customer_personal_Map", personal);
		session.setAttribute("customer_payment_Map", payment);
		session.setAttribute("customer_int_Map", internal);
		
		ObjectSearch os2 = new ObjectSearch("creditcard", (List) null);
		os2.setCondition("distr_id = ?");
		
		try {
			ResultList = os2.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it2 = ResultList.iterator();
		
		Map customerCreditMap = (Map)session.getAttribute("customer_credits");
		
		
		int creditNumber = 0;
		
		while (it2.hasNext()) {
			
			creditNumber++;
			Map credit = new HashMap();
			PersistableObject po2 = (PersistableObject)it2.next();
			
			Map m = po2.getValues();
			
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
			
				String nn = (String)ni.next();
			
				if (lcredit.contains(nn)) {
					if (m.get(nn) != null) {
						if (nn.equals("comment")) credit.put("comment", m.get(nn));
						else
						credit.put(nn, m.get(nn));
					}
				}
			
			}
			
			customerCreditMap.put(String.valueOf(creditNumber-1), credit);
			
		}
		
		customerCreditMap.put("count", new Integer(creditNumber));

		
		ObjectSearch os3 = new ObjectSearch("bank_account", (List) null);
		os3.setCondition("distr_id = ?");
		
		try {
			ResultList = os3.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it3 = ResultList.iterator();
		
		
		
		Map customerBankMap = (Map)session.getAttribute("customer_banks");
		
		
		int bankNumber = 0;
		
		int defaultBill = 0;
		
		int defaultBonus = 0;
		
		while (it3.hasNext()) {
		
			bankNumber++;
			Map bank = new HashMap();
			PersistableObject po3 = (PersistableObject)it3.next();
		
			Map m = po3.getValues();
		
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
		
				String nn = (String)ni.next();
		
				if (nn.equals("default_bill")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) defaultBill = bankNumber - 1;
					}
				}

				if (nn.equals("default_bonus")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) defaultBonus = bankNumber - 1;
					}
				}
				
				
				if (lbank.contains(nn)) {
					if (m.get(nn) != null) {
						bank.put(nn, m.get(nn));
					}
				}
			}
			
			customerBankMap.put(String.valueOf(bankNumber-1), bank);
			
		}
		
		customerBankMap.put("count", new Integer(bankNumber));
		customerBankMap.put("default_bonus", new Integer(defaultBonus));
		customerBankMap.put("default_bill", new Integer(defaultBill));

		
		
		
		ObjectSearch os4 = new ObjectSearch("address", (List) null);
		os4.setCondition("distr_id = ?");
		
		try {
			ResultList = os4.search(new Object[] {new Integer(id)});
		}	 catch (Exception e) {
			logger.error(e.getMessage());
			throw new ServletException(e);
		}
			
		Iterator it4 = ResultList.iterator();
		
		
		
		Map customerAddressMap = (Map)session.getAttribute("customer_addresses");
		
		
		int addressNumber = 0;
		
		int _defaultBill = 0;
		
		int _defaultDelivery = 0;
		
		while (it4.hasNext()) {
		
			addressNumber++;
			Map address = new HashMap();
			PersistableObject po4 = (PersistableObject)it4.next();
		
			Map m = po4.getValues();
		
			Set names = m.keySet();
			
			Iterator ni = names.iterator();
			
			while (ni.hasNext()) {
		
				String nn = (String)ni.next();
		
				if (nn.equals("default_delivery")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) _defaultDelivery = addressNumber - 1;
					}
				}

				if (nn.equals("default_bill")) {
					Object o = m.get(nn);
					if (o instanceof Boolean) {
						if (((Boolean)o).booleanValue()) _defaultBill = addressNumber - 1;
					}
				}
				
				
				if (laddress.contains(nn)) {
					if (m.get(nn) != null) {
						address.put(nn, m.get(nn));
					}
				}
			}
			
			customerAddressMap.put(String.valueOf(addressNumber-1), address);
			
		}
		
		customerAddressMap.put("count", new Integer(addressNumber));
		customerAddressMap.put("default_bill", new Integer(_defaultBill));
		customerAddressMap.put("default_delivery", new Integer(_defaultDelivery));
		customerAddressMap.remove("deleteList");
		
		
		
	}
	
	public static String formatSQLDate(java.sql.Date date) {
		if (date == null) return "";
		
		StringBuffer ret= new StringBuffer();
		
		DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN);
		
		
		
		return df.format(date);
		
	}

	public static java.sql.Date formatDate(String str) {
		java.sql.Date date;

		DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN);

		try {
			java.util.Date d = df.parse(str);
			date = new java.sql.Date(d.getTime());
		} catch (Exception e) {
			//this should be impossible
			return null;
			}
		 return date;
	}

	
	
	public static List getList(String[] sa) {
		List l = new ArrayList(sa.length);
		for (int i=0; i<sa.length; i++)
			l.add(sa[i]);
		
		return l;
	}
	
	public static boolean modifyInteressent(HttpSession session, Logger logger) throws ServletException {
		int distr_id;
		try {
			distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_INTERESSENT_ID"));
		} catch (Exception e) {
			return false;
		}
		
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute("interessent_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute("interessent_personal_Map"));
			if (session.getAttribute("interessent_int_Map")!=null)
			complex.putAll((Map)session.getAttribute("interessent_int_Map"));
			
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			complex.remove("sponsor_name");
			complex.remove("customer_sponsor_name");
			complex.remove("rows");

			complex.put("modified_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
			complex.put("modification_time", new java.sql.Date(System.currentTimeMillis()));
			complex.put("modification_ip", (String)session.getAttribute("USER_LOGGED_REMOTE_ADDRESS"));
					
			List l = new ArrayList();
			
			l.add("id");
			
			ObjectSearch os = new ObjectSearch("interessent", l);
			
			os.setCondition("id = ?");
			
			List result = os.search(new Object[] {new Integer(distr_id)});
			
			//meanwhile this address not exists any more
			if (result.size()<1) return false;
			
			PersistableObject po = (PersistableObject)result.get(0);
			
			Set names = complex.keySet();
			
			Iterator it = names.iterator();
			
			while (it.hasNext()) {
				String current = (String)it.next();
				po.set(current, complex.get(current));
			}
			
			try {
				po.update();
			} catch (Exception ex) {
				logger.error(ex.getMessage());
				throw new ServletException(ex);
			}
		
		} catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		}
		
		return true;
	
	}
	
	
	public static boolean modifyDistributor(HttpSession session, Logger logger) throws ServletException {
		int distr_id;
		try {
			distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
		} catch (Exception e) {
			return false;
		}
		
		
		
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute("customer_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute("customer_personal_Map"));
			if (session.getAttribute("customer_int_Map")!=null)
			complex.putAll((Map)session.getAttribute("customer_int_Map"));
			
			boolean noVat = false;
			String vid = (String)complex.get("vat_id");
			String country_code = (String)complex.get("country_code");
			
	        PersistableObject po_country = new PersistableObject("country", "country_code");
	        po_country.set("country_code", country_code);
	        po_country.load();
	        
	        String tax_id = po_country.getString("tax_id", "");
			
	        logger.info("DEBB: " + vid);
	        logger.info("DEBB: " + country_code);
	        
			if (vid != null && vid.length()>0)
				if (!"AT".equals(country_code))
					if (!"".equals(tax_id) && !"0".equals(tax_id))
						noVat = true;
				
			logger.info("DEBB: " + noVat);
			
			
			if (session.getAttribute("customer_payment_Map")!=null)
			complex.putAll((Map)session.getAttribute("customer_payment_Map"));
		
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			complex.remove("sponsor_name");
			complex.remove("customer_sponsor_name");
			complex.remove("rows");

			complex.put("modified_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
			complex.put("modification_time", new java.sql.Date(System.currentTimeMillis()));
			complex.put("modification_ip", (String)session.getAttribute("USER_LOGGED_REMOTE_ADDRESS"));
					
			
			List l = new ArrayList();
			
			l.add("id");
			
			ObjectSearch os = new ObjectSearch("distributor", l);
			
			os.setCondition("id = ?");
			
			List result = os.search(new Object[] {new Integer(distr_id)});
			
			//meanwhile this address not exists any more
			if (result.size()<1) return false;
			
			PersistableObject po = (PersistableObject)result.get(0);
			
			Set names = complex.keySet();
			
			Iterator it = names.iterator();
			
			while (it.hasNext()) {
				String current = (String)it.next();
				po.set(current, complex.get(current));
			}
			
			try {
				po.update();
			} catch (Exception ex) {
				logger.error(ex.getMessage());
				throw new ServletException(ex);
			}
		
			List l2 = new ArrayList();
			l2.add("id");
	        ObjectSearch os2 = new ObjectSearch("subscription_header", l2);
			
			os2.setCondition("distr_id = ?");
			
			List result2 = os2.search(new Object[] {new Integer(distr_id)});
			
			if (result2.size()>0) {
				
		         PersistableObject article = new PersistableObject("currentarticles","id");
				
				for (Iterator it2 = result2.iterator(); it2.hasNext();) {
					PersistableObject temppo = (PersistableObject)it2.next();
					String sid = temppo.getString("id", "");
					
					if (sid.equals("")) continue;
					
					ObjectSearch os3 = new ObjectSearch("subscription_detail", new String[] {"id"});
			    	os3.setCondition("subscr_id = ?");
			    	os3.setOrderBy(new String[] {"art_position"});
			    	List details = os3.search(new Object[] {new Long(sid)});
			    	
			    	Double new_brutto = new Double(0);
			    	for (Iterator it3 = details.iterator(); it3.hasNext(); ) {
			    		PersistableObject det = (PersistableObject)it3.next();
		    			String art_id = det.getString("art_id", "");
		    			String vatClass = "1";
				         try {
				             article.set("id",art_id);
				             article.load();
				             vatClass = article.getString("vat_id", "1");
				             
				             if (vatClass.equals("0")) vatClass="1";
				         } catch(Exception e) {
				             logger.info("There was a problem of getting article from currentarticles, id: " + art_id);
				             continue;
				         }
				         
		    			Double d_netto = (Double)det.get("netto");
		    			BigDecimal vat = (BigDecimal) po_country.get("vat"+vatClass);
		    			if (noVat) vat = new BigDecimal(0);
		    			double d_brutto = d_netto + (d_netto * vat.doubleValue())*.01;
		    			
		    			logger.info("VatClass: "+vatClass+", netto: "+d_netto+", brutto: "+d_brutto+", vat: "+vat);
		    			det.set("brutto", new Float(d_brutto));
		    			new_brutto+=d_brutto;
		    			det.set("vat_value", new Float(vat.floatValue()));
		    			
			    		det.update();
			    	}
					temppo.set("total_brutto", new Float(new_brutto));
					temppo.update();
				}
				
			}
		
		} catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		}
		
		return true;
	
	}	
	
	public static boolean modifyInteressentAddresses(HttpSession session, Logger logger) throws ServletException{
		int distr_id;
		try {
		 distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_INTERESSENT_ID"));
		} catch (Exception e) {
			return false;
		}
		try {
		
		
		Map addressMap = (Map)session.getAttribute("interessent_addresses");
		
		if (addressMap == null) return true;
		
		Integer iCount = (Integer)addressMap.get("count");
		
		if (iCount == null) return true;
		
		int count = iCount.intValue();
		
		Integer iDefBill = (Integer)addressMap.get("default_bill");
		
		Integer iDefDelivery = (Integer)addressMap.get("default_delivery");
		
		int defBill = 0;
		int defDelivery = 0;
		
		if (iDefBill != null) defBill = iDefBill.intValue();
		if (iDefDelivery != null) defDelivery = iDefDelivery.intValue();
		
		for (int i = 0; i<count; i++) {
			
			Map address = (Map)addressMap.get(String.valueOf(i));
			
			List deleteList = (List)addressMap.get("deleteList");
			
			boolean delete = false;
			
			if (deleteList!=null)
				if (deleteList.contains(new Integer(i)))
					delete = true;
			
			int addressId = -1;
			if (address.get("id")!=null)
				addressId = ((Integer)address.get("id")).intValue();
			
			address.put("distr_id", new Integer(distr_id));
			if (i==defBill) address.put("default_bill", new Boolean(true));
			else address.put("default_bill", new Boolean(false));
			
			if (i==defDelivery) address.put("default_delivery", new Boolean(true));
			else address.put("default_delivery", new Boolean(false));
			
			
			if (address.get("link")!=null)
				address.remove("link");
			if (address.get("saveState")!=null)
				address.remove("saveState");
			if (address.get("pageAction")!=null)
				address.remove("pageAction");
			if (address.get("row")!=null)
				address.remove("row");
			
			
			
			List l = new ArrayList();
			
			l.add("id");
			if (addressId!=-1) {
				ObjectSearch os = new ObjectSearch("interessent_address", l);
			
				os.setCondition("id = ?");
			
				List result = os.search(new Object[] {new Integer(addressId)});
			
			//	meanwhile this address not exists any more
				if (result.size()<1) continue;
			
				PersistableObject po = (PersistableObject)result.get(0);
			
				Set names = address.keySet();
			
				Iterator it = names.iterator();
			
				while (it.hasNext()) {
					String current = (String)it.next();
					po.set(current, address.get(current));
				}
			
				try {
					if (!delete) po.update();
					else po.delete();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {
				PersistableObject po = new PersistableObject("interessent_address", l, address);
				
				try {
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}	
			
			}
			}
			}catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		
		}
		return true;
		
	}	
	
	public static boolean modifyAddresses(HttpSession session, Logger logger) throws ServletException{
		int distr_id;
		try {
		 distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
		} catch (Exception e) {
			return false;
		}
		try {
		
		
		Map addressMap = (Map)session.getAttribute("customer_addresses");
		
		if (addressMap == null) return true;
		
		Integer iCount = (Integer)addressMap.get("count");
		
		if (iCount == null) return true;
		
		int count = iCount.intValue();
		
		Integer iDefBill = (Integer)addressMap.get("default_bill");
		
		Integer iDefDelivery = (Integer)addressMap.get("default_delivery");
		
		int defBill = 0;
		int defDelivery = 0;
		
		if (iDefBill != null) defBill = iDefBill.intValue();
		if (iDefDelivery != null) defDelivery = iDefDelivery.intValue();
		
		for (int i = 0; i<count; i++) {
			
			Map address = (Map)addressMap.get(String.valueOf(i));
			
			List deleteList = (List)addressMap.get("deleteList");
			
			boolean delete = false;
			
			if (deleteList!=null)
				if (deleteList.contains(new Integer(i)))
					delete = true;
			
			int addressId = -1;
			if (address.get("id")!=null)
				addressId = ((Integer)address.get("id")).intValue();
			
			address.put("distr_id", new Integer(distr_id));
			if (i==defBill) address.put("default_bill", new Boolean(true));
			else address.put("default_bill", new Boolean(false));
			
			if (i==defDelivery) address.put("default_delivery", new Boolean(true));
			else address.put("default_delivery", new Boolean(false));
			
			
			if (address.get("link")!=null)
				address.remove("link");
			if (address.get("saveState")!=null)
				address.remove("saveState");
			if (address.get("pageAction")!=null)
				address.remove("pageAction");
			if (address.get("row")!=null)
				address.remove("row");
			
			
			
			List l = new ArrayList();
			
			l.add("id");
			if (addressId!=-1) {
				ObjectSearch os = new ObjectSearch("address", l);
			
				os.setCondition("id = ?");
			
				List result = os.search(new Object[] {new Integer(addressId)});
			
			//	meanwhile this address not exists any more
				if (result.size()<1) continue;
			
				PersistableObject po = (PersistableObject)result.get(0);
			
				Set names = address.keySet();
			
				Iterator it = names.iterator();
			
				while (it.hasNext()) {
					String current = (String)it.next();
					po.set(current, address.get(current));
				}
			
				try {
					if (!delete) po.update();
					else po.delete();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {
				PersistableObject po = new PersistableObject("address", l, address);
				
				try {
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}	
			
			}
			}
			}catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		
		}
		return true;
		
	}
	

	public static boolean modifyCredits(HttpSession session,Logger logger) throws ServletException {
		int distr_id;
		try {
		 distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
		} catch (Exception e) {
			return false;
		}
		Map creditsMap = (Map)session.getAttribute("customer_credits");
		if (creditsMap == null) return true;
		
		Integer iCount = (Integer)creditsMap.get("count");
		
		if (iCount == null) return true;
		
		int count = iCount.intValue();
		
		
		try{
		
		for (int i = 0; i<count; i++) {
		
			Map credit = (Map)creditsMap.get(String.valueOf(i));
			credit.put("distr_id", new Integer(distr_id));
		
			
			List deleteList = (List)creditsMap.get("deleteList");
			
			boolean delete = false;
			
			if (deleteList!=null)
				if (deleteList.contains(new Integer(i)))
					delete = true;
				
			int creditId = -1;
			
			if (credit.get("id")!=null)
				creditId = ((Integer)credit.get("id")).intValue();
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (credit.get("link")!=null)
				credit.remove("link");
			if (credit.get("saveState")!=null)
				credit.remove("saveState");
			if (credit.get("pageAction")!=null)
				credit.remove("pageAction");
			if (credit.get("iban")!=null)
				credit.remove("iban");
			if (credit.get("account_number")!=null)
				credit.remove("account_number");
			if (credit.get("bank")!=null)
				credit.remove("bank");
			if (credit.get("default_bill")!=null)
				credit.remove("default_bill");
			if (credit.get("default_bonus")!=null)
				credit.remove("default_bonus");
			if (credit.get("bank_code")!=null)
				credit.remove("bank_code");
			if (credit.get("bic")!=null)
				credit.remove("bic");
			if (credit.get("debit_date")!=null)
				credit.remove("debit_date");
			
			if (credit.get("pay_method_id")!=null)
				credit.remove("pay_method_id");
			
			if (credit.get("vat_id")!=null)
				credit.remove("vat_id");
			
			if (credit.get("transferbonus")!=null)
				credit.remove("transferbonus");
			if (credit.get("row")!=null)
				credit.remove("row");
			
			if (credit.get("payment_slip")!=null)
				credit.remove("payment_slip");
			
			if (credit.get("allow_bank")!=null)
				credit.remove("allow_bank");
			
			
			if (creditId!=-1) {
				credit.put("modified_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
				credit.put("modification_time", new java.sql.Date(System.currentTimeMillis()));
				credit.put("modification_ip", (String)session.getAttribute("USER_LOGGED_REMOTE_ADDRESS"));

				
				ObjectSearch os = new ObjectSearch("creditcard", l);
				os.setCondition("id = ?");
				List result = os.search(new Object[] {new Integer(creditId)});
			//	meanwhile this address not exists any more
				if (result.size()<1) continue;
				PersistableObject po = (PersistableObject)result.get(0);
				Set names = credit.keySet();
				Iterator it = names.iterator();
				while (it.hasNext()) {
					String current = (String)it.next();
					po.set(current, credit.get(current));
				}
				try {
					if (!delete) po.update();
					else po.delete();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {
				
				PersistableObject po = new PersistableObject("creditcard", l, credit);
				
				try {
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}
			}
			
			
			
			
		}
		}
		catch (Exception e) {
			throw new ServletException(e);
		}
		
			
			
		
		
		return true;
		
	}

	
	public static boolean modifyBanks(HttpSession session, Logger logger) throws ServletException{
		
		int distr_id;
		try {
		 distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_CUSTOMER_ID"));
		} catch (Exception e) {
			return false;
		}
		try {
		
		Map banksMap = (Map)session.getAttribute("customer_banks");
		
		if (banksMap == null) return true;
		
		Integer iCount = (Integer)banksMap.get("count");
		
		if (iCount == null) return true;
		
		int count = iCount.intValue();
		
		Integer iDefBill = (Integer)banksMap.get("default_bill");
		
		Integer iDefBonus = (Integer)banksMap.get("default_bonus");
		
		int defBill = 0;
		int defBonus = 0;
		
		if (iDefBill != null) defBill = iDefBill.intValue();
		if (iDefBonus != null) defBonus = iDefBonus.intValue();
		
		for (int i = 0; i<count; i++) {
		
			Map bank = (Map)banksMap.get(String.valueOf(i));
			
			List deleteList = (List)banksMap.get("deleteList");
			
			boolean delete = false;
			
			if (deleteList!=null)
				if (deleteList.contains(new Integer(i)))
					delete = true;
				
			bank.put("distr_id", new Integer(distr_id));
			if (i==defBill) bank.put("default_bill", new Boolean(true));
			else bank.put("default_bill", new Boolean(false));
			
			if (i==defBonus) bank.put("default_bonus", new Boolean(true));
			else bank.put("default_bonus", new Boolean(false));
			
			int bankId = -1;
			
			if (bank.get("id")!=null)
				bankId = ((Integer)bank.get("id")).intValue();
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (bank.get("link")!=null)
				bank.remove("link");
			if (bank.get("saveState")!=null)
				bank.remove("saveState");
			if (bank.get("pageAction")!=null)
				bank.remove("pageAction");
			if (bank.get("cc_number")!=null)
				bank.remove("cc_number");
			if (bank.get("cc_org_id")!=null)
				bank.remove("cc_org_id");
			if (bank.get("valid_from")!=null)
				bank.remove("valid_from");
			if (bank.get("valid_to")!=null)
				bank.remove("valid_to");
			if (bank.get("fully")!=null)
				bank.remove("fully");
			
			if (bank.get("pay_method_id")!=null)
				bank.remove("pay_method_id");
			
			if (bank.get("vat_id")!=null)
				bank.remove("vat_id");
			
			if (bank.get("transferbonus")!=null)
				bank.remove("transferbonus");
			
			if (bank.get("row")!=null)
				bank.remove("row");			
			
			if (bank.get("payment_slip")!=null)
				bank.remove("payment_slip");
			
			if (bank.get("allow_bank")!=null)
				bank.remove("allow_bank");
			
			
			if (bankId!=-1) {
				bank.put("modified_by_id", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
				bank.put("modification_time", new java.sql.Date(System.currentTimeMillis()));
				bank.put("modification_ip", (String)session.getAttribute("USER_LOGGED_REMOTE_ADDRESS"));

				
				
				ObjectSearch os = new ObjectSearch("bank_account", l);
				os.setCondition("id = ?");
				List result = os.search(new Object[] {new Integer(bankId)});
			//	meanwhile this address not exists any more
				if (result.size()<1) continue;
				PersistableObject po = (PersistableObject)result.get(0);
				Set names = bank.keySet();
				Iterator it = names.iterator();
				while (it.hasNext()) {
					String current = (String)it.next();
					po.set(current, bank.get(current));
				}
				try {
					if (!delete) po.update();
					else po.delete();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {	
				try {
					PersistableObject po = new PersistableObject("bank_account", l, bank);
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.info(ex.getMessage());
					throw new ServletException(ex);
				}
			}
		}
		} catch (Exception e) {
			throw new ServletException(e);
		}
		return true;
		
	}	
	
	public static boolean _addCredits(HttpSession session, int dist_id, Logger logger) throws ServletException{
		Map creditsMap = (Map)session.getAttribute("new_customer_credits");
		if (creditsMap == null) return true;
		logger.info("addr");
		Integer iCount = (Integer)creditsMap.get("count");
		logger.info("addr");
		if (iCount == null) return true;
		logger.info("addr");
		int count = iCount.intValue();
		logger.info("addr");
		
		for (int i = 0; i<count; i++) {
			logger.info("addr "+i);
			Map credit = (Map)creditsMap.get(String.valueOf(i));
			credit.put("distr_id", new Integer(dist_id));
			
			List l = new ArrayList();
			
			l.add("id");
			
			if (credit.get("link")!=null)
				credit.remove("link");
			if (credit.get("saveState")!=null)
				credit.remove("saveState");
			if (credit.get("pageAction")!=null)
				credit.remove("pageAction");
			if (credit.get("iban")!=null)
				credit.remove("iban");
			if (credit.get("account_number")!=null)
				credit.remove("account_number");
			if (credit.get("bank")!=null)
				credit.remove("bank");
			if (credit.get("default_bill")!=null)
				credit.remove("default_bill");
			if (credit.get("default_bonus")!=null)
				credit.remove("default_bonus");
			if (credit.get("bank_code")!=null)
				credit.remove("bank_code");
			if (credit.get("bic")!=null)
				credit.remove("bic");
			if (credit.get("debit_date")!=null)
				credit.remove("debit_date");
			if (credit.get("pay_method_id")!=null)
				credit.remove("pay_method_id");
			
			if (credit.get("vat_id")!=null)
				credit.remove("vat_id");
			
			if (credit.get("transferbonus")!=null)
				credit.remove("transferbonus");
			if (credit.get("row")!=null)
				credit.remove("row");
			

			
			PersistableObject po = new PersistableObject("creditcard", l, credit);
			
			try {
				po.insert();
			} catch (Exception ex) {
				logger.info(ex.getMessage());
				throw new ServletException(ex);
			}
			
		}
		
		return true;
		
	}		
	
	
}


