/*
 *
 * Created on May 29, 2005
 *
 * Gy�rgy S�veges
 * Etixpert Kft.
 * Copyright(c) 2005
 *
 */
package com.etixpert.evolution.gui.servlets;

import java.io.IOException;
import java.math.BigDecimal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

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

import org.apache.log4j.Logger;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.etixpert.evolution.EvolutionException;
import com.etixpert.evolution.HibernateUtil;
import com.etixpert.evolution.ObjectSearch;
import com.etixpert.evolution.PersistableObject;
import com.etixpert.evolution.SuperPO;
import com.etixpert.evolution.Tools;

/**
 * @author Suveges Gyorgy
 *
 * TODO To change the template for this generated type comment go to
 * Window - Preferences - Java - Code Style - Code Templates
 */
public class OrderHelper {
    public final static int DETAILSFROMLEVEL = 200;
    public final static int INDEX_CREATE=0;
	public final static int INDEX_VIEW=1;
	public final static int INDEX_MODIFY=2;
	public final static int INDEX_DELETE=3;
	public final static int INDEX_NEXT_PROC=4;

	public final static int MASK_CREATE=1;
	public final static int MASK_VIEW=2;
	public final static int MASK_MODIFY=4;
	public final static int MASK_DELETE=8;
	public final static int MASK_NEXT_PROC=16;
	
	
    /**
     *
     */

    public static void loadOrderStatic(String orderid, HttpSession session, Logger logger) throws Exception {
       	//already checked
    	int id = Integer.parseInt(orderid);



    	ObjectSearch os = new ObjectSearch("order_header", new String[] {"id"});
    	os.setCondition("id = ?");
    	List result = os.search(new Object[] {new Long(id)});


    	//already checked
    	PersistableObject po = (PersistableObject)result.get(0);

    	SuperPO spo = new SuperPO("order_header", MainControl.logger);

    	spo.setMain(po.getValues());

    	java.sql.Date orderDate = (java.sql.Date)spo.getPOColumn("order_date");

    	Map jspMap = new HashMap();

    	jspMap.putAll(spo.getTextMap());

    	String pay_method_id = ((String[])jspMap.get("pay_method_id"))[0];
    	String account_id	 = ((String[])jspMap.get("account_id"))[0];
    	
		if ("1".equals(pay_method_id))
			jspMap.put("account_id_1", new String[] {account_id});
		else if ("2".equals(pay_method_id))
			jspMap.put("account_id_2", new String[] {account_id});

    	
    	String olid = spo.getColumn("orderer_level_id");

    	jspMap.putAll(getOrderPerson((String)spo.getColumn("ordered_by"), session));

    	jspMap.put("order_id", new String[] {orderid});

    	session.setAttribute("order_detail_static.jsp", jspMap);

    	ObjectSearch os2 = new ObjectSearch("order_detail", new String[] {"order_id", "art_position"});

    	os2.setCondition("order_id = ?");

    	List details = os2.search(new Object[] {new Long(orderid)});

    	setDetails(session, details, "order_details_static", "order_detail", orderDate, olid);
    }


	public static boolean[] getRights(HttpSession session, String oid, String cnr, int mask) throws Exception {
	    	Integer did = null;
	    	if (cnr!=null) did = new Integer(cnr);


	    	Integer uid = new Integer((String) session.getAttribute("USER_LOGGED_ID"));
	    	Integer lid = new Integer((String) session.getAttribute("USER_LOGGED_LEVEL_ID"));
	    	Transaction tx = null;
	    	try {
	    		Session hibernateSession = HibernateUtil.currentSession();
	    		tx = hibernateSession.beginTransaction();
	    		Connection conn = hibernateSession.connection();
	    		PersistableObject order= null;
	    		Integer status = null;
	    		if (oid!=null) {
	    			Long orderId = new Long(oid);
	    			order = new PersistableObject("order_header", "id");
	    			order.set("id", orderId);
	    			order.load(conn);
	    			did = (Integer) order.get("ordered_by");
	    			status = (Integer) order.get("order_status_id");
	    		}

	    		PersistableObject generalRights= null;
	    		PersistableObject orderStatusRights = null;
	    		if ((mask | MASK_CREATE) == mask) {
	    			generalRights = new PersistableObject("general_rights", "role_id");
	    		    generalRights.set("role_id", lid);
	    		    generalRights.load(conn);
	    		}

	    		if ((mask & ~MASK_CREATE)>0) {
	    			orderStatusRights = new PersistableObject("order_status_rights", new String[]{"role_id", "order_status_id"});
	    			orderStatusRights.set("role_id", lid);
	    			orderStatusRights.set("order_status_id", status);
	    			orderStatusRights.load(conn);
	    		}

	    		boolean create = false;
	    		if ((mask | MASK_CREATE) == mask) create = Tools.getRight(conn, generalRights, "order_create", uid, did);
	    		boolean view = false;
	    		if ((mask | MASK_VIEW) == mask) view = Tools.getRight(conn, orderStatusRights, "view", uid, did);
	    		boolean modify = false;
	    		if ((mask | MASK_MODIFY) == mask) modify = Tools.getRight(conn, orderStatusRights, "change", uid, did);
	    		boolean delete = false;
	    		if ((mask | MASK_DELETE) == mask) delete = Tools.getRight(conn, orderStatusRights, "storno", uid, did);
	    		boolean nextProc = false;
	    		if ((mask | MASK_NEXT_PROC) == mask) nextProc = Tools.getRight(conn, orderStatusRights, "nextproc", uid, did);
	    		tx.commit();
	    		HibernateUtil.closeSession();
	    		return new boolean[]{create, view, modify, delete, nextProc};

	    	} catch (Exception e) {
	    		MainControl.logger.error("Error occured. Rolling Back. ",e);
	    		if (tx!=null)
	    			tx.rollback();
	    		throw e;
	    	}


	    }
    public static String getVal(Map m, String name) {

    	if (m == null) return "";
    	String[] vals = (String[])m.get(name);
    	if (vals != null && vals.length>0 && vals[0] != null) return vals[0];
    	return "";
    }

    public static String getVal(Map m, String name, String defaultNull) {

    	if (m == null) return "";
    	String[] vals = (String[])m.get(name);
    	if (vals != null && vals.length>0 && vals[0] != null) return vals[0];
    	return defaultNull;
    }

    public static void setVal(Map m, String name, String value) {
        m.put(name, new String[]{value});

    }

    //mine!!
	public static String getCountryPostCodeOptions(HttpSession session, String whichMap, String name) throws Exception{
		StringBuffer sb = new StringBuffer("");
		Country[] countries = FormHelper.getCountries();

		for (int i = 0; i < countries.length; i++) {
			String selected="";
			if (getVal(session, whichMap, name).equals(countries[i].country_post_code)) selected=" selected";
			sb.append("<option"+selected+" value=\""+ countries[i].country_post_code + "\">"+countries[i].country_post_code+"</option>");
		}
		return sb.toString();
	}

    //mine!!!
    public static String getVal(HttpSession session, String whichMap, String name) {
		Map m = (Map)session.getAttribute(whichMap);
		if (m == null) return "";
		String[] vals = (String[])m.get(name);
		if (vals != null && vals.length>0 && vals[0] != null) return vals[0];
		return "";
    }

    public static String getMessage(HttpServletRequest req) throws IOException {
        HttpSession session = req.getSession();
        if (session.getAttribute("message")!=null) {
            String htmlMessage = "&nbsp;"+session.getAttribute("message")+"&nbsp;";
            session.removeAttribute("message");
            return htmlMessage;

        }

        return "";

    }
    
    public static boolean isFirstOrder(HttpServletRequest req) throws Exception {
    	return req.getParameter("fo")!=null;
    }

    public static void setMessage(HttpServletRequest req, String message) {
        req.getSession().setAttribute("message", message);
    }

    public static String generateArticleList(HttpSession session, String page, int level) throws Exception {
        Set positions = new TreeSet();
        Map map = (Map) session.getAttribute(page);
        StringBuffer sb = new StringBuffer();
        sb.append(generateArticleHeader(session, level));
        if (map!=null) {
            String posString = getVal(map, "positions");
            sb.append("<input type=\"hidden\" name=\"positions\" value=\"").append(posString).append("\"/>\n");
            if (posString!=null && posString.length()>0) {
                String[] pos = posString.split(";");

                for (int i=0; i<pos.length; i++)
                    sb.append(generateArticleRow(map,  pos[i], level));
            }
        }
        sb.append(generateNewArticleRow());
        sb.append(generateArticleTotal(map, level));
        return sb.toString();

    }

    private static String generateNewArticleRow() {
        StringBuffer sb = new StringBuffer();
        sb.append("<td>&nbsp;</td>\n");
        sb.append("<td><input type=\"text\" name=\"new_record\" size=\"10\" maxlength=\"10\" onChange=\"javascript:document.forms[0].saveState.value='process/new_order.jsp';document.forms[0].pageAction.value='orderadd';document.forms[0].submit();\"/></td>\n");
       // sb.append("<td><input type=\"text\" name=\"new_record\" maxlength=\"10\" onblur=\"alert(\'test\');\"/></td>\n");
        sb.append("<td colspan=\"8\">&nbsp;</td>\n");
        return sb.toString();
    }

