/*
 * 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.util.*;

import javax.servlet.ServletException;
import javax.servlet.http.*;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.sql.*;

import com.etixpert.evolution.*;

import org.apache.log4j.*;

import java.text.*;

import javax.servlet.jsp.jstl.fmt.*;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.*;
import org.hibernate.*;

public class FormHelper {
	
	public static String[] months_last_days = {"31", "28", "31", "30", "31", "30", "31", "31", "30", "31", "30", "31"};
	
	public static String getMonthOptions() {
		StringBuffer sb = new StringBuffer();
		java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis()); 
		int month = thisDay.getMonth();
		int year = thisDay.getYear();
		java.text.DateFormat df = java.text.DateFormat.getDateInstance(java.text.DateFormat.MEDIUM, Locale.GERMAN);
		for (int i=month-1; i>0; i--) {
			String date = "01."+(month<10?"0"+String.valueOf(i):String.valueOf(i))+"."+String.valueOf(year);
			sb.append("<option value=\""+date+"\">"+String.valueOf(year)+"."+String.valueOf(i)+"</option>");
		}
		return sb.toString();
	}
	
	public static Map checkDisallowBank(PageContext pc, Logger logger, Integer id, String from) throws Exception {
		HttpSession session = pc.getSession(); 
		Map pMap = (Map)session.getAttribute(from);
		
		Boolean b = (Boolean)pMap.get("allow_bank");
		
		if (b.booleanValue()) return null;
		
		Map ret = new HashMap();
		
		ObjectSearch os = new ObjectSearch("order_header", new String[] {"id"});
		os.setCondition("pay_method_id = 1 and order_status_id < 40 and ordered_by = ?");
		
		List l = os.search(new Object[] {id});
		
		if (l!=null) {
			ArrayList orders = new ArrayList();
			for (int i = 0; i<l.size(); i++) {
				PersistableObject act = (PersistableObject)l.get(i);
				orders.add(act.get("id"));
			}
			if (orders.size()!=0)
				ret.put("orders", orders);
		}
		
		ObjectSearch os2 = new ObjectSearch("subscription_header", new String[] {"id"});
		os2.setCondition("pay_method_id = 1 and distr_id = ?");
		
		List l2 = os2.search(new Object[] {id});
		
		if (l2!=null) {
			ArrayList abos = new ArrayList();
			for (int i = 0; i<l2.size(); i++) {
				PersistableObject act = (PersistableObject)l2.get(i);
				abos.add(act.get("id"));
			}
			if (abos.size()!=0)
				ret.put("abos", abos);
		}
		
		if (ret.keySet().size() == 0) return null;
		else return ret;
		
	}
	
	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 String generatePasswordPersonLine(HttpSession session) throws Exception{
		String pp = (String)session.getAttribute("password_person");
		
		if (pp == null) return "";
		
		String back = pp;
		
		PersistableObject po = new PersistableObject("distributor", "id");
		
		po.set("id", new Integer(pp));
		
		po.load();
 
		 		
 
		back = back + ", "+po.getString("lastname", "") + " "+ po.getString("firstname", "");
		
		return back;
	}
	
	public static void changePassword(PageContext pc, HttpServletRequest req) throws Exception {
		HttpSession session = pc.getSession();
		String old = req.getParameter("old_password");
		String newp = req.getParameter("new_password");
		String renewp = req.getParameter("re_new_password");
		
		boolean admin = false;
		boolean customer = false;
		boolean distributor = false;
		
		
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;

		PersistableObject po = new PersistableObject("distributor", "id");
		String pp = (String)session.getAttribute("password_person");
		
		if (pp == null) throw new Exception("password_person null");
		
		po.set("id", new Integer(pp));
		
		po.load();
		
		String orig_old = po.getString("password", "");
		
		
		
		if (!admin) {
			if (!orig_old.equals(old)) throw new Exception(LocaleSupport.getLocalizedMessage(pc,"OLD_PASSWORD_INVALID"));
		}
		
		if (!newp.equals(renewp)) throw new Exception(LocaleSupport.getLocalizedMessage(pc, "NEW_AND_RENEW_PASSWORDS_INVALID"));
		
		if (newp.length()<5) throw new Exception(LocaleSupport.getLocalizedMessage(pc, "WRONG_PASSWORD"));
		
		po.set("password", newp);
		
		po.update();
		
	}
	
	
	public static void newPasswordChangeStart(HttpSession session, String cnr) throws Exception {
		session.setAttribute("password_person", cnr);
	}
	
	public static void downloadData(String id, HttpServletResponse res) throws Exception {
		Map m = new HashMap();
		m.put("id", new Integer(id));
		PersistableObject po = new PersistableObject("financial", new String[] {"id"}, m);
		po.load();
		
		byte[] data = (byte[])po.get("data");
		
		//byte[] bdata = data.getBytes(data.length(), 1);
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition","attachment; filename="+po.getString("name","untitled")+".dat"); 
		OutputStream os = res.getOutputStream();
		os.write(data);
		
		java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());
		
		po.set("download_time", ts);
		
		po.update();
	}

	public static void downloadPDF(String id, HttpServletResponse res, boolean cc) throws Exception {
		Map m = new HashMap();
		m.put("id", new Integer(id));
		PersistableObject po = new PersistableObject("financial", new String[] {"id"}, m);
		po.load();
		
		byte[] data = (byte[])po.get("pdf");
		
		//byte[] bdata = data.getBytes(data.length(), 1);
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition","attachment; filename="+po.getString("name","untitled")+".pdf"); 
		OutputStream os = res.getOutputStream();
		os.write(data);
		
		if (cc) {
			java.sql.Timestamp ts = new java.sql.Timestamp(System.currentTimeMillis());
			po.set("download_time", ts);		
			po.update();
		}
		
	}
	
	public static void downloadPDF(byte[] data, String name, HttpServletResponse res) throws Exception {
		
		//byte[] bdata = data.getBytes(data.length(), 1);
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition","attachment; filename=" + (name != null ? name : "untitled") + ".pdf"); 
		OutputStream os = res.getOutputStream();
		os.write(data);
	}
	
	public static void logAcceptProtocol(PageContext pc, Logger logger, ArrayList res, Integer distr_id) throws Exception {
		HttpSession session = pc.getSession();
		
		StringBuffer sb = new StringBuffer();
		
		for (int i=0; i<res.size(); i++) {
			Map act = (Map)res.get(i);
			sb.append("("+act.get("id")+", "+act.get("lastname")+")");
			if (i<res.size()-1) sb.append(", ");
		}
		
		SuperPO spo = new SuperPO("accept_protocol", logger);
		
		spo.setPOColumn("accept_date", new java.sql.Date(System.currentTimeMillis()));
		spo.setPOColumn("accepted_by", new Integer((String)session.getAttribute("USER_LOGGED_ID")));
		spo.setPOColumn("distr_id", distr_id);
		spo.setPOColumn("similar_users", sb.toString());
		
		spo.insert();
	}
	
	public static boolean hasSimilars(PageContext pc, Logger logger, boolean dist) throws Exception {
		HttpSession session = pc.getSession();
		Map uMap = (Map)session.getAttribute((dist)?"new_user_personal_Map":"new_customer_personal_Map");
		
		if (uMap == null) return false;
		
		String lastName = (String)uMap.get("lastname");
		
		if (lastName == null) {
			logger.info("WARNING: lastname is null in hasSimilars function!");
			return false;
		}
		
		lastName = lastName.toUpperCase(Locale.GERMAN).trim();
		java.util.Date birthdate = (java.util.Date)uMap.get("birthdate");
		
		boolean hasAddress = true;
		ArrayList addr = new ArrayList();
		ArrayList par = new ArrayList();
		
		Map addressMap = (Map)session.getAttribute("new_user_addresses");
		
		if (addressMap != null) {
			Integer iCount = (Integer)addressMap.get("count");
			if (iCount != null) {
				int count = iCount.intValue();
				if (count == 0) hasAddress = false;
				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;
					}
					
					Map act = new HashMap();
					act.put("street", new String((String)address.get("street")));
					act.put("postcode", new String((String)address.get("postcode")));
					
					addr.add(act);
					
				}

			} else hasAddress = false;
		} else hasAddress = false;
	
		
		
		
		String condition = "(upper(trim(both ' ' from d.lastname)) = ?";
		par.add(lastName);
		//if (birthdate!=null) {
		condition = condition + " AND d.birthdate = ?";
		par.add(birthdate);
		//} else {
		//	condition = condition + " AND d.birthdate is null";
		//}
		
		condition = condition + ")";
	
		
		if (hasAddress) {
			StringBuffer plus = new StringBuffer();
			int count = addr.size();
			
			for (int i=0; i<count; i++) {
				Map act = (Map)addr.get(i);
				String street = (String)act.get("street");
				String plz = (String)act.get("postcode");
				
				if (street!=null) street = street.toUpperCase(Locale.GERMAN).trim();
				if (plz!=null) plz = plz.toUpperCase().trim();
				
				StringBuffer part1 = new StringBuffer();
				StringBuffer part2 = new StringBuffer();
				StringBuffer part3 = new StringBuffer();
				
				if ("".equals(plz) && "".equals(street)) {
					continue;
				}  else {
					par.add(lastName);
					if (!"".equals(plz)) {
						part1.append(" AND upper(trim(both ' ' from a.postcode)) = ?");
						par.add(plz);
					}
					if (!"".equals(street)) {
						part1.append(" AND upper(trim(both ' ' from a.street)) = ?");
						par.add(street);
					}
					
					if (!part1.toString().equals("")) {
						plus.append(" OR (upper(trim(both ' ' from d.lastname)) = ?"+part1.toString()+")");
					} else par.remove(par.size()-1);
					
					
					if (!"".equals(plz)) part2.append(" AND upper(trim(both ' ' from a.postcode)) = ?");
					if (!part2.toString().equals("")) {
						plus.append(" OR (upper(trim(both ' ' from d.lastname)) = ?"+part2.toString());
						par.add(lastName);
						par.add(plz);
						//if (birthdate!=null) {
						plus.append(" AND d.birthdate = ?");
						par.add(birthdate);
						//}
						//else plus.append(" AND d.birthdate is null");
						plus.append(")");
					}
					
					if (!"".equals(plz) && "".equals(street)) {
						part3.append("upper(trim(both ' ' from a.postcode)) = ?");
						par.add(plz);
					}
					else if (!"".equals(street) && !"".equals(plz)) {
						part3.append("upper(trim(both ' ' from a.postcode)) = ? AND upper(trim(both ' ' from a.street)) = ?");
						par.add(plz);
						par.add(street);
					}
					else if ("".equals(plz) && !"".equals(street)) {
						part3.append("upper(trim(both ' ' from a.street)) = ?");
						par.add(street);
					}
					
					if (!part3.toString().equals("")) {
						plus.append(" OR (" + part3.toString()+ ")");
					}
				
				}
				
				
				
			}
			
			condition = condition + plus.toString();
			
		}
        Session session_ = HibernateUtil.currentSession();
        Transaction tx = session_.beginTransaction();
        Connection conn = session_.connection();
        
        String select = "select d.lastname, d.id, d.birthdate, a.postcode, a.street from distributor d left join address a on (d.id = a.distr_id) where ";//:"select d.lastname, d.id, d.birthdate from distributor d where ";
        
	    PreparedStatement ps = conn.prepareStatement(select + "("+condition+") and d.active = true and d.birthdate is not null");
	    
	    logger.info("Checking similar exiting users: ");
	    logger.info("SQL: select d.lastname, d.id, d.birthdate, a.postcode, a.street from distributor d left join address a on (d.id = address.distr_id) where ("+condition+") and d.active = true and d.birthdate is not null");
	    
	    
	    Object[] params = null;
	    
	    params = par.toArray();
	    
        if (params!=null && params.length>0) 
            for (int i =0; i<params.length; i++) {
                ps.setObject(i+1, params[i]);
                logger.info("Parameter "+i+" : "+params[i]);
            }
	    
	    
        ResultSet rs = ps.executeQuery();
        
        boolean ret = false;
        
        ArrayList res = new ArrayList();
        
        if (rs!=null) {
        	logger.info("Results for similar users: ");
        	while (rs.next()) {
        		Map act = new HashMap();
        		logger.info("User id: "+rs.getInt("id")+ ", lastname: "+rs.getString("lastname"));
        		act.put("lastname", rs.getString("lastname"));
        		act.put("id", new Integer(rs.getInt("id")));
        		act.put("birthdate", new String(FormHelper.formatSQLDate(rs.getDate("birthdate"))));
       			act.put("postcode", rs.getString("postcode"));
       			act.put("street", rs.getString("street"));
        		
        		res.add(act);
        	}
        	
        	if (res.size()>0) {
        		ret = true;
        		session.setAttribute(dist?"SIMILAR_DISTRIBUTORS":"SIMILAR_CUSTOMERS", res);
        	}
        }
        
	    tx.commit();
	    HibernateUtil.closeSession();
	    
	    
	    return ret;
	}
	
	public static boolean checkDealer(PageContext pc, Logger logger, boolean modify) {
		String sessKey = modify?"CANNOT_MODIFY_USER":"CANNOT_ADD_USER";
		String iMapKey = modify?"user_int_Map":"new_user_int_Map";
		HttpSession session = pc.getSession();
		Map iMap = (Map)session.getAttribute(iMapKey);
		try {
			int sponsor = ((Integer)iMap.get("sponsor")).intValue();
		} catch (Exception e) {
			session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "NO_SPONSOR"));
			return false;		
		}
		try {
			int level_id = ((Integer)iMap.get("level_id")).intValue();
		} catch (Exception e) {
			session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "NO_DIST_TYPE"));
			return false;		
		}
		int level_id = ((Integer)iMap.get("level_id")).intValue();
		if (level_id == 80) {
			int sponsor = ((Integer)iMap.get("sponsor")).intValue();
			if (iMap.get("discount_rate")!=null) {
				Float dr = (Float)iMap.get("discount_rate");
				if (dr.floatValue() == -1) {
					session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "DEALER_WARNING_1"));
					return false;
				} else if (dr.floatValue() == -2) {
					session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "DEALER_WARNING_2"));
					return false;
				}
				
				if (sponsor!=0) {
					session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "DEALER_WARNING_3"));
					return false;
				}
			}
		}
		if (level_id == 300 || level_id == 350 || level_id == 330 || level_id == 370) {
			try {
				int count = DiscountHelper.getDefaultLevels(session).size();
				
				for (int i = 0; i< count; i++) {
					String name = "personal_discount_";
					if (level_id == 350) name = "gh_personal_discount_";
					else if (level_id == 330) name = "h_personal_discount";
					else if (level_id == 370) name = "a_personal_discount";
					
					if (iMap.get(name+(i+1))!=null) {
						Float f = (Float)iMap.get(name+(i+1));
						if (f.floatValue() == 0) continue;
						if (f.floatValue() == -1000) {
							session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "DEALER_WARNING_1"));
							return false;
						} else if (f.floatValue() == -2000) {
							session.setAttribute(sessKey, LocaleSupport.getLocalizedMessage(pc, "DEALER_WARNING_2"));
							return false;
						}
					}
					
				}
				
			} catch (Exception e) {
				session.setAttribute(sessKey, "unknown error: "+e.getMessage());
				return false;
			}
			
		}
		
		return true;
	}
	
	public static boolean checkConstraints(PageContext pc, Logger logger) {
		HttpSession session = pc.getSession();
		Map pMap = (Map)session.getAttribute("new_user_payment_Map");
		
		
		//Map uMap = (Map)session.getAttribute("new_user_personal_Map");
		Map iMap = (Map)session.getAttribute("new_user_int_Map");
		try {
			int sponsor = ((Integer)iMap.get("sponsor")).intValue();
		} catch (Exception e) {
			session.setAttribute("CANNOT_ADD_USER", LocaleSupport.getLocalizedMessage(pc, "NO_SPONSOR"));
			return false;		
		}
		try {
			int level_id = ((Integer)iMap.get("level_id")).intValue();
		} catch (Exception e) {
			session.setAttribute("CANNOT_ADD_USER", LocaleSupport.getLocalizedMessage(pc, "NO_DIST_TYPE"));
			return false;		
		}

		
		
		
		int pmethod = -1;
		try {
			pmethod = ((Integer)pMap.get("pay_method_id")).intValue();
		} catch (Exception e) {
			session.setAttribute("CANNOT_ADD_USER", LocaleSupport.getLocalizedMessage(pc, "NO_STANDARD_PAYMENT_METHOD"));
			return false;
		}
		
		if (pmethod == 2) {
			
			Map creditMap = (Map)session.getAttribute("new_user_credits");
			if (creditMap == null) return false;
			int count = ((Integer)creditMap.get("count")).intValue();
			if (count == 0) {
				session.setAttribute("CANNOT_ADD_USER", LocaleSupport.getLocalizedMessage(pc, "NO_CREDITCARD"));
				return false;
			}
			
			
			
		} else if (pmethod == 1) {
			
			Map bankMap = (Map)session.getAttribute("new_user_banks");
			
			if (bankMap == null) return false;
			
			int count = ((Integer)bankMap.get("count")).intValue();
			if (count == 0) {
				session.setAttribute("CANNOT_ADD_USER", LocaleSupport.getLocalizedMessage(pc, "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_USER", 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_USER", LocaleSupport.getLocalizedMessage(pc, "WARNING_PAYMENT_SLIP"));
					return false;					
				}
			} else {
				session.setAttribute("CANNOT_ADD_USER", 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_USER", LocaleSupport.getLocalizedMessage(pc, "NO_TRANSFERABLE_ACCOUNT"));
				return false;
			}
		}
		return true;
	}

	
	
	public static boolean hasAccount(HttpSession session) {
		Map bankMap = (Map)session.getAttribute("new_user_banks");
		Map creditMap = (Map)session.getAttribute("new_user_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 modifyBonusRow(HttpSession session, String where, int row, Logger logger) throws Exception{
		
		Map m = (Map)session.getAttribute(where);
		Map bonus = (Map)m.get(String.valueOf(row));
		
		if (bonus==null) return;
		
		String jsplink;
		
		jsplink = "user_detail_bonus.jsp";
		
		Map jspMap = (Map)session.getAttribute(jsplink);		
		
		session.setAttribute(jsplink, bonus);
		
		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_user_detail_address.jsp";
		else jsplink = "user_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_user_detail_payment.jsp";
		else jsplink = "user_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) {
				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_user_detail_payment.jsp";
		else jsplink = "user_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);
		
		
			logger.info("row deleted: "+row);
			
		
		
			if (m.containsKey("default_delivery")) {
				int dd = ((Integer)m.get("default_delivery")).intValue();
				logger.info("default delivery volt: "+dd);
				if (row == dd) {
					m.remove("default_delivery");
					
					boolean hasdd = m.containsKey("default_delivery");
					
					logger.info("hasdd: "+hasdd);
					
					
					int count = ((Integer)m.get("count")).intValue();
					
					logger.info("count: "+count);
					
					for (int u = 0; u<count; u++) {
						if (!deleteList.contains(new Integer(u))) {
							logger.info("uj default delivery: "+u);
							m.put("default_delivery", new Integer(u));
							break;
						}
					}
					
				}
			}

			if (m.containsKey("default_bill")) {
				int dd = ((Integer)m.get("default_bill")).intValue();
				if (row == dd) {
					m.remove("default_bill");
					int count = ((Integer)m.get("count")).intValue();
					
					for (int u = 0; u<count; u++) {
						if (!deleteList.contains(new Integer(u))) {
							m.put("default_bill", new Integer(u));
							break;
						}
					}
					
				}
			}

			if (m.containsKey("default_bonus")) {
				int dd = ((Integer)m.get("default_bonus")).intValue();
				if (row == dd) {
					m.remove("default_bonus");
					int count = ((Integer)m.get("count")).intValue();
					
					for (int u = 0; u<count; u++) {
						if (!deleteList.contains(new Integer(u))) {
							m.put("default_bonus", new Integer(u));
							break;
						}
					}
					
				}
			}		
			}
		
	}
	
	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 != 200 && h!=130 && h!=160) return true;
		
		return false;
	
	}

	public static boolean isExistingArticle(HttpSession session, String art_id) throws Exception {
		
		//for rights checking
		String user_logged_id = (String)session.getAttribute("USER_LOGGED_ID");
		
		ObjectSearch os = new ObjectSearch("article", (List) null);
		os.setCondition("id = ?");
		
		Integer intObj;
		
		
		
		List result;
		
		result = os.search(new Object[] {art_id});
		
		if (result.size()==0) return false;	
		return true;
	
	}	
	
	public static void loadArticle(HttpSession session, String art_id, Logger logger) throws Exception {
		java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
		
		PersistableObject po = new PersistableObject("article", new String[] {"id"});
		po.set("id", art_id);
		po.load();
		
		SuperPO spo = new SuperPO("article", logger);
		spo.setMain(po.getValues());
		
		Map jspMap = new HashMap();
		
		jspMap.putAll(spo.getCheckedTextMap());

		boolean combi = false;
		
		if (po.get("combi")!=null) {
			Boolean b = (Boolean)po.get("combi");
			combi = b.booleanValue();
		}
		
		
		ObjectSearch os = new ObjectSearch("article_history", new String[] {"art_id", "valid_from"});
		//os.setCondition("art_id = ? AND valid_from <= ? and valid_to >= ?");
		os.setCondition("art_id = ? AND valid_to = (select max(valid_to) from article_history where art_id = ?)");
		
		//List result = os.search(new Object[] {art_id, date, date});
		List result = os.search(new Object[] {art_id, art_id});
		
		java.sql.Date valid_from = null;
		java.sql.Date valid_to = null;
		
		if (result.size()>0) {
			PersistableObject po2 = (PersistableObject)result.get(0);
			
			valid_from = (java.sql.Date)po2.get("valid_from");
			valid_to = (java.sql.Date)po2.get("valid_to");
			
			SuperPO spo2 = new SuperPO("article_history", logger);
			spo2.setMain(po2.getValues());
			
			jspMap.putAll(spo2.getTextMap());
			
			DateFormat df = DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.GERMAN);
			String s =  df.format((java.sql.Date)valid_to);
			
			jspMap.put("valid_to", new String[] {s});
			
		}

		
		
		Map combiMap = (Map)session.getAttribute("combi_articles");
		combiMap.put("count", new Integer(0));		
		combiMap.remove("modify");
		
		
		if (combi) {
			
			ObjectSearch os2 = new ObjectSearch("combi_article_content", "combi_art_id");
			os2.setCondition("combi_art_id = ?");
			List result2 = os2.search(new Object[] {art_id});
			
			combiMap.put("count", new Integer(result2.size()));		
			
			for (int i=0; i<result2.size(); i++) {
				
				PersistableObject p = (PersistableObject)result2.get(i);
				String id = p.getString("art_id", "");
				String vol = p.getString("quantity", "0");
			
				Map rr = new HashMap();
				
				rr.put("art_id", id);
				rr.put("quantity", vol);
				
				combiMap.put(String.valueOf(i), rr);
			}
		}
		
		session.setAttribute("article_detail.jsp", jspMap);	
		session.setAttribute("CURRENT_ARTICLE_ID", art_id);
		session.setAttribute("CURRENT_ARTICLE_VALID_FROM", valid_from);
		logger.info("__VALID_DEBUG (load): CURRENT_ARTICLE_VALID_FROM: "+formatSQLDate(valid_from));
	}
	
	public static String generateUserDataHeaderString(PageContext pc) {
		HttpSession session = pc.getSession();
		
		StringBuffer sb = new StringBuffer();

		String s1 = "";
		String s2 = "";
		
		String deact = "";
		
		if (session.getAttribute("CURRENT_DISTRIBUTOR_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_DISTRIBUTOR_ID")!=null?(String)session.getAttribute("CURRENT_DISTRIBUTOR_ID"):"n/a");
		sb.append(", ");
		sb.append(session.getAttribute("CURRENT_DISTRIBUTOR_NAME")!=null?(String)session.getAttribute("CURRENT_DISTRIBUTOR_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 ArticleGroup[] getArticleGroups() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("article_group", l);
		
		os.setOrderBy(new String[] {"id"});
		
		List res = os.search();
		ArticleGroup[] ag = new ArticleGroup[res.size()+1];
		
		ag[0] = new ArticleGroup("0", "");
		
		for (int t = 1; t<ag.length; t++) {
			PersistableObject po = (PersistableObject)res.get(t-1);
			ag[t] = new ArticleGroup(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return ag;
	}
	

	//without partners
	public static DistributorMin[] getDistMin_wp() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("distributor", l);
		os.setOrderBy(new String[] {"lastname"});
		os.setCondition("partner_type_id = 0");
		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].subtype_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 level_subtype_id = po.getString("level_subtype_id", "");
			String val = (String)levels.get(level_id + ":" + level_subtype_id);
			dm[t] = new DistributorMin(String.valueOf(po.get("id")), (String)po.get("lastname")+", "+(String)po.get("firstname"), val); 
		}
		
		//"<option>A</option>";
		
		return dm;
		
	}
	
	//only Beraters
	public static DistributorMin[] getDistMin_wp_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 = 400 OR id = 0");
		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].subtype_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 level_subtype_id = po.getString("level_subtype_id", "");
			String val = (String)levels.get(level_id + ":" + level_subtype_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() 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].subtype_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 level_subtype_id = po.getString("level_subtype_id", "");
			String val = (String)levels.get(level_id + ":" + level_subtype_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);
		os.setOrderBy(new String[] {"id"});
		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 LagerMin[] getLagerMins() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("store", l);
		os.setOrderBy(new String[] {"id"});
		List res = os.search();
		LagerMin[] lagers = new LagerMin[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			lagers[t] = new LagerMin(String.valueOf(po.get("id")), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return lagers;
	}
	
	
	
	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 and id < 10");
		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[] getPMsWebshopOptions() 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[] getPMsWebshopOptionsWithPaymentSlip() 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 PM[] getPMsAll() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("payment_method", l);
		os.setCondition("id <> 5 and id < 10");
		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[] getSpecPMs(HttpSession session) throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("payment_method", l);
		
		if (session.getAttribute("distributor")!=null || session.getAttribute("customer")!=null)
			os.setCondition("id <> 5 and id < 10");
		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();
		List all = new LinkedList();
		
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("user_roles", l);
		os.setCondition("dist_type <> 'e'");
		os.setOrderBy(new String[] {"id"});
		List res = os.search();
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			all.add(new Level(String.valueOf(po.get("id")), "0", (String)po.get("descr"), (String)po.get("dist_type"))); 
			
			ObjectSearch os2 = new ObjectSearch("user_roles_sub", l);
			os2.setCondition("id = " + po.getString("id", "66"));
			os2.setOrderBy(new String[] {"subtype_id"});
			List res2 = os2.search();
			
			if (res2 != null && res.size() > 1) {
				for (int k = 1; k < res2.size(); k++) {
					PersistableObject po2 = (PersistableObject)res2.get(k);
					all.add(new Level(String.valueOf(po.get("id")), String.valueOf(po2.get("subtype_id")),(String)po2.get("descr"), (String)po.get("dist_type")));
				}
			} 
		}
		
		Level[] pms = new Level[all.size()];
		
		for (int h = 0; h < all.size(); h++)
			pms[h] = (Level)all.get(h);
		
		return pms;
	}	
	
	public static Level[] getDistLevels() throws SQLException {
		List all = new LinkedList();
		
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("user_roles", l);
		os.setCondition("dist_type = 'd'");
		os.setOrderBy(new String[] {"id"});
		List res = os.search();
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			all.add(new Level(String.valueOf(po.get("id")), "0",(String)po.get("descr"), (String)po.get("dist_type")));
			
			ObjectSearch os2 = new ObjectSearch("user_roles_sub", l);
			os2.setCondition("id = " + po.getString("id", "66"));
			os2.setOrderBy(new String[] {"subtype_id"});
			List res2 = os2.search();
			
			if (res2 != null && res.size() > 1) {
				for (int k = 1; k < res2.size(); k++) {
					PersistableObject po2 = (PersistableObject)res2.get(k);
					all.add(new Level(String.valueOf(po.get("id")), String.valueOf(po2.get("subtype_id")),(String)po2.get("descr"), (String)po.get("dist_type")));
				}
			} 
			
		}
		
		Level[] pms = new Level[all.size()];
		
		for (int h = 0; h < all.size(); h++)
			pms[h] = (Level)all.get(h);
		
		//"<option>A</option>";
		
		return pms;
	}	
	
	

	public static PartnerType[] getPartnerTypes() throws SQLException {
		List l = new ArrayList();
		l.add("id");
		
		ObjectSearch os = new ObjectSearch("partner_type", l);
		os.setOrderBy(new String[] {"id"});
		List res = os.search();
		PartnerType[] pts = new PartnerType[res.size()];
		
		for (int t = 0; t<res.size(); t++) {
			PersistableObject po = (PersistableObject)res.get(t);
			pts[t] = new PartnerType(po.getString("id", ""), (String)po.get("descr")); 
		}
		
		//"<option>A</option>";
		
		return pts;
	}

	
	
	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 userDetailPersonalToMap(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 userDetailPaymentToMap(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 String getSubtypeLevel(String level) {
		if (level != null && level.contains(":"))
			return level.substring(level.indexOf(":") + 1);
		
		return "0";
	}
	
	public static String getMainLevel(String level) {
		if (level != null && level.contains(":"))
			return level.substring(0, level.indexOf(":"));
		
		return level;
	}
	
	
	public static Map userDetailIntToMap(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));
			ret.put("annual_fee", new Boolean(false));
			
			boolean annual = false;
			int pt = 0;
			float dr = -1;
			String lid = "300";
			
			String[] lvalues = (String[])orig.get("level_id");
			String lvalue = null; 
				if (lvalues != null && lvalues.length>0) lvalue = lvalues[0];
			
			lid = getMainLevel(lvalue);
			
			String subType = null;
			
			while (i.hasNext()) {
				String name = (String)i.next();
				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("annual_fee")) {
					annual = true;
				}
				else if (name.equals("vat_id")) {
					ret.put(name, value);
				}
				else if (name.equals("sconto_days")) {
					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("sponsor") || name.indexOf("_id")!=-1) {
					if (name.equals("level_id")) {
						subType = getSubtypeLevel(value);
						value = getMainLevel(value);
						lid = value;
					}
					int iVal = 0;
					try {
						iVal = Integer.parseInt(value);
					} catch (NumberFormatException nfe) {
						iVal = -1;
					}
					if (iVal!=-1)
						ret.put(name, new Integer(iVal));
					
					if (subType != null) {
						ret.put("level_subtype_id", new Integer(subType));
					}
					
					if (name.equals("partner_type_id")) {
						pt = iVal;
					}
				} else if (name.equals("discount_rate")) {
					try {
						dr = Float.parseFloat(value);
						if (dr<0 || dr>70) dr = -2;
					} catch (NumberFormatException nfe) {
						dr = -1;
					}
				} else if (name.startsWith("personal_discount_")) {
					if (lid.equals("300")) {
						try {
							float val = Float.parseFloat(value);
							
							if (val < -70 || val > 70) val = -2000;
							if (val != 0) 
								ret.put(name, val);
						} catch (NumberFormatException nfe) {
							ret.put(name, new Float(-1000));
						}
					}
				}
				else if (name.startsWith("gh_personal_discount_")) {
					if (lid.equals("350")) {
						try {
							float val = Float.parseFloat(value);
							
							if (val < -70 || val > 70) val = -2000;
							if (val != 0) 
								ret.put(name, val);
						} catch (NumberFormatException nfe) {
							ret.put(name, new Float(-1000));
						}
					}
				}
				else if (name.startsWith("h_personal_discount_")) {
					if (lid.equals("330")) {
						try {
							float val = Float.parseFloat(value);
							
							if (val < -70 || val > 70) val = -2000;
							if (val != 0) 
								ret.put(name, val);
						} catch (NumberFormatException nfe) {
							ret.put(name, new Float(-1000));
						}
					}
				}
				else if (name.startsWith("a_personal_discount_")) {
					if (lid.equals("370")) {
						try {
							float val = Float.parseFloat(value);
							
							if (val < -70 || val > 70) val = -2000;
							if (val != 0) 
								ret.put(name, val);
						} catch (NumberFormatException nfe) {
							ret.put(name, new Float(-1000));
						}
					}
				}			
				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);
				}
				
			}
			
			if (subType != null)
				orig.put("level_subtype_id", new String[] {subType});
			
			if (lid.equals("80")) ret.put("discount_rate", new Float(dr));
			if (pt == 2 && annual) ret.put("annual_fee", new Boolean(true));
			
		} 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 addUserDetailCreditToMap(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) {
			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 addUserDetailBankToMap(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();
			
			boolean hasdd = addressMap.containsKey("default_bonus");
			boolean hasdb = addressMap.containsKey("default_bill");
		
			
			if (!hasdd)
				addressMap.put("default_bonus", new Integer(ii));
			if (!hasdb)
				addressMap.put("default_bill", new Integer(ii));

			
			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;
		
	}
	
	private static boolean hasOverlaps(Map origBonus, Map bonusMap, boolean modify) throws Exception {
		boolean overlap = false;
		
		String[] s1 = (String[])origBonus.get("valid_from");
		String[] s2 = (String[])origBonus.get("valid_to");
		
		if (s1 == null || s2 == null)
			throw new Exception("valid from or valid to fields are not given.");
		String valid_from = s1[0];
		String valid_to = s2[0];
		
		int vfrom = new Integer(valid_from).intValue();
		int vto = new Integer(valid_to).intValue();
		
		Integer count = (Integer)bonusMap.get("count");
		Integer mod = new Integer(-1);
		
		if (modify) {
			mod = (Integer)bonusMap.get("modify");
		}
		
		for (int i = 0; i < count.intValue(); i++) {
			if (modify && mod.intValue() == i) continue;
			Map check = (Map)bonusMap.get(String.valueOf(i));
			
			String[] cs1 = (String[])check.get("valid_from");
			String[] cs2 = (String[])check.get("valid_to");
			if (cs1 == null || cs2 == null)
				throw new Exception("valid from or valid to fields are not given for row: " + i);
			String c_valid_from = cs1[0];
			String c_valid_to = cs2[0];
			
			int cvfrom = new Integer(c_valid_from).intValue();
			int cvto = new Integer(c_valid_to).intValue();
			
			if (vfrom > cvto) continue;
			if (vto < cvfrom) continue;
			
			
			if (vfrom < cvto) {
				overlap = true;
				break;
			}
			
			if (vto > cvfrom) {
				overlap = true;
				break;
			}
			
			
		}
		
		
		
		return overlap;
	}
	
	public static void addUserDetailBonusToMap(Map origBonus, Map bonusMap, Logger log) throws Exception {
		boolean modify = false;
		
		if (bonusMap.get("modify")!=null) modify = true;
		
		if (hasOverlaps(origBonus, bonusMap, modify))
			throw new EvolutionException("valid_from and valid_to are overlapped with existing values.");
		
		//if (b.booleanValue()) {
		if (!modify) {
			Integer integer = (Integer)bonusMap.get("count");
			int ii = integer.intValue();
			bonusMap.put(String.valueOf(ii), origBonus);
			bonusMap.put("count", new Integer(ii+1));
		} else {
			Integer integer = (Integer)bonusMap.get("modify");
			String[] id;
			
			Map was = (Map)bonusMap.get(String.valueOf(integer.intValue()));
			
			id = (String[])was.get("id");
			
			if (id!=null)
				origBonus.put("id", id);
			bonusMap.put(String.valueOf(integer.intValue()), origBonus);
			bonusMap.remove("modify");
		}
		
	}
	
	public static void deleteCombiFromMap(Map combiMap, String row, Logger logger) {
		combiMap.remove(row);
		int h = Integer.parseInt(row);
		Integer integer = (Integer)combiMap.get("count");
		int ii = integer.intValue();
		
		for (int i=h+1; i<ii; i++) {
			Object o = combiMap.remove(String.valueOf(i));
			combiMap.put(String.valueOf(i-1), o);
		}
		combiMap.put("count", new Integer(ii-1));
	}

	public static void modifyCombiFromMap(Map combiMap, Map jsp, String row, Logger logger) {
		Map combi = (Map)combiMap.get(row);
		
		jsp.put("art_id", new String[] {(String)combi.get("art_id")});
		jsp.put("quantity", new String[] {(String)combi.get("quantity")});
		
		combiMap.put("modify", new Integer(row));
	}	
	
	public static void addCombiToMap(Map combiMap, String id, String q, Logger log) {
		
		boolean modify = false;
		
		if (combiMap.get("modify")!=null) modify = true;
		
		try {
			int hh= Integer.parseInt(q);
		} catch(Exception ignored) {
			q = "1";
		}
		
		if (q.trim().equals("")) q = "1";
		
		Map ret = new HashMap();
		ret.put("art_id", id);
		ret.put("quantity", q);
		
		//if (b.booleanValue()) {
		if (!modify) {
			Integer integer = (Integer)combiMap.get("count");
			int ii = integer.intValue();
			combiMap.put(String.valueOf(ii), ret);
			combiMap.put("count", new Integer(ii+1));
		} else {
			Integer integer = (Integer)combiMap.get("modify");
			combiMap.put(String.valueOf(integer.intValue()), ret);
			combiMap.remove("modify");
		}

	}
	
	public static void addUserDetailAddressToMap(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 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();
			
			boolean hasdd = addressMap.containsKey("default_delivery");
			boolean hasdb = addressMap.containsKey("default_bill");
		
			
			if (!hasdd)
				addressMap.put("default_delivery", new Integer(ii));
			if (!hasdb)
				addressMap.put("default_bill", new Integer(ii));
			
			addressMap.put(String.valueOf(ii), ret);
			addressMap.put("count", new Integer(ii+1));
		} else {
			Integer test = (Integer)addressMap.get("count");
			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 newLanguage(String descr) throws Exception {
		List l = new ArrayList();
		l.add("id");
		Map m = new HashMap();
		m.put("descr", descr);
		PersistableObject po = new PersistableObject("language", l, m);
		
		po.insert();
	}

	public static void newLevelAddress(String descr) throws Exception {
		List l = new ArrayList();
		l.add("id");
		Map m = new HashMap();
		m.put("descr", descr);
		PersistableObject po = new PersistableObject("level_address", 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 void modifyLanguage(String id, String descr) throws Exception {
		int i;
		
		try {
			i = Integer.parseInt(id);
		} catch (Exception e) {
			return;
		}
		ObjectSearch os = new ObjectSearch("language", "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 void modifyLevelAddress(String id, String descr) throws Exception {
		int i;
		
		try {
			i = Integer.parseInt(id);
		} catch (Exception e) {
			return;
		}
		ObjectSearch os = new ObjectSearch("level_address", "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 void newCountry(HttpServletRequest req, Logger logger) throws Exception {
		PersistableObject po = new PersistableObject("country", new String[] {"country_code"});
		String[] weNeed = new String[] {"country_code", "country_post_code","name","tel_code","freight_art_id","vat1","vat2",
				"vat3","vat4","vat5","vatbonus","tax_id","comment","default_store_id"};
		
		for (int i = 0; i<weNeed.length; i++) {
			String value = req.getParameter(weNeed[i]);
			
			if (weNeed[i].equals("tel_code") || weNeed[i].equals("default_store_id")) {
				Integer iVal = null;
				try {
					
					int t = Integer.parseInt(value);
					iVal = new Integer(t);
				} catch (Exception e) {
				}
				if (iVal!=null) {
					po.set(weNeed[i], iVal);
				}
			} else if (weNeed[i].startsWith("vat")) {
				BigDecimal bd = null;
				try {	
					bd = new BigDecimal(value);
				} catch (Exception ignored) {
					}
				
				if (bd != null) {
					po.set(weNeed[i], bd);
				}
			} else {
				po.set(weNeed[i], value);
			}
		}
		
		
		po.insert();
	
	}
	
	public static void modifyCountry(String id, HttpServletRequest req, Logger logger) throws Exception {
		
		
		ObjectSearch os = new ObjectSearch("country", "country_code");
		os.setCondition("country_code = ?");
		
		List l = os.search(new Object[] {id});
		 
		if (l.size()!=1) return;
		
		PersistableObject po = (PersistableObject)l.get(0);
		
		String[] weNeed = new String[] {"country_post_code","name","tel_code","freight_art_id","vat1","vat2",
				"vat3","vat4","vat5","vatbonus","tax_id","comment","default_store_id"};
		
		for (int i = 0; i<weNeed.length; i++) {
			
			String value = req.getParameter(id+weNeed[i]);
			if (weNeed[i].equals("tel_code") || weNeed[i].equals("default_store_id")) {
				Integer iVal = null;
				try {
					
					int t = Integer.parseInt(value);
					iVal = new Integer(t);
					
				} catch (Exception e) {
				}
				if (iVal!=null)
					po.set(weNeed[i], iVal);
			} else if (weNeed[i].startsWith("vat")) {
				BigDecimal bd = null;
				try {	
					bd = new BigDecimal(value);
				} catch (Exception ignored) {
					}
				
				if (bd != null)
				po.set(weNeed[i], bd);
			} else {
				po.set(weNeed[i], value);
			}
		}
		

		po.update();
		
	}	
	
	public static String generateLevelAddressRows(PageContext pc) throws Exception {
		
		LevelAddress[] titles = getLevelAddresses();
		
		StringBuffer sb = new StringBuffer();
		
		for (int i=0; i<titles.length; i++) {
			LevelAddress title = titles[i];	
			sb.append("<tr>"+
					"<td id=\"accountTableDataContent\"><input type=text name="+ title.id + " value=\""+ title.value+ "\"></td>"+
					"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='modify_level_address';top.mainFrame.document.forms[0].whichModify.value='"+ title.id+"';link('process/options_level_address.jsp');\">"+ LocaleSupport.getLocalizedMessage(pc, "MODIFY")+"</a></td>"+
					"</tr>");
		}
		sb.append("<tr>"+
		"<td id=\"accountTableDataContent\"><input type=\"text\" name=\"new\"/></td>"+
		"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='new_level_address';link('process/options_level_address.jsp');\">"+ LocaleSupport.getLocalizedMessage(pc, "ADD")+"</a></td>" +
		"</tr>");
		
		return sb.toString();
		
	}

	public static String getBrutto(String netto, String vat_perc) {
		
		BigDecimal nettoBd = new BigDecimal(netto);
		BigDecimal vatBd = new BigDecimal(vat_perc);
		
		double n = nettoBd.doubleValue();
		
		double p = vatBd.doubleValue();
		
		double brutto = n + p*n*.01;
		
		NumberFormat nf = NumberFormat.getInstance(Locale.ENGLISH);
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		nf.setGroupingUsed(false);
		return nf.format(brutto);
	}
	
	
	public static String getCountryCode(HttpSession session) throws Exception {
		PersistableObject po = new PersistableObject("distributor", "id");
		po.set("id", session.getAttribute("USER_LOGGED_ID"));
		po.load();
		return po.getString("country_code", "");
	}
	
	public static String generateArticleSearchRows(HttpSession session) throws Exception {		
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		else if	(session.getAttribute("customer")!=null) customer = true;
		else if	(session.getAttribute("distributor")!=null) distributor = true;
		
		if (session.getAttribute("for_id")==null && session.getAttribute("for_name")==null) return "";
		
		boolean for_id = true;
		String forWhat = (String)session.getAttribute("for_id");
		
		if (forWhat == null) for_id = false;

		List results = null;
		
		if (for_id) {		
			String from_id = (String)session.getAttribute("aid_from");
			if (from_id == null) from_id = "";
			
			String from_to = (String)session.getAttribute("aid_to");
		
			if (from_to == null || "".equals(from_to)) from_to = "ZZZZZZZZZZZZZZ";
			
			ObjectSearch os = new ObjectSearch("article", new String[] {"id"});
			os.setCondition("lower(id)>=? AND lower(id)<=?");
			
			os.setOrderBy(new String[] {"id"});
			
			try {
				results = os.search(new Object[] {from_id.toLowerCase(), from_to.toLowerCase()});
			} catch (Exception e) {
				return e.getMessage();
			}
		} else {
			String from_name = (String)session.getAttribute("descr");
			ObjectSearch os = new ObjectSearch("article", new String[] {"id"});
			
			os.setCondition("lower(descr) like ?");
			os.setOrderBy(new String[] {"descr"});
			try {
				results = os.search(new Object[] {"%"+from_name.toLowerCase()+"%"});
			} catch (Exception e) {
				return e.getMessage();
			}
		}
		StringBuffer sb = new StringBuffer();
		String country_code = "";
		
		if (distributor || customer) country_code = getCountryCode(session);
		
		
		for (int i = 0; i<results.size(); i++) {
		    PersistableObject po = (PersistableObject)results.get(i);
		    String id = po.getString("id", "");
		    String descr = po.getString("descr", "");
		    String combi = po.getString("combi", "");
		    if (combi.equals("true")) combi = "ja"; else combi = "nein";
		    Map values = getArticle(id, MainControl.logger);
		    
		    String linkTo = "<a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = 'load_article'; javascript:top.mainFrame.document.forms[0].artId.value = '" + id + "'; link('process/article_detail.jsp');\">"+ id +"</a>";
		    
		    if (admin) {
		    	if (values.get("netto")==null) continue;
		    	String netto = ((String[])values.get("netto"))[0];
		    	String netto_c = ((String[])values.get("netto_customer"))[0];
		    	String netto_s_c = ((String[])values.get("netto_silver_customer"))[0];
		    	String netto_g_c = ((String[])values.get("netto_gold_customer"))[0];
		    	String netto_v_c = ((String[])values.get("netto_vip_customer"))[0];
		    	String bonus = ((String[])values.get("bonus"))[0];
		    	
		    	
				java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
				nf.setMinimumFractionDigits(2);
				nf.setMaximumFractionDigits(2);
				nf.setGroupingUsed(false);
		    	
				Logger logger = MainControl.logger;
				
				
				
		    	String vat_class = ((String[])values.get("vat_id"))[0];
		    	
			    sb.append("<tr>"+
				          "<td id=\"accountTableDataContent\">"+ linkTo +"</td>"+
				          "<td id=\"accountTableDataContent\">"+ descr + "</td>"+
				          "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!netto.equals("")?nf.format(nf.parse(netto)):"")+"</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!netto_c.equals("")?nf.format(nf.parse(netto_c)):"")+"</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!netto_s_c.equals("")?nf.format(nf.parse(netto_s_c)):"")+"</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!netto_g_c.equals("")?nf.format(nf.parse(netto_g_c)):"")+"</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!netto_v_c.equals("")?nf.format(nf.parse(netto_v_c)):"")+"</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ vat_class+"</td>"+						 
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!bonus.equals("")?nf.format(nf.parse(bonus)):"")+"</td>"+
						  "<td id=\"accountTableDataContent\">"+combi  +"</td>"+
				        "</tr>");
		    } else if (distributor) {
		    	String netto = ((String[])values.get("netto"))[0];
		    	String bonus = ((String[])values.get("bonus"))[0];

		    	
		    	String vat_class = ((String[])values.get("vat_id"))[0];
		    	
		    	String vat_perc;

				java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
				nf.setMinimumFractionDigits(2);
				nf.setMaximumFractionDigits(2);
				nf.setGroupingUsed(false);
		    	
		    	
		    	PersistableObject p = new PersistableObject("country", "country_code");
		    	p.set("country_code", country_code);
		    	p.load();
		    	vat_perc = p.getString("vat"+String.valueOf(vat_class), "");
		    	
		    	String brutto = getBrutto(netto, vat_perc);
		    	
			    sb.append("<tr>"+
				          "<td id=\"accountTableDataContent\">"+ linkTo +"</td>"+
				          "<td id=\"accountTableDataContent\">"+ descr + "</td>"+
				          "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!netto.equals("")?nf.format(nf.parse(netto)):"")+"</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ vat_perc +" %</td>"+
						  "<tdstyle=\"text-align: right;\"  id=\"accountTableDataContent\">"+ (!brutto.equals("")?nf.format(nf.parse(brutto)):"") +"</td>"+
						 
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!bonus.equals("")?nf.format(nf.parse(bonus)):"")+"</td>"+
						  "<td id=\"accountTableDataContent\">"+combi  +"</td>"+
				        "</tr>");    	
		    } else if (customer) {
		    	String netto = "";
		    	if (session.getAttribute("vip_customer")!=null)
		    		netto = ((String[])values.get("netto_vip_customer"))[0];
		    	else netto = ((String[])values.get("netto_customer"))[0];		    	
		    	String vat_class = ((String[])values.get("vat_id"))[0];
		    	
		    	String vat_perc;
		    	
				java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
				nf.setMinimumFractionDigits(2);
				nf.setMaximumFractionDigits(2);
				nf.setGroupingUsed(false);
		    	
		    	PersistableObject p = new PersistableObject("country", "country_code");
		    	p.set("country_code", country_code);
		    	p.load();
		    	vat_perc = p.getString("vat"+String.valueOf(vat_class), "");
		    	
		    	String brutto = getBrutto(netto, vat_perc);
		    	
			    sb.append("<tr>"+
				          "<td id=\"accountTableDataContent\">"+ linkTo +"</td>"+
				          "<td id=\"accountTableDataContent\">"+ descr + "</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ vat_perc +" %</td>"+
						  "<td style=\"text-align: right;\" id=\"accountTableDataContent\">"+ (!brutto.equals("")?nf.format(nf.parse(brutto)):"") +"</td>"+
						  "<td id=\"accountTableDataContent\">"+combi  +"</td>"+
				        "</tr>"); 		    
		    }
		}
		return sb.toString();
	}
	
	public static String[] generateArticleSupplierListRows(HttpSession session) throws Exception {		
		List results = null;
		ObjectSearch os = new ObjectSearch("article", new String[] {"id"});
			
		try {
			results = os.search("select id, descr, inventory, ordered from article order by id");
		} catch (Exception e) {
			return new String[] {e.getMessage(), "0"};
		}
			
		StringBuffer sb = new StringBuffer();
		
		ArrayList artid = null;
		artid = new ArrayList();
		
		ArrayList ord = new ArrayList();
		
		int size = results.size();
		
		for (int i = 0; i<size; i++) {
		    PersistableObject po = (PersistableObject)results.get(i);
		    String id = po.getString("id", "n/a");
		    String descr = po.getString("descr", "n/a");

		    String inventory = po.getString("inventory", "n/a");
		    String ordered = po.getString("ordered", "n/a");
		    
		    ord.add(ordered);
		    
		    artid.add(id);
	    	
			Logger logger = MainControl.logger;
	    	
		    sb.append("<tr>"+
			          //"<td id=\"accountTableDataContent\">"+ "<input type=\"checkbox\" name=\"selected\" value=\""+i+"\" >" +"</td>"+
			          "<td id=\"accountTableDataContent\">"+ id + "</td>"+
			          "<td id=\"accountTableDataContent\">"+ descr+"</td>"+
					  "<td id=\"accountTableDataContent\">"+ inventory+"</td>"+
					  "<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" MAXLENGTH=\"7\" name=\""+ i +"quantity\" value=\""+ ""+"\"/></td>"+
					  "<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" onBlur=\"return val(this, '"+ordered+"')\" MAXLENGTH=\"7\" name=\""+ i +"ordered\" value=\""+ordered+ "\"/></td>"+
					  "<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" MAXLENGTH=\"50\" name=\""+ i +"supplier_name\" value=\""+ ""+"\"/></td>"+
					  "<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" MAXLENGTH=\"50\" name=\""+ i +"supplier_order_id\" value=\""+ ""+"\"/></td>"+
			        "</tr>");
	
		}
		session.setAttribute("art_id_list", artid);
		session.setAttribute("ordered_list", ord);
		return new String[] {sb.toString(), ""+size};
	}
	
	
	public static String generateArticleSupplierListHeader(PageContext pc) {
		StringBuffer sb = new StringBuffer();

        sb.append("<col width=\"85\"><col width=\"185\"><col width=\"70\"><col width=\"70\"><col width=\"80\">"+
                "<col width=\"155\"><col width=\"155\"><tr>"+
                	//"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "SELECT") + "</td>"+
                	"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ARTICLE_ID") + "</td>"+
    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "INVENTORY")+"</td>"+
    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "QUANTITY2")+"</td>"+
    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ORDERED")+"</td>"+
    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "SUPPLIER_NAME")+"</td>"+
    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "SUPPLIER_ORDER_ID")+"</td>"+
    	   		"</tr>");
		
		
		return sb.toString();
	}
	
	public static String generateArticleListHeader(PageContext pc) {
		HttpSession session = pc.getSession();
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		else if	(session.getAttribute("customer")!=null) customer = true;
		else if	(session.getAttribute("distributor")!=null) distributor = true;
		
		StringBuffer sb = new StringBuffer();
		
		if (admin) {
	        sb.append("<col width=\"70\"><col width=\"240\"><col width=\"70\"><col width=\"70\"><col width=\"70\">"+
            "<col width=\"70\"><col width=\"70\"><col width=\"40\"><col width=\"80\"><col width=\"50\"><tr>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ID") + "</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NETTO_CUSTOMER")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NETTO_SILVER_CUSTOMER")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NETTO_GOLD_CUSTOMER")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NETTO_VIP_CUSTOMER")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "BONUS_VALUE")+"</td>"+
				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "COMBI")+"</td>"+
	   		"</tr>");
		}
		else if (customer) {
	        sb.append("<col width=\"110\"><col width=\"500\"><col width=\"70\"><col width=\"70\"><col width=\"70\">"+
	                "<tr>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ID")+"</td>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT")+"</td>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
						"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "COMBI")+"</td>"+
	    	   		"</tr>");
		} else if (distributor) {
	        sb.append("<col width=\"100\"><col width=\"370\"><col width=\"70\"><col width=\"70\"><col width=\"70\">"+
	                "<col width=\"70\"><col width=\"70\"><tr>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ID")+"</td>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td>"+
	    				"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT")+"</td>"+
						"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
						"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "BONUS_VALUE")+"</td>"+
						"<td id=\"accountTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "COMBI")+"</td>"+
	    	   		"</tr>");			
		}
		return sb.toString();
	}
	
	
	public static String  generateDistributorSearchRows(HttpSession session) throws Exception{
		//if (session.getAttribute("DIST_LISTED")==null) return "";
		boolean for_id = true;
		boolean for_email = false;
		boolean for_company = false;
		String forWhat = (String)session.getAttribute("for_id");
		String forEmail = (String)session.getAttribute("for_email");
		String forCompany = (String)session.getAttribute("for_company");
		
		if (forWhat == null) for_id = false;
		if (forEmail != null) for_email = true;
		if (forCompany != null) for_company = true;
		
		List results = new ArrayList();
		
		String orderBy = (String)session.getAttribute("sorted_by");
		
		if (orderBy==null) return "<tr></tr>";
		
		if (for_email) {
			String email = (String)session.getAttribute("email");
			String condition = "lower(email) like(?) AND deleted = false";
			if (email==null || "".equals(email)) return "";
		
			ObjectSearch os = new ObjectSearch("distributor", new String[] {"id"});
			os.setOrderBy(new String[] {orderBy});
			os.setCondition(condition);
		
			os.setOrderBy(new String[] {orderBy});
			
			try {
				results = os.search(new Object[] {"%"+email.toLowerCase()+"%"});
			} catch (Exception e) {
				return e.getMessage();
			}
			
			ObjectSearch os2 = new ObjectSearch("interessent", new String[] {"id"});
			os2.setOrderBy(new String[] {orderBy});
			os2.setCondition(condition);
		
			os2.setOrderBy(new String[] {orderBy});
			
			try {
				results.addAll(os2.search(new Object[] {"%"+email.toLowerCase()+"%"}));
			} catch (Exception e) {
				return e.getMessage();
			}
						
		} else if (for_company) {
			String company = (String)session.getAttribute("company");
			String condition = "lower(company) like(?) AND deleted = false";
			if (company==null || "".equals(company)) return "";
		
			ObjectSearch os = new ObjectSearch("distributor", new String[] {"id"});
			os.setOrderBy(new String[] {orderBy});
			os.setCondition(condition);
		
			os.setOrderBy(new String[] {orderBy});
			
			try {
				results = os.search(new Object[] {"%"+company.toLowerCase()+"%"});
			} catch (Exception e) {
				return e.getMessage();
			}
			
			ObjectSearch os2 = new ObjectSearch("interessent", new String[] {"id"});
			os2.setOrderBy(new String[] {orderBy});
			os2.setCondition(condition);
		
			os2.setOrderBy(new String[] {orderBy});
			
			try {
				results.addAll(os2.search(new Object[] {"%"+company.toLowerCase()+"%"}));
			} catch (Exception e) {
				return e.getMessage();
			}				

		}
		else if (for_id) {		
			String from_id = (String)session.getAttribute("id_from");
			String from_to = (String)session.getAttribute("id_to");
			String condition = "id>?-1 AND id<?+1 AND id>1000000 AND deleted = false";
			if (from_id==null || from_to==null) return "";
		
			if (from_to.equals("")) from_to = "999999999";
		
			Integer iFrom;
			Integer iTo;
		
			try {
				iFrom = new Integer(Integer.parseInt(from_id));
				iTo = new Integer(Integer.parseInt(from_to));
			} catch (Exception e) {return "integernull";}
			ObjectSearch os = new ObjectSearch("distributor", new String[] {"id"});
			os.setOrderBy(new String[] {orderBy});
			os.setCondition(condition);
		
			os.setOrderBy(new String[] {orderBy});
			
			try {
				results = os.search(new Object[] {iFrom, iTo});
			} catch (Exception e) {
				return e.getMessage();
			}
			
			ObjectSearch os2 = new ObjectSearch("interessent", new String[] {"id"});
			os2.setOrderBy(new String[] {orderBy});
			os2.setCondition(condition);
		
			os2.setOrderBy(new String[] {orderBy});
			
			try {
				results.addAll(os2.search(new Object[] {iFrom, iTo}));
			} catch (Exception e) {
				return e.getMessage();
			}

		} else {
			String from_name = (String)session.getAttribute("name_from");
			String to_name = (String)session.getAttribute("name_to");
			
			if (from_name==null || to_name==null) return "";
			
			String condition = "lastname>=? AND lastname<=?";
			
			boolean short_ = false;
			
			if (to_name.equals("")) {
				condition = "lastname>=?";
				short_ = true;
			}
			
			ObjectSearch os = new ObjectSearch("distributor", new String[] {"id"});
			os.setOrderBy(new String[] {orderBy});
			
			os.setCondition(condition + " AND deleted = false");
			try {
				if (!short_)
					results = os.search(new Object[] {from_name, to_name});
				else
					results = os.search(new Object[] {from_name});
			} catch (Exception e) {
				return e.getMessage();
			}
			
			ObjectSearch os2 = new ObjectSearch("interessent", new String[] {"id"});
			os2.setOrderBy(new String[] {orderBy});
			
			os2.setCondition(condition + " AND deleted = false");
			try {
				if (!short_)
					results.addAll(os2.search(new Object[] {from_name, to_name}));
				else
					results.addAll(os2.search(new Object[] {from_name}));
			} catch (Exception e) {
				return e.getMessage();
			}

		}
		
		StringBuffer sb = new StringBuffer();
		
		Level[] levels = getLevels();
		
		Level[] levelsInt = FormHelperC.getInteressentLevels();
		
		Map levelMap = new HashMap();
		
		for (int g = 0; g<levels.length; g++)
			levelMap.put(levels[g].id + ":" + levels[g].subtype_id, levels[g].value);
		
		for (int g = 0; g<levelsInt.length; g++)
			levelMap.put(levelsInt[g].id + ":" + levelsInt[g].subtype_id , levelsInt[g].value);
		
		
		SortingMap sortedMap = new SortingMap();
		
		if (orderBy == null) orderBy = "id";
		
		for (int j = 0; j<results.size(); j++) {
			PersistableObject po = (PersistableObject)results.get(j);
			Object key = (orderBy.equals("id")) ? po.get("id") : po.getString(orderBy, "");
			sortedMap.put(key, po);
		}
		
		
		for (Iterator it = sortedMap.getSortedValues().iterator(); it.hasNext();) {
			PersistableObject po = (PersistableObject)it.next();
		    String id = po.getString("id", "");
		    boolean interessent = false;
		    if (id.length() > 3) {
		    	interessent = id.charAt(2) == '9';
		    }
		    String lastname = po.getString("lastname", "");
		    String firstname = po.getString("firstname", "");
		    String email = po.getString("email", "n/a");
		    String company = po.getString("company", "n/a");
		    
		    if (email.length()>23) {
		    	email = email.substring(0,20) + "...";
		    }
		    if (company.length()>23) {
		    	company = company.substring(0,20) + "...";
		    }
		    boolean active = true;
		    
		    Boolean bactive = (Boolean)po.get("active");
		    if (bactive!=null)
		    	active = bactive.booleanValue();
		    
		    
		    String country_code = po.getString("country_code", "");
			
		    String level = "";
		    
		    String level_id = po.getString("level_id", "");
		    
		    String level_id_key = po.getString("level_id", "") + ":" + po.getString("level_subtype_id", "0");
		    
		    if (levelMap.get(level_id_key)!=null) level = (String)levelMap.get(level_id_key); 
		    
		    String linkTo = "user_detail_personal.jsp";
		    
		    if (level_id.equals("100") || level_id.equals("130") ||
		    		level_id.equals("160") || level_id.equals("200")) linkTo = "customer_detail_personal.jsp"; 
		    
		    if (level_id.startsWith("50") && level_id.length() == 4)
		    	interessent = true;
		    
		    if (interessent)
		    	linkTo = "interessent_detail_personal.jsp";

		    String link = "<a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='distributor_data';top.mainFrame.document.forms[0].distID.value='"+id+"';top.mainFrame.document.forms[0].levelID.value='"+level_id+"';link('process/"+linkTo+"');\">"+id+"</a>";
		    
		    String link2 = interessent? "":"<a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='start_new_order';top.mainFrame.document.forms[0].cnr.value='"+id+"';link('process/new_order.jsp');\">Bestellen</a>";
		    
		    String s1 = "";
			String s2 = "";
			
			if (!active) {
				s1 = "<span class=\"deactivated\">";
				s2 = "</span>";
			}
		    
		    sb.append("<tr>"+
		          "<td id=\"accountTableDataContent\">"+ link +"</td>"+
		          "<td id=\"accountTableDataContent\">"+ s1 + lastname + s2 + "</td>"+
		          "<td id=\"accountTableDataContent\">"+ s1 + firstname + s2 + "</td>"+
		          "<td id=\"accountTableDataContent\">"+ s1 + email + s2 + "</td>"+
		          "<td id=\"accountTableDataContent\">"+ s1 + company + s2 + "</td>"+
		          "<td id=\"accountTableDataContent\">"+ s1 + country_code + s2 + "</td>"+
				  "<td id=\"accountTableDataContent\">"+ s1 + level + s2 + "</td>"+
				  "<td id=\"accountTableDataContent\">"+ link2+"</td>"+
		          "</tr>");
		
		}
		
		return sb.toString();
		
	}
	
	
	public static String generateCountryRows(PageContext pc) throws Exception {
		
		ObjectSearch os = new ObjectSearch("country", new String[] {"country_code"});
		
		List l = os.search();
		
		StringBuffer sb = new StringBuffer();
		
		LagerMin[] lm = getLagerMins();
		
		
		for (int i=0; i<l.size(); i++) {
			PersistableObject po = (PersistableObject)l.get(i);
			String cc = po.getString("country_code", "");
			String cpc = po.getString("country_post_code", "");
			String name = po.getString("name", "");
			String tc = po.getString("tel_code", "");
			String faid = po.getString("freight_art_id", "");
			String vat1 = po.getString("vat1", "");
			String vat2 = po.getString("vat2", "");
			String vat3 = po.getString("vat3", "");
			String vat4 = po.getString("vat4", "");
			String vat5 = po.getString("vat5", "");
			String vatb = po.getString("vatbonus", "");
			String tax_id = po.getString("tax_id", "");
			String comment = po.getString("comment", "");
			String def_store_id = po.getString("default_store_id", "");
			
			String link;
			
			link = "<a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='modify_country';top.mainFrame.document.forms[0].whichModify.value='"+ cc+"';link('process/options_country.jsp');\">Mod.</a>";
			
			StringBuffer lagerSelection = new StringBuffer(); 
			lagerSelection.append("<select name=\""+cc+"default_store_id\">");
			for (int z=0;z<lm.length;z++) {
				String selected = "";
				if (def_store_id.equals(lm[z].id)) selected = " selected";
				lagerSelection.append("<option"+ selected +" value=\""+ lm[z].id+"\">"+lm[z].descr+"</option>");
			}
			lagerSelection.append("</select>");	
			
			
			
			sb.append("<table width=\"800\" border=\"1\" id=\"mainTable\">"+
					"<col width=\"60\"><col width=\"60\"><col width=\"140\"><col width=\"60\"><col width=\"140\"><col width=\"160\">"+
					"<tr>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "LAND_KZ")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "POST_KZ")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NAME")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "TELCODE")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "FREIGHT_ARTICLE")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td><tr>");			
			sb.append("<tr>"+
					"<td id=\"accountTableDataContent\">"+  cc +"</td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"country_post_code\" value=\""+ cpc+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" name=\""+ cc +"name\" value=\""+ name+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"tel_code\" value=\""+ tc+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" name=\""+ cc +"freight_art_id\" value=\""+ faid+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" name=\""+ cc +"comment\" value=\""+ comment+"\"></td>"+
					"</tr>");
			sb.append("<table width=\"800\" border=\"1\" id=\"mainTable\">"+
					"<col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"120\"><col width=\"120\"><col width=\"60\">"+
					"<tr>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT1")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT2")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT3")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT4")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT5")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "BONUS")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "TAX_ID")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "STORE")+"</td>"+
					"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "OPT")+"</td>");
			
			sb.append("<tr>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"vat1\" value=\""+ vat1+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"vat2\" value=\""+ vat2+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"vat3\" value=\""+ vat3+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"vat4\" value=\""+ vat4+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"vat5\" value=\""+ vat5+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\""+ cc +"vatbonus\" value=\""+ vatb+"\"></td>"+
					"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle2\" name=\""+ cc +"tax_id\" value=\""+ tax_id+"\"></td>"+
					"<td id=\"accountTableDataContent\">"+  lagerSelection.toString() +"</td>"+
					"<td id=\"accountTableDataContent\">"+ link +"</td>"+
					"</tr></table><br>");
			}
		StringBuffer lagerSelection0 = new StringBuffer(); 
		lagerSelection0.append("<select name=\"default_store_id\">");
		for (int z=0;z<lm.length;z++) {
			lagerSelection0.append("<option value=\""+ lm[z].id+"\">"+lm[z].descr+"</option>");
		}
		lagerSelection0.append("</select>");	

		String linknew;
		
		linknew = "<a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='new_country';link('process/options_country.jsp');\">Hinz.</a>";

		sb.append("<br>");
		
		sb.append("<table width=\"800\" border=\"1\" id=\"mainTable\">"+
				"<col width=\"60\"><col width=\"60\"><col width=\"140\"><col width=\"60\"><col width=\"140\"><col width=\"160\">"+
				"<tr>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "LAND_KZ")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "POST_KZ")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "NAME")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "TELCODE")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "FREIGHT_ARTICLE")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td><tr>");			
		sb.append("<tr>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"country_code\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"country_post_code\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" name=\"name\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"tel_code\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" name=\"freight_art_id\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"middle\" name=\"comment\"></td>"+
				"</tr>");
		sb.append("<table width=\"800\" border=\"1\" id=\"mainTable\">"+
				"<col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"50\"><col width=\"120\"><col width=\"120\"><col width=\"60\">"+
				"<tr>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT1")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT2")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT3")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT4")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "VAT5")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "BONUS")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "TAX_ID")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "STORE")+"</td>"+
				"<td id=\"mainTableHeaderContent\">"+ LocaleSupport.getLocalizedMessage(pc, "OPT")+"</td>");
		
		sb.append("<tr>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"vat1\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"vat2\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"vat3\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"vat4\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"vat5\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\" id=\"little\" name=\"vatbonus\"></td>"+
				"<td id=\"accountTableDataContent\"><input type=\"text\"  id=\"middle2\" name=\"tax_id\"></td>"+
				"<td id=\"accountTableDataContent\">"+  lagerSelection0.toString() +"</td>"+
				"<td id=\"accountTableDataContent\">"+ linknew + "</td>"+
				"</tr></table><br>");
		return sb.toString();
		
	}	
	
	public static String generateTitleRows(PageContext pc) throws Exception {
		
		Title[] titles = getTitles();
		
		StringBuffer sb = new StringBuffer();
		
		for (int i=0; i<titles.length; i++) {
			Title title = titles[i];
			
			sb.append("<tr>"+
					"<td id=\"accountTableDataContent\"><input type=text name="+ title.id + " value=\""+ title.value+ "\"></td>"+
					"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='modify_title';top.mainFrame.document.forms[0].whichModify.value='"+ title.id+"';link('process/options_title.jsp');\">"+ LocaleSupport.getLocalizedMessage(pc, "MODIFY")+"</a></td>"+
					"</tr>");
		}
		sb.append("<tr>"+
		"<td id=\"accountTableDataContent\"><input type=\"text\" name=\"new\"/></td>"+
		"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='new_title';link('process/options_title.jsp');\">"+ LocaleSupport.getLocalizedMessage(pc, "ADD")+"</a></td>" +
		"</tr>");
		
		return sb.toString();
		
	}
	
	public static String generateLanguageRows(PageContext pc) throws Exception {
		
		Language[] languages = getLanguages();
		
		StringBuffer sb = new StringBuffer();
		
		for (int i=0; i<languages.length; i++) {
			Language language = languages[i];
			
			sb.append("<tr>"+
					"<td id=\"accountTableDataContent\"><input type=text name="+ language.id + " value=\""+ language.value+ "\"></td>"+
					"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='modify_language';top.mainFrame.document.forms[0].whichModify.value='"+ language.id+"';link('process/options_language.jsp');\">Modifizieren</a></td>"+
					"</tr>");
		}
		sb.append("<tr>"+
		"<td id=\"accountTableDataContent\"><input type=\"text\" name=\"new\"/></td>"+
		"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value='new_language';link('process/options_language.jsp');\">"+ LocaleSupport.getLocalizedMessage(pc, "ADD")+"</a></td>" +
		"</tr>");
		
		return sb.toString();
		
	}	

	public static String generateDownloadRows(PageContext pc) throws Exception{
		ObjectSearch os = new ObjectSearch("financial", new String[] {"id"});
		os.setOrderBy(new String[] {"download_time"});
		
		Integer from;
		
		try {
			from = new Integer((String)pc.getSession().getAttribute("dfs_dateFrom"));
		} catch (Exception ex) {
			from = new Integer(FormHelper.getDefaultDateForDownloadFiles());
		}

		Integer to;

		try {
			to = new Integer((String)pc.getSession().getAttribute("dfs_dateTo"));
		} catch (Exception ex) {
			to = new Integer(FormHelper.getDateFormatForDownloadFiles(FormHelper.formatSQLDate(new java.sql.Date(System.currentTimeMillis()))));
		}


		
		List result = os.search("select id, name, data, pdf, download_time, SUBSTRING(name, '([0-9]{1,8})')::int4 as a from financial where SUBSTRING(name, '([0-9]{1,8})')::int4>=? and SUBSTRING(name, '([0-9]{1,8})')::int4<=? order by a", new Object[] {from, to});
		
		StringBuffer sb = new StringBuffer("");
		
		for (int i=0; i<result.size(); i++) {
			PersistableObject po = (PersistableObject)result.get(i);
			String name = po.getString("name", "n/a");
			Timestamp ts = (Timestamp)po.get("download_time");
			
			String id = po.getString("id", "0");
			
			Map m = new HashMap();
			m.put("id", new Integer(id));
			PersistableObject check = new PersistableObject("financial", new String[] {"id"}, m);
			check.load();
			
			boolean isFirst = true;
			
			if (check.get("data")==null) isFirst = false;
			
			String link1 = "<a href=\"process/download_data?pageAction=download_data&id=" + id + "&saveState=nothing\">"+ LocaleSupport.getLocalizedMessage(pc, "LINK1_DOWNLOAD")+"</a>";

			
			String ac = "download_pdf";
			if (name.startsWith("CC"))
				ac = "download_ccpdf";
			
			String link2 = "<a href=\"process/download_pdf?pageAction="+ac+"&id=" + id + "&saveState=nothing\">"+ LocaleSupport.getLocalizedMessage(pc, "LINK2_DOWNLOAD")+"</a>";
			
			
			sb.append("<tr>");
			sb.append("<td id=\"accountTableDataContent\">"+name+"</td>");
			sb.append("<td id=\"accountTableDataContent\">"+(isFirst?link1:"&nbsp;")+"</td>");
			sb.append("<td id=\"accountTableDataContent\">"+link2+"</td>");
			sb.append("<td id=\"accountTableDataContent\">"+formatSQLTimestamp(ts)+"</td>");
			sb.append("</tr>");
		}
		
		
		return sb.toString();
	}

	public static String[] getArticleIDs() throws Exception {
		ObjectSearch os = new ObjectSearch("article", new String[] {"id"});
		List result = os.search();
		String[] ret = new String[result.size()];
		for (int i = 0; i<ret.length; i++) {
			PersistableObject po = (PersistableObject)result.get(i);
			ret[i] = po.getString("id", "") + ", "+po.getString("descr", "");
		}			
		
		
		return ret;
		
	}
	
	
	public static String generateCombiTableRows(HttpSession session, String where) throws Exception{
		Map combiMap = (Map)session.getAttribute(where);
		
		String deleteLink;
		String deleteLink0;
		
		String modifyLink0;

		if (where.startsWith("new")) {
			deleteLink = "new_article.jsp";
			deleteLink0 = "new_delete_combi";
			modifyLink0 = "new_modify_combi";
		}
		else {
			deleteLink = "article_detail.jsp";
			deleteLink0 = "delete_combi";
			modifyLink0 = "modify_combi";
		}
		int i = ((Integer)combiMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";
		
		StringBuffer sb = new StringBuffer();
		
		for (int j = 0; j<i; j++) {
			Map combi = (Map)combiMap.get(String.valueOf(j));
			
			PersistableObject p = new PersistableObject("article", new String[] {"id"});
			p.set("id", (String)combi.get("art_id"));
			p.load();
			
			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\">"+ combi.get("art_id")+"</td>" +
			"<td id=\"accountTableDataContent\">"+ p.getString("descr", "") +"</td>" +
			"<td id=\"accountTableDataContent\">"+ combi.get("quantity")+"</td>" +
			"</tr>");
		}
		
		return sb.toString();		
		
		
	}
	
	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_user_detail_payment.jsp";
			deleteLink0 = "new_user_delete_bank_row";
			modifyLink0 = "new_user_modify_bank_row";
		}
		else {
			deleteLink = "user_detail_payment.jsp";
			deleteLink0 = "user_delete_bank_row";
			modifyLink0 = "user_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_user_detail_payment.jsp";
			deleteLink0 = "new_user_delete_credit_row";
			modifyLink0 = "new_user_modify_credit_row";
		}
		else {
			deleteLink = "user_detail_payment.jsp";
			deleteLink0 = "user_delete_credit_row";
			modifyLink0 = "user_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 addDistributor(HttpSession session, Logger logger) throws ServletException {
		int newID = -1;
		String password = "";
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute("new_user_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_user_personal_Map"));
			if (session.getAttribute("new_user_int_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_user_int_Map"));
			if (session.getAttribute("new_user_payment_Map")!=null)
			complex.putAll((Map)session.getAttribute("new_user_payment_Map"));
		
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			
			complex.remove("sponsor_name");
			complex.remove("row");
			
			List distDiscLevels = new ArrayList();
			
			Integer level_id_ = (Integer)complex.get("level_id");
			Integer level_subtype_id = (Integer)complex.get("level_subtype_id");
			
			for (int k = 1; k<100; k++) {
				boolean gh = false;
				boolean h = false;
				boolean a = false;
				
				String key = "personal_discount_"+k;
				if (level_id_ !=null && level_id_.intValue() == 350) {
					key = "gh_personal_discount_"+k;
					gh = true;
				}
				else if (level_id_ !=null && level_id_.intValue() == 330) {
					key = "h_personal_discount_"+k;
					h = true;
				} else if (level_id_ !=null && level_id_.intValue() == 370) {
					key = "a_personal_discount_"+k;
					a = true;
				}
					
				if (complex.containsKey(key)) {
					Float perc = (Float)complex.get(key);
					distDiscLevels.add(new DistributorDiscountLevel(new Integer(0), new Integer(k), perc));
					complex.remove(key);
					if (gh) {
						complex.remove("personal_discount_"+k);
						complex.remove("h_personal_discount_"+k);
						complex.remove("a_personal_discount_"+k);
					}
					else if (h) {
						complex.remove("personal_discount_"+k);
						complex.remove("gh_personal_discount_"+k);
						complex.remove("a_personal_discount_"+k);
					}
					else if (a) {
						complex.remove("personal_discount_"+k);
						complex.remove("gh_personal_discount_"+k);
						complex.remove("h_personal_discount_"+k);
					}
					else {
						complex.remove("gh_personal_discount_"+k);
						complex.remove("h_personal_discount_"+k);
						complex.remove("a_personal_discount_"+k);
					}
				}
			}			

			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));
			
			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")));
			
			password = generatePassword();
			
			logger.info("Generated password: ----------------------------------- "+password);
			
			complex.put("password", password);
			
			Distributor d = new Distributor(complex);
		
			newID = d.generateID();
			
			d.insert();

			Integer level_id = (Integer)complex.get("level_id");
			
			if (level_id!=null) 
				if (level_id.intValue() == 80) {
					SuperPO spo2 = new SuperPO("discount_history", logger);

					spo2.setColumn("distr_id", ""+newID);
					Float dr = (Float)complex.get("discount_rate");
					spo2.setPOColumn("discount_rate", dr);
					
					java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis()); 
					spo2.setColumn("begin_time", formatSQLDate(thisDay));
					spo2.setColumn("end_time", "31.12.2100");
					spo2.insert();
				}
			
			if (level_id!=null)
				if (level_id.intValue() == 300 || level_id.intValue() == 350 || level_id == 330 || level_id == 370) {
					DiscountHelper.saveNewLevels(new Integer(newID), distDiscLevels, session);
				} else {
					DiscountHelper.deleteLevels(new Integer(newID), distDiscLevels, session);
				}
			
			if (complex.get("annual_fee")!=null)
				if (((Boolean)complex.get("annual_fee")).booleanValue()==true)
				session.setAttribute("ABO_WARNING", "yes");
			
			
		} catch (Exception e) {
			logger.info(e.getMessage());
			throw new ServletException(e);
		}
		session.setAttribute("LAST_GENERATED_USER_PASSWORD", password);
		return newID;
	}
	
	public static boolean addAddresses(HttpSession session, int dist_id, Logger logger) throws ServletException{
		try {
	
		Map addressMap = (Map)session.getAttribute("new_user_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;
			}
			
			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{
		Map banksMap = (Map)session.getAttribute("new_user_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");
			
			
			
			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 addCredits(HttpSession session, int dist_id, Logger logger) throws ServletException{
		Map creditsMap = (Map)session.getAttribute("new_user_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");			
			
			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 cancelNewOrder(HttpSession session) throws Exception {
		session.setAttribute("new_order.jsp", null);
		
		Map newArticles = new HashMap();
		newArticles.put("count", new Integer(0));
		
		//Map modifiedArticles = new HashMap();
		//modifiedArticles.put("count", new Integer(0));
		
		session.setAttribute("articles_new", newArticles);
		//session.setAttribute("articles_modify", modifiedArticles);
		
	}
	
	
	public static void cancelNewUser(HttpSession session) throws Exception {
		session.setAttribute("new_user_detail_personal.jsp", null);
		session.setAttribute("new_user_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_user_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"});
		
		inte.put("partner_type_id", new String[] {"0"});
		
		inte.put("level_id", new String[] {"300"});
		
		int siz = DiscountHelper.getDefaultLevels(session).size();
		
		if (siz<4) siz = 4;
		
		for (int i = 0; i < siz; i++) {
			inte.put("personal_discount_"+(i+1), new String[] {"0"});
			inte.put("gh_personal_discount_"+(i+1), new String[] {"0"});
			inte.put("h_personal_discount_"+(i+1), new String[] {"0"});
			inte.put("a_personal_discount_"+(i+1), new String[] {"0"});
		}
		
		session.setAttribute("new_user_detail_int.jsp", inte);
		
		session.setAttribute("new_user_personal_Map", null);
		session.setAttribute("new_user_payment_Map", null);
		
		session.setAttribute("new_user_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_user_addresses", addressMap);
		
		//Logger logger = MainControl.logger;
		
		
		
		bankMap.put("count", new Integer("0"));
		bankMap.put("default_bill", new Integer("0"));
		bankMap.put("defaul_bonus", new Integer("0"));
		session.setAttribute("new_user_banks", bankMap);
		
		creditMap.put("count", new Integer("0"));
		session.setAttribute("new_user_credits", creditMap);
		
		session.setAttribute("SIMILAR_DISTRIBUTORS", null);
		
	}
	
	
	
	public static String generateBonusTableRows(HttpSession session, String where) {
		Map bonusMap = (Map)session.getAttribute(where);
		if (bonusMap == null) return "<tr>bonusMap null</tr>";
		String modifyLink0 = "user_detail_bonus.jsp";
		String modifyLink1 = "user_modify_bonus_row";
		int i = ((Integer)bonusMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";

		StringBuffer sb = new StringBuffer("");
		
		for (int j = 0; j<i; j++) {
			Map bonus = (Map)bonusMap.get(String.valueOf(j));

			String q_metric = ((String[])bonus.get("q_metric"))[0];
			String q_type = ((String[])bonus.get("q_type"))[0];
			
			if (q_type.equals("0")) q_type = "Punkte";
			
			String q_value = ((String[])bonus.get("q_value"))[0];
			
			String calc_metric = ((String[])bonus.get("calc_metric"))[0];
			String calc_type = ((String[])bonus.get("calc_type"))[0];
			
			if (calc_type.equals("0")) calc_type = "Bonuswert";
			
			String calc_value = ((String[])bonus.get("calc_value"))[0];
			String calc_value_type = ((String[])bonus.get("calc_value_type"))[0];
			
			if (calc_value_type.equals("0")) calc_value_type = "%"; else calc_value_type="wert";
			
			String q = q_metric + " (" + q_type + ") &ge; " + q_value;
			
			String c = calc_metric + " (" + calc_type + ") : "+calc_value+" ("+calc_value_type+")";
			
			String g_f = ((String[])bonus.get("valid_from"))[0];
			String g_t = ((String[])bonus.get("valid_to"))[0];
			
			String g = g_f + "-"+g_t;
			
			sb.append("<tr>" +
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink1+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ modifyLink0 +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
			"<td id=\"accountTableDataContent\">"+q+"</td>"+
            "<td id=\"accountTableDataContent\">"+ c +"</td>"+
		  	"<td id=\"accountTableDataContent\">"+ g + "</td>"+
	    	"<td id=\"accountTableDataContent\">"+((String[])bonus.get("descr"))[0]+"</td>"+
			"</tr>");
		}
		
		return sb.toString();
		
	}
	
	
	public static String generateBonusTableRows2(HttpSession session, String where) {
		Map bonusMap = (Map)session.getAttribute(where);
		if (bonusMap == null) return "<tr>bonusMap null</tr>";
		String modifyLink0 = "user_detail_bonus.jsp";
		String modifyLink1 = "user_modify_bonus_row";
		int i = ((Integer)bonusMap.get("count")).intValue();
		if (i == 0) return "<tr></tr>";

		StringBuffer sb = new StringBuffer("");
		
		for (int j = 0; j<i; j++) {
			Map bonus = (Map)bonusMap.get(String.valueOf(j));

			String db0 = ((String[])bonus.get("db0"))[0];
			String db1 = ((String[])bonus.get("db1"))[0];
			String db2 = ((String[])bonus.get("db2"))[0];
			String db3 = ((String[])bonus.get("db3"))[0];
			String db4 = ((String[])bonus.get("db4"))[0];
			
			String t1b1 = ((String[])bonus.get("t1b1"))[0];
			String t1b2 = ((String[])bonus.get("t1b2"))[0];
			String t1b3 = ((String[])bonus.get("t1b3"))[0];
			
			String tbq = ((String[])bonus.get("tbq"))[0];

			String t2b1 = ((String[])bonus.get("t2b1"))[0];
			String t2b2 = ((String[])bonus.get("t2b2"))[0];
			String t2b3 = ((String[])bonus.get("t2b3"))[0];

			String t2l1c = ((String[])bonus.get("t2_level1_criteria"))[0];
			
			String t3b1 = ((String[])bonus.get("t3b1"))[0];
			String t3b2 = ((String[])bonus.get("t3b2"))[0];
			String t3b3 = ((String[])bonus.get("t3b3"))[0];

			String t3l1c = ((String[])bonus.get("t3_level1_criteria"))[0];
			String t3l2c = ((String[])bonus.get("t3_level2_criteria"))[0];
			
			
			String g_f = ((String[])bonus.get("valid_from"))[0];
			String g_t = ((String[])bonus.get("valid_to"))[0];
			
			String g = g_f + "-"+g_t;
			
			java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
			nf.setMinimumFractionDigits(2);
			nf.setMaximumFractionDigits(3);
			nf.setGroupingUsed(false);			
			
//			sb.append("<tr>" +
//			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink1+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ modifyLink0 +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
//			"<td id=\"accountTableDataContent\">"+nf.format(db1)+"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(db2) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(db3) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(db4) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t1b1) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t1b2) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t1b3) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t2b1) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t2b2) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t2b3) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t3b1) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t3b2) +"</td>"+
//            "<td id=\"accountTableDataContent\">"+ nf.format(t3b3) +"</td>"+

			sb.append("<tr>" +
			"<td id=\"accountTableDataContent\"><a href=\"javascript:top.mainFrame.document.forms[0].pageAction.value = '"+ modifyLink1+"'; top.mainFrame.document.forms[0].row.value = '" + String.valueOf(j)+  "';link('process/"+ modifyLink0 +"');\"><img border=\"0\" src=\"img/modify.gif\"/></a></td>"+
		  	"<td id=\"accountTableDataContent\" style=\"word-wrap: break-word;\">"+ g + "</td>"+
	    	"<td id=\"accountTableDataContent\">"+((String[])bonus.get("descr"))[0]+"</td>"+			
			"<td id=\"accountTableDataContent\">"+ db0+"</td>"+
			"<td id=\"accountTableDataContent\">"+ db1+"</td>"+
            "<td id=\"accountTableDataContent\">"+ db2 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ db3 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ db4 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ tbq +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t1b1 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t1b2 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t1b3 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t2b1 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t2b2 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t2b3 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t2l1c +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t3b1 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t3b2 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t3b3 +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t3l1c +"</td>"+
            "<td id=\"accountTableDataContent\">"+ t3l2c +"</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_user_detail_address.jsp";
			deleteLink0 = "new_user_delete_address_row";
			modifyLink0 = "new_user_modify_address_row";
		}
		else {
			deleteLink = "user_detail_address.jsp";
			deleteLink0 = "user_delete_address_row";
			modifyLink0 = "user_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';
		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 loadDistributor(HttpSession session, Logger logger) throws Exception {
		
		String dist_id = (String)session.getAttribute("CURRENT_DISTRIBUTOR_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();
		
		List defLevels = DiscountHelper.getDefaultLevels(session);
		
		
		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","level_id", "level_subtype_id", "homepage", "annual_fee", "partner_type_id", "discount_rate", "sconto_days"};


		
		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 distrDiscLevels = DiscountHelper.loadDistributorDiscountLevels(dist_id);
		
		for (int g = 0; g<defLevels.size(); g++) {
			String label = "personal_discount_"+(g+1);
			linternal.add(label);
			all.put(label, new Float(DiscountHelper.isThereDistributorPercentage(new Integer(g+1), distrDiscLevels)));
			
			String label2 = "gh_" + label;
			linternal.add(label2);
			all.put(label2, new Float(DiscountHelper.isThereDistributorPercentage(new Integer(g+1), distrDiscLevels)));
			
			String label3 = "h_" + label;
			linternal.add(label3);
			all.put(label3, new Float(DiscountHelper.isThereDistributorPercentage(new Integer(g+1), distrDiscLevels)));
			
			String label4 = "a_" + label;
			linternal.add(label4);
			all.put(label4, new Float(DiscountHelper.isThereDistributorPercentage(new Integer(g+1), distrDiscLevels)));
			
		}		
		
		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);
				
			}
			
			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)) {
				if (actualName.startsWith("personal_disc") || actualName.startsWith("gh_personal_disc")) {
					jspPut = ""+((Float)actualValue).intValue();
				}

				if (actualName.startsWith("level_id")) {
					jspPut = "" + ((Integer)actualValue) + ":" + all.get("level_subtype_id");
				}

				
				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");
		
		if (internal.containsKey("level_id")) session.setAttribute("original_level_id", ""+internal.get("level_id"));
		
		session.removeAttribute("CURRENT_DISTRIBUTOR_DEACTIVATED");
		
		session.setAttribute("CURRENT_DISTRIBUTOR_NAME", name);
		if (po.get("active")!=null) {
			Boolean bactive = (Boolean)po.get("active");
			boolean active = bactive.booleanValue();
			if (!active) session.setAttribute("CURRENT_DISTRIBUTOR_DEACTIVATED", "yes");
		}

		
		session.setAttribute("user_detail_personal.jsp", jspPersonal);
		session.setAttribute("user_detail_payment.jsp", jspPayment);
		session.setAttribute("user_detail_int.jsp", jspInternal);
		
		session.setAttribute("user_detail_address.jsp", new HashMap());
		session.setAttribute("user_detail_bonus.jsp", new HashMap());
		
		session.setAttribute("user_personal_Map", personal);
		session.setAttribute("user_payment_Map", payment);
		session.setAttribute("user_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("user_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("user_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("user_addresses", userAddressMap);
		
		
		ObjectSearch oss = new ObjectSearch("individual_bonus_2", new String[] {"id"});
		oss.setCondition("distr_id = ?");
		List dd;
		dd = oss.search(new Object[] {new Integer(id)});
		
		
		
		Map bonusMap = (Map)session.getAttribute("user_bonuses");
		
		bonusMap.clear();
		
		bonusMap.put("count", new Integer(0));
		
		if (dd.size()>0) {
			for (int d = 0; d < dd.size(); d++) {
				PersistableObject po20 = (PersistableObject)dd.get(d);
				Integer ID = (Integer)po20.get("id");
				SuperPO spo = new SuperPO("individual_bonus_2", logger);
				spo.setColumn("id", ID.toString());
				Map text = spo.load();
				String[] percentages = new String[] {"db0", "db1", "db2", "db3", "db4", 
						"t1b1", "t1b2", "t1b3",
						"t2b1", "t2b2", "t2b3",
						"t3b1", "t3b2", "t3b3"};
				
				for (int n = 0; n<percentages.length; n++) {
					String[] ac = (String[])text.get(percentages[n]);
					if (ac!=null && ac.length>0) {
						String v = ac[0];
						if ((v!=null) && !"".equals(v)) {
							float fl = new Float(v).floatValue();
							ac[0] = ""+((float)Math.round(new Float(fl * 100).floatValue()*10)) / 10;
						}
							
					}
					
				}
				
				bonusMap.put(String.valueOf(d), text);
			}
			
			bonusMap.put("count", new Integer(dd.size()));
			
		} else {
			session.setAttribute("user_detail_bonus.jsp", null);
		}
		
		
		if (internal.get("level_id")!=null)
			if ("80".equals(""+internal.get("level_id"))) {
				ObjectSearch osHist = new ObjectSearch("discount_history", new String[] {"distr_id", "begin_time"});
				osHist.setCondition("distr_id = ? AND begin_time <= ? and end_time >= ?");
				java.sql.Date date = new java.sql.Date(System.currentTimeMillis());
				List result = osHist.search(new Object[] {new Integer(id), date, date});
				
				java.sql.Date valid_from = null;
				
				if (result.size()>0) {
					PersistableObject po2 = (PersistableObject)result.get(0);
					
					valid_from = (java.sql.Date)po2.get("begin_time");
					session.setAttribute("CURRENT_DISCOUNT_RATE_VALID_FROM", valid_from);
				}
			}
	}
	
	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 String getDefaultDateForDownloadFiles2() {
	long i = System.currentTimeMillis();
	java.sql.Date now = new java.sql.Date(i);
	int year = now.getYear();
	int month = now.getMonth();
	if (month == 0) {
		year--;
		month = 12;
	} else {
		month--;
	}
	year+=1900;	
		
	String syear = String.valueOf(year);
	String needZero = (month<10)?"0":"";
	String smonth = needZero+String.valueOf(month);
		
	return "01."+month+"."+year;
}

	public static String getDefaultDateForDownloadFiles() {
		long i = System.currentTimeMillis();
		java.sql.Date now = new java.sql.Date(i);
		int year = now.getYear();
		int month = now.getMonth();
		if (month == 0) {
			year--;
			month = 12;
		} else {
			month--;
		}
		year+=1900;	
		String syear = String.valueOf(year);
		String needZero = (month<10)?"0":"";
		String smonth = needZero+String.valueOf(month);
		
		return syear+smonth+"01";
	}
	
	public static String getDateFormatForDownloadFiles(String date) {
		return date.substring(6)+date.substring(3,5)+date.substring(0,2);
	}

	public static String formatSQLTimestamp(Timestamp ts) {
		if (ts == null) return "";
		
		//StringBuffer ret= new StringBuffer();
		
		DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.LONG, Locale.GERMAN);
		
		//DateFormat df = new SimpleDateFormat("dd.MM.yyyy HH:mm.ss");
		
		return df.format(ts);
		
	}
	
	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 modifyIndividualBonus(HttpSession session, Logger logger) throws Exception {
		
		
		Map bonusMap = (Map)session.getAttribute("user_bonuses");
		
		int count = ((Integer)bonusMap.get("count")).intValue();
		
		for (int i = 0; i < count; i++) {
			Map bonus = (Map)bonusMap.get(String.valueOf(i));
			String[] percentages = new String[] {"db0", "db1", "db2", "db3", "db4", 
					"t1b1", "t1b2", "t1b3",
					"t2b1", "t2b2", "t2b3",
					"t3b1", "t3b2", "t3b3"};
			
			for (int n = 0; n<percentages.length; n++) {
				String[] ac = (String[])bonus.get(percentages[n]);
				if (ac!=null && ac.length>0) {
					String v = ac[0];
					if ((v!=null) && !"".equals(v)) {
						float fl = new Float(v).floatValue();
						ac[0] = ""+((float)Math.round(new Float(fl / 100)*1000))/1000;
					}
						
				}
				
			}
			SuperPO spo = new SuperPO("individual_bonus_2", logger);
			spo.addMap(bonus);
			if (bonus.get("id")!=null) {
				spo.update();
			} else {
				spo.setColumn("distr_id", (String)session.getAttribute("CURRENT_DISTRIBUTOR_ID"));
				spo.insert();
			}
		}
		
			
		return true;
	}
	
	private static void setRounded2Digits(String columnName, String columnValue, SuperPO spo) {
		if (columnValue != null) {
			try {
				BigDecimal value = new BigDecimal(columnValue);
				value = value.setScale(2, BigDecimal.ROUND_HALF_EVEN);
				spo.setColumn(columnName, value.toString());
			} catch (Exception ignored) {}
		}
	}
	
	public static boolean newArticle(HttpSession session, Logger logger) throws Exception {
		Transaction tx = null; 
		try {
		    Session hibernateSession = HibernateUtil.currentSession();
		    tx = hibernateSession.beginTransaction();
		    Connection conn = hibernateSession.connection();
		    Map jspMap = (Map)session.getAttribute("new_article.jsp");		
			String current_article_id = ((String[])jspMap.get("id"))[0];
			
			java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis()); 
			
			
			SuperPO spo = new SuperPO("article", logger);
			spo.addMap(jspMap);
			
			boolean combi = false;
			
			if (spo.getColumn("combi")!=null) combi = true;
			
			spo.insert(conn);
			
			//new entry
			SuperPO spo2 = new SuperPO("article_history", logger);
			spo2.addMap(jspMap);
			
			set2DigitsForArticle(spo2);
			
			spo2.setColumn("valid_from", formatSQLDate(thisDay));
			
			String strValidTo = "";
			if (jspMap.get("valid_to") instanceof String[])
				strValidTo = ((String[])jspMap.get("valid_to"))[0];
			else
				strValidTo = (String)jspMap.get("valid_to");
				
			if ("".equals(strValidTo)) strValidTo = "31.12.2100";
			
			spo2.setColumn("valid_to", strValidTo);
			
			spo2.setColumn("art_id", current_article_id);
			
			Integer uid = new Integer((String) session.getAttribute("USER_LOGGED_ID"));
			spo2.setColumn("user_changed", uid + "");
			
			spo2.insert(conn);
			
			
			
			if (combi) {
			
				Map combiMap = (Map)session.getAttribute("new_combi_articles");
				int count = ((Integer)combiMap.get("count")).intValue();
				
			
				
				for (int i = 0; i < count; i++) {
					SuperPO toAdd = new SuperPO("combi_article_content", logger);
					Map actual = (Map)combiMap.get(String.valueOf(i));
					
					toAdd.addMap(actual);
					toAdd.setColumn("combi_art_id", current_article_id);
					toAdd.insert(conn);
				}
	
			}
			
			tx.commit();
			HibernateUtil.closeSession();
			return true;
		} catch (Exception e) {
		    logger.error("Error adding article");
		    logger.info("rolling back");
		    try {
			    if (tx!=null)
			        tx.rollback();
			    HibernateUtil.closeSession();
		    } catch (Exception ex) {}
		    throw e;
		}
	}

	public static Map getArticle(String id, Logger logger) throws Exception {
		
		Map ret = new HashMap();
		
		java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis()); 
		
		
		ObjectSearch os = new ObjectSearch("article_history", new String[] {"art_id", "valid_from"});
		//os.setCondition("art_id = ? AND valid_from <= ? and valid_to >= ?");
		
		os.setCondition("art_id = ? AND valid_to = (select max(valid_to) from article_history where art_id = ?)");
		
		//List result = os.search(new Object[] {id, thisDay, thisDay});
		
		List result = os.search(new Object[] {id, id});
		
		PersistableObject po = new PersistableObject("article", new String[] {"id"});
		po.set("id", id);
		po.load();
		
		SuperPO spo = new SuperPO("article", logger);
		spo.setMain(po.getValues());
		
		ret.putAll(spo.getTextMap());
		
		if (result.size()>0) {
			PersistableObject po2 = (PersistableObject)result.get(0);
			SuperPO spo2 = new SuperPO("article_history", logger);
			spo2.setMain(po2.getValues());
			ret.putAll(spo2.getTextMap());
		}
		return ret;
	}
	
	public static void addSupplierRow(HttpSession session, HttpServletRequest req, Logger logger) throws Exception {
		Transaction tx = null;
		
		try {
			Session hibernateSession = HibernateUtil.currentSession();
			tx= hibernateSession.beginTransaction();
			Connection conn = hibernateSession.connection();
			
			
			
			String count_ = req.getParameter("count");
			
			if (count_ == null) {
				logger.info("WARNING: count of articles for supplier table is null");
				return;
			}
			
			int count = new Integer(count_).intValue();
			
			ArrayList toSession = new ArrayList();
			
			for (int i=0; i<count; i++) {
				

				
				String id = (String)((ArrayList)session.getAttribute("art_id_list")).get(i);
				String quantity = req.getParameter(i+"quantity");
				
				String supplier_name = req.getParameter(i+"supplier_name");
				String supplier_order_id = req.getParameter(i+"supplier_order_id");

				String ordered = req.getParameter(i+"ordered");
				String ordered_before = (String)((ArrayList)session.getAttribute("ordered_list")).get(i);
				
				boolean ordChanged = !ordered.equals(ordered_before);

				if (ordChanged) {
					boolean ok = true;
					try {
						new Integer(ordered);
					} catch (Exception e) {
						ok = false;
					}
					
					if (ok) {
						logger.info("Ordered field changed for article id: "+id+", old value: "+ordered_before+", new value: "+ordered);
						SuperPO artSave = new SuperPO("article", logger);
						artSave.setColumn("id", id);
						artSave.load(conn);
						artSave.setColumn("ordered", ordered);
						artSave.update(conn);
						logger.info("Updated successfully.");
						
						logger.info("Inserting new row into protocol table.");
						java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis());
						SuperPO spop = new SuperPO("protocol", logger);
						spop.setPOColumn("prot_date", thisDay);
						spop.setPOColumn("table_name", "article");
						spop.setPOColumn("field_name", "ordered");
						spop.setPOColumn("before", ""+ordered_before);
						spop.setPOColumn("after", ""+ordered);
						String logged = (String)session.getAttribute("USER_LOGGED_ID");
						Integer log = new Integer(logged);
						spop.setPOColumn("changed_by", log);
						spop.setPOColumn("datatype", "int32");
						spop.setPOColumn("identifier", id);
						spop.insert(conn);
						logger.info("Successfully inserted");
					} else {
						
					}
					
				}
				
				if ("".equals(supplier_name) && "".equals(supplier_order_id) && "".equals(quantity)) continue;
				
				try {
					logger.info("checking quantity "+quantity);
					quantity = new Integer(quantity).toString();
					logger.info("ok");
				} catch (Exception e) {
					logger.info("not ok, this line will be skipped with 0 quantity");
					quantity = "0";
				}
				logger.info("Quantity: "+quantity+", article id: "+id);
				if (quantity.equals("0")) continue;
				
				SuperPO save = new SuperPO("supplier_order", logger);
				
				java.sql.Date date = new java.sql.Date(new GregorianCalendar().getTimeInMillis());
				
				save.setColumn("article_id", id);
				save.setPOColumn("order_date", date);
				save.setColumn("quantity", quantity);
				
				
				
				save.setColumn("supplier_name", supplier_name);
				save.setColumn("order_id", supplier_order_id);
				
				logger.info("Trying to insert...");
				
				save.insert(conn);
				
				toSession.add(new String[] {id, quantity});
				
				logger.info("Inserted but not committed still");
			}
			
			
			tx.commit();
			
			logger.info("committed");
			
			HibernateUtil.closeSession();
			
			session.setAttribute("SUPPLIER_ADDED", toSession);
			
		} catch (Exception ex) {
		    logger.error("Error modifying supplier table ",ex);
		    logger.info("rolling back");
		    try {
			    if (tx!=null)
			        tx.rollback();
			    HibernateUtil.closeSession();
		    } catch (Exception e) {}
		    throw ex;
		}
	}
	
	private static void set2DigitsForArticle(SuperPO spo2) throws Exception {
		String netto = spo2.getColumn("netto");
		String netto_customer = spo2.getColumn("netto_customer");
		String netto_vip_customer = spo2.getColumn("netto_vip_customer");
		String netto_silver_customer = spo2.getColumn("netto_silver_customer");
		String netto_gold_customer = spo2.getColumn("netto_gold_customer");
		String netto_handler = spo2.getColumn("netto_handler");
		String netto_grosshandler = spo2.getColumn("netto_grosshandler");			
		
		setRounded2Digits("netto", netto, spo2);
		setRounded2Digits("netto_customer", netto_customer, spo2);
		setRounded2Digits("netto_silver_customer", netto_silver_customer, spo2);
		setRounded2Digits("netto_gold_customer", netto_gold_customer, spo2);
		setRounded2Digits("netto_vip_customer", netto_vip_customer, spo2);
		setRounded2Digits("netto_handler", netto_handler, spo2);
		setRounded2Digits("netto_grosshandler", netto_grosshandler, spo2);	
	}
	
	public static boolean modifyArticle(HttpSession session, Logger logger) throws Exception {
		Transaction tx = null;
		try {
			Session hibernateSession = HibernateUtil.currentSession();
			tx= hibernateSession.beginTransaction();
			Connection conn = hibernateSession.connection();
			
			java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis()); 
			java.sql.Date yesterDay = new java.sql.Date(System.currentTimeMillis()-24*60*60*1000);
		
			PersistableObject po = new PersistableObject("article_history", new String[] {"art_id" , "valid_from"});
		
			String current_article_id = (String)session.getAttribute("CURRENT_ARTICLE_ID");
			po.set("art_id", current_article_id);
			java.sql.Date vf = (java.sql.Date)session.getAttribute("CURRENT_ARTICLE_VALID_FROM"); 
			logger.info("__VALID_DEBUG (modify): CURRENT_ARTICLE_VALID_FROM: "+formatSQLDate(vf));
			po.set("valid_from", session.getAttribute("CURRENT_ARTICLE_VALID_FROM"));
			po.load(conn);
		
			SuperPO spo = new SuperPO("article", logger);
			
			spo.setColumn("id", current_article_id);
			spo.load(conn);
			Integer inv = (Integer)spo.getPOColumn("inventory");
			Integer min_inv = (Integer)spo.getPOColumn("minimum_inventory");
			//Double order_price = (Double)spo.getPOColumn("order_price");
			
			spo.addMap((Map)session.getAttribute("article_detail.jsp"));
		
			boolean combi = false;
		
			if (spo.getColumn("combi")!=null) combi = true;
		
			spo.update(conn);
		
			String strThisDay = formatSQLDate(thisDay);
			String qq = formatSQLDate((java.sql.Date)po.get("valid_from"));
		
			logger.info("strThisDay: "+strThisDay);
			logger.info("qq: "+qq);
			
			Map jspMap = (Map)session.getAttribute("article_detail.jsp");
			String strValidTo = "";
			if (jspMap.get("valid_to") instanceof String[])
				strValidTo = ((String[])jspMap.get("valid_to"))[0];
			else
				strValidTo = (String)jspMap.get("valid_to");
				
			if ("".equals(strValidTo)) strValidTo = "31.12.2100";
			
			if (strThisDay.equals(qq)) {
				//update
				SuperPO spo2 = new SuperPO("article_history", logger);
				spo2.setMain(po.getValues());
				spo2.addMap(jspMap);
				
				set2DigitsForArticle(spo2);
				
				spo2.setColumn("valid_to", strValidTo);
				
				spo2.update(conn);
			} else {
			//	new entry
				po.set("valid_to", yesterDay);
				po.update(conn);
				SuperPO spo2 = new SuperPO("article_history", logger);
				spo2.addMap(jspMap);
				
				set2DigitsForArticle(spo2);
				
				spo2.setColumn("valid_from", formatSQLDate(thisDay));
				spo2.setColumn("valid_to", strValidTo);
				spo2.setColumn("art_id", current_article_id);
				spo2.insert(conn);
				session.setAttribute("CURRENT_ARTICLE_VALID_FROM", thisDay);
			}
		
			ObjectSearch os = new ObjectSearch("combi_article_content", new String[] {"combi_art_id", "art_id"});
			os.setCondition("combi_art_id = ?");
			List result = os.search(conn, new Object[] {current_article_id});
			
			for (int i = 0; i<result.size(); i++) {
				PersistableObject act = (PersistableObject)result.get(i);
				act.delete(conn);
			}
			
			if (combi) {
				Map combiMap = (Map)session.getAttribute("combi_articles");
				int count = ((Integer)combiMap.get("count")).intValue();				
				for (int i = 0; i < count; i++) {
					SuperPO toAdd = new SuperPO("combi_article_content", logger);
					Map actual = (Map)combiMap.get(String.valueOf(i));
					toAdd.addMap(actual);
					toAdd.setColumn("combi_art_id", current_article_id);
					toAdd.insert(conn);
				}
				
			}			

			Integer new_inv = (Integer)spo.getPOColumn("inventory");
			Integer new_min_inv = (Integer)spo.getPOColumn("minimum_inventory");

			
			if (new_inv.intValue()!=inv.intValue()) {
				SuperPO spop = new SuperPO("protocol", logger);
				spop.setPOColumn("prot_date", thisDay);
				spop.setPOColumn("table_name", "article");
				spop.setPOColumn("field_name", "inventory");
				spop.setPOColumn("before", ""+inv);
				spop.setPOColumn("after", ""+new_inv);
				String logged = (String)session.getAttribute("USER_LOGGED_ID");
				Integer log = new Integer(logged);
				spop.setPOColumn("changed_by", log);
				spop.setPOColumn("datatype", "int32");
				spop.setPOColumn("identifier", current_article_id);
				spop.insert(conn);
			}
			
			if (new_min_inv.intValue()!=min_inv.intValue()) {
				SuperPO spop = new SuperPO("protocol", logger);
				spop.setPOColumn("prot_date", thisDay);
				spop.setPOColumn("table_name", "article");
				spop.setPOColumn("field_name", "minimum_inventory");
				spop.setPOColumn("before", ""+min_inv);
				spop.setPOColumn("after", ""+new_min_inv);
				String logged = (String)session.getAttribute("USER_LOGGED_ID");
				Integer log = new Integer(logged);
				spop.setPOColumn("changed_by", log);
				spop.setPOColumn("datatype", "int32");
				spop.setPOColumn("identifier", current_article_id);
				spop.insert(conn);
			}
						
			tx.commit();
			HibernateUtil.closeSession();
			return true;
		} catch (Exception ex) {
		    logger.error("Error modifying article ",ex);
		    logger.info("rolling back");
		    try {
			    if (tx!=null)
			        tx.rollback();
			    HibernateUtil.closeSession();
		    } catch (Exception e) {}
		    throw ex;
		}
	}
	
	
	public static boolean modifyDistributor(HttpSession session, Logger logger) throws ServletException {
		int distr_id;
		try {
			distr_id = Integer.parseInt((String)session.getAttribute("CURRENT_DISTRIBUTOR_ID"));
		} catch (Exception e) {
			return false;
		}
		try {
			Map complex = new HashMap();
		
			if (session.getAttribute("user_personal_Map")!=null)
			complex.putAll((Map)session.getAttribute("user_personal_Map"));
			
			
			if (session.getAttribute("user_int_Map")!=null)
			complex.putAll((Map)session.getAttribute("user_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("user_payment_Map")!=null)
			complex.putAll((Map)session.getAttribute("user_payment_Map"));
		
			complex.remove("link");
			complex.remove("saveState");
			complex.remove("pageAction");
			complex.remove("sponsor_name");
			complex.remove("rows");
			
			List distDiscLevels = new ArrayList();
			
			Integer level_id_ = (Integer)complex.get("level_id");
			
			for (int k = 1; k<100; k++) {
				boolean gh = false;
				boolean h = false;
				boolean a = false;
				
				String key = "personal_discount_"+k;
				if (level_id_ != null && level_id_.intValue() == 350) {
					key = "gh_" + key;
					gh = true;
				}
				else if (level_id_ != null && level_id_.intValue() == 330) {
					key = "h_" + key;
					h = true;
				}
				else if (level_id_ != null && level_id_.intValue() == 370) {
					key = "a_" + key;
					a = true;
				}
					
				if (complex.containsKey(key)) {
					Float perc = (Float)complex.get(key);
					distDiscLevels.add(new DistributorDiscountLevel(new Integer(distr_id), new Integer(k), perc));
					complex.remove(key);
				}
				
				try {
					if (gh) {
						complex.remove("personal_discount_"+k);
						complex.remove("h_personal_discount_"+k);
						complex.remove("a_personal_discount_"+k);
					}
					else if (h) {
						complex.remove("personal_discount_"+k);
						complex.remove("gh_personal_discount_"+k);
						complex.remove("a_personal_discount_"+k);
					}
					else if (a) {
						complex.remove("personal_discount_"+k);
						complex.remove("h_personal_discount_"+k);
						complex.remove("gh_personal_discount_"+k);
					}					
					else {
						complex.remove("gh_personal_discount_"+k);
						complex.remove("h_personal_discount_"+k);
						complex.remove("a_personal_discount_"+k);
					}
				} catch (Exception ignored) {}
			}
			
			
			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);
			
			Float original_dr = (Float)po.get("discount_rate");
			
			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);
			}
		
			if (complex.get("annual_fee")!=null)
				if (((Boolean)complex.get("annual_fee")).booleanValue()==true)
				session.setAttribute("ABO_WARNING", "yes");
		
			
			Integer level_id = (Integer)complex.get("level_id");
			
			if (level_id!=null) 
				if (level_id.intValue() == 80) {
					java.sql.Date thisDay = new java.sql.Date(System.currentTimeMillis()); 
					java.sql.Date yesterDay = new java.sql.Date(System.currentTimeMillis()-24*60*60*1000);

					PersistableObject discHist = new PersistableObject("discount_history", new String[] {"distr_id", "begin_time"});
					discHist.set("distr_id", new Integer(distr_id));
					java.sql.Date bt = (java.sql.Date)session.getAttribute("CURRENT_DISCOUNT_RATE_VALID_FROM"); 
					discHist.set("begin_time", bt);
					discHist.load();

					String strThisDay = formatSQLDate(thisDay);
					String qq = formatSQLDate(bt);

					Float new_dr = (Float)complex.get("discount_rate");
					
					
					if (original_dr != null && new_dr!=null)
						if (original_dr.floatValue()!=new_dr.floatValue()) {
							if (strThisDay.equals(qq)) {
								//update
								SuperPO spo2 = new SuperPO("discount_history", logger);
								spo2.setMain(discHist.getValues());
								spo2.setPOColumn("discount_rate", complex.get("discount_rate"));
								spo2.update();
							} else {
							//	new entry
								discHist.set("end_time", yesterDay);
								discHist.update();
								SuperPO spo2 = new SuperPO("discount_history", logger);
								spo2.addMap((Map)session.getAttribute("article_detail.jsp"));
								spo2.setColumn("begin_time", formatSQLDate(thisDay));
								spo2.setColumn("end_time", "31.12.2100");
								spo2.setPOColumn("discount_rate", complex.get("discount_rate"));
								spo2.setColumn("distr_id", ""+distr_id);
								spo2.insert();
								session.setAttribute("CURRENT_DISCOUNT_RATE_VALID_FROM", thisDay);
							}
						}
				}

			if (level_id != null)
				if (level_id.intValue() == 300 || level_id.intValue() == 350 || level_id.intValue() == 330 || level_id.intValue() == 370) {
					DiscountHelper.saveNewLevels(new Integer(distr_id), distDiscLevels, session);
				} else {
					DiscountHelper.deleteLevels(new Integer(distr_id), distDiscLevels, session);
				}
			
			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("Error: ", e);
			
			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_DISTRIBUTOR_ID"));
		} catch (Exception e) {
			return false;
		}
		try {
		
		
		Map addressMap = (Map)session.getAttribute("user_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.error(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {
				PersistableObject po = new PersistableObject("address", l, address);
				
				try {
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.error(ex.getMessage());
					throw new ServletException(ex);
				}	
			
			}
			}
			}catch (Exception e) {
			logger.error(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_DISTRIBUTOR_ID"));
		} catch (Exception e) {
			return false;
		}
		Map creditsMap = (Map)session.getAttribute("user_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.error(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {
				
				PersistableObject po = new PersistableObject("creditcard", l, credit);
				
				try {
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.error(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_DISTRIBUTOR_ID"));
		} catch (Exception e) {
			return false;
		}
		try {
		
		Map banksMap = (Map)session.getAttribute("user_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.error(ex.getMessage());
					throw new ServletException(ex);
				}
			} else {	
				try {
					PersistableObject po = new PersistableObject("bank_account", l, bank);
					if (!delete) po.insert();
				} catch (Exception ex) {
					logger.error(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_user_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;
		
	}		
	
	
}


