<%@ page import="com.fenalco.utilities.lists.ListView"%>
<%@ page import="com.fenalco.entities.User"%>
<%@ page import="com.fenalco.entities.DataAccess"%>
<%@ page import="com.fenalco.entities.Supplier"%>
<%@ page import="com.fenalco.entities.PaymentMethodList"%>
<%@ page import="com.fenalco.entities.PaymentMethod"%>
<%@ page import="java.util.Hashtable"%>
<%@ page import="java.util.Vector"%>
<%@ page import="java.util.Enumeration"%>
<%
    ListView cart = ( ListView )request.getAttribute( "cartView" );
	Enumeration selectedPays =  ((Vector)request.getAttribute( "selectedPayments" )).elements();
	
    double totalDiscount = 0;
    String message = null;
    message = ( String )request.getAttribute( "message" );
    System.out.println( "El mensaje es: " + message );
    if( message == null )
    {
        message = "";
    }
    
    Hashtable suppliersPayments = ( Hashtable )request.getAttribute( "suppliersPayments" );
    
    double subtotal = 0.0;
    double base = 0.0;
    double iva = 0.0;
    double total = 0.0;
    
    int prods = 0;
    
    String helpId = "45";
    
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<link rel='stylesheet' style='text/css' href='../css/tablas.css'>
<title>Mi carrito de compras</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<script type='text/javascript' language='javascript' src='../js/library.js'></script>
<script>

    function updateDiscount(supp)
    {
		
		document.forms[0].action="/minorista/micarrito";
		document.forms[0].submit();
    }


    function removeProduct( supp, id )
    {
        var resp = confirm( " Está seguro de que desea eliminar el producto del carrito ?" );
        if( resp )
        {
            var name = "producto_" + supp + "_" + id;
            document.getElementById( name ).value = "0";
			document.getElementById( 'event' ).value = "modificar_cantidad";
            document.forms[0].submit();
        }
    }
    
    function validateForm(){
        var flag = true;
        var message = "Han ocurrido los siguientes errores:\n";
        document.list.pay_ids.value = "";
        
        
        for(var i = 0; i < document.carrito.elements.length; i++){
        
            if(document.carrito.elements[i].name.indexOf("payment_")== 0 ){
                document.list.pay_ids.value = document.list.pay_ids.value+document.carrito.elements[i].value+";";
            }
        }
        
        
         if(!flag){
                    window.alert(message);
        }
        else{
             document.getElementById("make_order").disabled = true;
            document.getElementById("make_quote").disabled = true;
            document.getElementById("make_list").disabled = true;
            document.getElementById("modify").disabled = true;
            document.getElementById("confirm").innerHTML =  "<hr><font color='#FF0000' size='2'><b><br><%=( (User)session.getAttribute("user") ).getFirstName()%> su lista está siendo generada, por favor espere un momento....<br></b></font><hr>";
        }
        return flag;
    }
    
    function makeOrder()
    {
        document.getElementById( 'event' ).value = "pedido";
        document.getElementById("confirm").innerHTML =  "<hr><font color='#FF0000' size='2'><b><br><%=( (User)session.getAttribute("user") ).getFirstName()%> su pedido está siendo generado, por favor espere un momento....<br></b></font><hr>";
        document.getElementById("make_order").disabled = true;
        document.getElementById("make_quote").disabled = true;
        document.getElementById("make_list").disabled = true;
        document.getElementById("modify").disabled = true;
        
        document.forms[0].submit();
    }
    
	function modifyQuantity()
	{
            document.getElementById( 'event' ).value = "modificar_cantidad";
             document.getElementById("make_order").disabled = true;
            document.getElementById("make_quote").disabled = true;
            document.getElementById("make_list").disabled = true;
            document.getElementById("modify").disabled = true;
             document.getElementById("confirm").innerHTML =  "<hr><font color='#FF0000' size='2'><b><br><%=( (User)session.getAttribute("user") ).getFirstName()%> su pedido está siendo modificado, por favor espere un momento....<br></b></font><hr>";
            document.forms[0].submit();
	}
	
	function makeQuote()
        {
            document.getElementById( 'event' ).value = "cotizacion";
            document.getElementById("confirm").innerHTML =  "<hr><font color='#FF0000' size='2'><b><br><%=( (User)session.getAttribute("user") ).getFirstName()%> su cotización está siendo generada, por favor espere un momento....<br></b></font><hr>";
            document.getElementById("make_order").disabled = true;
            document.getElementById("make_quote").disabled = true;
            document.getElementById("make_list").disabled = true;
            document.getElementById("modify").disabled = true;

            document.forms[0].submit();
        }
        
        function makeList()
        {
            var message = "";
            var flag = true;
            if(isEmpty(document.list.name)){
                    message = message + "- El nombre de la lista es vacío.\n";
                    flag = false;
            }
             if(!flag){
                        window.alert(message);
            }
            else{    document.getElementById( 'event' ).value = "lista";
                document.getElementById("confirm").innerHTML =  "<hr><font color='#FF0000' size='2'><b><br><%=( (User)session.getAttribute("user") ).getFirstName()%> su lista está siendo generada, por favor espere un momento....<br></b></font><hr>";
                document.getElementById("make_order").disabled = true;
                document.getElementById("make_quote").disabled = true;
                document.getElementById("make_list").disabled = true;
                document.getElementById("modify").disabled = true;

                document.list.submit();
            }
        }
	
	
	
	function back(){
            document.getElementById("make_order").disabled = true;
            document.getElementById("make_quote").disabled = true;
            document.getElementById("make_list").disabled = true;
            document.getElementById("modify").disabled = true;
            document.getElementById("confirm").innerHTML =  "<hr><font color='#FF0000' size='2'><b><br><%=( (User)session.getAttribute("user") ).getFirstName()%>  por favor espere un momento....<br></b></font><hr>";
            return true; 
        }
	
   function showMessage(){
        var message = "<%=message%>";
        if(message!=null && message!="")
        {
            window.alert(message);
        }
        return true;
    }