	public static String generateMailDetailsHeader(PageContext pc) throws Exception {
		HttpSession session = pc.getSession();

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

		boolean dealer = false;

		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		StringBuffer sb = new StringBuffer("<tr>");
		if (dealer) {
			sb.append("<td>ArtId</td>"+
					"<td colspan=\"3\">"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
		}
		if (admin || distributor) {
			sb.append("<td>ArtId</td>"+
			"<td colspan=\"3\">"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "BONUSW")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
		}
		else if (customer) {
			
			sb.append("<td>"+LocaleSupport.getLocalizedMessage(pc, "ART_ID")+"</td>"+
			"<td colspan=\"3\">"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
			"<td colspan=\"3\">"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
			
		}
		sb.append("</tr>");
		return sb.toString();
	}

	public static String generateOrderDetailsHeader(PageContext pc, String from) throws Exception {
		HttpSession session = pc.getSession();

		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;
		boolean dealer = false;
		boolean dealer_order = false;
		boolean customer_order = false;
		boolean customer_discount = false;
		
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		Map orders = (Map)session.getAttribute(from);
		String level_id = (String)orders.get("ordering_level_id");
		if ("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id)) {
			dealer_order = true;
		} else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer_order = true;
			String sponsor = OrderHelper.getVal(session, from.startsWith("new")?"new_order.jsp":"order_detail.jsp", "sponsor");
			if ("0".equals(sponsor) || "43002857".equals(sponsor) || "43005029".equals(sponsor))
				customer_discount = true;
		}
		
		
		
		StringBuffer sb = new StringBuffer();
		sb.append("<table id=\"dataTable\" width=\"850\">");
		if (distributor) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"60\">"+
					"<col width=\"60\"><col width=\"60\"><col width=\"60\"><col width=\"70\">"+
					"<col width=\"210\">");
			sb.append("<tr id=\"dataTableHeaderContent\">");
			sb.append("<td>L</td><td>ArtId</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "BONUSW")+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
			sb.append("</tr>");
		}
		else if (admin) {
			
			if (dealer_order || customer_discount) {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"260\">"+"<col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\"><col width=\"70\"><col width=\"60\"><col width=\"60\"><col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\">");
						sb.append("<tr id=\"dataTableHeaderContent\">");
						sb.append("<td>L</td><td>ArtId</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "INVENTORY")+"</td>"+"<td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO_LIST")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "DISC_PERC")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "DISC")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>");
						sb.append("</tr>");
			} else if (customer_order) {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"255\">"+"<col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\"><col width=\"60\"><col width=\"60\">" +
						"<col width=\"195\">");
						sb.append("<tr id=\"dataTableHeaderContent\">");
						sb.append("<td>L</td><td>ArtId</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "INVENTORY")+"</td>"+"<td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+						
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
						sb.append("</tr>");
			} else {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"255\">"+"<col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\"><col width=\"60\"><col width=\"60\">" +
						"<col width=\"60\">"+
						"<col width=\"135\">");
						sb.append("<tr id=\"dataTableHeaderContent\">");
						sb.append("<td>L</td><td>ArtId</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "INVENTORY")+"</td>"+"<td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "BONUSW")+
						"<td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
						sb.append("</tr>");
				
			}
		}
		else if (customer) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"60\">"+
			"<col width=\"60\"><col width=\"60\"><col width=\"340\">");
			sb.append("<tr id=\"dataTableHeaderContent\">");
			sb.append("<td>"+LocaleSupport.getLocalizedMessage(pc, "L")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_ID")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
			"<td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
			sb.append("</tr>");
		} else if (dealer) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"70\">"+
					"<col width=\"80\"><col width=\"80\"><col width=\"70\"><col width=\"70\">"+
					"<col width=\"150\">");
					sb.append("<tr id=\"dataTableHeaderContent\">");
					sb.append("<td>L</td><td>ArtId</td><td>"+LocaleSupport.getLocalizedMessage(pc, "ART_NAME")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "PIECE")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "DISC_PERC")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "NETTO")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "VAT_PERC")+"</td><td>"+LocaleSupport.getLocalizedMessage(pc, "BRUTTO")+"</td>"+
					"<td>"+LocaleSupport.getLocalizedMessage(pc, "COMMENT")+"</td>");
					sb.append("</tr>");
		}
		return sb.toString();
	}

	public static String generateMailDetailsRows(HttpSession session, String from) throws Exception {
		boolean admin = false;
		boolean distributor = false;
		boolean customer_discount = false;
		boolean customer_order = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;

		boolean dealer = false;
		boolean dealer_order = false;
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		Map orders = (Map)session.getAttribute(from);
		
		String level_id = (String)orders.get("ordering_level_id");
		if ("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id)) {
			dealer_order = true;
		} else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer_order = true;
			String sponsor = OrderHelper.getVal(session, from.startsWith("new")?"new_order.jsp":"order_detail.jsp", "sponsor");
			if (("0".equals(sponsor) || "43002857".equals(sponsor) || "43005029".equals(sponsor)) && admin)
				customer_discount = true;
		}	
		
		StringBuffer sb = new StringBuffer();

		


		if (orders!=null) {
			int count = 0;
			if (orders.get("count")!=null)
				count = ((Integer)orders.get("count")).intValue();

			for (int i = 0; i < count; i++)
			{
				sb.append("<tr>");
				Map order = (Map)orders.get(String.valueOf(i));
				if (order == null) continue;
				String id = ((String[])order.get("art_id"))[0];
				String name = ((String[])order.get("art_name"))[0];
				String quantity = ((String[])order.get("quantity"))[0];
				String bonus = ((String[])order.get("bonus"))[0];
				String brutto = ((String[])order.get("brutto"))[0];
				String netto = ((String[])order.get("netto"))[0];
				String vat_val = ((String[])order.get("vat_value"))[0];
				
				String comment = ((String[])order.get("comment"))[0];
				String trade = ((String[])order.get("trade_margin"))[0];
				
				String brutto_disc = null;
				String netto_disc = null;
				String discount_perc = null;
				String discount = null;
				
				if (order.get("netto_disc")!=null)
					netto_disc = ((String[])order.get("netto_disc"))[0];
				if (order.get("brutto_disc")!=null)
					brutto_disc = ((String[])order.get("brutto_disc"))[0];
				if (order.get("discount_perc")!=null)
					discount_perc = ((String[])order.get("discount_perc"))[0];
				if (order.get("discount")!=null)
					discount = ((String[])order.get("discount"))[0];

				
				
				String[] counted = countValues(new String[] {netto, brutto, bonus, trade, netto_disc, brutto_disc, discount_perc, discount, "0", vat_val}, quantity);

				if (new Float(counted[3]).floatValue() > 0 && (dealer || dealer_order || customer_discount))
					counted[0] = counted[3];
				
				if (new Float(counted[4]).floatValue() > 0 && (dealer || dealer_order || customer_discount))
					counted[1] = counted[4];
				
				
				sb.append("<td>"+id+"</td>");
				sb.append("<td colspan=\"3\">"+name+"</td>");
				sb.append("<td>"+quantity+"</td>");
				
				if (admin || distributor || dealer)
					sb.append("<td>"+counted[0] + "</td>");
				else if (customer_order || customer_discount)
					sb.append("<td>"+counted[0] + "</td>");

				sb.append("<td>"+vat_val+"</td>");
				sb.append("<td>"+counted[1]+"</td>");

				if (admin || distributor) {
					//sb.append("<td>"+counted[2]+"</td>");
					sb.append("<td>"+counted[2]+"</td>");
					sb.append("<td>"+comment+"</td>");
				} else 
					sb.append("<td colspan=\"3\">"+comment+"</td>");
				sb.append("</tr>");
			}
		}
		
		sb.append("</table>");
		
		return sb.toString();
	}
	
	public static void reCountDiscount(double total, Map from, HttpSession session) throws Exception {
		
	}

	public static String generateOrderDetailsRows(HttpSession session, String from) throws Exception {
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;

		boolean dealer = false;
		boolean dealer_order = false;
		boolean customer_order = false;
		boolean customer_discount = false;
		
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		StringBuffer sb = new StringBuffer();

		Map orders = (Map)session.getAttribute(from);

		String level_id = (String)orders.get("ordering_level_id");
		if (("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id)) && admin) {
			dealer_order = true;
		} else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer_order = true;
			String sponsor = OrderHelper.getVal(session, from.startsWith("new")?"new_order.jsp":"order_detail.jsp", "sponsor");
			if (("0".equals(sponsor) || "43002857".equals(sponsor) || "43005029".equals(sponsor)) && admin)
				customer_discount = true;
		}
		
		boolean subscription = from.indexOf("abo")!=-1;
		String page,pagemap;
		String add_command;
		String mod_quantity_command;
		String mod_comment_command;
		String delete_command;

		if (from.equals("order_details")) {
			pagemap = "order_detail.jsp";
			page= pagemap;
			add_command = "orderadd";
			mod_quantity_command = "orderchange_quantity";
			mod_comment_command = "orderchange_comment";
			delete_command = "deleteorderdetail";
		} else if (from.equals("user_abo_details") || from.equals("customer_abo_details")) {
		    String prefix = from.startsWith("customer")?"customer_":"user_";
		    pagemap = prefix+"abo_detail.jsp";
		    page="abo_detail.jsp?prefix="+prefix;
		    add_command = "aboadd";
		    mod_quantity_command="abochange_quantity";
		    mod_comment_command="abochange_comment";
		    delete_command="deleteabodetail";
		} else if (from.equals("user_new_abo_details")) {
		    pagemap = "user_new_abo.jsp";
		    page="new_abo.jsp?prefix=user_";
		    add_command = "new_aboadd";
		    mod_quantity_command = "new_abochange_quantity";
		    mod_comment_command = "new_abochange_comment";
		    delete_command = "deletenewabodetail";
		} else if (from.equals("customer_new_abo_details")) {
		    pagemap = "customer_new_abo.jsp";
		    page = "new_abo.jsp?prefix=customer_";
		    add_command = "new_aboadd";
		    mod_quantity_command = "new_abochange_quantity";
		    mod_comment_command = "new_abochange_comment";
		    delete_command = "deletenewabodetail";
		}else {
			pagemap = "new_order.jsp";
			
			page= pagemap;
			add_command = "new_orderadd";
			mod_quantity_command = "new_orderchange_quantity";
			mod_comment_command = "new_orderchange_comment";
			delete_command = "deleteneworderdetail";
		}

		/*boolean dealer = false;
		float dr = 0;
		Map temp = (Map)session.getAttribute(pagemap);
		if (temp!=null) {
			if (temp.containsKey("orderingLevelId")) {
				String level_id = ((String[])temp.get("orderingLevelId"))[0];
				if ("80".equals(level_id)) {
					dealer = true;
					if (temp.containsKey("orderingDiscountRate")) {
						String sdr = ((String[])temp.get("orderingDiscountRate"))[0];
						if (sdr!=null && !"".equals(sdr))
							dr = new Float(sdr).floatValue();
					}
				}
			}
		}*/
		
		if (orders!=null) {
			int count = 0;
			if (orders.get("count")!=null)
				count = ((Integer)orders.get("count")).intValue();

			for (int i = 0; i < count; i++)
			{
				Map order = (Map)orders.get(String.valueOf(i));
				if (order == null) continue;
				String id = ((String[])order.get("art_id"))[0];
				String name = ((String[])order.get("art_name"))[0];
				
				 PersistableObject po_article = new PersistableObject("article", "id");
				 po_article.set("id", id);
				 Integer inventory_ = new Integer(-1);
				 Double order_price = new Double(0);
				 try {
					 po_article.load();
					 inventory_ = (Integer)po_article.get("inventory");
					 order_price = (Double)po_article.get("order_price");
					 order.put("order_price", new String[] {""+order_price});
					 
				 } catch (Exception e) {}
				 
				String inventory = inventory_.toString();
				
				String quantity = ((String[])order.get("quantity"))[0];
				String bonus = ((String[])order.get("bonus"))[0];
				String brutto = ((String[])order.get("brutto"))[0];
				String netto = ((String[])order.get("netto"))[0];
				String brutto_disc = null;
				String netto_disc = null;
				String discount_perc = null;
				String discount = null;
				String list = null;
				
				if (order.get("netto_disc")!=null)
					netto_disc = ((String[])order.get("netto_disc"))[0];
				if (order.get("brutto_disc")!=null)
					brutto_disc = ((String[])order.get("brutto_disc"))[0];
				if (order.get("discount_perc")!=null)
					discount_perc = ((String[])order.get("discount_perc"))[0];
				if (order.get("discount")!=null)
					discount = ((String[])order.get("discount"))[0];
				if (order.get("list")!=null) {
//					if (dealer || dealer_order)
//						list = ((String[])order.get("netto"))[0];
//					else 
						list = ((String[])order.get("list"))[0];
				}
					
				String vat_val = ((String[])order.get("vat_value"))[0];

				String comment = ((String[])order.get("comment"))[0];
				String trade = ((String[])order.get("trade_margin"))[0];


				String[] counted = countValues(new String[] {netto, brutto, bonus, trade, netto_disc, brutto_disc, discount_perc, discount, list, vat_val}, quantity);

				if (new Float(counted[3]).floatValue() != 0 && (dealer || dealer_order || customer_discount))
					counted[0] = counted[3];
				
				if (new Float(counted[4]).floatValue() != 0 && (dealer || dealer_order || customer_discount))
					counted[1] = counted[4];
				
				sb.append("<tr id=\"dataTableDataContent\">");

				sb.append("<td><a href=\"javascript:top.mainFrame.document.forms[0].pos.value = '"+String.valueOf(i)+"'; link('process/"+page+"', '"+delete_command+"');\">" +
					"<img border=\"0\" src=\"img/delete.gif\"/></a></td>");

				sb.append("<td>"+id+"</td>");
				sb.append("<td>"+name+"</td>");
				
				if (admin)
					sb.append("<td style=\"text-align: right;\">"+inventory+"</td>");
				
				sb.append("<td><input class=\"little\" name=\"quantity"+String.valueOf(i)+"\" value=\""+ quantity +"\" "+
				"onchange=\"javascript:document.forms[0].saveState.value='process/"+ pagemap + "';document.forms[0].pageAction.value='"+ mod_quantity_command+"';document.forms[0].pos.value='").append(String.valueOf(i)).append("';document.forms[0].submit();\""+
				" onblur=\"javascript:document.forms[0].saveState.value='process/"+ pagemap + "';document.forms[0].pageAction.value='"+ mod_quantity_command+"';document.forms[0].pos.value='").append(String.valueOf(i)).append("';document.forms[0].submit();\"/></td>");
				
				if (subscription)
					sb.append("<td style=\"text-align: center;\"><input type=\"checkbox\" name=\"subscription"+String.valueOf(i)+"\" value=\"yes\" " + getChecked(session, order, "subscription")+"></td>");
				//liste
				if (dealer_order || customer_discount) {
					sb.append("<td style=\"text-align: right;\">"+ counted[7] + "</td>");
				}
				
				if ((dealer || (admin && (dealer_order || customer_discount))) && !subscription)
					sb.append("<td style=\"text-align: right;\">"+ counted[5] + "</td>");
				if (dealer_order || customer_discount)
					sb.append("<td style=\"text-align: right;\">"+ counted[6] + "</td>");
				if (admin || distributor || dealer)
					sb.append("<td style=\"text-align: right;\">"+ counted[0] + "</td>");
				
					
				sb.append("<td style=\"text-align: right;\">"+ vat_val + "</td>");

				sb.append("<td style=\"text-align: right;\">"+ counted[1] + "</td>");

				String commentclass = "large";

				if ((admin && !customer_order && !dealer_order && !customer_discount) || distributor) {
					//sb.append("<td style=\"text-align: right;\">"+ counted[2] + "</td>");
					sb.append("<td style=\"text-align: right;\">"+ counted[2] + "</td>");
					commentclass = "small1";
				} else if (dealer) commentclass ="small1";
				else if (customer) commentclass = "large";
				
				if (customer_order) {
					if (subscription)
						commentclass = "small1";
					else
						commentclass = "normal";
				}
				if (distributor) commentclass = "normal";
				
				if (!dealer_order && !customer_discount) {
					sb.append("<td><input class=\""+commentclass+"\" name=\"comment"+ String.valueOf(i)+"\" value=\""+ comment+"\" "+
							"onchange=\"javascript:document.forms[0].saveState.value='process/"+pagemap+"';document.forms[0].pageAction.value='"+ mod_comment_command+"';document.forms[0].pos.value='").append(String.valueOf(i)).append("';document.forms[0].submit();\">");
					sb.append("</td></tr>");
				}
			}
		}

		sb.append("<tr id=\"dataTableDataContent\">");
		if (admin) {
			
			if (!subscription) {
				if (dealer_order || customer_discount)
					sb.append("<td>&nbsp;</td><td colspan=\"10\">");
				else if (customer_order)
					sb.append("<td>&nbsp;</td><td colspan=\"8\">");
				else 
					sb.append("<td>&nbsp;</td><td colspan=\"9\">");
			}
			else {
				if (dealer_order || customer_discount)
					sb.append("<td>&nbsp;</td><td colspan=\"11\">");
				else if (customer_order)
					sb.append("<td>&nbsp;</td><td colspan=\"9\">");
				else 
					sb.append("<td>&nbsp;</td><td colspan=\"10\">");
			}
		} else if (distributor) {
			if (!subscription)
				sb.append("<td>&nbsp;</td><td colspan=\"8\">");
			else
				sb.append("<td>&nbsp;</td><td colspan=\"9\">");			
		} 
		else {
			if (dealer)
				sb.append("<td>&nbsp;</td><td colspan=\"8\">");
			else 
				sb.append("<td>&nbsp;</td><td colspan=\"6\">");
		}

		sb.append("<input class=\"small0\" name=\"art_id\" "+
		"maxlength=\"10\" tabindex=1 onChange=\"javascript:document.forms[0].saveState.value='process/"+pagemap+"';document.forms[0].pageAction.value='"+add_command+"';document.forms[0].submit();\">");
		sb.append("</td></tr>");

		sb.append("</table>");

		return sb.toString();
	}

	public static String getChecked(HttpSession session, Map m, String name ) {
		
		if (m == null) return "";
		String[] vals = (String[])m.get(name);
		if (vals != null && vals.length>0 && vals[0] != null && !vals[0].equals("")) return " checked";
		return "";
	}
	
	public static String generateStaticOrderDetailsRows(HttpSession session, String from) throws Exception {
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;

		boolean dealer = false;
		boolean dealer_order = false;
		boolean customer_order = false;
		
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		StringBuffer sb = new StringBuffer();

		Map orders = (Map)session.getAttribute(from);

		String level_id = (String)orders.get("ordering_level_id");
		if ("300".equals(level_id)) {
			dealer_order = true;
		} else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id))
			customer_order = true;
		
		
		String page,pagemap;
		String add_command;
		String mod_quantity_command;
		String mod_comment_command;
		String delete_command;

		if (from.equals("order_details_static")) {
			pagemap = "order_detail_static.jsp";
			page= pagemap;
		} 	else {
			pagemap = "new_order.jsp";
			page= pagemap;
			add_command = "new_orderadd";
			mod_quantity_command = "new_orderchange_quantity";
			mod_comment_command = "new_orderchange_comment";
			delete_command = "deleteneworderdetail";
		}

		if (orders!=null) {
			int count = 0;
			if (orders.get("count")!=null)
				count = ((Integer)orders.get("count")).intValue();

			for (int i = 0; i < count; i++)
			{
				Map order = (Map)orders.get(String.valueOf(i));
				if (order == null) continue;
				String id = ((String[])order.get("art_id"))[0];
				String name = ((String[])order.get("art_name"))[0];
				String quantity = ((String[])order.get("quantity"))[0];
				String bonus = ((String[])order.get("bonus"))[0];
				String brutto = ((String[])order.get("brutto"))[0];
				String netto = ((String[])order.get("netto"))[0];
				String vat_val = ((String[])order.get("vat_value"))[0];
				String comment = ((String[])order.get("comment"))[0];
				String trade = ((String[])order.get("trade_margin"))[0];
				String brutto_disc = null;
				String netto_disc = null;
				String discount_perc = null;
				String discount = null;
				String list = null;
				
				if (order.get("netto_disc")!=null)
					netto_disc = ((String[])order.get("netto_disc"))[0];
				if (order.get("brutto_disc")!=null)
					brutto_disc = ((String[])order.get("brutto_disc"))[0];
				if (order.get("discount_perc")!=null)
					discount_perc = ((String[])order.get("discount_perc"))[0];
				if (order.get("discount")!=null)
					discount = ((String[])order.get("discount"))[0];
				if (order.get("list")!=null)
					discount = ((String[])order.get("list"))[0];
				
				
				String[] counted = countValues(new String[] {netto, brutto, bonus, trade, netto_disc, brutto_disc, discount_perc, discount, list, vat_val}, quantity);

				if (new Float(counted[3]).floatValue() > 0 && dealer)
					counted[0] = counted[3];
				
				if (new Float(counted[4]).floatValue() > 0 && dealer)
					counted[1] = counted[4];				
				
				sb.append("<tr id=\"dataTableDataContent\">");

				sb.append("<td>&nbsp;</td>");

				sb.append("<td>"+id+"</td>");
				sb.append("<td>"+name+"</td>");
				sb.append("<td>"+ quantity +"</td>");
				
				if ((admin && dealer_order) || dealer)
					sb.append("<td style=\"text-align: right;\">"+ counted[5] + "</td>");
				
				if (admin || distributor || dealer)
					sb.append("<td style=\"text-align: right;\">"+ counted[0] + "</td>");
				sb.append("<td style=\"text-align: right;\">"+ vat_val + "</td>");
				sb.append("<td style=\"text-align: right;\">"+ counted[1] + "</td>");
				

				String commentclass = "large";

				if ((admin && !dealer_order && !customer_order) || distributor) {
					//sb.append("<td style=\"text-align: right;\">"+ counted[2] + "</td>");
					sb.append("<td style=\"text-align: right;\">"+ counted[2] + "</td>");
					commentclass = "small1";
				}

				sb.append("<td>"+ comment);
				sb.append("</td></tr>");
			}
		}
		sb.append("</table>");

		return sb.toString();
	}


	public static String[] countValues(String[] origs, String quantity) {
		String netto = origs[0]; if (netto.equals("")) netto = "0";
		String brutto = origs[1]; if (brutto.equals("")) brutto = "0";
		String bonus = origs[2]; if (bonus.equals("")) bonus = "0";
		String trade = origs[3]; if (trade.equals("")) trade = "0";
		
		String netto_disc = origs[4]; if (netto_disc==null || netto_disc.equals("")) netto_disc = "0";
		String brutto_disc = origs[5]; if (brutto_disc == null || brutto_disc.equals("")) brutto_disc = "0";
		String disc_perc = origs[6]; if (disc_perc == null || "".equals(disc_perc)) disc_perc = "0";
		String discount = origs[7]; if (discount == null || "".equals(discount)) discount = "0";
		String list = origs[8]; if (list == null || "".equals(list)) list = "0";
		String vat_val = origs[9]; if (vat_val == null || "".equals(vat_val)) vat_val = "0";

		
		double n = Double.parseDouble(netto);
		double n_disc = Double.parseDouble(netto_disc);
		BigDecimal br = new BigDecimal(brutto);
		BigDecimal br_disc = new BigDecimal(brutto_disc);
		double bo = Double.parseDouble(bonus);
		double t = Double.parseDouble(trade);
		double discp = Double.parseDouble(disc_perc);
		double disc = Double.parseDouble(discount);
		double l = Double.parseDouble(list);
		double vat = Double.parseDouble(vat_val);
		
		int q = Integer.parseInt(quantity);

		java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		nf.setGroupingUsed(false);

		java.text.NumberFormat nf3 = java.text.NumberFormat.getInstance(Locale.ENGLISH);
		nf3.setMinimumFractionDigits(3);
		nf3.setMaximumFractionDigits(3);
		nf3.setGroupingUsed(false);
		
		
		String[] ret = new String[8];

		ret[0] = nf.format(n*q);
		
		//ret[1] = nf.format(br.doubleValue()*q);
		ret[1] = nf.format(n * q + (n * q  * vat)*0.01);
		ret[2] = nf.format(bo*q);
		ret[3] = nf.format(n_disc*q);
		//ret[4] = nf.format(br_disc.doubleValue()*q);
		ret[4] = nf.format(n_disc * q + (n_disc * q  * vat)*0.01);
		ret[5] = nf.format(discp);
		ret[6] = nf.format(disc * q);
		ret[7] = nf.format(l * q);
		
		return ret;
	}

	public static double countNetto(HttpSession session, String from) throws Exception {
		double n = 0;
		Map m = (Map)session.getAttribute(from);
		int count = 0;

		if (m.get("count")!=null)
			count = ((Integer)m.get("count")).intValue();

		for (int i = 0; i<count; i++) {

			Map actual = (Map)m.get(String.valueOf(i));
			if (actual == null) continue;

			int q = 0;

			String quantity = ((String[])actual.get("quantity"))[0];

			try {
				q = Integer.parseInt(quantity);
			} catch (Exception e) {
				q = 0;
			}

			String ns = ((String[])actual.get("netto"))[0];

			double dnetto = Double.parseDouble(ns);

			n = n+dnetto*q;
		}		
		
		return n;
	}
	
	public static String[] countTotals(HttpSession session, String from, boolean discount_count, boolean firstOrder) throws Exception {
		Map m = (Map)session.getAttribute(from);
		
		boolean _new = false;
		if (from.indexOf("new")>-1)
			_new = true;
		
		String level_id = (String)m.get("ordering_level_id");
		boolean therapeut = false;
		boolean handler = false;
		boolean grossdealer = false;
		boolean customer = false;
		boolean apotheker = false;
		
		if ("300".equals(level_id) || "t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			therapeut = true;
		}
		else if ("350".equals(level_id)) {
			grossdealer = true;
		} else if ("330".equals(level_id)) {
			handler = true;
		} else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer = true;
		} else if ("370".equals(level_id)) {
			apotheker = true;
		}
			
		
		int count = 0;
		if (m.get("count")!=null)
			count = ((Integer)m.get("count")).intValue();


		java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		nf.setGroupingUsed(false);
		
		if ((therapeut || grossdealer || handler || customer || apotheker) && discount_count) {
			 
			int type = DiscountHelper.LEVEL_TYPE_BERATER;
			if (therapeut) 
				type = DiscountHelper.LEVEL_TYPE_THERAPEUT;
			else if (grossdealer || handler || apotheker)
				type = DiscountHelper.LEVEL_TYPE_GROSSHANDLER;
			else if (customer)
				type = DiscountHelper.LEVEL_TYPE_CUSTOMER;
			
			int lev = DiscountHelper.getLevel(countNetto(session, from), session, type);
			 
			 
			 Map discount = (Map)session.getAttribute("CURRENT_HANDLER_DISCOUNT");
			 Integer discount_level = (Integer)m.get("discount_level");
			 if (discount_level == null) {
				 discount_level = new Integer(0);
			 }

			 Logger logger = MainControl.logger;
			 logger.info("DEBUGI: " + discount_level + " and " + lev + " and " + count);
			 
			 
			// if (lev != discount_level.intValue()) {
			 if (true) {
				 
				 for (int i = 0; i<count; i++) {
					 	Float perc = (Float)discount.get(new Integer(lev));
					 	logger.info("DEBUGG: perc: "+perc);
					 	Map actual = (Map)m.get(String.valueOf(i));
						if (actual == null) continue;

						int q = 0;
						String quantity = ((String[])actual.get("quantity"))[0];

						try {
							q = Integer.parseInt(quantity);
						} catch (Exception e) {
							q = 0;
						}

						String ns = ((String[])actual.get("netto"))[0];
						String brs = ((String[])actual.get("brutto"))[0];
						String bos = ((String[])actual.get("bonus"))[0];
						
						double dnetto = Double.parseDouble(ns);
						BigDecimal dbrutto = new BigDecimal(brs);
						double dbonus = Double.parseDouble(bos);
						
						boolean counted = false;
						
						if (perc == null) perc = new Float(0);
						
						if (dbonus == 0) {
							perc = new Float(0);
						}
						else if (firstOrder) {
							String sd = (String)session.getAttribute("special_discount");
							if (!_new) sd = (String)session.getAttribute("loaded_special_discount");
							double sdDouble;
							try {
								sdDouble = Double.parseDouble(sd);
							} catch (Exception e) {
								sdDouble = 5;
							}
							perc = new Float(sdDouble);
						} else if (grossdealer) {
							String sd = (String)session.getAttribute("special_discount_grosshandler");
							if (!_new) sd = (String)session.getAttribute("loaded_special_discount_grosshandler");
							double sdDouble;
							try {
								sdDouble = Double.parseDouble(sd);
							} catch (Exception e) {
								sdDouble = 5;
							}
							perc = new Float(sdDouble);
						} else if (handler) {
							String sd = (String)session.getAttribute("special_discount_handler");
							if (!_new) sd = (String)session.getAttribute("loaded_special_discount_handler");
							double sdDouble;
							try {
								sdDouble = Double.parseDouble(sd);
							} catch (Exception e) {
								sdDouble = 0;
							}
							perc = new Float(sdDouble);
						} else if (apotheker) {
							String sd = (String)session.getAttribute("special_discount_apotheker");
							if (!_new) sd = (String)session.getAttribute("loaded_special_discount_apotheker");
							double sdDouble;
							try {
								sdDouble = Double.parseDouble(sd);
							} catch (Exception e) {
								sdDouble = 0;
							}
							perc = new Float(sdDouble);
						}else if (therapeut) {
							String sd = (String)session.getAttribute("special_added_discount");
							if (!_new) sd = (String)session.getAttribute("loaded_special_added_discount");
							double sdDouble;
							try {
								sdDouble = Double.parseDouble(sd);
							} catch (Exception e) {
								sdDouble = 0;
							}
							if (sdDouble != 0)
								counted = true;
							perc = perc + new Float(sdDouble);
						} else if (customer) {
							logger.info("customer processing");
							String sd = (String)session.getAttribute("special_discount_customer");
							if (!_new) sd = (String)session.getAttribute("loaded_special_discount_customer");
							double sdDouble;
							try {
								logger.info("customer special discount: " + sd);
								sdDouble = Double.parseDouble(sd);
							} catch (Exception e) {
								logger.info("Exception occured: " + e.getMessage());
								sdDouble = 0;
							}
							perc = new Float(sdDouble);
							
						}
							
						
						double dnetto_disc = dnetto * (100 - perc.floatValue()) / 100;
						BigDecimal dbrutto_disc = new BigDecimal(dbrutto.doubleValue() * (100 - perc.floatValue()) / 100);
						
						double ddisc = dnetto - dnetto_disc;
						
						if (lev == 0 && !firstOrder && !counted) {
							actual.remove("netto_disc");
							actual.remove("brutto_disc");
							actual.remove("discount_perc");
							actual.remove("discount");
							continue;
						}						
						
				  		actual.put("netto_disc", new String[] {nf.format(dnetto_disc)});
						actual.put("brutto_disc", new String[] {nf.format(dbrutto_disc)});
						actual.put("discount_perc", new String[] {nf.format(perc)});
						actual.put("discount", new String[] {nf.format(ddisc)});
						logger.info("DEBUGG: " + dnetto_disc + " bonus: "+dbonus);
				 }
				 //m.put("discount_perc", perc);
				 m.put("discount_level", new Integer(lev));
			 }
			 
		}
		
		String netto = "";
		String brutto = "";

		String bonus = "";
		String trade = "";
		String netto_disc = "";
		String brutto_disc = "";
		String list = "";
		String discount = "";

		double n = 0;
		BigDecimal br = new BigDecimal(0);

		double bo = 0;
		double t = 0;
		BigDecimal n_disc = new BigDecimal(0);
		BigDecimal br_disc = new BigDecimal(0);
		double list_d = 0;
		double disc_d = 0;
		
		for (int i = 0; i<count; i++) {

			Map actual = (Map)m.get(String.valueOf(i));
			if (actual == null) continue;

			int q = 0;

			String quantity = ((String[])actual.get("quantity"))[0];

			try {
				q = Integer.parseInt(quantity);
			} catch (Exception e) {
				q = 0;
			}

			String ns = ((String[])actual.get("netto"))[0];
			String brs = ((String[])actual.get("brutto"))[0];
			String bos = ((String[])actual.get("bonus"))[0];
			String ts = ((String[])actual.get("trade_margin"))[0];
			String vats = ((String[])actual.get("vat_value"))[0];

			double vat = Double.parseDouble(vats);
			
			String ds = "0";
			String ls = "0";
			
			if (actual.get("discount")!=null)
				ds = ((String[])actual.get("discount"))[0];
			
			if (actual.get("list")!=null) {
				ls = (((String[])actual.get("list"))[0]);
				MainControl.logger.info("list is : " + ls);
			}
			
			String ns_disc = "0";
			String brs_disc = "0";
			
			if (actual.get("netto_disc")!=null)
				ns_disc = ((String[])actual.get("netto_disc"))[0];
			else ns_disc = ns;
			
			if (actual.get("brutto_disc")!=null)
				brs_disc = ((String[])actual.get("brutto_disc"))[0];
			else brs_disc = brs;

			double dnetto = Double.parseDouble(ns);
			
			double act_list = Double.parseDouble(ls);
			double act_disc = Double.parseDouble(ds);
			
			BigDecimal dbrutto = new BigDecimal(brs);
			
			
			
			double dbonus = Double.parseDouble(bos);

			double dtrade = Double.parseDouble(ts);
			
			BigDecimal dnetto_disc = new BigDecimal(ns_disc);
			BigDecimal dbrutto_disc = new BigDecimal(brs_disc);

			n = n+dnetto*q;
			
			list_d = list_d + act_list*q;
			disc_d = disc_d + act_disc*q;
			
			//br = br.add(dbrutto.multiply(new BigDecimal(q)));
			BigDecimal toBruttoAdd = new BigDecimal(dnetto*q + (dnetto * q * vat)*0.01);
			
			br = br.add(toBruttoAdd.setScale(2, BigDecimal.ROUND_HALF_EVEN));
			
			bo = bo+dbonus*q;
			t = t+dtrade*q;
			
			n_disc = n_disc.add(dnetto_disc.multiply(new BigDecimal(q)));
			//br_disc = br_disc.add(dbrutto_disc.multiply(new BigDecimal(q)));
			
			BigDecimal toBruttoDiscAdd = new BigDecimal(dnetto_disc.doubleValue() * q + (dnetto_disc.doubleValue() * q * vat)*0.01);
			
			br_disc = br_disc.add(toBruttoDiscAdd.setScale(2, BigDecimal.ROUND_HALF_EVEN));
		}

		
		 
		netto=nf.format(n);
		brutto = nf.format(br);

		bonus = nf.format(bo);
		trade = nf.format(t);
		netto_disc = nf.format(n_disc);
		brutto_disc = nf.format(br_disc);
		
		list = nf.format(list_d);
		discount = nf.format(disc_d);
		
		return new String[] {netto, brutto, bonus, trade, netto_disc, brutto_disc, list, discount};
	}



	public static String generateMailTextTotalRow(PageContext pc, String from) throws Exception {
		HttpSession session = pc.getSession();

		Map m = (Map)session.getAttribute(from);
		
		String level_id = (String)m.get("ordering_level_id");
		
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;
		boolean dealer = false;
		boolean dealer_order = false;
		if ("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id))
			dealer_order = true;
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		String totalNetto = "";
		String totalBrutto = "";

		String totalBonus = "";
		String totalTradeMargin = "";
		String totalNetto_disc = "";
		String totalBrutto_disc = "";
		
		boolean firstorder = (session.getAttribute("new_fo")!=null || session.getAttribute("modify_fo")!=null);
		
		String[] values = countTotals(session, from, true, firstorder);

		totalNetto = values[0];
		totalBrutto = values[1];

		totalBonus = values[2];
		totalTradeMargin = values[3];
		totalNetto_disc = values[4];
		totalBrutto_disc = values[5];

		StringBuffer sb = new StringBuffer();
		sb.append("<table border=\"1\" cell-spacing=\"0\" style=\"width: auto;\"><tr>");
		if (admin || distributor) {
			sb.append("<td colspan=\"5\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td>"
			+"<td>"+(dealer_order?totalNetto_disc:totalNetto)+"</td>"
			+"<td>&nbsp;</td>"
			+"<td>"+ (dealer_order?totalBrutto_disc:totalBrutto) + "</td>"
			+"<td>"+ totalBonus+"</td><td>&nbsp;</td>");
		}
		else if (customer) {
			sb.append("<td colspan=\"5\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td>"+
					"<td>&nbsp;</td>"+
					"<td>"+totalBrutto_disc+"</td><td colspan=\"3\">&nbsp;</td>");
		}
		else if (dealer) {
			sb.append("<td colspan=\"5\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td>"+
					"<td>"+totalNetto_disc+"</td>"+
					"<td>&nbsp;</td>"+
					"<td>"+totalBrutto_disc+"</td><td colspan=\"3\">&nbsp;</td>");
		}
		
		sb.append("</tr>");
		
		return sb.toString();
	}

	public static String generateOrderTotalRow(PageContext pc, String from) throws Exception {

		HttpSession session = pc.getSession();

		Map m = (Map)session.getAttribute(from);
		

		
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;
		boolean dealer = false;
		
		boolean dealer_order = false;
		boolean customer_order = false;
		boolean customer_discount = false;
		
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		String level_id = (String)m.get("ordering_level_id");
		if ("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id))
			dealer_order = true;
		else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer_order = true;
			String sponsor = OrderHelper.getVal(session, from.startsWith("new")?"new_order.jsp":"order_detail.jsp", "sponsor");
			if ("0".equals(sponsor) || "43002857".equals(sponsor) || "43005029".equals(sponsor))
				customer_discount = true;
		}
		
		String totalNetto = "";
		String totalBrutto = "";
		String totalBonus = "";
		String totalTradeMargin = "";
		String totalNetto_disc = "";
		String totalBrutto_disc = "";		
		String totalList = "";
		String totalDisc = "";
		
		boolean firstorder = (session.getAttribute("new_fo")!=null || session.getAttribute("modify_fo")!=null);
		String[] values = countTotals(session, from, false, firstorder);
		boolean subscription = from.indexOf("abo")!=-1;
		totalNetto = values[0];
		totalBrutto = values[1];

		totalBonus = values[2];
		totalTradeMargin = values[3];
		
		totalNetto_disc = values[4];
		totalBrutto_disc = values[5];
		String totalNetto_spec = (!totalNetto.equals(totalNetto_disc)) ? totalNetto_disc: totalNetto;
		String totalBrutto_spec = (!totalBrutto.equals(totalBrutto_disc)) ? totalBrutto_disc : totalBrutto;
		
		totalList = values[6];
		totalDisc = values[7];
		

		StringBuffer sb = new StringBuffer();
		sb.append("<table id=\"dataTable\" style=\"table-layout:fixed; font-size:12px;\" width=\"840\">");
		if (distributor) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"60\">"+
					(subscription?"<col width=\"40\">":"")+
					"<col width=\"60\"><col width=\"60\"><col width=\"60\"><col width=\"70\">"+
					"<col width=\"210\">");
			sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\"><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td>&nbsp;</td><td>&nbsp;</td>"+
					(subscription?"<td>&nbsp;</td>":"")+
			"<td style=\"text-align: right;\">"+ totalNetto + "</td>"+
			"<td>&nbsp;</td>"+
			"<td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
			"<td style=\"text-align: right;\">"+ totalBonus + "</td>"+
			"<td>&nbsp;</td></tr>");
		} else if (admin) {

			if (dealer_order || customer_discount) {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"260\"><col width=\"60\"><col width=\"60\">"+
						(subscription?"<col width=\"40\">":"")+
						"<col width=\"60\"><col width=\"70\"><col width=\"60\"><col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\">");
				sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\">" +
				"<td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td colspan=\"2\">&nbsp;</td>" +
				"<td>&nbsp;</td>"+
				(subscription?"<td>&nbsp;</td>":"")+
				"<td style=\"text-align: right;\">"+totalList+"</td>"+
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+totalDisc+"</td>"+
				"<td style=\"text-align: right;\">"+ totalNetto_spec + "</td>"+
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+ totalBrutto_spec + "</td>");
				
			} else if (customer_order) {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"255\">"+"<col width=\"60\"><col width=\"60\">"+
						(subscription?"<col width=\"40\">":"")+
						"<col width=\"60\"><col width=\"60\"><col width=\"60\">" +
						
						"<col width=\"195\">");
				sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\"><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td colspan=\"2\">&nbsp;</td><td>&nbsp;</td>"+
						(subscription?"<td>&nbsp;</td>":"")+
						"<td style=\"text-align: right;\">"+ totalNetto + "</td>"+
						"<td>&nbsp;</td>"+
						"<td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
				
				"<td>&nbsp;</td></tr>");
			} else {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"255\">"+"<col width=\"60\"><col width=\"60\">"+
						(subscription?"<col width=\"40\">":"")+
						"<col width=\"60\"><col width=\"60\"><col width=\"60\">" +
						"<col width=\"60\">"+
						"<col width=\"135\">");
				sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\"><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td colspan=\"2\">&nbsp;</td><td>&nbsp;</td>"+
						(subscription?"<td>&nbsp;</td>":"")+
						"<td style=\"text-align: right;\">"+ totalNetto + "</td>"+
						"<td>&nbsp;</td>"+
						"<td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
				
				"<td style=\"text-align: right;\">"+ totalBonus + "</td>"+
				"<td>&nbsp;</td></tr>");
			}

		}
		else if (customer) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"60\">"+
					(subscription?"<col width=\"40\">":"")+
			"<col width=\"60\"><col width=\"60\"><col width=\"340\">");
			sb.append("<tr><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td>&nbsp;</td><td>&nbsp;</td>"+
					(subscription?"<td>&nbsp;</td>":"")+
			"<td>&nbsp;</td><td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
			"<td>&nbsp;</td></tr>");
		} else if (dealer) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"70\">"+
					(subscription?"<col width=\"40\">":"")+
			"<col width=\"80\"><col width=\"80\"><col width=\"70\"><col width=\"70\"><col width=\"150\">");
			sb.append("<tr><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td>&nbsp;</td><td>&nbsp;</td>"+
					(subscription?"<td>&nbsp;</td>":"")+
					
					"<td style=\"text-align: right;\">&nbsp;</td>"+
					"<td style=\"text-align: right;\">"+ totalNetto_spec + "</td>"+
					"<td>&nbsp;</td>"+
					"<td style=\"text-align: right;\">"+ totalBrutto_spec + "</td>"+
			"<td>&nbsp;</td></tr>");
			
		}

		sb.append("</table>");


			sb.append("<input type=\"hidden\" name=\"total_netto\" value=\""+ totalNetto+"\">");
			sb.append("<input type=\"hidden\" name=\"total_bonus\" value=\""+ totalBonus+"\">");
			sb.append("<input type=\"hidden\" name=\"total_trade_margin\" value=\""+ totalTradeMargin+"\">");
			sb.append("<input type=\"hidden\" name=\"total_brutto\" value=\""+ totalBrutto+"\">");

			sb.append("<input type=\"hidden\" name=\"total_netto_trader\" value=\""+ totalNetto_disc+"\">");
			sb.append("<input type=\"hidden\" name=\"total_brutto_trader\" value=\""+ totalBrutto_disc+"\">");


		return sb.toString();
	}

	public static String generateOrderUpperTotalRow(PageContext pc, String from) throws Exception {

		HttpSession session = pc.getSession();

		Map m = (Map)session.getAttribute(from);
		
		String level_id = (String)m.get("ordering_level_id");
		
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;
		boolean dealer = false;
		boolean dealer_order = false;
		boolean customer_order = false;
		boolean customer_discount = false;
		
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		if ("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id))
			dealer_order = true;
		else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer_order = true;
			String sponsor = OrderHelper.getVal(session, from.startsWith("new")?"new_order.jsp":"order_detail.jsp", "sponsor");
			if ("0".equals(sponsor) || "43002857".equals(sponsor) || "43005029".equals(sponsor))
				customer_discount = true;
		}
		
		
		String totalNetto = "";
		String totalBrutto = "";
		String totalBonus = "";
		String totalTradeMargin = "";
		String totalNetto_disc = "";
		String totalBrutto_disc = "";
		String totalList = "";
		String totalDisc = "";

		boolean firstorder = (session.getAttribute("new_fo")!=null || session.getAttribute("modify_fo")!=null);
		String[] values = countTotals(session, from, true, firstorder);

		totalNetto = values[0];
		totalBrutto = values[1];

		totalBonus = values[2];
		totalTradeMargin = values[3];
		totalNetto_disc = values[4];
		totalBrutto_disc = values[5];
		
		totalList = values[6];
		totalDisc = values[7];
		
		String totalNetto_spec = (!totalNetto.equals(totalNetto_disc)) ? totalNetto_disc : totalNetto;
		String totalBrutto_spec = (!totalBrutto.equals(totalBrutto_disc)) ? totalBrutto_disc : totalBrutto;
		
		StringBuffer sb = new StringBuffer();
		sb.append("<table id=\"dataTable\" style=\"table-layout:fixed; font-size:12px;\" width=\"800\">");
		if (distributor) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"60\">"+
					"<col width=\"60\"><col width=\"60\"><col width=\"60\"><col width=\"70\">"+
					"<col width=\"210\">");
			sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\"><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td>&nbsp;</td><td>&nbsp;</td>"+
			"<td style=\"text-align: right;\">"+ totalNetto + "</td>"+
			"<td>&nbsp;</td>"+
			"<td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
			"<td style=\"text-align: right;\">"+ totalBonus + "</td>"+
			"<td>&nbsp;</td></tr>");
		} else if (admin) {
			
			if (dealer_order || customer_discount) {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"260\"><col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\"><col width=\"70\"><col width=\"60\"><col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\">");
				sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\">" +
				"<td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td colspan=\"2\">&nbsp;</td>" +
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+totalList+"</td>"+
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+totalDisc+"</td>"+
				"<td style=\"text-align: right;\">"+ totalNetto_spec + "</td>"+
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+ totalBrutto_spec + "</td>");
				
			} else if (customer_order) {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"255\">"+"<col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\"><col width=\"60\"><col width=\"60\">" +
						
						"<col width=\"195\">");
				sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\"><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td colspan=\"2\">&nbsp;</td><td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+ totalNetto + "</td>"+
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
				"<td>&nbsp;</td></tr>");
			} else {
				sb.append("<col width=\"30\"><col width=\"70\">"+"<col width=\"255\">"+"<col width=\"60\"><col width=\"60\">"+
						"<col width=\"60\"><col width=\"60\"><col width=\"60\">" +
						"<col width=\"60\">"+
						"<col width=\"135\">");
				sb.append("<tr style=\"padding-left: 0px;padding-right: 0px;\"><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td colspan=\"2\">&nbsp;</td><td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+ totalNetto + "</td>"+
				"<td>&nbsp;</td>"+
				"<td style=\"text-align: right;\">"+ totalBrutto + "</td>"+
				"<td style=\"text-align: right;\">"+ totalBonus + "</td>"+
				"<td>&nbsp;</td></tr>");
			}
			
		}
		else if (customer) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"60\">"+
			"<col width=\"60\"><col width=\"60\"><col width=\"340\">");
			sb.append("<tr><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td>&nbsp;</td><td>&nbsp;</td>"+
			"<td>&nbsp;</td><td style=\"text-align: right;\">" + totalBrutto + "</td>"+
			"<td>&nbsp;</td></tr>");
		} else if (dealer) {
			sb.append("<col width=\"30\"><col width=\"70\"><col width=\"230\"><col width=\"70\">"+
			"<col width=\"80\"><col width=\"80\"><col width=\"70\"><col width=\"70\"><col width=\"150\">");
			sb.append("<tr><td colspan=\"2\">"+LocaleSupport.getLocalizedMessage(pc, "TOTAL")+":</td><td>&nbsp;</td><td>&nbsp;</td>"+
					"<td style=\"text-align: right;\">&nbsp;</td>"+
					"<td style=\"text-align: right;\">"+ totalNetto_spec + "</td>"+
			"<td>&nbsp;</td>"+
			"<td style=\"text-align: right;\">"+ totalBrutto_spec + "</td>"+
			"<td>&nbsp;</td></tr>");
		}

		sb.append("</table>");

		return sb.toString();
	}


    public static boolean checkOrderID(HttpSession session, String idstr) throws Exception {
		Logger logger = MainControl.logger;


		long id = 0;
		try {
			id = Long.parseLong(idstr);
		} catch (Exception e) {

			return false;
		}

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


		ObjectSearch os = new ObjectSearch("order_header", new String[] {"id"});
    	os.setCondition("id = ?");

    	List result = os.search(new Object[] {new Long(id)});

    	if (result.size()==0) return false;

    	/*if (admin || specialAgent) return true;

    	if (distributor) {
    		String current_user = (String)session.getAttribute("USER_LOGGED_ID");
    		PersistableObject po = (PersistableObject)result.get(0);

    		if (current_user.equals(po.getString("ordered_by", "")))
    			return true;
    		else return false;
    	}
    	*/

    	return true;
    }

    public static void checkAndRepairOrder(Session session, Long id) {
        Transaction tx = null;
        Logger logger = MainControl.logger;
        try {
		    tx = session.beginTransaction();
		    Connection conn = session.connection();
		    ObjectSearch os = new ObjectSearch();
		    List l1 = os.search(conn, "select {fn check_and_repair_order(?)} as repaired",new Object[]{id});
		    PersistableObject po = (PersistableObject) l1.get(0);
		    Boolean repaired = (Boolean) po.get("repaired");
		    tx.commit();
		    if (repaired.booleanValue())
			    logger.warn("!!!!Order "+id+" was in an inconsistent form. Repaired.");
			else
			    logger.info("Checking the sums of order "+id+" is ok. The totals match");

		} catch (Exception e) {
		    MainControl.logger.warn("error occured when checking ths sums of order. Ignoring! ",e);
		    if (tx!=null)
		       try {
		        tx.rollback();
		       } catch(Exception e1){}
		}


    }

	public static String addOrder(PageContext pc, Logger logger, boolean mail)  throws Exception {
	 HttpSession session = pc.getSession();
	 Map jspMap = (Map)session.getAttribute("new_order.jsp");
	 
	 String ordered_by = ((String[])jspMap.get("ordered_by"))[0];
	 
	 logger.info("ordered_by"+ordered_by);
	 
	 boolean[] rights = getRights(session, null, ((String[])jspMap.get("ordered_by"))[0], MASK_CREATE );
	 if (!rights[INDEX_CREATE])
		 throw new EvolutionException(LocaleSupport.getLocalizedMessage(pc, "NO_RIGHT"));

//		for (Object key : jspMap.keySet()) {
//			String keyStr = (String)key;
//			Object val = jspMap.get(key);
//			if (val instanceof String[]) {
//				String[] values = (String[])val;
//				String value = "";
//				try {
//					value = new String(values[0].getBytes(), "ISO-8859-2");
//				} catch (Exception e) {
//					value = "encoding not supported!";
//				}
//				jspMap.put(keyStr, new String[] {value});
//			}
//			
//		}
	 
	 Transaction tx = null;
	 Exception lastException = null;
	 for (int j=0; j<3; j++) {
	   try {
	       org.hibernate.Session hibernateSession = HibernateUtil.currentSession();
	       tx= hibernateSession.beginTransaction();
	       Connection conn = hibernateSession.connection();
		     boolean admin = false;
			boolean distributor = false;
			boolean customer = false;
			if	(session.getAttribute("admin")!=null) admin = true;
			if	(session.getAttribute("customer")!=null) customer = true;
			if	(session.getAttribute("distributor")!=null) distributor = true;
			
			Map orders = (Map)session.getAttribute("new_order_details");
			
			String level_id = (String)orders.get("ordering_level_id");
			String level_subtype_id = (String)orders.get("ordering_level_subtype_id"); 
			
			//boolean dealer = false;
			//if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {

			//order header



			String totalBrutto = ((String[])jspMap.get("total_brutto"))[0];

			double tb = 0;

			try {
				tb = Double.parseDouble(totalBrutto);
			} catch (Exception ex) {
				throw new EvolutionException(LocaleSupport.getLocalizedMessage(pc, "TOTAL_BRUTTO_IS_WRONG")+": "+totalBrutto);
			}

//			if (tb < 0) {
//				session.setAttribute("new_order_error", "Total Brutto < 0");
//				return "";
//			}

			jspMap.put("order_created_by", new String[] {(String)session.getAttribute("USER_LOGGED_ID")});

			java.sql.Date thisDate = new java.sql.Date(System.currentTimeMillis());

			jspMap.put("order_date", new String[] {FormHelper.formatSQLDate(thisDate)});


			jspMap.put("order_status_id", new String[] {"10"});
			jspMap.put("store_descr", new String[] {"Villach"});



			String ot = "3";

			if (distributor || customer) ot = "2";

			jspMap.put("order_type", new String[] {ot});


			String pay_method_id = ((String[])jspMap.get("pay_method_id"))[0];
			if ("1".equals(pay_method_id) || "2".equals(pay_method_id)) {
				String acc_id = "";
				if ("1".equals(pay_method_id))
					acc_id = ((String[])jspMap.get("account_id_1"))[0];
				if ("2".equals(pay_method_id))
					acc_id = ((String[])jspMap.get("account_id_2"))[0];
				jspMap.put("account_id", new String[] {acc_id});
			}

			if (!"3".equals(pay_method_id) && !"4".equals(pay_method_id) && !"6".equals(pay_method_id)) {
				jspMap.put("bonus_date", new String[] {FormHelper.formatSQLDate(thisDate)});
			}


			PersistableObject po = new PersistableObject("payment_method", "id");
			po.set("id", new Integer(pay_method_id));

			try {
				po.load(conn);
				jspMap.put("pay_method_descr", new String[] {po.getString("descr", "")});
			} catch (Exception e) {

			}



			SuperPO spo = new SuperPO("order_header", logger);

			boolean fo = session.getAttribute("new_fo")!=null;
			
			spo.setPOColumn("first_order", new Boolean(fo));
			
			if ("350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id)) {
				try {
					int val = Integer.parseInt(((String[])jspMap.get("new_sconto_days"))[0]);
					spo.setPOColumn("sconto_days", new Integer(val));
				} catch (Exception e) {
					spo.setPOColumn("sconto_days", new Integer(0));
				}
			} else {
				if ("6".equals(pay_method_id)) {
					try {
						int val = Integer.parseInt(((String[])jspMap.get(fo?"new_fo_sconto_days":"new_sconto_days"))[0]);
						spo.setPOColumn("sconto_days", new Integer(val));
					} catch (Exception e) {
						spo.setPOColumn("sconto_days", new Integer(0));
					}
				}
			}
			
			if ("350".equals(level_id)) {
				try {
					double val = Double.parseDouble((String)session.getAttribute("special_discount_grosshandler"));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
			} else if ("330".equals(level_id)) {
				try {
					double val = Double.parseDouble((String)session.getAttribute("special_discount_handler"));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
			} else if ("370".equals(level_id)) {
				try {
					double val = Double.parseDouble((String)session.getAttribute("special_discount_apotheker"));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
			}
			else if (session.getAttribute("special_discount") !=null) {
				try {
					double val = Double.parseDouble((String)session.getAttribute("special_discount"));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
				
			} else if (session.getAttribute("special_added_discount") !=null) {
				try {
					double val = Double.parseDouble((String)session.getAttribute("special_added_discount"));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
				
			} else if (session.getAttribute("special_discount_customer")!=null && ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id))) {
				try {
					double val = Double.parseDouble((String)session.getAttribute("special_discount_customer"));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
			}
			
			

			
			spo.addMap(jspMap);

			logger.info("level_id: " + level_id);
			logger.info("level_subtype_id: " + level_subtype_id);
			
			spo.setColumn("orderer_level_id", level_id);
			spo.setColumn("orderer_level_subtype_id", level_subtype_id);
			
			spo.insert(conn);

			ObjectSearch last = new ObjectSearch();
			List l = last.search(conn,"select {fn currval('seq_order_header')}");
			PersistableObject currvalRow = (PersistableObject) l.get(0);

			Long newid = (Long) currvalRow.get("currval");

			String orderid = String.valueOf(newid);


			//order details
			

			int count = 0;

			try {
				count = ((Integer)orders.get("count")).intValue();
			} catch (Exception e) {
				logger.warn("count cannot be achieved fromn order_details");

				throw new EvolutionException(LocaleSupport.getLocalizedMessage(pc, "INCONSISTENCE_ERROR"));
			}

			for (int i = 0; i<count; i++) {
				SuperPO act = new SuperPO("order_detail", logger);
				Map a = (Map)orders.get(String.valueOf(i));
				if (a==null) continue;
				act.addMap(a);
				act.setColumn("order_id", orderid);
				act.setColumn("art_position", String.valueOf(i));
				if (a.get("netto_disc")!=null) {
					String[] fff = (String[])a.get("netto_disc");
					if (fff!=null && fff.length > 0)
						act.setColumn("netto_trader", fff[0]);
				} else {
					String[] fff = (String[])a.get("netto");
					if (fff!=null && fff.length > 0)
						act.setColumn("netto_trader", fff[0]);
				}
					
				if (a.get("brutto_disc")!=null) {
					String[] fff = (String[])a.get("brutto_disc");
					if (fff!=null && fff.length > 0)
						act.setColumn("brutto_trader", fff[0]);
				} else {
					String[] fff = (String[])a.get("brutto");
					if (fff!=null && fff.length > 0)
						act.setColumn("brutto_trader", fff[0]);
				}

				act.insert(conn);
			}
			tx.commit();


			checkAndRepairOrder(hibernateSession, newid);



			HibernateUtil.closeSession();


			if (ot.equals("2") || mail) {
				logger.info("in");
				try {
					MyMailSender mms = new MyMailSender(logger);
					String email = getEmail(ordered_by);
					
						
					logger.info("email: "+email);
					if (!email.equals("") && email.length()>3 && email.indexOf("@")!=-1) {
						String mailText = getMailText(orderid, pc, jspMap, orders, true, logger);
						logger.info("mailText got successfully");
						mms.send(email, orderid, mailText);
					}
					
					
				} catch (Exception e) {
					logger.info("error");
					logger.warn("Message couldn't delivered to the recipients: "+session.getAttribute("USER_LOGGED_ID")+" order id: "+orderid+" error: "+e.getMessage());
				}
			}
			
			if (session.getAttribute("new_fo")!=null)
				session.removeAttribute("new_fo");
			if (session.getAttribute("special_discount") != null)
				session.removeAttribute("special_discount");
			if (session.getAttribute("special_added_discount") != null)
				session.removeAttribute("special_added_discount");
			if (session.getAttribute("special_discount_customer") != null)
				session.removeAttribute("special_discount_customer");
			
			return orderid;
	   } catch (Exception ex) {
	       lastException =ex;


	       try {
	           if (tx!=null)
	            tx.rollback();
	        HibernateUtil.closeSession();
	       } catch (Exception e) {}
	       if (ex instanceof EvolutionException) throw ex;
	       logger.error("Error occuring when creating the order",ex);
		    if (j<2) logger.info("Trying to fix it, executing it one more time");


	   }
	 }


	 throw lastException;
	}

	private static String part(PageContext pc, String header, String key, Map jsp) {
		StringBuffer sb = new StringBuffer(LocaleSupport.getLocalizedMessage(pc, header));
		String possible = part0(jsp, key);		
		sb.append(": "+possible);
		sb.append("<br>");
		return sb.toString();
	} 

	private static String part(PageContext pc, String header, String value) {
		StringBuffer sb = new StringBuffer(LocaleSupport.getLocalizedMessage(pc, header));
		sb.append(": "+value);
		sb.append("<br>");
		return sb.toString();		
	}

	private static String part(PageContext pc, String header, String[] values) {
		StringBuffer sb = new StringBuffer(LocaleSupport.getLocalizedMessage(pc, header));
		sb.append(": ");
		for (int i=0; i<values.length; i++)
			sb.append(values[i]);
		sb.append("<br>");
		return sb.toString();		
	}	

	private static String part0(Map jsp, String key) {
		String possible = "";
		try {
			possible = ((String[])jsp.get(key))[0];
		} catch (Exception e) {
			
		}
		return possible;
	}

	public static String getTotalBrutto(PageContext pc, String from) throws Exception {
		HttpSession session = pc.getSession();

		Map m = (Map)session.getAttribute(from);
		
		String level_id = (String)m.get("ordering_level_id");		
		
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		boolean customer_order = false;
		boolean customer_discount = false;
		
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;
		boolean dealer = false;
		if ("t".equals(session.getAttribute("USER_LOGGED_TYPE"))) {
			dealer = true;
			distributor = false;
		}
		
		String totalNetto = "";
		String totalBrutto = "";
		String totalBonus = "";
		String totalTradeMargin = "";
		String totalNetto_disc = "";
		String totalBrutto_disc = "";

		boolean firstorder = (session.getAttribute("new_fo")!=null || session.getAttribute("modify_fo")!=null);
		String[] values = countTotals(session, from, false, firstorder);

		totalNetto = values[0];
		totalBrutto = values[1];

		totalBonus = values[2];
		totalTradeMargin = values[3];
		totalNetto_disc = values[4];
		totalBrutto_disc = values[5];
		
		if ("300".equals(level_id) || "350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id))
			dealer = true;
		else if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
			customer_order = true;
			String sponsor = OrderHelper.getVal(session, from.startsWith("new")?"new_order.jsp":"order_detail.jsp", "sponsor");
			if (("0".equals(sponsor) || "43002857".equals(sponsor) || "43005029".equals(sponsor)) && admin)
				customer_discount = true;
		}
		
		return (dealer || customer_discount)?totalBrutto_disc:totalBrutto;
		
	}	
	
	private static String getMailText(String orderid, PageContext pc, Map jsp, Map details, boolean new_, Logger logger) throws Exception {
		logger.info("1");
		StringBuffer sb = new StringBuffer();
		sb.append("<html><body font-family=\"courier\">");
		sb.append(LocaleSupport.getLocalizedMessage(pc, "ORDER_MAIL_HEADER0")+"<br><br>");
		sb.append(LocaleSupport.getLocalizedMessage(pc, "ORDER_MAIL_HEADER"));
		sb.append("<br><br>");
		logger.info("2");
		sb.append(part(pc, "ORDER_NR2", orderid));
		sb.append(part(pc, "ROOT_ID", "ordered_by", jsp));
		sb.append(part(pc, "DISTRIBUTOR_TYPE", "distr_type", jsp));
		sb.append(part(pc, "SPONSOR", "sponsor", jsp));
		sb.append(part(pc, "TEL", "tel", jsp));
		sb.append(part(pc, "DELIVERY_LEVEL_ADDRESS", "delivery_title", jsp));
		logger.info("3");
		sb.append(part(pc, "DELIVERY_NAME", "delivery_name", jsp));
		sb.append(part(pc, "DELIVERY_ADDRESS", 
		  new String[] {part0(jsp,"delivery_country_id")+"-", 
		  				part0(jsp,"delivery_postcode")+", ", 
		  				part0(jsp,"delivery_city")+", ", 
		  				part0(jsp,"delivery_street")}));
		logger.info("4");
		sb.append(part(pc, "BILLING_LEVEL_ADDRESS", "billing_title", jsp));
		sb.append(part(pc, "BILLING_NAME", "billing_name", jsp));
		sb.append(part(pc, "BILLING_ADDRESS", 
		  new String[] {part0(jsp,"billing_country_id")+"-", 
						part0(jsp,"billing_postcode")+", ", 
						part0(jsp,"billing_city")+", ", 
						part0(jsp,"billing_street")}));
		logger.info("5");
		sb.append(part(pc, "PAYMENT_METHOD", getPaymentOption(pc, new_?"new_order.jsp":"order_detail.jsp")));
		sb.append(part(pc, "SHIPPING_TYPE", getShippingOption(pc, new_?"new_order.jsp":"order_detail.jsp")));						
		sb.append(part(pc, "COMMENT", "comment", jsp));
		
		logger.info("6");
		sb.append("<br>");
		
		logger.info("7");
		sb.append(generateMailTextTotalRow(pc, new_?"new_order_details":"order_details"));

		logger.info("8");
		sb.append(generateMailDetailsHeader(pc));
		logger.info("9");
		sb.append(generateMailDetailsRows(pc.getSession(), new_?"new_order_details":"order_details"));

		logger.info("10");
		
		sb.append("<br>");
		//thanks to
		sb.append(LocaleSupport.getLocalizedMessage(pc, "ORDER_MAIL_HEADER2"));
		sb.append("<br>");
		
		String paymentMethodId = getPaymentMethod(pc, new_?"new_order.jsp":"order_detail.jsp");
		String line1 = "ORDER_MAIL_BRUTTO_LINE_NN";
		String line2 = "ORDER_MAIL_BRUTTO_LINE2_NN";
		
		if ("1".equals(paymentMethodId)) {
			line1 = "ORDER_MAIL_BRUTTO_LINE_BA";
			line2 = "ORDER_MAIL_BRUTTO_LINE2_BA";			
		} else if ("2".equals(paymentMethodId)) {
			line1 = "ORDER_MAIL_BRUTTO_LINE_CC";
			line2 = "ORDER_MAIL_BRUTTO_LINE2_CC";						
		} else if ("4".equals(paymentMethodId)) {
			line1 = "ORDER_MAIL_BRUTTO_LINE_VA";
			line2 = "ORDER_MAIL_BRUTTO_LINE2_VA";						
		} else if ("6".equals(paymentMethodId)) {
			line1 = "ORDER_MAIL_BRUTTO_LINE_ES";
			line2 = "ORDER_MAIL_BRUTTO_LINE2_ES";						
		}
		
		sb.append(LocaleSupport.getLocalizedMessage(pc, line1));
		sb.append(" " + getTotalBrutto(pc, new_?"new_order_details":"order_details")+" ");
		sb.append(LocaleSupport.getLocalizedMessage(pc, line2));
		sb.append("<br><br>");
		
		sb.append(LocaleSupport.getLocalizedMessage(pc, "ORDER_MAIL_OSTER"));
		
		
		sb.append("<br>");

		sb.append("</body></html>");
		
		logger.info("11");
		
		return sb.toString();
	}


	public static boolean modifyOrder(PageContext pc, Logger logger, boolean mail) throws Exception {
		HttpSession session = pc.getSession();
		Map jspMap = (Map)session.getAttribute("order_detail.jsp");

		String totalBrutto = ((String[])jspMap.get("total_brutto"))[0];

//		for (Object key : jspMap.keySet()) {
//			String keyStr = (String)key;
//			Object val = jspMap.get(key);
//			if (val instanceof String[]) {
//				String[] values = (String[])val;
//				String value = "";
//				try {
//					value = new String(values[0].getBytes(), "ISO-8859-2");
//				} catch (Exception e) {
//					value = "encoding not supported!";
//				}
//				jspMap.put(keyStr, new String[] {value});
//			}
//			
//		}
		
		Transaction tx = null;
		try {
			double tb = 0;
			Session hibernateSession = HibernateUtil.currentSession();
			tx= hibernateSession.beginTransaction();
			Connection conn = hibernateSession.connection();

			try {
				tb = Double.parseDouble(totalBrutto);
			} catch (Exception ex) {
				throw new EvolutionException(LocaleSupport.getLocalizedMessage(pc, "TOTAL_BRUTTO_IS_WRONG")+": "+totalBrutto);
			}

//			if (tb < 0) {
//				session.setAttribute("order_error", LocaleSupport.getLocalizedMessage(pc, "TOTAL_BRUTTO_LESS_THAN_ZERO"));
//				return false;
//			}


			//order details
			Map orders = (Map)session.getAttribute("order_details");
			String level_id = (String)orders.get("ordering_level_id");
			String level_subtype_id = (String)orders.get("ordering_level_subtype_id");
			
			int count = 0;

			String orderid = (String)session.getAttribute("CURRENT_ORDER_ID");

			try {
				count = ((Integer)orders.get("count")).intValue();
			} catch (Exception e) {

				logger.warn("count cannot be achieved from order_details");
				throw new EvolutionException(LocaleSupport.getLocalizedMessage(pc, "INCONSISTENCE_ERROR"));
			}

			ObjectSearch os = new ObjectSearch("order_detail", new String[] {"order_id", "art_position"});

			os.setCondition("order_id = ?");

			List toDelete = os.search(conn, new Object[] {new Integer(orderid)});

			for (int z = 0; z<toDelete.size(); z++) {
				PersistableObject del = (PersistableObject)toDelete.get(z);
				del.delete(conn);
			}

			for (int i = 0; i<count; i++) {
				SuperPO act = new SuperPO("order_detail", logger);
				Map a = (Map)orders.get(String.valueOf(i));
				if (a==null) continue;
				act.addMap(a);
				act.setColumn("order_id", orderid);
				act.setColumn("art_position", String.valueOf(i));
				if (a.get("netto_disc")!=null) {
					String[] fff = (String[])a.get("netto_disc");
					if (fff!=null && fff.length > 0)
						act.setColumn("netto_trader", fff[0]);
				} else {
					String[] fff = (String[])a.get("netto");
					if (fff!=null && fff.length > 0)
						act.setColumn("netto_trader", fff[0]);
				}
				if (a.get("brutto_disc")!=null) {
					String[] fff = (String[])a.get("brutto_disc");
					if (fff!=null && fff.length > 0)
						act.setColumn("brutto_trader", fff[0]);
				} else {
					String[] fff = (String[])a.get("brutto");
					if (fff!=null && fff.length > 0)
						act.setColumn("brutto_trader", fff[0]);
				}
				act.insert(conn);
			}

			//order header


			String pay_method_id = ((String[])jspMap.get("pay_method_id"))[0];
			if ("1".equals(pay_method_id) || "2".equals(pay_method_id)) {
				String acc_id = "";
				if ("1".equals(pay_method_id))
					acc_id = ((String[])jspMap.get("account_id_1"))[0];
				if ("2".equals(pay_method_id))
					acc_id = ((String[])jspMap.get("account_id_2"))[0];
				jspMap.put("account_id", new String[] {acc_id});
			}

			jspMap.put("id", new String[] {orderid});
			jspMap.put("order_created_by", new String[] {(String)session.getAttribute("USER_LOGGED_ID")});




			PersistableObject po = new PersistableObject("payment_method", "id");
			po.set("id", new Integer(pay_method_id));

			try {
				po.load(conn);

				jspMap.put("pay_method_descr", new String[] {po.getString("descr", "")});


			} catch (Exception e) {
				logger.warn("payment description cannot be loaded: id: "+pay_method_id);
			}

			SuperPO spo = new SuperPO("order_header", logger);
			spo.setColumn("id", (String)session.getAttribute("CURRENT_ORDER_ID"));
			spo.load(conn);

			Integer old_pmi = (Integer)spo.getPOColumn("pay_method_id");
			
			if ("350".equals(level_id) || "330".equals(level_id) || "370".equals(level_id)) {
				try {
					String attr = "330".equals(level_id) ? "loaded_special_discount_handler": ("350".equals(level_id) ? "loaded_special_discount_grosshandler" : "loaded_special_discount_apotheker");
					double val = Double.parseDouble((String)session.getAttribute(attr));
					spo.setPOColumn("discount_rate", new BigDecimal(val));
				} catch (Exception e) {
					spo.setPOColumn("discount_rate", new BigDecimal(0));
				}
				
				try {
					int val = Integer.parseInt(((String[])jspMap.get("modify_sconto_days"))[0]);
					spo.setPOColumn("sconto_days", new Integer(val));
				} catch (Exception e) {
					spo.setPOColumn("sconto_days", new Integer(0));
				}

			} else {
				if (session.getAttribute("loaded_special_discount") !=null) {
					try {
						double val = Double.parseDouble((String)session.getAttribute("loaded_special_discount"));
						spo.setPOColumn("discount_rate", new BigDecimal(val));
					} catch (Exception e) {
						spo.setPOColumn("discount_rate", new BigDecimal(0));
					}
					session.removeAttribute("loaded_special_discount");
				}
				if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id)) {
					if (session.getAttribute("loaded_special_discount_customer") != null) {
						try {
							double val = Double.parseDouble((String)session.getAttribute("loaded_special_discount_customer"));
							spo.setPOColumn("discount_rate", new BigDecimal(val));
						} catch (Exception e) {
							spo.setPOColumn("discount_rate", new BigDecimal(0));
						}
					}
				}
				if (session.getAttribute("loaded_special_added_discount") !=null) {
					try {
						logger.info("");
						double val = Double.parseDouble((String)session.getAttribute("loaded_special_added_discount"));
						spo.setPOColumn("discount_rate", new BigDecimal(val));
					} catch (Exception e) {
						spo.setPOColumn("discount_rate", new BigDecimal(0));
					}
					session.removeAttribute("loaded_special_added_discount");
				}
				
				if ("6".equals(pay_method_id)) {
					boolean fo = session.getAttribute("modify_fo")!=null;
					try {
						int val = Integer.parseInt(((String[])jspMap.get(fo?"modify_fo_sconto_days":"modify_sconto_days"))[0]);
						spo.setPOColumn("sconto_days", new Integer(val));
					} catch (Exception e) {
						spo.setPOColumn("sconto_days", new Integer(0));
					}

				}
			}
			
			spo.addMap(jspMap);

			Map rv = spo.getMain();

			if (!"3".equals(pay_method_id) && !"4".equals(pay_method_id) && !"6".equals(pay_method_id)) {

				java.sql.Date od = (java.sql.Date)rv.get("order_date");

				rv.put("bonus_date", od);

			} else {
				if (("4".equals(pay_method_id) && old_pmi.intValue() != 4) ||
					("3".equals(pay_method_id) && old_pmi.intValue() != 3) ||
					("6".equals(pay_method_id) && old_pmi.intValue() != 6))
						{
					rv.put("bonus_date", null);
					rv.put("payment_status", new Boolean(false));
				}
			}


			spo.update(conn);
			tx.commit();

			Long oid = new Long(orderid);
			checkAndRepairOrder(hibernateSession, oid);

			HibernateUtil.closeSession();
			
			String ordered_by = ((String[])jspMap.get("ordered_by"))[0];
			
			if (mail) {
				logger.info("in");
				try {
					MyMailSender mms = new MyMailSender(logger);
					logger.info("in2");
					String email = getEmail(ordered_by);
					
					logger.info("in3");
						
					logger.info("email"+email);
					if (!email.equals("") && email.length()>3 && email.indexOf("@")!=-1)
						mms.send(email, orderid, getMailText(orderid, pc, jspMap, orders, false, logger));
					
					
				} catch (Exception e) {
					logger.info("error");
					logger.warn("Message couldn't delivered to the recipients: "+session.getAttribute("USER_LOGGED_ID")+" order id: "+orderid+" error: "+e.getMessage());
				}
			}

			
			
			return true;
		} catch (Exception ex) {
		    logger.error("Error modifying order ",ex);
		    logger.info("rolling back");
		    try {
			    if (tx!=null)
			        tx.rollback();
			    HibernateUtil.closeSession();
		    } catch (Exception e) {}
		    throw ex;
		}
	}

	public static String getLevelAddress(PersistableObject orderingPerson) throws Exception {
		PersistableObject po = orderingPerson.getReferencedObject("level_address_id","level_address","id");
		String titleDescr="";
		if (po!=null)
			titleDescr=po.getString("descr","");
		return titleDescr;

	}

	public static String getLevelAddress(Connection conn, PersistableObject orderingPerson) throws Exception {
		PersistableObject po = orderingPerson.getReferencedObject(conn, "level_address_id","level_address","id");
		String titleDescr="";
		if (po!=null)
			titleDescr=po.getString("descr","");
		return titleDescr;

	}
	
	public static String getTitle(PersistableObject orderingPerson) throws Exception {
		PersistableObject po = orderingPerson.getReferencedObject("titel_id","title","id");
		String titleDescr="";
		if (po!=null)
			titleDescr=po.getString("descr","");
		if (!titleDescr.equals("")) titleDescr = titleDescr+" ";
		return titleDescr;
	}
	
	public static String getTitle(Connection conn, PersistableObject orderingPerson) throws Exception {
		PersistableObject po = orderingPerson.getReferencedObject(conn, "titel_id","title","id");
		String titleDescr="";
		if (po!=null)
			titleDescr=po.getString("descr","");
		if (!titleDescr.equals("")) titleDescr = titleDescr+" ";
		return titleDescr;
	}

	public static String getLevel(PersistableObject orderingPerson) throws Exception {
		ObjectSearch os = new ObjectSearch("user_roles_sub", new String[] {"id", "subtype_id"});
    	os.setCondition("id = ? and subtype_id = ?");
    	List result = os.search(new Object[] {orderingPerson.get("level_id"), orderingPerson.get("level_subtype_id")});
		
    	String titleDescr="n/a";
    	
		if (result.size() > 0)
			titleDescr= ((PersistableObject)result.get(0)).getString("descr","");
		
		return titleDescr;
	}

	public static String getShippingDescr(PersistableObject orderingPerson) throws Exception {
		PersistableObject po = orderingPerson.getReferencedObject("shipping_id","shipping","id");
		String titleDescr="";
		if (po!=null)
			titleDescr=po.getString("descr","");
		return titleDescr;
	}

	public static void newOrderStart(PageContext pc, String distr_id) throws Exception {
    	HttpSession session = pc.getSession();
    	int id = Integer.parseInt(distr_id);
    	Map jspMap = new HashMap();

    	
    	
    	jspMap.putAll(getOrderPersonFirst(pc, distr_id));

    	jspMap.put("ordered_by", new String[] {distr_id});

    	Float f = (Float)session.getAttribute("CURRENT_GROSSHANDLER_DISCOUNT");
    	Float f2 = (Float)session.getAttribute("CURRENT_NEW_HANDLER_DISCOUNT");
    	Float f3 = (Float)session.getAttribute("CURRENT_CUSTOMER_DISCOUNT");
    	Float f4 = (Float)session.getAttribute("CURRENT_NEW_APOTHEKER_DISCOUNT");
    	
    	session.setAttribute("special_discount_grosshandler", "" + f);
    	session.setAttribute("special_discount_handler", "" + f2);
    	session.setAttribute("special_discount_customer", "" + f3);
    	session.setAttribute("special_discount_apotheker", "" + f4);
    	
    	MainControl.logger.info("special discount grosshandler: " + f);
		MainControl.logger.info("special discount handler: " + f2);
		MainControl.logger.info("special discount customer: " + f3);
		MainControl.logger.info("special discount apotheker: " + f4);
    	
    	session.setAttribute("new_order.jsp", jspMap);
	}

	public static String getStatus(String orderId) throws Exception {
    	ObjectSearch os = new ObjectSearch("order_header", new String[] {"id"});
    	os.setCondition("id = ?");
    	List result = os.search(new Object[] {new Long(orderId)});
    	PersistableObject po = (PersistableObject)result.get(0);

    	return po.getString("order_status_id", "90");
	}

    public static String loadOrder(HttpSession session, String orderID) throws Exception {
    	//already checked
    	int id = Integer.parseInt(orderID);

    	ObjectSearch os = new ObjectSearch("order_header", new String[] {"id"});
    	os.setCondition("id = ?");
    	List result = os.search(new Object[] {new Long(id)});

    	//already checked
    	PersistableObject po = (PersistableObject)result.get(0);

    	SuperPO spo = new SuperPO("order_header", MainControl.logger);

    	spo.setMain(po.getValues());

    	Map jspMap = new HashMap();

    	jspMap.putAll(spo.getTextMap());
    	
    	String pay_method_id = ((String[])jspMap.get("pay_method_id"))[0];
    	String account_id	 = ((String[])jspMap.get("account_id"))[0];
		
		if ("1".equals(pay_method_id))
			jspMap.put("account_id_1", new String[] {account_id});
		else if ("2".equals(pay_method_id))
			jspMap.put("account_id_2", new String[] {account_id});
    	
    	Boolean firstOrder = (Boolean)spo.getPOColumn("first_order");	
    	
    	jspMap.put(firstOrder?"modify_fo_sconto_days":"modify_sconto_days", new String[] {spo.getColumn("sconto_days")});

    	jspMap.putAll(getOrderPerson((String)spo.getColumn("ordered_by"), session));

    	java.sql.Date orderDate = (java.sql.Date)spo.getPOColumn("order_date");
    	
    	BigDecimal discount_rate = (BigDecimal)spo.getPOColumn("discount_rate");
    	Integer sconto_days = (Integer)spo.getPOColumn("sconto_days");
    	
    	java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);


    	
    	if (sconto_days != null) {
    		session.setAttribute("modify_sconto_days", "" + sconto_days.intValue());
    	}
    	
    	if (session.getAttribute("modify_fo")!=null)
    		session.removeAttribute("modify_fo");
    	
    	if (firstOrder)
    		session.setAttribute("modify_fo", "true");
    	
    	boolean canmod = false;

    	if (spo.getColumn("order_status_id").equals("10") || spo.getColumn("order_status_id").equals("20"))
    		canmod = true;

    	if (canmod)
    		jspMap.put("canmod", new String[] {"yes"});
    	else
    		jspMap.put("canmod", new String[] {"no"});

    	session.setAttribute("order_detail.jsp", jspMap);

    	ObjectSearch os2 = new ObjectSearch("order_detail", new String[] {"order_id", "art_position"});

    	os2.setCondition("order_id = ?");
    	os2.setOrderBy(new String[] {"art_position"});
    	List details = os2.search(new Object[] {new Long(orderID)});

    	Map detailsMap = (Map)session.getAttribute("order_details");
    	if (detailsMap!=null) detailsMap.clear();
    	
    	String[] kkk = (String[])jspMap.get("orderingLevelId");
    	String olid = null;
    	if (kkk != null && kkk.length>0) {
    		olid = kkk[0];
    		detailsMap.put("ordering_level_id", olid);
    	}
    	
    	if (discount_rate !=null) {
    		if (firstOrder)
    			session.setAttribute("loaded_special_discount", nf.format(discount_rate.doubleValue()));
    		else if ("350".equals(olid))
    			session.setAttribute("loaded_special_discount_grosshandler", nf.format(discount_rate.doubleValue()));
    		else if ("330".equals(olid))
    			session.setAttribute("loaded_special_discount_handler", nf.format(discount_rate.doubleValue()));
    		else if ("370".equals(olid))
    			session.setAttribute("loaded_special_discount_apotheker", nf.format(discount_rate.doubleValue()));
    		else if ("300".equals(olid))
    			session.setAttribute("loaded_special_added_discount", nf.format(discount_rate.doubleValue()));
    		else if ("100".equals(olid) || "130".equals(olid) || "160".equals(olid) || "200".equals(olid))
    			session.setAttribute("loaded_special_discount_customer", nf.format(discount_rate.doubleValue()));
    		
    	}
    	
    	setDetails(session, details, "order_details", "order_detail", orderDate, olid);
    	
    	return (String)spo.getColumn("order_status_id");
    }

    public static void setDetails(HttpSession session, List details, String detailsAttr, String detailsTable, java.sql.Date orderDate, String olid) throws Exception {
    	Map detailsMap = (Map)session.getAttribute(detailsAttr);
    	Logger logger = MainControl.logger;
    	java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
    	nf.setGroupingUsed(false);
    	nf.setMaximumFractionDigits(2);
    	nf.setMinimumFractionDigits(2);
    	for (int i=0; i<details.size(); i++) {
    		Map actual = new HashMap();

    		PersistableObject p = (PersistableObject)details.get(i);

    		SuperPO conv = new SuperPO(detailsTable, MainControl.logger);

    		conv.setMain(p.getValues());
    		logger.info("setD elott:"+i);
    		actual.putAll(conv.getTextMap());
    		
    		String art_id = p.getString("art_id", "0");
    		
    		ObjectSearch os = new ObjectSearch("article_history", new String[] {"art_id", "valid_from"});
    		os.setCondition("art_id = ? AND valid_from <= ? and valid_to >= ?");
    		
    		
    		List result = os.search(new Object[] {art_id, orderDate, orderDate});
    		if (result.size()>0) {
    			PersistableObject po2 = (PersistableObject)result.get(0);
    			po2.get("");
    			String nettoType = "netto";
    			if ("300".equals(olid))
    				nettoType = "netto_handler";
    			if ("350".equals(olid) || "330".equals(olid) || "370".equals(olid))
    				nettoType = "netto_grosshandler";
    			if ("100".equals(olid))
    				nettoType = "netto_customer";
    			if ("130".equals(olid))
    				nettoType = "netto_silver_customer";
    			if ("160".equals(olid))
    				nettoType = "netto_gold_customer";
    			if ("200".equals(olid))
    				nettoType = "netto_vip_customer";
    			
    			Double netto = (Double)po2.get(nettoType);
    			
    			actual.put("list", new String[] {nf.format(netto.doubleValue())});
    		}
    		
    		
    		logger.info("setD utan:"+i);
    		
    		//detailsMap.put(p.getString("art_position", "0"), actual);
    		detailsMap.put(""+i, actual);
    	}
    	detailsMap.put("count", new Integer(details.size()));
    }

    public static String generateTels(PersistableObject po) {
    	String tel1 = po.getString("tel1", "");
    	String tel2 = po.getString("tel2", "");
    	String mobil = po.getString("mobil", "");

    	StringBuffer sb = new StringBuffer();

    	if (!tel1.equals(""))
    		sb.append(tel1+", ");
    	if (!tel2.equals(""))
    		sb.append(tel2+", ");
    	if (!mobil.equals(""))
    		sb.append(mobil+", ");

    	String ret = sb.toString();

    	if (ret.endsWith(", ")) ret = ret.substring(0, ret.length()-2);

    	return ret;
    }


	public static Map getOrderPerson(String distr_id, HttpSession session) throws Exception {
		Map m = new HashMap();

		PersistableObject po = new PersistableObject("distributor", new String[] {"id"});

		po.set("id", new Integer(distr_id));

		po.load();

		List addresses = getAddresses(po);

		m.put("distr_type", new String[] {getLevel(po)});

		Boolean ps = (Boolean)po.get("payment_slip");
		if (ps!=null)
			m.put("payment_slip", ps);		
		
		m.put("sponsor", new String[] {po.getString("sponsor", "n/a")});
		m.put("tel", new String[] {generateTels(po)});
		m.put("orderingCountry", new String[] {po.getString("country_code", "")});
		m.put("company", new String[] {po.getString("company", "")});
		
		String level = po.getString("level_id", "100");
		String level_subtype = po.getString("level_subtype_id", "0");
		
		if ("300".equals(level))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_HANDLER, false);
		else if ("350".equals(level))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_GROSSHANDLER, false);
		else if ("330".equals(level))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_HANDLER, true);
		else if ("370".equals(level))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_APOTHEKER, true);
		else if ("100".equals(level) || "130".equals(level) || "160".equals(level) || "200".equals(level))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_CUSTOMER, false);

		
		m.put("orderingLevelId", new String[] {level});
		m.put("orderingLevelSubtypeId", new String[] {level_subtype});
		m.put("orderingDiscountRate", new String[] {po.getString("discount_rate", "0")});
		m.put("UID", new String[] {po.getString("vat_id", "")});
		return m;

	}

	public static Map getOrderPersonFirst(PageContext pc, String distr_id) throws Exception {
		HttpSession session = pc.getSession();
		Map m = new HashMap();

		PersistableObject po = new PersistableObject("distributor", new String[] {"id"});

		po.set("id", new Integer(distr_id));

		po.load();

		Boolean bool = (Boolean)po.get("active");
		if (bool !=null) {
			boolean b = bool.booleanValue();
			if (!b) throw new EvolutionException("Benutzer ist deaktiviert!");
		}

/*		if (distr_id.startsWith("41")) {
			List cardData = getCreditCards(po);
			if (cardData == null || cardData.size() == 0) {
				throw new EvolutionException("Keine Kreditkarte angegeben!");
			}
			
		}
	*/	
		Logger logger = MainControl.logger;

		List addresses = getAddresses(po);

		m.put("sponsor", new String[] {po.getString("sponsor", "n/a")});
		m.put("tel", new String[] {generateTels(po)});
		m.put("orderingCountry", new String[] {po.getString("country_code", "")});
		m.put("company", new String[] {po.getString("company", "")});
		m.put("orderingLevelId", new String[] {po.getString("level_id", "100")});
		m.put("orderingLevelSubtypeId", new String[] {po.getString("level_subtype_id", "0")});
		m.put("new_sconto_days", new String[] {po.getString("sconto_days", "0")});
		
		String level_id = po.getString("level_id", "100");
		
		if ("300".equals(level_id))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_HANDLER, false);
		if ("350".equals(level_id))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_GROSSHANDLER, false);
		if ("330".equals(level_id))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_HANDLER, true);
		if ("370".equals(level_id))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_APOTHEKER, true);
		if ("100".equals(level_id) || "130".equals(level_id) || "160".equals(level_id) || "200".equals(level_id))
			DiscountHelper.cacheOrderingDistributorLevels(new Integer(distr_id), session, DiscountHelper.LEVEL_TYPE_CUSTOMER, false);
		
		Map orders = (Map)session.getAttribute("new_order_details");
		
		logger.info("get first level_id " + po.getString("level_id", "100"));
		logger.info("get first level_subtype_id " + po.getString("level_subtype_id", "100"));
		
    	orders.put("ordering_level_id", po.getString("level_id", "100"));
    	orders.put("ordering_level_subtype_id", po.getString("level_subtype_id", "0"));
		
		m.put("orderingDiscountRate", new String[] {po.getString("discount_rate", "0")});
		
		m.put("UID", new String[] {po.getString("vat_id", "")});

		Boolean ps = (Boolean)po.get("payment_slip");
		if (ps!=null)
			m.put("payment_slip", ps);
		

		for (int i = 0; i<addresses.size(); i++) {

			PersistableObject address = (PersistableObject)addresses.get(i);
			Boolean def_delivery = (Boolean)address.get("default_delivery");
			Boolean def_bill = (Boolean)address.get("default_bill");

			if (def_delivery.booleanValue()) {
				m.put("delivery_postcode", new String[] {address.getString("postcode", "")});
				m.put("delivery_city", new String[] {address.getString("city", "")});
				m.put("delivery_street", new String[] {address.getString("street", "")});
				m.put("delivery_country_id", new String[] {address.getString("country_post_code", "")});
				String delivery_name = address.getString("delivery_name", "");
				if (!delivery_name.equals(""))
					m.put("delivery_name", new String[] {delivery_name});
			}

			if (def_bill.booleanValue()) {
				m.put("billing_postcode", new String[] {address.getString("postcode", "")});
				m.put("billing_city", new String[] {address.getString("city", "")});
				m.put("billing_street", new String[] {address.getString("street", "")});
				m.put("billing_country_id", new String[] {address.getString("country_post_code", "")});
				String delivery_name = address.getString("delivery_name", "");
				if (!delivery_name.equals(""))
					m.put("billing_name", new String[] {delivery_name});
			}
		}

		if (m.get("billing_name")==null || m.get("billing_name").equals("")) {
			m.put("billing_name", new String[]
			  {getTitle(po)+po.getString("firstname", "")+" "+po.getString("lastname", "")});
			m.put("billing_title", new String[] {getLevelAddress(po)});
		}

		if (m.get("delivery_name")==null || m.get("delivery_name").equals("")) {
			m.put("delivery_name", new String[]
			  {getTitle(po)+po.getString("firstname", "")+" "+po.getString("lastname", "")});
			m.put("delivery_title", new String[] {getLevelAddress(po)});
		}

		PersistableObject country = new PersistableObject("country", "country_code");
		country.set("country_code", po.getString("country_code", ""));
		country.load();

		String freight = country.getString("freight_art_id", "0");

		m.put("pay_method_id", new String[] {po.getString("pay_method_id", "4")});

		m.put("shipping_descr", new String[] {getShippingDescr(po)});

		m.put("distr_type", new String[] {getLevel(po)});

		addNewOrderDetail(pc, freight, po.getString("country_code", ""), po.getString("level_id", ""), po.getString("discount_rate", "0"), po.getString("vat_id", ""));

		return m;
	}

	public static String getShippingOptions(PageContext pageContext, String whichMap) throws Exception {
		return getShippingOptions(pageContext, whichMap, false);
	}

	
	public static String getShippingOptions(PageContext pageContext, String whichMap, boolean skipPaketDienst) throws Exception {
		Shipping[] ss = FormHelper.getShippings();
		HttpSession session = pageContext.getSession();
		Map jsp = (Map)session.getAttribute(whichMap);

		String shipping_descr = (jsp.get("shipping_descr")!=null)?
		((String[])jsp.get("shipping_descr"))[0]:"";

		StringBuffer sb = new StringBuffer();

		for (int i = 0; i<ss.length; i++) {
			Shipping s = ss[i];
			if (skipPaketDienst && s.id.equals("2")) continue;
			String selected = shipping_descr.equalsIgnoreCase(s.value)?" selected":"";
			sb.append("<option"+ selected +" value=\"" + s.value + "\">"+ s.value+"</option>");
		}
		return sb.toString();
	}

	public static String getShippingOption(PageContext pageContext, String whichMap) throws Exception {
		Shipping[] ss = FormHelper.getShippings();
		HttpSession session = pageContext.getSession();
		Map jsp = (Map)session.getAttribute(whichMap);
		String ret = "";

		String shipping_descr = (jsp.get("shipping_descr")!=null)?
		((String[])jsp.get("shipping_descr"))[0]:"";



		for (int i = 0; i<ss.length; i++) {
			Shipping s = ss[i];
			if (shipping_descr.equalsIgnoreCase(s.value)) {
				ret = s.value;
				break;
			}
		}
		return ret;

	}

	public static String getPaymentMethod(PageContext pageContext, String whichMap) throws Exception {
		HttpSession session = pageContext.getSession();
		Map jsp = (Map)session.getAttribute(whichMap);
		String pay_method_id = (jsp.get("pay_method_id")!=null)?
				((String[])jsp.get("pay_method_id"))[0]:"";


		return pay_method_id;
	}
	
	public static String getPaymentOption(PageContext pageContext, String whichMap) throws Exception {
		HttpSession session = pageContext.getSession();

		
		Map jsp = (Map)session.getAttribute(whichMap);
		
		
		PM[] ss = FormHelper.getPMsAll();
		
		/*if (jsp.get("payment_slip")!=null) {
			Boolean ps = (Boolean)jsp.get("payment_slip");
			if (ps.booleanValue())
				ss = FormHelper.getPMsAll();
			else ss = FormHelper.getPMs();
		}
		else
			ss = FormHelper.getPMs();*/
		

		String ret = "";

		String pay_method_id = (jsp.get("pay_method_id")!=null)?
				((String[])jsp.get("pay_method_id"))[0]:"";

				for (int i = 0; i<ss.length; i++) {
					PM s = ss[i];
					if (pay_method_id.equalsIgnoreCase(s.id)) {
						ret = s.value;
						break;
					}
				}

				return ret;
	}

	public static String getPaymentOptions(PageContext pageContext, String whichMap) throws Exception {
		HttpSession session = pageContext.getSession();
		PM[] ss;
		
		Map jsp = (Map)session.getAttribute(whichMap);

		String pay_method_id = (jsp.get("pay_method_id")!=null)?
				((String[])jsp.get("pay_method_id"))[0]:"";


		boolean slip_selected = pay_method_id.equals("6");		
		
		boolean admin = session.getAttribute("admin")!=null;
		
		if (jsp.get("payment_slip")!=null) {
			Boolean ps = (Boolean)jsp.get("payment_slip");
			if (ps.booleanValue())
				ss = FormHelper.getPMsWebshopOptionsWithPaymentSlip();
			else {
				if (!slip_selected) {
					if (admin) 
						ss = FormHelper.getPMsWebshopOptions();
					else
						ss = FormHelper.getPMs();
				}
				else ss = FormHelper.getPMsWebshopOptionsWithPaymentSlip();
			}
		}
		else {
			if (!slip_selected) {
				if (admin) 
					ss = FormHelper.getPMsWebshopOptions();
				else
					ss = FormHelper.getPMs();
			}
			else ss = FormHelper.getPMsAll();
		}

		
		StringBuffer sb = new StringBuffer();

		Map m = (Map)session.getAttribute(whichMap);
		String d_id = ((String[])m.get("ordered_by"))[0];
		
		if (d_id.startsWith("41")) {
			boolean ccSel = pay_method_id.equalsIgnoreCase("2");
			boolean vkSel = pay_method_id.equalsIgnoreCase("4");
				
			sb.append("<option " + (ccSel ? "selected " : "") + "value=\"2\">Kreditkarte</option>");
			sb.append("<option " + (vkSel ? "selected " : "") + "value=\"4\">Vorauskassa</option>");
			
			for (int i=0; i<ss.length; i++) {
				PM s = ss[i];
				if (s.id.length() < 2) continue;
				String selected = pay_method_id.equalsIgnoreCase(s.id)?" selected":"";
				sb.append("<option"+ selected +" value=\"" + s.id + "\">"+ s.value+"</option>");
			}
			
		} else {
			for (int i = 0; i<ss.length; i++) {
				PM s = ss[i];
				String selected = pay_method_id.equalsIgnoreCase(s.id)?" selected":"";

				boolean append = true;

				if (s.id.equals("1")) {
					if (getAccountOptions(session, whichMap, "bank").equals("")) append = false;
				}
				else if (s.id.equals("2")) {
					if (getAccountOptions(session, whichMap, "creditcard").equals("")) append = false;
				}
				if (append)
					sb.append("<option"+ selected +" value=\"" + s.id + "\">"+ s.value+"</option>");
			}
		}
		
		return sb.toString();
	}

	public static String getEmail(String id) throws Exception {
		PersistableObject po = new PersistableObject("distributor", new String[] {"id"});

		po.set("id", new Integer(id));

		po.load();
		
		
		return po.getString("email", "");
	}

	public static String getAccountOptions(HttpSession session, String whichMap, String type) throws Exception{
		PersistableObject po = new PersistableObject("distributor", new String[] {"id"});

		Map m = (Map)session.getAttribute(whichMap);

		String id = ((String[])m.get("ordered_by"))[0];

		po.set("id", new Integer(id));

		po.load();

		List l = type.equals("bank")?getBankAccounts(po):getCreditCards(po);

		String idOnPage = type.equals("bank") ? "account_id_1" : "account_id_2"; 
		String idValue = null;
		
		if (m.get(idOnPage)!=null) {
			idValue = ((String[])m.get(idOnPage))[0];
		}
		
		StringBuffer sb = new StringBuffer();

		boolean toCode = true;


		for (int i=0; i<l.size(); i++) {
			String selected = "";

			PersistableObject p = (PersistableObject)l.get(i);

			String value = p.getString("id", "");

			boolean def = false;
			
			
			if (idValue!=null) {
				if (value.equals(idValue))
					def = true;
			}
			else if (p.get("default_bill")!=null) {
				Boolean b = (Boolean)p.get("default_bill");
				if (b!=null)
					def = b.booleanValue();
			}
			
			if (def) selected = " selected";
			String number = type.equals("bank")?"account_number":"cc_number";

			String screen = toCode?decodeCardNumber(p.getString(number, ""), 4):p.getString(number, "");

			sb.append("<option"+selected+" value=\""+value+"\">"+screen+"</option>");
		}

		return sb.toString();
	}

	//unused
    private static String generateArticleHeader(HttpSession session, int level) throws Exception {
		boolean admin = false;
		boolean distributor = false;
		boolean customer = false;
		if	(session.getAttribute("admin")!=null) admin = true;
		if	(session.getAttribute("customer")!=null) customer = true;
		if	(session.getAttribute("distributor")!=null) distributor = true;

        StringBuffer sb = new StringBuffer();
        sb.append("<table>");
        sb.append(" <tr>");
        sb.append(" <th>&nbsp;</th>");
        sb.append(" <th>ArtikelNr</th>");
        sb.append(" <th>Bezeichnung</th>");
        sb.append("<th>St&uuml;ck</th>");
        if (level<100 || level>DETAILSFROMLEVEL) sb.append(" <th>Netto</th>");
        if (level<100 || level>DETAILSFROMLEVEL) sb.append(" <th>Bonuswert</th>");
        if (level<100 || level>DETAILSFROMLEVEL) sb.append(" <th>Punkte</th>");
        if (level<100 || level>DETAILSFROMLEVEL) sb.append(" <th>MWSt</th>");
        sb.append("<th>Brutto</th>");
        sb.append(" </tr>\n");
        return sb.toString();
    }

    //unused
    private  static String generateArticleTotal(Map map, int level) throws Exception {
        StringBuffer sb = new StringBuffer();
        String totalNetto = getVal(map, "totalNetto");
        String totalBonus = getVal(map, "totalBonus");
        String totalPoints = getVal(map, "totalPoints");
        String totalBrutto = getVal(map, "totalBrutto");
        totalNetto=totalNetto.equals("")?"0.00":totalNetto; totalBonus=totalBonus.equals("")?"0.00":totalBonus;
        totalPoints=totalPoints.equals("")?"0.00":totalPoints;
        sb.append("<tr>\n");
		sb.append("<th colspan=\"4\"><div align=right>Total:</div></th>\n");
		sb.append("<input type=\"hidden\" name=\"totalNetto\" value=\"").append(totalNetto).append("\"/>");
		sb.append("<input type=\"hidden\" name=\"totalBrutto\" value=\"").append(totalBrutto).append("\"/>");
		sb.append("<input type=\"hidden\" name=\"totalPoints\" value=\"").append(totalPoints).append("\"/>");
		sb.append("<input type=\"hidden\" name=\"totalBonus\" value=\"").append(totalBonus).append("\"/>");

		if (level<100 || level>DETAILSFROMLEVEL) sb.append("<th>").append(totalNetto.equals("")?"0.00":new BigDecimal(totalNetto).setScale(2, BigDecimal.ROUND_HALF_UP).toString()).append("</th>\n");
		if (level<100 || level>DETAILSFROMLEVEL) sb.append("<th>").append(totalBonus.equals("")?"0.00":new BigDecimal(totalBonus).setScale(2, BigDecimal.ROUND_HALF_UP).toString()).append("</th>\n");
		if (level<100 || level>DETAILSFROMLEVEL) sb.append("<th>").append(totalPoints.equals("")?"0.00":new BigDecimal(totalPoints).setScale(3, BigDecimal.ROUND_HALF_UP).toString()).append("</th>\n");
		if (level<100 || level>DETAILSFROMLEVEL) sb.append("<th>&nbsp;</th>\n");
		sb.append("<th>").append(totalBrutto.equals("")?"0.00":new BigDecimal(totalBrutto).setScale(3, BigDecimal.ROUND_HALF_UP).toString()).append("</th>\n");
		sb.append("</table>");
		return sb.toString();


    }

    //unused
    private static String generateArticleRow(Map map, String pos, int level) throws Exception {
        StringBuffer sb = new StringBuffer();
        String id = getVal(map, "id"+pos);
        String descr = getVal(map, "descr"+pos);
        String quantity = getVal(map, "quant"+pos,"0");
        String netto = getVal(map, "netto"+pos);
        String vat = getVal(map, "vat"+pos);
        String bonus = getVal(map, "bonus"+pos);
        String points = getVal(map, "points"+pos);
        String tradeMargin = getVal(map, "trade"+pos);
        String brutto = getVal(map, "brutto" + pos);

        org.apache.log4j.Logger logger = MainControl.logger;



        sb.append("<tr>\n");
        sb.append("<td><input type=\"button\" name=\"L"+pos+"\" value=\"L\"/></td>\n");
		sb.append("<td><input type=\"text\" name=\"id").append(pos).append("\" value=\"").append(id).append("\" size=\"10\" "+
		        "maxlength=\"10\"/></td>\n");
		sb.append("<input type=\"hidden\" name=\"descr").append(pos).append("\" value=\"").append(descr).append("\"/>\n");
		sb.append("<td>").append(descr).append("</td>");
		sb.append("<input type=\"hidden\" name=\"oldquant").append(pos).append("\" value=\"").append(quantity).append("\"/>\n");
		sb.append("<td><input type=\"text\" name=\"quant").append(pos);
		if (!quantity.equals("")) sb.append("\" value=\"").append(quantity).append("\"");
		sb.append(" size=\"5\" onchange=\"javascript:document.forms[0].saveState.value='process/new_order.jsp';document.forms[0].pageAction.value='orderchange_quantity';document.forms[0].pos.value='").append(pos).append("';document.forms[0].submit();\"/></td>\n");
		sb.append("<input type=\"hidden\" name=\"netto").append(pos).append("\" value=\"").append(netto).append("\"/>\n");
		BigDecimal quant = new BigDecimal(quantity.equals("")?"0":quantity);
		if (level<100 || level>DETAILSFROMLEVEL) {

		    BigDecimal b_netto = new BigDecimal(netto);
		    sb.append("<td>").append(b_netto.multiply(quant)).append("</td>\n");
		}

		sb.append("<input type=\"hidden\" name=\"bonus").append(pos).append("\" value=\"").append(bonus).append("\"/>\n");
		if (level<100 || level>DETAILSFROMLEVEL) {
		    BigDecimal b_bonus = new BigDecimal(bonus);
		    sb.append("<td>").append(b_bonus.multiply(quant)).append("</td>\n");

		}
		sb.append("<input type=\"hidden\" name=\"points").append(pos).append("\" value=\"").append(points).append("\"/>\n");
		if (level<100 || level>DETAILSFROMLEVEL) {
		    BigDecimal b_points = new BigDecimal(points);
		    sb.append("<td>").append(b_points.multiply(quant)).append("</td>\n");
		}
		sb.append("<input type=\"hidden\" name=\"trade").append(pos).append("\" value=\"").append(tradeMargin).append("\"/>\n");
		sb.append("<input type=\"hidden\" name=\"vat").append(pos).append("\" value=\"").append(vat).append("\"/>\n");
		if (level<100 || level>DETAILSFROMLEVEL) sb.append("<td>").append(vat).append("</td>\n");

		double brutto_d = (new Double(brutto)).doubleValue();
		double quantity_d = (new Double(quantity)).doubleValue();
		brutto_d = brutto_d*quantity_d;

		sb.append("<input type=\"hidden\" name=\"brutto").append(pos).append("\" value=\"").append(brutto).append("\"/>\n");
		sb.append("<td>").append(brutto_d).append("</td>\n");
		sb.append("</tr>\n");
		return sb.toString();

    }

    public static String generateOption(String value,  String v, boolean selected) {
	 	StringBuffer sb = new StringBuffer();
	 	sb.append("<option value=\"").append(value).append("\"").append(selected?" selected>":">").append(v).append("</option>\n");
	 	return sb.toString();
	 }

    public static List getCreditCards(PersistableObject user) throws SQLException, EvolutionException {
 		Map map = new HashMap();
 		map.put("id", "distr_id");
 		return user.getMNObjects("creditcard", "id", map);
    }

    public static List getCreditCards(PersistableObject user, Connection c) throws SQLException, EvolutionException {
 		Map map = new HashMap();
 		map.put("id", "distr_id");
 		return user.getMNObjects(c, "creditcard", "id", map);
    }    
    
    public static List getBankAccounts(PersistableObject user) throws SQLException, EvolutionException  {
	 	Map map = new HashMap();
	 	map.put("id", "distr_id");
	 	if (((Boolean)user.get("allow_bank")).booleanValue())
	 	return user.getMNObjects("bank_account", "id", map);
	 	else return new ArrayList();

	}

    public static List getBankAccounts(PersistableObject user, Connection c) throws SQLException, EvolutionException  {
	 	Map map = new HashMap();
	 	map.put("id", "distr_id");
	 	if (((Boolean)user.get("allow_bank")).booleanValue())
	 	return user.getMNObjects(c, "bank_account", "id", map);
	 	else return new ArrayList();
	}
    
	public static List getAddresses(PersistableObject user) throws Exception  {
	   Map map = new HashMap();
	   map.put("id", "distr_id");
	   return user.getMNObjects("address", "id", map);

	}

	public static List getAddresses(Connection conn, PersistableObject user) throws Exception  {
		   Map map = new HashMap();
		   map.put("id", "distr_id");
		   return user.getMNObjects(conn, "address", "id", map);

	}
	
    public static String generateOptions(List list, String value, String innerHtml, boolean halfSecret, HttpSession session) {
        Map m = (Map) session.getAttribute("new_order.jsp");
        StringBuffer sb = new StringBuffer();
        for (int i=0; i<list.size(); i++) {
            PersistableObject po = (PersistableObject) list.get(i);
            String f = OrderHelper.getVal(m, "value","");
            sb.append(generateOption(po.get(value).toString(), halfSecret?decodeCardNumber(po.getString(innerHtml,""),4):po.getString(innerHtml,""), f.equalsIgnoreCase(po.get(value).toString())));

        }
        return sb.toString();
    }

    public static String decodeCardNumber(String number, int n) {
        if (number==null || number.equals(""))
            return "";

        int lastPos = number.length()-n;
        if (lastPos<0) lastPos=0;

        String last = number.substring(lastPos);
        return "*******"+last;


    }

	public static void addNewOrderDetail(PageContext pc, String id, String country_code, 
			String levelStr, String drStr, String uid) throws Exception {
		HttpSession session = pc.getSession();
		PersistableObject po = new PersistableObject("currentarticles","id");
		try {
			po.set("id",id);
			po.load();
		} catch(Exception e) {
			session.setAttribute("new_order_error",LocaleSupport.getLocalizedMessage(pc, "NO_ARTICLE"));
			return;
		}
		//Map myMap = FormHelper.getArticle(id, MainControl.logger);

		 //boolean noVat = uid!=null && uid.length()>0 && "DE".equals(country_code);
		 
		
		 PersistableObject po_article = new PersistableObject("article", "id");
		 po_article.set("id", id);
		 Integer inventory = new Integer(-1);
		 Double order_price = new Double(0);
		 try {
			 po_article.load();
			 inventory = (Integer)po_article.get("inventory");
			 order_price = (Double)po_article.get("order_price");
		 } catch (Exception e) {
		 }
		
		String descr = (String) po.get("descr");
		PersistableObject po_country = new PersistableObject("country", "country_code");
		po_country.set("country_code", country_code);
		po_country.load();
		int level = 100;
		
		String tax_id = po_country.getString("tax_id", "");
		boolean noVat = uid!=null && uid.length()>0 && !"".equals(tax_id) && !"0".equals(tax_id)
		&& !"AT".equals(country_code);

		try {
		   level = Integer.parseInt(levelStr);
		} catch (Exception e) {
		   level = 100;
		}
		
		 boolean dealer = false;
		 float dr = 0;
		 if (level==80) {
			 dealer = true;
			 try {
				 dr = new Float(drStr).floatValue();
			 } catch (Exception e) {
				 throw new Exception("Discount rate is invalid : "+drStr);
			 }
		 }  
		
		
		Double netto = (Double) po.get("netto");
		Double bonus = (Double) po.get("bonus");
		String vatClass = po.getString("vat_id", "1");

		if (vatClass.equals("0")) vatClass="1";

		 Double netto_customer = (Double) po.get("netto_customer");
		 Double netto_silver_customer = (Double) po.get("netto_silver_customer");
		 Double netto_gold_customer = (Double) po.get("netto_gold_customer");
		 Double netto_vip_customer = (Double) po.get("netto_vip_customer");
		 Double netto_handler = (Double) po.get("netto_handler");
		BigDecimal vat = (BigDecimal) po_country.get("vat"+vatClass);
		if (noVat) vat = new BigDecimal(0);
		BigDecimal brutto = new BigDecimal(0);

		//int level= Integer.valueOf(OrderHelper.getVal(m, "orderingLevel")).intValue();

		double d_bonus = bonus.doubleValue();
        
		double d_nettoDist = netto.doubleValue(); 
		 double d_nettoCustomer = netto_customer.doubleValue();
		 double d_nettoSilverCustomer = netto_silver_customer.doubleValue();
		 double d_nettoGoldCustomer = netto_gold_customer.doubleValue();
		 double d_nettoVipCustomer = netto_vip_customer.doubleValue();
		 double d_nettoHandler = netto_handler.doubleValue();

		double d_netto = 0;
		 double tradeMargin = 0;
		 
		 if (level == 100) {
			 d_netto = d_nettoCustomer;
			 tradeMargin = (d_bonus * 25) / 100;
		 }
		 else if (level == 130) {
			 d_netto = d_nettoSilverCustomer;
			 tradeMargin = (d_bonus * 15) / 100;
		 }
		 else if (level == 160) {
			 d_netto = d_nettoGoldCustomer;
			 tradeMargin = (d_bonus * 10) / 100;
		 }
		 else if (level == 200) {
			 d_netto = d_nettoVipCustomer;
			 tradeMargin = (d_bonus * 5) / 100;
		 }
		 else if (level == 300) {
			 d_netto = d_nettoHandler;
		 }
		 else d_netto = d_nettoDist;
		 org.apache.log4j.Logger logger = MainControl.logger;

		 if (dealer) {
			 if (d_bonus !=0)
				 d_netto = d_bonus * (100 - dr) / 100;
		 }



		double d_brutto = d_netto + (d_netto * vat.doubleValue())*.01;
		java.text.NumberFormat nf = java.text.NumberFormat.getInstance(Locale.ENGLISH);
		nf.setMinimumFractionDigits(2);
		nf.setMaximumFractionDigits(2);
		nf.setGroupingUsed(false);

		Map orders = (Map)session.getAttribute("new_order_details");
		
		String level_id = (String)orders.get("ordering_level_id");
		String level_subtype_id = (String)orders.get("ordering_level_subtype_id");
		
		int count = 0;
		orders.clear();

		if (level_id !=null)
			orders.put("ordering_level_id", level_id);
		
		if (level_id !=null)
			orders.put("ordering_level_subtype_id", level_subtype_id);
		
		
		Map newRow = new HashMap();
		
		if (dealer) {

			d_bonus = 0;
		}
		
		newRow.put("inventory", new String[] {""+inventory.intValue()});
		newRow.put("order_price", new String[] {""+order_price.doubleValue()});
	   newRow.put("netto", new String[] {nf.format(d_netto)});
	   newRow.put("brutto", new String[] {nf.format(d_brutto)});

	   newRow.put("bonus", new String[] {nf.format(d_bonus)});
	   newRow.put("trade_margin", new String[] {nf.format(tradeMargin)});
	   newRow.put("art_id", new String[] {id});
	   newRow.put("art_name", new String[] {descr});
	   newRow.put("art_position", new String[] {String.valueOf(count)});
	   newRow.put("comment", new String[] {""});
	   newRow.put("list", new String[] {nf.format(d_nettoDist)});
	   newRow.put("quantity", new String[] {String.valueOf("1")});
	   newRow.put("vat_value", new String[] {nf.format(vat)});

	   orders.put(String.valueOf(count), newRow);

	   orders.put("count", new Integer(count+1));



	}


}