</script>
<body bgcolor="#ffffff" background="../images/shopkeeper/general/fondo.jpg" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0" onload="showMessage()">
<!-- 
-->

<table border="0" cellpadding="0" cellspacing="0" width="780">
    <%@ include file="encabezado.jsp" %>
</table>
<table width="760" border="0" cellspacing="0" cellpadding="0">
    <tr>
        <td width="155" valign="top">
			<%@ include file="menuminorista.jsp" %>
	</td>
        <td width='603' valign="top">
                    <%
                        String tittle = "Carrito de Compras";
                    %>
                    <%@ include file="/titulo.jsp" %>
                    
            <table>
			    <tr>
                    <td width="596">
					<form action="/minorista/actualizarcarrito" method="post" name="carrito">
						<input type="hidden" name="event">
						
            
                        <table>
						
              <%
                                while( cart.move() )
                                {
                                        double discount = 0.0;
                                        int supplierId = ( ( Integer )cart.nextElement() ).intValue();
                                        String supplierName = Supplier.getName( supplierId );
                                        ListView products = ( ListView )cart.nextElement();
                                        double minOrderValue = (new Supplier(supplierId)).getMinimunOrder();
                                        PaymentMethodList paymentMethodList = ( PaymentMethodList )suppliersPayments.get( supplierId + "" );
                             %>
              <tr> 
                <td width="587"> <p>&nbsp;</p><table width="478" border="0" align="center" cellpadding="0" cellspacing="0" bgcolor="#FCF8D1">
                    <tr valign="top"> 
                      <td colspan="4" height="10"><img src="../images/sysmanager/barra1form.gif" width="477" height="10"></td>
                    </tr>
                    <tr> 
                      <td width="8" height="25" bgcolor="#FAF09F">&nbsp;</td>
                      <td width="164" height="25" bgcolor="#FAF09F"><span class="Estilo6"><b>PROVEEDOR</b></span></td>
                      <td width="6" height="25">&nbsp;</td>
                      <td width="300" height="25"><b><font color="#006633" size="4"><%=supplierName%></font></b></td>
                    </tr>
                    <tr> 
                      <td height="25" bgcolor="#FAF09F">&nbsp;</td>
                      <td height="25" bgcolor="#FAF09F"><strong>Forma de Pago/Descuento:</strong></td>
                      <td height="25">&nbsp;</td>

                      <td height="25"><select name='payment_<%=supplierId%>' id='select' onChange="updateDiscount(<%=supplierId%>)">
                          <%
                                            Vector paymentList = paymentMethodList.getPaymentMethods();
                                            int selectedPay = ((Integer)selectedPays.nextElement()).intValue();
                                            for( int i = 0; i < paymentList.size(); i++ )
                                            {
                                                String selected = "";
                                                PaymentMethod paymentMethod = ( PaymentMethod )paymentList.elementAt( i );

                                                if( paymentMethod.getId()== selectedPay ){
                                                        selected = "selected";
                                                        discount = (new PaymentMethod(selectedPay)).getDiscount();
                                                }
												
                                                %>
                          <option value='<%=paymentMethod.getId( )%>'  <%=selected%>><%=paymentMethod.getName()+"("+paymentMethod.getDiscount()+"%)"%></option>
                          <%
                                            }
                                        %>
                        </select></td>
                    </tr>
                    <tr> 
                      <td width="8" height="25" bgcolor="#FAF09F">&nbsp;</td>
                      <td width="164" height="25" bgcolor="#FAF09F"><span class="Estilo6"><b>Valor mínimo de compra</b></span></td>
                      <td width="6" height="25">&nbsp;</td>
                      <td width="300" height="25"><b><font color="#006633"><%=DataAccess.getCurrency(minOrderValue)%></font></b></td>
                    </tr>
                    <tr valign="bottom"> 
                      <td colspan="4"><img src="../images/sysmanager/barra2form.gif" width="477" height="10"></td>
                    </tr>
                  </table></td>
              </tr>
              <tr> 
                <td> <table width="100%" border="0">
                    <tr class='tableheader'> 
                      <td><div align="center"><strong><font color="White">C&oacute;digo 
                          de Barras</font></strong></div></td>
                      <td><div align="center"><strong><font color="White">Nombre</font></strong></div></td>
                      <td><div align="center"><strong><font color="White">Categor&iacute;a</font></strong></div></td>
                      <td><div align="center"><strong><font color="White">Marca</font></strong></div></td>
                      <td><div align="center"><strong><font color="White">Precio 
                          Unit.</font></strong></div></td>
                      <td colspan='2'><div align="center"><strong><font color="White">Cant.</font></strong></div></td>
                      <td><div align="center"><strong><font color="White">Precio 
                          Total</font></strong></div></td>
                    </tr>
                    <%
                                                    double subtotal_prov = 0.0;
                                                    double base_prov = 0.0;
                                                    double iva_prov = 0.0;
                                                    double total_prov = 0.0;

                                                    while( products.move() )
                                                    {
                                                            int id = Integer.parseInt( ( String )products.nextElement() );
                                                            prods++;
                                            %>
                    <tr bgcolor="<%=prods%2==0?"#efefef":"fffff"%>"> 
                      <td><%=products.nextElement()%></td>
                      <td><%=products.nextElement()%></td>
                      <td><%=products.nextElement()%></td>
                      <td><%=products.nextElement()%></td>
                      <td align="right"><%=DataAccess.getCurrency( Double.parseDouble( ( String )products.nextElement() ) )%></td>
                      <td><input name="producto_<%=supplierId%>_<%=id%>" id="producto_<%=supplierId%>_<%=id%>" type="text" value="<%=products.nextElement()%>" size="2" maxlength="10"></td>
                      <td><a href='javascript:removeProduct(<%=supplierId%>, <%=id%>)'><img src='/images/buttons/shopkeeper/desactivar.gif' alt='Eliminar del Carrito' width="14" height="15" border='0'></a></td>
                      <%
                                                    // este es el valor del producto
                                                    double sub_aux = Double.parseDouble( ( String )products.nextElement() );
                                                    double iva_por = Double.parseDouble( ( String )products.nextElement() );
                                                    
                                                    double sin_iva = 0.0;
                                                    double con_iva = 0.0;
                                                    double iva_val = 0.0;
                                                    
                                                    if( iva_por > 0 )
                                                    {
                                                        sin_iva = sub_aux / ( 1 + iva_por / 100 );
                                                        con_iva = sub_aux;
                                                        iva_val = con_iva - sin_iva;
                                                        
                                                        base_prov += sin_iva;
                                                        iva_prov += iva_val;
                                                    }
                                                    else
                                                    {
                                                        iva_val = 0;
                                                        sin_iva = sub_aux;
                                                        con_iva = sub_aux;
                                                    }
                                                    
                                                    subtotal_prov += sin_iva;
                                                    total_prov += con_iva;
                                                    
                                                    double suma_sub = 0.0;
//                                                    total += subTotal;
//                                                    sub += subTotal;
                                                %>
                      <td align="right"><%=DataAccess.getCurrency( sub_aux )%></td>
                    </tr>
                    <%
                                                    }
                                                    discount = (discount*subtotal_prov/100);
                                                    total_prov -= discount;
                                                    totalDiscount += discount;
													
                                                    subtotal += subtotal_prov;
                                                    base += base_prov;
                                                    iva += iva_prov;
                                                    total += total_prov;

                                            %>
                  </table></td>
              </tr>
              <tr> 
                <td align="center"> <table width="100%" border="0" cellpadding="0" cellspacing="0" bgcolor="#E8E8F4">
                    <tr> 
                      <td width="16">&nbsp;</td>
                      <td width="529"><table width="100%"  border="0" cellspacing="0" cellpadding="3">
                          <tr> 
                            <td align="left"><div align="left"><strong>TOTAL SIN I.V.A</strong></div></td>
                            <td align="right"><strong><font color="#FF0000"><%=DataAccess.getCurrency( subtotal_prov )%></font></strong></td>
                            <td>&nbsp;</td>
                            <td><strong>BASE DEL I.V.A GRAVADO</strong></td>
                            <td><strong><font color="#FF0000"><%=DataAccess.getCurrency( base_prov )%></font></strong></td>
                          </tr>
                          <tr> 
                            <td width="21%" align="left"><div align="left">Valor del I.V.A. 
                                (+)</div></td>
                            <td width="25%" align="right"><strong><font color="#FF0000">

								<%=DataAccess.getCurrency( iva_prov )%></font></strong>

							</td>
                            <td width="7%">&nbsp;</td>
                            <td width="35%">&nbsp; </td>
                            <td width="12%"><span class="style4"></span></td>
                          </tr>
                          <tr>
                            <td align="left">Descuento(-)</td>
                            <td  align="right"><strong><font color="#FF0000">
								<%=DataAccess.getCurrency( discount )%></font></strong>
							</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                          </tr>
                          <tr> 
                            <td colspan="2" height="5"><hr size="2"></td>
                            <td></td>
                            <td></td>
                            <td></td>
                          </tr>
                          <tr> 
                            <td><strong>TOTAL</strong></td>
                            <td align="right">

								<strong><font color="#FF0000"><%=DataAccess.getCurrency( total_prov )%></font></strong>

							</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                            <td>&nbsp;</td>
                          </tr>
                        </table></td>
                      <td width="16">&nbsp;</td>
                    </tr>
                  </table></td>
              </tr>
              <%
                            }
                    %>
              <%
                        if( prods > 0 )
                        {
                    %>
            </table>
            </form> 
                    </td>
            </tr>
            <tr>
                
          <td align="left"> <p> 
              <%
			  	tittle = "Total de la compra";
              %>
              <%@ include file="/titulo.jsp" %>
            </p>
            <table width="560" border="0" cellpadding="0" cellspacing="0" bgcolor="#E8E8F4">
              <tr> 
                <td width="16" align="left" valign="top"><img src="images/bus1.gif" width="16" height="14"></td>
                <td width="529">&nbsp;</td>
                <td width="15" align="right" valign="top"><img src="images/bus3.gif" width="15" height="14"></td>
              </tr>
              <tr> 
                <td>&nbsp;</td>
                <td><table width="100%"  border="0" cellspacing="0" cellpadding="3">
                    <tr> 
                      <td align="left"><strong>TOTAL SIN I.V.A</strong></td>
                      <td align="right"><strong><font color="#FF0000"><%=DataAccess.getCurrency( subtotal )%></font></strong></td>
                      <td>&nbsp;</td>
                      <td><strong>BASE DEL I.V.A GRAVADO</strong></td>
                      <td><strong><font color="#FF0000"><%=DataAccess.getCurrency( base )%></font></strong></td>
                    </tr>
                    <tr> 
                      <td width="22%" align="left">Valor del I.V.A. (+)</td>
                      <td width="25%" align="right"><strong><font color="#FF0000"><%=DataAccess.getCurrency( iva )%></font></strong></td>
                      <td width="5%">&nbsp;</td>
                      <td width="35%">&nbsp; </td>
                      <td width="13%"><span class="style4"></span></td>
                    </tr>
                    <tr>
                      <td align="left">Total Descuento (-)</td>
                      <td align="right"><strong><font color="#FF0000"><%=DataAccess.getCurrency( totalDiscount )%></font></strong></td>
                      <td>&nbsp;</td>
                      <td>&nbsp;</td>
                      <td>&nbsp;</td>
                    </tr>
                    <tr> 
                      <td colspan="2" height="5"><hr size="2"></td>
                      <td></td>
                      <td></td>
                      <td></td>
                    </tr>
                    <tr> 
                      <td><strong>TOTAL</strong></td>
                      <td align="right"><strong><font color="#FF0000"><%=DataAccess.getCurrency( total )%></font></strong></td>
                      <td>&nbsp;</td>
                      <td>
                        <input id='modify' name="submit" type="button" value="Recalcular" onClick="modifyQuantity()"> 
                      </td>
                      <td>&nbsp;</td>
                    </tr>
                    <tr>
                        <td colspan='5'><hr size="2"></td>
                    </tr>
                    <tr>
                        <td colspan='5' align="center">
                         <input type="button" value="Generar Pedido" onClick='makeOrder()' id="make_order">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                         <input type="button" value="Generar Cotización" id="make_quote" onClick='makeQuote()'>
                          <form name='list' action="/minorista/actualizarcarrito" method="post" >
                                <input type="button" value="Guardar lista de compra" id="make_list" onclick='makeList()'>&nbsp;&nbsp;<input type="text" name='name' value='lista' onclick="this.value=''">
                                <input type="hidden" name="event" value="lista"> 
                                <input type="hidden" name="pay_ids" value=""> 
                                 </td>
                            </form>
                        </td>
                    </tr>
                  </table></td>
                <td>&nbsp;</td>
              </tr>
              <tr> 
                <td align="left" valign="bottom"><img src="images/bus2.gif" width="16" height="15"></td>
                <td>&nbsp;</td>
                <td align="right" valign="bottom"><img src="images/bus4.gif" width="15" height="15"></td>
              </tr>
            </table>
           
          </td>
            </tr>
         
            <tr>
                <td>
                    <center><div id="confirm" ></div></center>
                </td>
            </tr>
            
        <tr align='center'> 
          <td align="center"><!--
<table cellpadding='0' cellspacing='0'>
               <tr> 
                <td valign='top' align='left'><b>1. Pedido</b></td>
                <td align='right'> <form action="/minorista/actualizarcarrito" method="post">
                    
                    <input type="button" value="Generar" onClick='makeOrder()' id="make_order">
                  </form></td>
              </tr>              <tr> 
                <td valign='top' align='left'><b> 2. Cotizaci&oacute;n</b> </td>
                <td align='right'> <form action="/minorista/actualizarcarrito" method="post">
                    <input type="hidden" name="event" value="cotizacion">
                    <input type="submit" value="Generar" id="make_quote">
                  </form></td>
              </tr>
              <tr> 
                <td colspan='2' valign='top' align='left'> <b>3. Lista de compra</b> 
                </td>
              </tr>
              <tr> 
                <form name='list' action="/minorista/actualizarcarrito" method="post" onSubmit="return validateForm();">
                  <td> <input type="text" name='list_name'> </td>
                  <td align='right'> <input type="hidden" name="event" value="lista"> 
                  <input type="hidden" name="pay_ids" value=""> 
                    <input type="submit" value="Guardar" id="make_list"> </td>
                </form>
              </tr>
            </table>-->
            <p><a id='back' href="/minorista/catalogo"><img  alt='Volver al catálogo..'  border='0' src='/images/buttons/shopkeeper/seguir_comprando.gif' onclick='return back();' ></a> </p></td>
            </tr>
            
             <%
            }
            else
            {
                %>
                <p align="center" >
                    <font color="#FF0000" size="3"><br><br><strong>
                        El carrito de compras no contiene ning&uacute;n producto.<br>
                        Para agregar productos vaya al <a href="/minorista/catalogo">Cat&aacute;logo</a></strong>.
                    </font>
                <p><img src="/minorista/imagenes/carrito_pub.gif" ></p>
                <%
            }
        %>
      
      <p>&nbsp; </p>                       
        
        </table>
 
</td>
</tr>
</table>




</body>
</html>
// “Copyright (C) <2008> Multilateral Investment Fund of the Inter-American Development Bank.
// Este archivo es parte de <ICT4BUS-PVL>
// < ICT4BUS-PVL > es software libre: usted puede redistribuirlo y/o modificarlo bajo los términos de la Licencia Pública General GNU publicada por la Fundación para el Software Libre, ya sea la versión 3 de la Licencia, o (a su elección) cualquier versión posterior.
// < ICT4BUS-PVL > se distribuye con la esperanza de que sea útil, pero SIN GARANTÍA ALGUNA; ni siquiera la garantía implícita MERCANTIL o de APTITUD PARA UN PROPÓSITO DETERMINADO. 
// Consulte los detalles de la Licencia Pública General GNU para obtener una información más detallada. 
// Debería haber recibido una copia de la Licencia Pública General GNU junto a este programa. En caso contrario, consulte http://www.gnu.org/licenses/.”
