/**************************************************************************
 *  App.js
 *
 *  Implementacion de procedimientos generales de la aplicacion.
 *
 *  Autor: Manuel Palma Martín.
 *
 *  Copyright (c) 2009,2010,2011 FerSoft Informática S.L.
 *  Todos los derechos reservados.
 */

   var AccederConLogin = false;
   var TipoDocumento = "";
   var ObsPorLinea = false;
   var VerStock = false;
   var ReqPago = false;
   var Tit1Div = "";
   var Tit2Div = "";
   var UtlArtDes = false;
   var UtlArtNov = false;
   var TipPagIni = "I";
   var TipoMenuFam = "1";
   var DecimalesEnCantidades = 0;
   var sDecCanInput;
   var MostrarHistoPed = false;
   var FormasDeEnvio = null;
   
   var oBannerSinTitulo, oBannerConTitulo;
   var lMostrarEfectoCesta = false;
   var sHtmInicio;
   var lTipoMenuImagen = false;
   var lTipoMenuCapa = false;
   var lTipoMenuLista = false;
   
   var _ClassName_ = (Prototype.Browser.IE ? 'className' : 'class');
   
   var RecordarUsuarioYClave = false;
   var DesactivarPerdidaDeSesion = false;
   var AutoLogin = false;   
   var AutoLoginUsuario = "";
   var AutoLoginClave = "";
   
   var TblTwtt = null;
   
window.onload = function()
{
   $('CuadroAviso').hide();
   $('CuadroAviso').Ocultar = function() {
      $('CuadroAviso').hide();
   }
   $('CuadroAviso').Mostrar = function(sTxt) {
      var sTbl  = "<table border='0' width='100%' cellpadding='0' cellspacing='10px'>";
          sTbl += " <tr style='vertical-align: top;'>";
          sTbl += "    <td>" + sTxt + "</td>";
          sTbl += "    <td><a href='javaScript:$(\"CuadroAviso\").Ocultar();'><img src='./images/app/accion_borrar.gif' border='0'></a></td>";
          sTbl += " </tr>";
          sTbl += " </table>";
      $('CuadroAviso').innerHTML = sTbl;
      $('CuadroAviso').show();
   }
   if(ExisteId('SelBuscar')) $('SelBuscar').hide();
   if(ExisteId('SelMarca')) $('SelMarca').hide();
   if(ExisteId('TblTwtt')) {
      TblTwtt = (document.getElementById('TblTwtt')).cloneNode(true);
      $('TblTwtt').parentNode.removeChild($('TblTwtt'));
   }
   DivFondo(true, 40);
   $('DivPausa').hide();
   $('DivAtencion').hide();
   $('DivPregunta').hide();   
   $('DivVerImagen').hide();
   $('DivArticuloCantidad').hide();
   $('DivArticuloBorrar').hide();
   $('SpanLogin').hide();
   $('SpanLogout').hide();
   if(ExisteId('DivDescArticulo')) $('DivDescArticulo').hide();
   if(ExisteId('MenuProductos')) $('MenuProductos').hide();
   VerBuscador(false);   
   $('TblLogin').hide();
   $('Tbl_Cesta').hide();
   if(ExisteId('TblCliente')) $('TblCliente').hide();
   $('TblSinConexion').hide();
   if(ExisteId('TdHistorico1')) {
      $('TrHistorico1').hide();
      $('TrHistorico2').hide();
      $('TdHistorico2').EventosAsignados = false;
   }
   if(ExisteId('TdVendido1')) {
      $('TrVendido1').hide();
      $('TrVendido2').hide();
      $('TdVendido2').EventosAsignados = false;
   }   
   if(ExisteId('TdMasVendido1')) {
      $('TrMasVendido1').hide();
      $('TrMasVendido2').hide();
      $('TdMasVendido2').EventosAsignados = false;
   }   
   if(ExisteId('TdNuevoCliente')) EnlaceNuevoCliente(false);

   Destacados(false);
   Novedades(false);

   oBannerSinTitulo = $('BannerSinTitulo').cloneNode(true);
   oBannerConTitulo = $('BannerConTitulo').cloneNode(true);
   $('BannerSinTitulo').parentNode.removeChild($('BannerSinTitulo'));
   $('BannerConTitulo').parentNode.removeChild($('BannerConTitulo'));

   /*************
    * Configuracion de banner de inicio
    */
   MsjReloj('Conectando con el servidor. Espere ...');
   $('DivPausa').show();
   var top  = ((document.layers ? window.innerHeight : document.body.clientHeight) - $('DivPausa').offsetHeight) / 2;
   var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivPausa').offsetWidth) / 2;
   if(top < 1) top = 1;
   if(left < 1) left = 1;
   $('DivPausa').style.top  =  document.body.scrollTop + top;
   $('DivPausa').style.left = left;

   if(ExisteId('BotInicio')) {
      if($('BotInicio').nodeName == "IMG") lTipoMenuImagen = true;
      else if($('BotInicio').nodeName == "LI") lTipoMenuLista = true;
   } else if(ExisteId('OpcMenuInicio'))  lTipoMenuCapa   = true;
   
   if(lTipoMenuImagen) {
      BotonImagen('BotInicio', 'BtnInicioSel.jpg', function(){PaginaInicio(false);});
      BotonImagen('BotEmpresa', 'BtnEmpresaSel.jpg', PaginaEmpresa);
      BotonImagen('BotAviso', 'BtnAvisoSel.jpg', PaginaLegal);
      if(ExisteId('BotCondiCompra')) {
         BotonImagen('BotAviso', 'BtnAvisoSel.jpg', function() {
            _("app.aspx", "acc=" + "_PLANTILLA_&documento=CondicionesDeCompra", function(oVal) {
               $('TdContenido').innerHTML = oVal.HTML;
            });
         });
      }
      if(ExisteId('BotContacto')) BotonImagen('BotContacto', 'BtnContactoSel.jpg', PaginaContacto);
   } else if(lTipoMenuCapa) {
      OpcionMenu('OpcMenuInicio', function(){PaginaInicio(false);});
      OpcionMenu('OpcMenuEmpresa', PaginaEmpresa);
      OpcionMenu('OpcMenuAviso', PaginaLegal);
      ToolTip('OpcMenuInicio', 'Mostrar p&aacute;gina de inicio');
      ToolTip('OpcMenuEmpresa', 'Datos de la empresa');
      ToolTip('OpcMenuAviso', 'Informaci&oacute;n sobre marcas y LOPD');
      if(ExisteId('OpcCondiCompra')) {
         OpcionMenu('OpcCondiCompra', function() {
            _("app.aspx", "acc=" + "_PLANTILLA_&documento=CondicionesDeCompra", function(oVal) {
               $('TdContenido').innerHTML = oVal.HTML;
            });
         });
         ToolTip('OpcCondiCompra', 'Mostrar condiciones de compra');         
      }
      if(ExisteId('OpcMenuContacto')) {
         OpcionMenu('OpcMenuContacto', PaginaContacto);
         ToolTip('OpcMenuContacto', 'Solicitud de informaci&oacute;n');
      }
   } else if(lTipoMenuLista) {
      Event.observe('BotInicio', 'click', function(){PaginaInicio(false);});
      ToolTip('BotInicio', 'Mostrar p&aacute;gina de inicio');
      if(ExisteId('BotEmpresa')) {
         Event.observe('BotEmpresa', 'click', PaginaEmpresa);
         ToolTip('BotEmpresa', 'Datos de la empresa');
      }
      if(ExisteId('BotContacto')) {
         if(! $('BotContacto').Inicializado) {
            $('BotContacto').firstChild.setAttribute('id', '_A_BotContacto');
            BotonLink('_A_BotContacto', PaginaContacto);
            $('BotContacto').Inicializado = true;
            ToolTip('BotContacto', 'Mostrar p&aacute;gina de contacto');
         }
         $('BotContacto').firstChild.removeAttribute(_ClassName_);
      }   
      
      if(ExisteId('BotAviso')) {
         if(! $('BotAviso').Inicializado) {
            $('BotAviso').firstChild.setAttribute('id', '_A_BotAviso');
            BotonLink('_A_BotAviso', PaginaLegal);
            $('BotAviso').Inicializado = true;
            ToolTip('BotAviso', 'Mostrar p&aacute;gina de aviso legal');
         }
         $('BotAviso').firstChild.removeAttribute(_ClassName_);
      }      
   }

   if(ExisteId('LnkInicio')) BotonLink('LnkInicio', function(){PaginaInicio(false);});
   if(ExisteId('LnkEmpresa')) BotonLink('LnkEmpresa', PaginaEmpresa);
   if(ExisteId('LnkCondiciCompra')) BotonLink('LnkCondiciCompra', function() {
      _("app.aspx", "acc=" + "_PLANTILLA_&documento=CondicionesDeCompra", function(oVal) {
         $('TdContenido').innerHTML = oVal.HTML;
         ScrollUp();
      });
   });
   if(ExisteId('LnkContacto')) {
      BotonLink('LnkContacto', PaginaContacto); 
      $('LnkContacto').removeAttribute(_ClassName_);
   }
   if(ExisteId('LnkAviso')) BotonLink('LnkAviso', PaginaLegal);   
     
   if(ExisteId('TdCondicionesDeCompra')) {
      Event.observe('TdCondicionesDeCompra', 'mouseover', function() {
         $('TdCondicionesDeCompra').removeClassName('TdOpcion');
         $('TdCondicionesDeCompra').addClassName('TdOpcionSel');
      });
      Event.observe('TdCondicionesDeCompra', 'mouseout', function() {
         $('TdCondicionesDeCompra').removeClassName('TdOpcionSel');
         $('TdCondicionesDeCompra').addClassName('TdOpcion');
      });         
      Event.observe('TdCondicionesDeCompra', 'click', function() {
         _("app.aspx", "acc=" + "_PLANTILLA_&documento=CondicionesDeCompra", function(oVal) {
            $('TdContenido').innerHTML = oVal.HTML;
         });
      });
   }

   if(document.MenuCliente != undefined) document.MenuCliente();
   
   
   $('LogEmail').value = '';
   $('LogClave').value = '';
   $('TblLogin').show();
   _("app.aspx", "acc=" + encodeURIComponent("_CHEQUEAR_CONEXION_BD_"), function(oChk) {
      if(oChk.Resultado) {
         if(lTipoMenuImagen) BotonImagen('BotDocumentacion', 'BtnDocumentacionSel.jpg', PaginaDocumentacion);
         else if(lTipoMenuLista) {
            if(ExisteId('BotDocumentacion')) {
               if(! $('BotDocumentacion').Inicializado) {
                  $('BotDocumentacion').firstChild.setAttribute('id', '_A_BotDocumentacion');
                  BotonLink('_A_BotDocumentacion', PaginaDocumentacion);
                  $('BotDocumentacion').Inicializado = true;
                  ToolTip('BotDocumentacion', 'Mostrar p&aacute;gina de documentaci&oacute;n');
                  
               }
               $('BotDocumentacion').firstChild.removeAttribute(_ClassName_);
            }            
         }

         if(ExisteId('LnkDocumentacion')) {
            BotonLink('LnkDocumentacion', PaginaDocumentacion);
            $('LnkDocumentacion').removeAttribute(_ClassName_);
         }

         if(ExisteId('TxtBuscar')) {
            $('TxtBuscar').TxtVacio = 'Texto a buscar ...';
            $('TxtBuscar').value = $('TxtBuscar').TxtVacio;
            Event.observe('TxtBuscar', 'focus', function() {
               if($('TxtBuscar').value == $('TxtBuscar').TxtVacio) $('TxtBuscar').value = '';
            });
            Event.observe('TxtBuscar', 'blur', function() {
               if($('TxtBuscar').value == '') $('TxtBuscar').value = $('TxtBuscar').TxtVacio;
            });
            $('TxtBuscar').BuscarArticulos = function() {
               var sParam1 = "", sParam2 = "", sParam3 = "";
            
               MsjReloj('Buscando productos. Espere ...');
               
               sParam1 = $("TxtBuscar").value;
               if(sParam1 == $('TxtBuscar').TxtVacio) sParam1 = "";
               $('TxtBuscar').focus();
               
               if(ExisteId('SelBuscar')) {
                  sParam2 = $('SelBuscar').value;
                  if(sParam2 == '*') sParam2 = "";
               }
               
               if(ExisteId('SelMarca')) {
                  sParam3 = $('SelMarca').value;
                  if(sParam3 == '*') sParam3 = "";
               }               
               
               var sUrlBusqueda = "acc=" + encodeURIComponent("_BUSCAARTICULO_") + "&param1=" + encodeURIComponent(sParam1);
               if(sParam2 != "") sUrlBusqueda += "&param2=" + encodeURIComponent(sParam2);
               if(sParam3 != "") sUrlBusqueda += "&param3=" + encodeURIComponent(sParam3);
               
               _("app.aspx", sUrlBusqueda, VerArticulos);
            }
            OnEnter('TxtBuscar', function() {$('TxtBuscar').blur(); $('TxtBuscar').BuscarArticulos();});            
            if(ExisteId('LupaBuscar')) {
               ToolTip('LupaBuscar', 'Buscar articulos');
               Event.observe('LupaBuscar', 'click', $('TxtBuscar').BuscarArticulos, 'Buscar art&iacute;culos');
            } else if(ExisteId('SpanBuscar')) Boton('SpanBuscar', $('TxtBuscar').BuscarArticulos, 'Buscar art&iacute;culos');
         }
         
         OnEnter('LogEmail', 'LogClave');
         OnEnter('LogClave', Identificarse);

         if(ExisteId('SpanIdentifi')) Boton('SpanIdentifi', function() {Identificarse();}, 'Identificarse');
         else if(ExisteId('LnkIdentifi'))  BotonLink('LnkIdentifi', Identificarse);
         if(ExisteId('BotonLogout')) Boton('BotonLogout', function() {Logout(); }, 'Salir');
         else if(ExisteId('LnkLogout')) BotonLink('LnkLogout', Logout);
         
         if(ExisteId('LnkMisPedidos')) {
            BotonLink('LnkMisPedidos', function() {
               _("app.aspx", "acc=" + "_PLANTILLA_&documento=Historico", function(oVal) {
                  $('TdContenido').innerHTML = oVal.HTML;
                  HistoricoDePedidos();
               });
            });
         }

         if(ExisteId('TdRegistrarse')) {
            Event.observe('TdRegistrarse', 'mouseover', function() {
               $('TdRegistrarse').removeClassName('TdOpcion');
               $('TdRegistrarse').addClassName('TdOpcionSel');
            });
            Event.observe('TdRegistrarse', 'mouseout', function() {
               $('TdRegistrarse').removeClassName('TdOpcionSel');
               $('TdRegistrarse').addClassName('TdOpcion');
            });
            Event.observe('TdRegistrarse', 'click', function() {
               if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
               _("app.aspx", "acc=" + "_PLANTILLA_&documento=registro", function(oVal) {
                  $('TdContenido').innerHTML = oVal.HTML;
               	$('imgCaptcha').src = $('imgCaptcha').src.split('?')[0] + '?x=' + (new Date()).toUTCString();
                  $('email').focus();
                  if(ExisteId('Lnk2Aviso') && ExisteId('TblAvisoLegal')) {
                     $('TblAvisoLegal').hide();
                     BotonLink('Lnk2Aviso', function() {
                        if($('TblAvisoLegal').visible()) $('TblAvisoLegal').hide();
                        else $('TblAvisoLegal').show();
                     });
                  }
                  Boton('RefrescaCaptCha', function() {
                     $('imgCaptcha').src = $('imgCaptcha').src.split('?')[0] + '?x=' + (new Date()).toUTCString();
                  }, 'Cambiar validaci&oacute;n');
                  Boton('NuevoRegistro', function() {
                     if(! $('Conformidad').checked) {
                        Alert('No ha indicado si ha leido el aviso legal.');
                        $('Conformidad').focus();
                        return;
                     }
                     var aInput = $$('INPUT');
                     var sInput = "";
                     for(j = 0 ; j < aInput.length; j++)
                        sInput += ((sInput.length > 0 ? ',' : '') + aInput[j].id.toUpperCase());
                     _("app.aspx", "acc=" + encodeURIComponent("_NUEVO_USUARIO_") + "&param1=2"       +
                                                "&param2=" + encodeURIComponent($("nombre").value)    +
                                                "&param3=" + encodeURIComponent($("direccion").value) +
                                                "&param4=" + encodeURIComponent($("codpostal").value) +
                                                "&param5=" + encodeURIComponent($("poblacion").value) +
                                                "&param6=" + encodeURIComponent($("provincia").value) +
                                                "&param7=" + encodeURIComponent($("telefono").value)  +
                                                "&param8=" + encodeURIComponent($("nif").value)       +
                                                "&param9=" + encodeURIComponent($("email").value)     +
                                                "&paramA=" + encodeURIComponent($("clave").value)     +
                                                "&paramB=" + encodeURIComponent($("clave2").value)    +
                                                "&paramC=" + encodeURIComponent($("Validacion").value) +
                                                "&orden=" + encodeURIComponent(sInput), function(oVal2) {
                                                   $('TdContenido').innerHTML = oVal2.HTML;
                                                });
                  }, 'Enviar datos');
                  OnEnter('email', 'clave');
                  OnEnter('clave', 'clave2');
                  OnEnter('clave2', 'nombre');
                  OnEnter('nombre', 'nif');
                  OnEnter('nif', 'direccion');
                  OnEnter('direccion', 'codpostal');
                  OnEnter('codpostal', 'poblacion');
                  OnEnter('poblacion', 'provincia');
                  OnEnter('provincia', 'telefono');
                  OnEnter('telefono', 'Validacion');
                  OnEnter('Validacion', 'Conformidad');
                  OnEnter('Conformidad', NuevoRegistro.OnClick);
               });
            });
         }

         if(ExisteId('TdResetClave')) {
            Event.observe('TdResetClave', 'mouseover', function() {
               $('TdResetClave').removeClassName('TdOpcion');
               $('TdResetClave').addClassName('TdOpcionSel');
            });
            Event.observe('TdResetClave', 'mouseout', function() {
               $('TdResetClave').removeClassName('TdOpcionSel');
               $('TdResetClave').addClassName('TdOpcion');
            });
            Event.observe('TdResetClave', 'click', ResetearClave);
         } else if(ExisteId('LnkResetClave'))  BotonLink('LnkResetClave', ResetearClave);

         _("app.aspx", "acc=" + encodeURIComponent("_PARAMETROS_"), function(oVal1) {
            if(!oVal1.Logado) AvisoNavegador();
            Config(oVal1);
            CargaBanners(oVal1, true);
            //PaginaInicio(true); La llamada se hace desde CargaBanners
         });
      } else {
         AutoLogin = false;
         if(ExisteId('MenuProductos')) {
            var oObj = $('MenuProductos').parentNode;
            while((oObj.nodeName != 'TR')) oObj = oObj.parentNode;
            oObj.parentNode.removeChild(oObj);
         }         
         $('TblSinConexion').show();
         $('SpanLogin').show();
         if(ExisteId('TxtBuscar')) $('TxtBuscar').disable();
         $('LogEmail').disable();
         $('LogClave').disable();
         if(ExisteId('TdRegistrarse')) $('TdRegistrarse').hide();
         $('TdResetClave').hide();
         if(ExisteId('DivCabBuscador')) while($('DivCabBuscador').hasChildNodes()) $('DivCabBuscador').removeChild($('DivCabBuscador').lastChild);
         
         if(lTipoMenuCapa) {                  
            $('OpcMenuContacto').style.color='#777777';
            $('OpcMenuContacto').style.cursor='normal';
            $('LnkContacto').style.color='#777777';
            $('LnkContacto').style.cursor='normal';
            BotonLink('LnkContacto');
            
            $('OpcMenuNovedades').style.color='#777777';
            $('OpcMenuNovedades').style.cursor='normal';
            $('LnkNovedades').style.color='#777777';
            $('LnkNovedades').style.cursor='normal';
            $('OpcMenuOfertas').style.color='#777777';
            $('OpcMenuOfertas').style.cursor='normal';
            $('LnkOfertas').style.color='#777777';
            $('LnkOfertas').style.cursor='normal';
         }
         
         AvisoNavegador();
         _("app.aspx", "acc=" + encodeURIComponent("_PARAMETROS_"), function(oVal1) {
            CargaBanners(oVal1, false);
            //PaginaInicio(false); La llamada se hace desde CargaBanners
         });
      }
   });
}

function Logout()
{
   if($('TblCesta').NumLineas == 0) cTit = '&iquest;Desea abandonar la sesi&oacute;n actual?';
   else cTit = '&iquest;Desea vaciar cesta y abandonar la sesi&oacute;n actual?';
   Confirm(cTit, function() {
      _("app.aspx", "acc=_LOGOUT_", function(oVal) {
         if(RecordarUsuarioYClave) {
            AutoLoginUsuario = ""; 
            AutoLoginClave = "";
            SalvarDatosAutoLogin();
         }
         if(AccederConLogin) {
            if(ExisteId('MenuProductos')) $('MenuProductos').hide();
            VerBuscador(false);
            $('Tbl_Cesta').hide();
            Destacados(false);
            Novedades(false);
         }
         if(MostrarHistoPed && ExisteId('TdHistorico1')) {
            if($('TrHistorico1').visible()) EnlaceHistorico(1, false);
            if($('TrHistorico2').visible()) EnlaceHistorico(2, false);
         }
         if(ExisteId('TdVendido1')) {
            if($('TrVendido1').visible()) EnlaceVendido(1, false);
            if($('TrVendido2').visible()) EnlaceVendido(2, false);
         }                  
         if(ExisteId('TdMasVendido1')) {
            if($('TrMasVendido1').visible()) EnlaceMasVendido(1, false);
            if($('TrMasVendido2').visible()) EnlaceMasVendido(2, false);
         }
         if(ExisteId('TdNuevoCliente')) EnlaceNuevoCliente(false);
         $('LogEmail').value = '';
         $('LogClave').value = '';
         $('email2').innerHTML = '';
         $('usr2').innerHTML = '';
         if(ExisteId('Perfil')) $('Perfil').innerHTML = '';
         $('SpanLogin').show();
         $('SpanLogout').hide();
         BotonCambiarClave(false);
         if(Control1() == 'UsuarioCreado') $('TdContenido').innerHTML = '';
         _("app.aspx", "acc=" + "_PLANTILLA_&documento=inicio", function(oVal) {
            $('TdContenido').innerHTML = oVal.HTML;
            lMostrarEfectoCesta = true;
            ActualizarCesta();
         });
      });
   });
}

function ResetearClave()
{
   if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=resetearclave", function(oVal) {
      $('TdContenido').innerHTML = oVal.HTML;
      Boton('BotEnviar', function() {
         _("app.aspx", "acc=" + encodeURIComponent("_RESETEAR_CLAVE_") + "&param1=" + encodeURIComponent($("email").value) + "&param2=" + encodeURIComponent($("nif").value),
            function() {
               var sTbl = "<table class='TblAviso' 'cellpadding'='0' 'cellspacing'='0'>";
               sTbl    +=    "<tbody>";
               sTbl    +=       "<tr>";
               sTbl    +=          "<td>Se le ha enviado una nueva clave.</td>";
               sTbl    +=       "</tr>";
               sTbl    +=    "</tbody>";
               sTbl    += "</table>";
               $('TdContenido').innerHTML = sTbl;
            }
         );
      }, 'Generar y enviar nueva clave');
      
      OnEnter('email', 'nif');
      OnEnter('nif', BotEnviar.OnClick);
      $('email').focus();
   });
}

function AvisoNavegador()
{
   if(typeof document.body.style.maxHeight == 'undefined')
      $('CuadroAviso').Mostrar('<p align=\'justify\'>Se ha detectado una versi&oacute;n de navegador no actualizada.&nbsp;' +
            'Para una mejor experiencia de usuario y correcto renderizado de los elementos integrantes de este sitio web se recomienda como m&iacute;nimo uno de los siguientes navegadores:&nbsp;' +
            'Internet Explorer 7, Mozilla Firefox 3.6, Apple Safari 5.0, Opera 9 o Google Chrome 10.0</p>');
}

function Destacados(Activo)
{
   if(ExisteId('OpcMenuOfertas')) {
      if(!Activo || !UtlArtDes) {
         OpcionMenu('OpcMenuOfertas');
         ToolTip('OpcMenuOfertas');
         BotonLink('LnkOfertas');
      } else {
         OpcionMenu('OpcMenuOfertas', PaginaDestacados);
         ToolTip('OpcMenuOfertas', 'Mostrar ofertas');
         BotonLink('LnkOfertas', PaginaDestacados);
      }
   }
   if(ExisteId('TblDestacados')) {
      if(!Activo || !UtlArtDes) {
         $('TblDestacados').hide();
         $('TblDestacados').stopObserving('mouseover');
         $('TblDestacados').stopObserving('mouseout');
         $('TblDestacados').stopObserving('click');
      } else {
         $('TblDestacados').show();
         Event.observe('TdDestacados', 'mouseover', function() {
            $('TdDestacados').removeClassName('TdOpcion');
            $('TdDestacados').addClassName('TdOpcionSel');
         });
         Event.observe('TdDestacados', 'mouseout', function() {
            $('TdDestacados').removeClassName('TdOpcionSel');
            $('TdDestacados').addClassName('TdOpcion');
         });
         Event.observe('TdDestacados', 'click', function() {MsjReloj('Buscando productos destacados. Espere ...'); _("app.aspx", "acc=" + "_ARTICULOSDESTACADOS_", VerArticulos);});
      }
   }
   if(UtlArtDes) {
      if(ExisteId('BotDestacados')) {
         if(! $('BotDestacados').Inicializado) {
            $('BotDestacados').firstChild.setAttribute('id', '_A_BotDestacados');
            BotonLink('_A_BotDestacados', PaginaDestacados);
            ToolTip('BotDestacados', 'Mostrar art&iacute;culos destacados');
            $('BotDestacados').Inicializado = true;
         }
         if(Activo) $('BotDestacados').firstChild.removeAttribute(_ClassName_);
         else       $('BotDestacados').firstChild.setAttribute(_ClassName_, 'Disabled');
      }
      if(ExisteId('LnkDestacados')) {
         if($('LnkDestacados').nodeName == "A") {
            if(Activo) {
               if($('LnkDestacados').readAttribute(_ClassName_) == "Disabled") $('LnkDestacados').removeClassName('Disabled');
            } else
               if($('LnkDestacados').readAttribute(_ClassName_) != "Disabled") $('LnkDestacados').addClassName('Disabled');
         }
      }
   }
}

function Novedades(Activo)
{
   if(ExisteId('OpcMenuNovedades')) {
      if(!Activo || !UtlArtNov) {
         OpcionMenu('OpcMenuNovedades');
         ToolTip('OpcMenuNovedades');
         BotonLink('LnkNovedades');
      } else {
         OpcionMenu('OpcMenuNovedades', PaginaNovedades);
         ToolTip('OpcMenuNovedades', 'Mostrar novedades');
         BotonLink('LnkNovedades', PaginaNovedades);
      }
   }
   if(ExisteId('TblNovedades')) {
      if(!Activo || !UtlArtNov) {
         $('TblNovedades').hide();
         $('TblNovedades').stopObserving('mouseover');
         $('TblNovedades').stopObserving('mouseout');
         $('TblNovedades').stopObserving('click');
      } else {
         $('TblNovedades').show();
         Event.observe('TdNovedades', 'mouseover', function() {
            $('TdNovedades').removeClassName('TdOpcion');
            $('TdNovedades').addClassName('TdOpcionSel');
         });
         Event.observe('TdNovedades', 'mouseout', function() {
            $('TdNovedades').removeClassName('TdOpcionSel');
            $('TdNovedades').addClassName('TdOpcion');
         });
         Event.observe('TdNovedades', 'click', function() {MsjReloj('Buscando novedades. Espere ...'); _("app.aspx", "acc=" + "_ARTICULOSNOVEDAD_", VerArticulos);});
      }
   }
   if(UtlArtNov) {
      if(ExisteId('BotNovedades')) {
         if(! $('BotNovedades').Inicializado) {
            $('BotNovedades').firstChild.setAttribute('id', '_A_BotNovedades');
            BotonLink('_A_BotNovedades', PaginaNovedades);
            ToolTip('BotNovedades', 'Mostrar novedades');
            $('BotNovedades').Inicializado = true;
         }
         if(Activo) $('BotNovedades').firstChild.removeAttribute(_ClassName_);
         else       $('BotNovedades').firstChild.setAttribute(_ClassName_, 'Disabled');
      }   
      if(ExisteId('LnkNovedades')) {
         if($('LnkNovedades').nodeName == "A") {
            if(Activo) {
               if($('LnkNovedades').readAttribute('class') == "Disabled") $('LnkNovedades').removeClassName('Disabled');
            } else
               if($('LnkNovedades').readAttribute('class') != "Disabled") $('LnkNovedades').addClassName('Disabled');
         }
      }
   }
}

function CargaBanners(oVal, lValPagInicio)
{
   var nBanner = 0;
   var oBanner, oCol, oTd, oImg, sWidth;

   document.Tweets_TdId = '';
   document.Tweets_Usr = '';
   document.Tweets_Rpp = '';
   document.Lst_Shell_Background = '';
   document.Lst_Shell_Color = '';
   document.Lst_Tweets_Background = '';
   document.Lst_Tweets_Color = '';
   document.Lst_Tweets_Links = '';
         
   oVal.Banners.each(function(Banner) {
      nBanner++;
      if(((Banner.Tipo == "I" || Banner.Tipo == "L") && Banner.File != '') || ((Banner.Tipo == "Y" || Banner.Tipo == "F") && Banner.Link != '') || (Banner.Tipo == "T" && Banner.Usr != '' && TblTwtt != null)) {
         oBanner = (Banner.Titulo == '' ? oBannerSinTitulo.cloneNode(true) : oBannerConTitulo.cloneNode(true));
         oCol = $(Banner.Posicion == 'Derecha' ? 'ColDer' : 'ColIzq');
         (oCol.getElementsByTagName('TBODY')[0]).appendChild(oBanner);      
         if(Banner.Titulo != '') {
            $('TitBanner').appendChild(document.createTextNode(Banner.Titulo));
            $('TitBanner').setAttribute('id', Banner.Titulo + nBanner); 
         }
         oTd = oBanner.getElementsByTagName((Banner.Titulo == '' ? 'TBODY' : 'TFOOT'))[0]
         oTd = oTd.getElementsByTagName('TD')[0];
         oImg =  oTd.getElementsByTagName('IMG')[0];
         if(Banner.Tipo != 'I') {
            sWidth = oImg.getAttribute('width');
            oTd.removeChild(oImg);
         }
              
         switch(Banner.Tipo) {
            case "I":
               oImg.setAttribute('src', './data/banners/' + Banner.File);
               if(Banner.Link != '') {
                  oImg.setAttribute('id', 'ImgBanner' + nBanner);
                  $('ImgBanner' + nBanner).URL = Banner.Link;
                  Event.observe('ImgBanner' + nBanner, 'mouseover', function() {this.style.cursor='pointer';});
                  Event.observe('ImgBanner' + nBanner, 'mouseout', function()  {this.style.cursor='normal';});
                  Event.observe('ImgBanner' + nBanner, 'click', function()  {window.open(this.URL);});
                  ToolTip('ImgBanner' + nBanner, Banner.Link);
               }
               break;
               
            case "L":
               oImg = document.createElement('EMBED');
               oImg.setAttribute('width', sWidth);
               oImg.setAttribute('src', './data/banners/' + Banner.File);
               if(Banner.Alto > 0) oImg.setAttribute('height', Banner.Alto + 'px');
               oTd.appendChild(oImg);
               break;
            
            case 'Y':            
               oEmb = document.createElement('EMBED');
               oEmb.setAttribute('width', sWidth);
               if(Banner.Alto > 0) oEmb.setAttribute('height', Banner.Alto + 'px');
               oEmb.setAttribute('src', Banner.Link);
               oEmb.setAttribute('allowscriptaccess', 'always');
               oEmb.setAttribute('allowfullscreen', 'true');
               oTd.appendChild(oEmb);
               break;
                  
            case 'F':
               oDiv = document.createElement('DIV');               
               oDiv.setAttribute('id', 'fb-root');
               oTd.appendChild(oDiv);
               oDiv = document.createElement('DIV');
               oDiv.setAttribute(_ClassName_, 'fb-like-box');
               oDiv.setAttribute('data-href', Banner.Link);
               oDiv.setAttribute('data-width', "" + sWidth);
               oDiv.setAttribute('data-show-faces', (Banner.Show_Faces ? 'true' : 'false'));
               oDiv.setAttribute('data-stream', (Banner.Show_Stream ? 'true' : 'false'));
               oDiv.setAttribute('data-header', (Banner.Header ? 'true' : 'false'));
               oTd.appendChild(oDiv);
               
               eval("(function(d, s, id) {" +
                    "  var js, fjs = d.getElementsByTagName(s)[0]; " +
                    "  if (d.getElementById(id)) {return;} " +
                    "  js = d.createElement(s); js.id = id; " +
                    "  js.src = 'http://connect.facebook.net/es_ES/all.js#xfbml=1'; " +
                    "  fjs.parentNode.insertBefore(js, fjs); " +
                    "}(document, 'script', 'facebook-jssdk')); ");
                    
               break;
   
            case 'T':
               oTd.setAttribute('id', 'TdTwitter' + nBanner);            
               if(document.Tweets_Usr != '') {
                  document.Tweets_TdId += '<|>'; 
                  document.Tweets_Usr += '<|>';
                  document.Tweets_Rpp += '<|>';
                  document.Lst_Shell_Background += '<|>';
                  document.Lst_Shell_Color += '<|>';
                  document.Lst_Tweets_Background += '<|>';
                  document.Lst_Tweets_Color += '<|>';
                  document.Lst_Tweets_Links += '<|>';
               }
               document.Tweets_TdId += 'TdTwitter' + nBanner;
               document.Tweets_Usr += Banner.Usr;
               document.Tweets_Rpp += Banner.Rpp;
               document.Lst_Shell_Background += Banner.Shell_Background;
               document.Lst_Shell_Color += Banner.Shell_Color;
               document.Lst_Tweets_Background += Banner.Tweets_Background;
               document.Lst_Tweets_Color += Banner.Tweets_Color;
               document.Lst_Tweets_Links += Banner.Tweets_Links;
               break;
            }
      }
   });
   
   if(document.Tweets_Usr != '') {
      document.Tweets_TdId = document.Tweets_TdId.split('<|>');
      document.Tweets_Usr = document.Tweets_Usr.split('<|>');
      document.Tweets_Rpp = document.Tweets_Rpp.split('<|>');
      document.Lst_Shell_Background = document.Lst_Shell_Background.split('<|>');
      document.Lst_Shell_Color = document.Lst_Shell_Color.split('<|>');
      document.Lst_Tweets_Background = document.Lst_Tweets_Background.split('<|>');
      document.Lst_Tweets_Color = document.Lst_Tweets_Color.split('<|>');
      document.Lst_Tweets_Links = document.Lst_Tweets_Links.split('<|>');
      PonerTwitters(0, lValPagInicio);
   } else PaginaInicio(lValPagInicio);
   
}   

function PonerTwitters(nElem, lValPagInicio)
{
   if(nElem < document.Tweets_TdId.length) {
      document.Shell_Background = document.Lst_Shell_Background[nElem];
      document.Shell_Color = document.Lst_Shell_Color[nElem];
      document.Tweets_Background = document.Lst_Tweets_Background[nElem];
      document.Tweets_Color = document.Lst_Tweets_Color[nElem];
      document.Tweets_Links = document.Lst_Tweets_Links[nElem];
      
      $(document.Tweets_TdId[nElem]).appendChild(TblTwtt.cloneNode(true));
      
      _("app.aspx", "acc=" + "_LEE_TWETTER_&Usuario=" + document.Tweets_Usr[nElem] + "&NumTweets=" + document.Tweets_Rpp[nElem], function(oVal) {
         if(oVal.Tweets.length > 0) PonerTwitter(oVal.Tweets);
         PonerTwitters(nElem + 1, lValPagInicio);
      });
   } else PaginaInicio(lValPagInicio);
}

function PonerTwitter(jTwt)
{
   var oThead = $('TblTwtt').getElementsByTagName('THEAD')[0];
   var oTbody = $('TblTwtt').getElementsByTagName('TBODY')[0];
   var oTr = (oTbody.getElementsByTagName('TR')[0]).cloneNode(true);
   oTbody.removeChild(oTbody.getElementsByTagName('TR')[0]);
   var oTfoot = $('TblTwtt').getElementsByTagName('TFOOT')[0];         

   $('TdTheadTblTwt').style.color = document.Shell_Color;   
   $('User_Screen_Name').style.color = document.Shell_Color;   
   $('TdTheadTblTwt').style.background = document.Shell_Background;
   $('TdTheadTblTwt').setAttribute('id', '');
   
   $('TdTfootTblTwt').style.color = document.Shell_Color;
   $('TdTfootTblTwt').style.background = document.Shell_Background;
   $('TdTfootTblTwt').setAttribute('id', '');
   
   $('Usr_Profile_Image_Lnk').href = 'http://twitter.com/intent/user?screen_name=' + jTwt[0].screen_name;
   $('Usr_Profile_Image_Lnk').setAttribute('id', '');
   $('Usr_Profile_Image').src = jTwt[0].profile_image_url;
   $('Usr_Profile_Image').setAttribute('id', '');
   $('User_Name').innerHTML = jTwt[0].name;
   $('User_Name').setAttribute('id', '');
   $('User_Screen_Name').innerHTML = jTwt[0].screen_name;
   $('User_Screen_Name').href = 'http://twitter.com/intent/user?screen_name=' + jTwt[0].screen_name;
   $('User_Screen_Name').setAttribute('id', '');
   
   jTwt.each(function(Tweet) {
      oTbody.appendChild(oTr.cloneNode(true));
      $('TdTbodyTblTwt').style.color = document.Tweets_Color;
      $('TdTbodyTblTwt').style.background = document.Tweets_Background;
      $('TdTbodyTblTwt').setAttribute('id', '');
      
      $('Tweet_Url').style.color=document.Tweets_Links;
      $('Created_At').style.color=document.Tweets_Links;         
      $('Tweet_Reply').style.color=document.Tweets_Links;            
      $('Tweet_ReTweet').style.color=document.Tweets_Links;
      $('Tweet_Favorite').style.color=document.Tweets_Links;
      $('Tweet_Lnks').style.borderBottom = 'dashed #ececec 1px';

      $('Tweet_Lnks').setAttribute('id', '');
                  
      var k = (Tweet.text.toUpperCase()).lastIndexOf('HTTP:');
      if(k > -1) Tweet.text = Tweet.text.substring(0, k);
      $('Tweet_Text').innerHTML = Tweet.text;
      $('Tweet_Text').setAttribute('id', '');
      
      $('Tweet_Url').href = Tweet.url;
      $('Tweet_Url').innerHTML = Tweet.url;
      $('Tweet_Url').setAttribute('id', '');
      
      $('Created_At').href = 'http://twitter.com/' + jTwt[0].screen_name + '/status/' + Tweet.id_str;
      $('Created_At').innerHTML = TwitterDateConverter(Tweet.created_at);
      $('Created_At').setAttribute('id', '');
      
      $('Tweet_Reply').href = 'http://twitter.com/intent/tweet?in_reply_to=' + Tweet.id_str;
      $('Tweet_Reply').setAttribute('id', '');
      
      $('Tweet_ReTweet').href = 'http://twitter.com/intent/retweet?tweet_id=' + Tweet.id_str;
      $('Tweet_ReTweet').setAttribute('id', '');
      
      $('Tweet_Favorite').href = 'http://twitter.com/intent/favorite?tweet_id=' + Tweet.id_str;
      $('Tweet_Favorite').setAttribute('id', '');            
   });

   $('TblTwtt').setAttribute('id', '');
}

function TwitterDateConverter(time)
{
   var k = time.lastIndexOf(' ');
   var Anno = time.substring(k);
   time = time.substring(0, k);
   time = time.substring(0, time.lastIndexOf(' ')) + Anno;
   
	var date = new Date(time),
		diff = (((new Date()).getTime() - date.getTime()) / 1000),
		day_diff = Math.floor(diff / 86400);
 
	if ( isNaN(day_diff) || day_diff < 0 || day_diff >= 365 )
		return (day_diff >= 365 ? 'more than 1 year ago' : '');
 
	return day_diff == 0 && (
			diff < 60 && "just now" ||
			diff < 120 && "1 minute ago" ||
			diff < 3600 && Math.floor( diff / 60 ) + " minutes ago" ||
			diff < 7200 && "1 hour ago" ||
			diff < 86400 && Math.floor( diff / 3600 ) + " hours ago") ||
		day_diff == 1 && "Yesterday" ||
		day_diff < 7 && day_diff + " days ago" ||
		day_diff < 365 && Math.ceil( day_diff / 7 ) + " weeks ago";
}

function Config(oVal)
{
   AccederConLogin = oVal.AccederConLogin;
   TipoDocumento = oVal.TipoDocumento;
   ObsPorLinea = oVal.ObsPorLinea;
   VerStock = oVal.VerStock;
   ReqPago = oVal.ReqPago;
   Tit1Div = oVal.Tit1Div;
   Tit2Div = oVal.Tit2Div;
   UtlArtDes = oVal.UtlArtDes;
   UtlArtNov = oVal.UtlArtNov;
   TipPagIni = oVal.TipPagIni;   
   TipoMenuFam = oVal.TipoMenuFam;
   RecordarUsuarioYClave = oVal.RecordarUsuarioYClave;
   DesactivarPerdidaDeSesion = oVal.DesactivarPerdidaDeSesion;
   FormasDeEnvio = oVal.FormasDeEnvio;
   
   if(RecordarUsuarioYClave) CargarDatosAutoLogin();
   
   if(oVal.Logado) {
      $('SpanLogin').hide();
      $('SpanLogout').show();
      $('email2').innerHTML = oVal.EmlLogado;
      $('usr2').innerHTML = oVal.UsrLogado;
      if(ExisteId('Perfil')) $('Perfil').innerHTML = oVal.Perfil;
      BotonCambiarClave(true);
      if(ExisteId('MenuProductos')) $('MenuProductos').show();
      VerBuscador(true);
      if(TipoDocumento != '') $('Tbl_Cesta').show();      
      Destacados(true);
      Novedades(true);
      if(ExisteId('TblCliente')) {
         if(oVal.AgenteLogado) {
            $('TblCliente').show();
            $('TdNomCliente').innerHTML = (oVal.ClienteAsignado == '' ? 'No hay cliente seleccionado' : oVal.ClienteAsignado);
            $('TrHistorico2').show();
            if(oVal.ClienteAsignado.length > 0) {
               if(ExisteId('TdHistorico1')) EnlaceHistorico(2, true);
               if(ExisteId('TdVendido1')) EnlaceVendido(2, true);
               if(ExisteId('TdMasVendido1')) EnlaceMasVendido(2, true);
            }
            Boton('BotonSelCli', function() {SeleccionarCliente();}, 'Seleccionar cliente');
            if(ExisteId('TdNuevoCliente')) EnlaceNuevoCliente(oVal.CreaClientes);
         } else {
            if(ExisteId('TdHistorico1')) EnlaceHistorico(1, true);
            if(ExisteId('TdVendido1')) EnlaceVendido(1, true);
            if(ExisteId('TdMasVendido1')) EnlaceMasVendido(1, true);
            $('TblCliente').hide();
         }
      }
      AutoLogin = false;
   } else {
      $('SpanLogin').show();
      $('SpanLogout').hide();
      if(!AccederConLogin) {
         if(ExisteId('MenuProductos')) $('MenuProductos').show();
         VerBuscador(true);
         if(TipoDocumento != '') $('Tbl_Cesta').show();
         Destacados(true);
         Novedades(true);
      }
      AutoLogin = (RecordarUsuarioYClave && AutoLoginUsuario != "" && AutoLoginClave != "" ? true : false);            
   }
   DecimalesEnCantidades = oVal.DecimalesEnCantidades;
   sDecCanInput = "";
   if(DecimalesEnCantidades > 0) {
      sDecCanInput +=  ",";
      k = DecimalesEnCantidades;
      while(k-- > 0) sDecCanInput += '0';
   }
   MostrarHistoPed = oVal.MostrarHistoPed;
   if(ExisteId('TdHistorico1') && !MostrarHistoPed) {
      $('TdHistorico1').parentNode.removeChild($('TdHistorico1'));
      $('TdHistorico2').parentNode.removeChild($('TdHistorico2'));
   }
   if(ExisteId('LnkNovedades') && UtlArtNov) BotonLink('LnkNovedades', PaginaNovedades);
   if(ExisteId('LnkDestacados') && UtlArtDes) BotonLink('LnkDestacados', PaginaDestacados);
   if(DesactivarPerdidaDeSesion) HttpRefresSesion = true;
   
   if(!oVal.FiltrarBusquedaPorFamilia) {
      if(ExisteId('TitBuscar')) $('TitBuscar').parentNode.removeChild($('TitBuscar'));
      if(ExisteId('SelBuscar')) $('SelBuscar').parentNode.removeChild($('SelBuscar'));
   }
   
   if(!oVal.FiltrarBusquedaPorMarca) {
      if(ExisteId('TitMarca')) $('TitMarca').parentNode.removeChild($('TitMarca'));
      if(ExisteId('SelMarca')) $('SelMarca').parentNode.removeChild($('SelMarca'));
   }   

   if(ExisteId('RelacionDeArticulosCSS') && oVal.FrmArticulos != undefined) $('RelacionDeArticulosCSS').href='css/RelacionDeArticulos' + oVal.FrmArticulos + '.css';
}

function Alert(cTxt, idFoco)
{
   DivFondo(true);
   $('TextoAtencion').innerHTML = cTxt;
   if(idFoco) $('AtencionAceptar').idFoco = idFoco;
   else       $('AtencionAceptar').idFoco = null;
   Boton('AtencionAceptar', function(){
      $('DivAtencion').hide(); 
      DivFondo(false);
      if($('AtencionAceptar').idFoco != null) $($('AtencionAceptar').idFoco).focus();
   }, 'Aceptar y cerrar');   
   $('DivAtencion').show();
   var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivAtencion').offsetHeight) / 2;
   var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivAtencion').offsetWidth) / 2;
   if(top < 1) top =  1;
   if(left < 1) left = 1;
   $('DivAtencion').style.top  = document.body.scrollTop + top;
   $('DivAtencion').style.left = left;
   if(!Prototype.Browser.IE) {
      document.onkeypress = function(e) {
         if(e.keyCode == Event.KEY_RETURN || e.keyCode == Event.KEY_ESC) {
            document.onkeypress = null;
            $('AtencionAceptar').OnClick();
         }
      }
   }
}

function Confirm(cTxt, FuncionAceptar, FuncionCancelar)
{
   DivFondo(true);
   $('TextoPregunta').innerHTML = cTxt;
   Boton('PreguntaAceptar', function() {
      $('DivPregunta').hide();
      DivFondo(false);
      if(FuncionAceptar != undefined) FuncionAceptar();
   }, 'Aceptar y cerrar');
   Boton('PreguntaCancelar', function() {
      $('DivPregunta').hide();
      DivFondo(false);
      if(FuncionCancelar != undefined) FuncionCancelar();
   }, 'Cancelar y cerrar');
   $('DivPregunta').show();
   var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivPregunta').offsetHeight) / 2;
   var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivPregunta').offsetWidth) / 2;
   if(top < 1) top = 1;
   if(left < 1) left = 1;
   $('DivPregunta').style.top  = document.body.scrollTop + top;
   $('DivPregunta').style.left = left;      
   if(!Prototype.Browser.IE) {
      document.onkeypress = function(e) {
         if(e.keyCode == Event.KEY_ESC) {
            document.onkeypress = null;
            $('PreguntaCancelar').OnClick();
         }
      }   
   }
}

function VerDatosArticulo(oArt) 
{
   if(ExisteId('DivDescArticulo')) {
      var nAltoMaxImagen = null;
      var nAnchoMaxImagen = null;
   
      if(oArt.Imagen != undefined && oArt.Imagen != '') {
      }
      
      DivFondo(true);
      if(ExisteId('TdTitDescArticulo')) $('TdTitDescArticulo').innerHTML = oArt.Titulo;
      if(ExisteId('TdDescArticulo'))    $('TdDescArticulo').innerHTML = oArt.Descripcion;
      if(ExisteId('TdImgDescArticulo') && oArt.Imagen != undefined && oArt.Imagen != '') {
         while($('TdImgDescArticulo').hasChildNodes()) $('TdImgDescArticulo').removeChild($('TdImgDescArticulo').lastChild);
         var oImg = document.createElement("IMG");
         oImg.setAttribute('src', oArt.Imagen);
         oImg.setAttribute('border', '0');
         $('TdImgDescArticulo').Imagen = oArt.Imagen;
         $('TdImgDescArticulo').Alto = oArt.ImgHeight;
         $('TdImgDescArticulo').Ancho = oArt.ImgWith;
         if(ExisteId('AltoMaximoDeImagenes')) nAltoMaxImagen = parseInt($('AltoDescMaxImg').value);
         if(ExisteId('AnchoMaximoDeImagenes')) nAnchoMaxImagen = parseInt($('AnchoDescMaxImg').value);
         if(nAltoMaxImagen != null && oArt.ImgHeight > nAltoMaxImagen) {
            nRel = oArt.ImgHeight / oArt.ImgWith;
            oArt.ImgHeight = nAltoMaxImagen;
            oArt.ImgWith = oArt.ImgHeight / nRel;
         }
         if(nAnchoMaxImagen != null && oArt.ImgWith > nAnchoMaxImagen) {
            nRel = oArt.ImgWith / oArt.ImgHeight;
            oArt.ImgWith = nAnchoMaxImagen;
            oArt.ImgHeight = oArt.ImgWith / nRel;
         }
         oImg.setAttribute('height', oArt.ImgHeight);
         oImg.setAttribute('width', oArt.ImgWith);
         $('TdImgDescArticulo').appendChild(oImg);         
         $('TdImgDescArticulo').setStyle('cursor: pointer;');
         ToolTip('TdImgDescArticulo', 'Ampliar');
         if($('TdImgDescArticulo').DefFnc == undefined) Event.observe('TdImgDescArticulo', 'click', function() { 
            $('TdImgDescArticulo').DefFnc = true;
            $('DivDescArticulo').hide(); 
            DivFondo(false); 
            VerImagen(this); 
         });
      }
      
      Boton('DescArticuloAceptar', function(){
         $('DivDescArticulo').hide(); 
         DivFondo(false);
      }, 'Cerrar');   
      $('DivDescArticulo').show();
      
      var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivDescArticulo').offsetHeight) / 2;
      var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivDescArticulo').offsetWidth) / 2;
      if(top < 1) top =  1;
      if(left < 1) left = 1;
      $('DivDescArticulo').style.top  = document.body.scrollTop + top;
      $('DivDescArticulo').style.left = left;
      if(!Prototype.Browser.IE) {
         document.onkeypress = function(e) {
            if(e.keyCode == Event.KEY_RETURN || e.keyCode == Event.KEY_ESC) {
               document.onkeypress = null;
               $('DescArticuloAceptar').OnClick();
            }
         }
      }
   }
}

function OnEnter(id, fnc)
{
   Event.observe(id, 'keypress', function(e) {
      if(e.keyCode == Event.KEY_RETURN) {
         $(id).blur();
         Event.stop(e);
         if(fnc != undefined) {
            if(typeof fnc == 'string') $(fnc).focus();
            else {
               $(id).OnEnter = fnc;
               $(id).OnEnter();
            }
         } else if($(id).OnEnter != undefined) $(id).OnEnter();
      }
   });
}
function OnEsc(id, fnc)
{
   Event.observe(id, 'keypress', function(e) {
      if(e.keyCode == Event.KEY_ESC) {
         $(id).blur();
         Event.stop(e);
         if(fnc != undefined) {
            $(id).OnEsc = fnc;
            $(id).OnEsc();
         } else if($(id).OnEsc != undefined) $(id).OnEsc();
      }
   });
}

function DivFondo(show, nOpac)
{
   var Opacidad = (nOpac == undefined ? 1 : nOpac)
   var aSelect = $$('SELECT');
   if(Prototype.Browser.IE && aSelect.length > 0) {
      for(x = 0; x < aSelect.length; x++) {
         if(aSelect[x].getAttribute('id') != 'SelBuscar' && aSelect[x].getAttribute('id') != 'SelMarca') { 
            if(show) aSelect[x].hide();
            else     aSelect[x].show();
         }
      }
   }
   if(show) {
      $('DivFondo').show();
      $('DivFondo').style.left  = "0px";
      $('DivFondo').style.top   = "0px";
      $('DivFondo').style.width = (document.layers ? window.innerWidth : document.body.clientWidth);
      $('DivFondo').style.height= Math.max(Math.max(document.body.scrollHeight, document.documentElement.scrollHeight),
                                           Math.max(document.body.offsetHeight, document.documentElement.offsetHeight),
                                           Math.max(document.body.clientHeight, document.documentElement.clientHeight)) + "px";
      $('DivFondo').style.opacity = "" + (Opacidad / 100);
      $('DivFondo').style.filter = "alpha(opacity=" + Opacidad + ")";
   } else {
      $('DivFondo').hide();
   }
}


function MsjReloj(sTxt) { $('MsjPausa').innerHTML = sTxt; }
function DivReloj(show)
{
   if(show) {
      DivFondo(true);
      $('DivPausa').show();
      var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivPausa').offsetHeight) / 2;
      var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivPausa').offsetWidth) / 2;
      if(top < 1) top = 1;
      if(left < 1) left = 1;
      $('DivPausa').style.top  =  document.body.scrollTop + top;
      $('DivPausa').style.left = left;
   } else {
      $('DivPausa').hide();
      $('MsjPausa').innerHTML = '';
      DivFondo(false);
   }
}

function Boton(cId, Funcion, cToolTip)
{
   if(!ExisteId(cId)) {
      $('CuadroAviso').Mostrar('Boton: El Boton \'' + cId + '\' no existe.');
      return;
   }
   $(cId).removeClassName('SpanBoton');
   $(cId).removeClassName('SpanBoton_Over');
   $(cId).removeClassName('SpanBoton_Disabled');
   
   $(cId).stopObserving('mouseover');
   $(cId).stopObserving('mouseout');
   $(cId).stopObserving('mousemove');
   $(cId).stopObserving('click');

   if(Funcion == undefined || Funcion == null) {
      $(cId).Habilitado = false;
      $(cId).addClassName('SpanBoton_Disabled');
      $(cId).stopObserving('mouseover');
      $(cId).stopObserving('mouseout');
      $(cId).stopObserving('click');
      $(cId).OnClick = undefined;
   } else {
      $(cId).Habilitado = true;
      $(cId).addClassName('SpanBoton');
      $(cId).OnClick = Funcion;
      Event.observe(cId, 'mouseover', function() {
         if(this.Habilitado) {
            $(cId).removeClassName('SpanBoton');
            $(cId).addClassName('SpanBoton_Over');
         }
      });
      Event.observe(cId, 'mouseout', function() {
         if(this.Habilitado) {
            $(cId).removeClassName('SpanBoton_Over');
            $(cId).addClassName('SpanBoton');
         }
      });      
      Event.observe(cId, 'click', function() { 
         if(this.Habilitado) {
            if(this.OnClick != undefined) this.OnClick(); 
            else alert('Funcion de boton no definida');
         }
      });
   }
   
   if(cToolTip == undefined) ToolTip(cId);
   else                      ToolTip(cId, cToolTip);
}

function HabilitarBoton(cId, valor)
{
   if(!ExisteId(cId)) {
      $('CuadroAviso').Mostrar('HabilitarBoton: El Boton \'' + cId + '\' no existe.');
      return;
   }   
   if(valor) {
      $(cId).removeClassName('SpanBoton_Disabled');
      $(cId).addClassName('SpanBoton');
      $(cId).Habilitado = true;
   } else {
      $(cId).removeClassName('SpanBoton');
      $(cId).addClassName('SpanBoton_Disabled');
      $(cId).Habilitado = false;
   }
}

function BotonImagen(cId, cImg, Funcion)
{
   if(!ExisteId(cId)) {
      $('CuadroAviso').Mostrar('BotonImagen: El Boton \'' + cId + '\' no existe.');
      return;
   }
   var ImgSel = $(cId).src;
   $(cId).Normal = ImgSel;
   var j = ImgSel.length - 1;
   while(j > -1) {
      if(ImgSel.charAt(j) == '/') {
         j++;
         $(cId).Seleccionado = ImgSel.substring(0, j) + cImg;
         j = -1;
      }  else j--;
   }
   $(cId).Funcion = (Funcion == undefined || Funcion == null) ? null : Funcion;
   Event.observe(cId, 'mouseover', function() { this.src=this.Seleccionado; this.style.cursor='pointer';});
   Event.observe(cId, 'mouseout', function() { this.src=this.Normal; this.style.cursor='normal';});
   Event.observe(cId, 'click', function() { if(this.Funcion != null) this.Funcion(); });
}

function BotonLink(cId, Funcion)
{
   if(!ExisteId(cId)) {
      $('CuadroAviso').Mostrar('BotonLink: El enlace \'' + cId + '\' no existe.');
      return;
   }
   if($(cId).nodeName == "A") {
      $(cId).Funcion = Funcion;
      Event.observe(cId, 'click', function() {if(this.getAttribute(_ClassName_) != 'Disabled') this.Funcion();});
   } else {
      if($(cId).Clase == null) $(cId).Clase = $(cId).readAttribute('class');
      if(Funcion == undefined) {
         $(cId).removeClassName($(cId).Clase);
         $(cId).removeClassName($(cId).Clase + 'Hover');
         $(cId).addClassName($(cId).Clase + 'Desh');
         $(cId).stopObserving('mouseover');
         $(cId).stopObserving('mouseout');
         $(cId).stopObserving('click');
      } else {
         $(cId).removeClassName($(cId).Clase + 'Hover');
         $(cId).removeClassName($(cId).Clase + 'Desh');
         $(cId).addClassName($(cId).Clase);
         $(cId).Funcion = (Funcion == undefined || Funcion == null) ? null : Funcion;
         Event.observe(cId, 'mouseover', function() { 
            $(cId).removeClassName($(cId).Clase); 
            $(cId).removeClassName($(cId).Clase + 'Desh');
            $(cId).addClassName($(cId).Clase + 'Hover'); 
         });
         Event.observe(cId, 'mouseout', function()  { 
            $(cId).removeClassName($(cId).Clase + 'Hover');
            $(cId).removeClassName($(cId).Clase + 'Desh');
            $(cId).addClassName($(cId).Clase); 
         });
         Event.observe(cId, 'click', function() { if(this.Funcion != null) this.Funcion(); });
      }
   }
}

function OpcionMenu(cId, Funcion)
{
   if(!ExisteId(cId)) {
      $('CuadroAviso').Mostrar('OpcionMenu: La opcion \'' + cId + '\' no existe.');
      return;
   }
   if($(cId).NombreDeClase == null) $(cId).NombreDeClase = $(cId).getAttribute('CLASS');   
   if(Funcion == null) {
      $(cId).removeClassName($(cId).NombreDeClase);
      $(cId).removeClassName($(cId).NombreDeClase + 'Sel');
      $(cId).addClassName($(cId).NombreDeClase + 'Desh');
      $(cId).stopObserving('mouseover');
      $(cId).stopObserving('mouseout');
      $(cId).stopObserving('click');
   } else {
      $(cId).removeClassName($(cId).NombreDeClase + 'Sel');
      $(cId).removeClassName($(cId).NombreDeClase + 'Desh');
      $(cId).addClassName($(cId).NombreDeClase); 
      $(cId).Funcion = Funcion;
      if($(cId).NombreDeClase != null) {
         Event.observe(cId, 'mouseover', function() { 
            $(cId).removeClassName($(cId).NombreDeClase);
            $(cId).removeClassName($(cId).NombreDeClase + 'Desh');
            $(cId).addClassName($(cId).NombreDeClase + 'Sel'); 
         });
         Event.observe(cId, 'mouseout', function()  { 
            $(cId).removeClassName($(cId).NombreDeClase + 'Sel');
            $(cId).removeClassName($(cId).NombreDeClase + 'Desh');
            $(cId).addClassName($(cId).NombreDeClase); 
         });
      }
      Event.observe(cId, 'click', function() { this.Funcion(); });   
   }
}

function ToolTip(cId, cTxt)
{
   if(!ExisteId(cId)) {
      $('CuadroAviso').Mostrar('ToolTip: El elemento \'' + cId + '\' no existe.');
      return;
   }
   if(cTxt != undefined) $(cId).TxtToolTip = cTxt;
   
   if($(cId).TxtToolTip) {
      Event.observe(cId, 'mouseover', function() {
         if(!this.TimeOnToolTip)  this.TimeOnToolTip  =  500;
         if(!this.TimeOffToolTip) this.TimeOffToolTip = 2500;
         if($('toolTip').idTimeout) clearTimeout($('toolTip').idTimeout);
         var ev = arguments[0] ? arguments[0] : event;
         $('toolTip').style.top  = ev.clientY + 20 + document.body.scrollTop + "px";
         $('toolTip').style.left = ev.clientX + 13 + document.body.scrollLeft + "px";
         $('toolTip').innerHTML = this.TxtToolTip;
         $('toolTip').idTimeout = setTimeout("$('toolTip').style.display = 'block'; Opacidad('toolTip', 70); $('toolTip').idTimeout = setTimeout(\"$('toolTip').hide();\", " + this.TimeOffToolTip + ");", this.TimeOnToolTip);
      });
      
      Event.observe(cId, 'mousemove', function() {
         var ev = arguments[0] ? arguments[0] : event;
         $('toolTip').style.top  = ev.clientY + 20 + document.body.scrollTop + "px";
         $('toolTip').style.left = ev.clientX + 13 + document.body.scrollLeft + "px";
      });
   
      Event.observe(cId, 'mouseout', function() {
         if($('toolTip').idTimeout) clearTimeout($('toolTip').idTimeout);
         $('toolTip').hide();
      });
      
      Event.observe(cId, 'click', function() {
         if($('toolTip').idTimeout) clearTimeout($('toolTip').idTimeout);
         $('toolTip').hide();
      });   
   }
}

function VerImagen(oImg)
{
   var Alto   = (document.layers ? window.innerHeight : document.body.clientHeight);
   var Ancho  = (document.layers ? window.innerWidth : document.body.clientWidth);

   DivFondo(true);
   
   $('ImgVerImagen').src = oImg.Imagen;
   var Rel = oImg.Ancho / oImg.Alto;
   if(Rel >= 1) {
      oImg.Ancho = Ancho / 3;
      oImg.Alto  = oImg.Ancho / Rel;
      $('ImgVerImagen').style.width = oImg.Ancho;
      $('ImgVerImagen').style.height = "";
   } else {
      oImg.Alto = Alto / 3;
      oImg.Ancho = oImg.Alto * Rel;
      $('ImgVerImagen').style.width = "";
      $('ImgVerImagen').style.height = oImg.Alto;
   }
   $('DivVerImagen').style.top  = document.body.scrollTop + ((Alto - oImg.Alto) / 2) - 30;
   $('DivVerImagen').style.left = (Ancho - oImg.Ancho) / 2;
   $('DivVerImagen').show();   
   Boton('ImagenAceptar', function() {
      $('ImgVerImagen').src = './images/app/blanco.gif';
      $('DivVerImagen').hide(); 
      DivFondo(false); 
   }, 'Cerrar');
   if(!Prototype.Browser.IE) {
      document.onkeypress = function(e) {
         if(e.keyCode == Event.KEY_RETURN || e.keyCode == Event.KEY_ESC) {
            document.onkeypress = null;
            $('ImagenAceptar').OnClick();
         }
      }   
   }
}

function Control1(sVal)
{
   var aHidden = $$('INPUT');
   for(x = 0; x < aHidden.length; x++)
      if(aHidden[x].type.toUpperCase() == 'HIDDEN' && aHidden[x].id == 'Control1') {
         if(sVal == undefined) return aHidden[x].value;
         else {
            aHidden[x].value = sVal;
            return;
         }
      }
   return '';
}

function PonerMenuProductos(Fnc)
{
   if(ExisteId('MenuProductos')) {
      _("app.aspx", "acc=_MENUPRODUCTOS_", function(oVal) {
         $('MenuProductos').nId = 1;
         $('MenuProductos').ListaID = "";
         var oTbody = $('MenuProductos').getElementsByTagName('TBODY')[0];
         ((oTbody.getElementsByTagName('TR')[0]).getElementsByTagName('DIV')[0]).style.display='none';
         var oTr = (oTbody.getElementsByTagName('TR')[0]).cloneNode(true);
         oTbody.removeChild(oTbody.getElementsByTagName('TR')[0]);
         OpcionMenuProductos(oTbody, oTr, oVal.Opciones, 1, '', null);
         if($('MenuProductos').ListaID.length > 0) {
            $('MenuProductos').ListaID = $('MenuProductos').ListaID.split('&');
            for(j = 0 ; j < $('MenuProductos').ListaID.length ; j++) {
               sId = $('MenuProductos').ListaID[j];
               $(sId).setStyle('cursor: pointer;');
               Event.observe(sId, 'mouseover', function() {(this.getElementsByTagName('SPAN')[0]).setAttribute(_ClassName_, 'Underline');});
               Event.observe(sId, 'mouseout',  function() {(this.getElementsByTagName('SPAN')[0]).removeAttribute(_ClassName_);});
               Event.observe(sId, 'click', function() {
                  MostarOpcMenuProductos(this);
                  if(this.Busqueda != '') _("app.aspx", "acc=" + "_LISTAARTICULOS_&" + this.Busqueda, VerArticulos);
               });
            }
         } else {
            $('MenuProductos').hide();
            Alert("En este momento no hay productos disponibles");
         }
         PonerFamilias(Fnc);
      });
   } else PonerFamilias(Fnc);
}

function MostarOpcMenuProductos(oOpc)
{
   var oTbl = oOpc; 
   while(oTbl.nodeName != "TABLE") oTbl = oTbl.parentNode;
   var oTbody = oTbl.getElementsByTagName('TBODY')[0];
   var oTr = oTbody.getElementsByTagName('TR');
   
   if(oTr.length > 0) {
      for(j = 0; j < oTr.length ; j++) {
         if(oTr[j].Raiz == oOpc.id) {
            var oDiv = (oTr[j].getElementsByTagName('TD')[0]).getElementsByTagName('DIV')[0];
            if(oOpc.Visible) {
               var oTbl2 = oDiv.getElementsByTagName('TABLE')[0];
               var oSubOpc = (((oTbl2).getElementsByTagName('THEAD')[0]).getElementsByTagName('TR')[0]).getElementsByTagName('TD')[0];
               if(oSubOpc.Visible) MostarOpcMenuProductos(oSubOpc);
               (oOpc.getElementsByTagName('IMG')[0]).setAttribute('src', './images/app/Opcion_Mas.gif');
               oDiv.style.display = 'none';
            } else {
               (oOpc.getElementsByTagName('IMG')[0]).setAttribute('src', './images/app/Opcion_Menos.gif');
               oDiv.style.display = 'block';
            }
         }
      }
      oOpc.Visible = ! oOpc.Visible;
   }
}

function OpcionMenuProductos(oTbody, oTr, Opciones, Nivel, Busqueda, Raiz)
{
   var j, Nombre, oOpc, Mostrados = 0, lMostrar = true, sId;
   
   for(j = 0; j < Opciones.length; j++) {
      sId = '_OpcMenu_' + $('MenuProductos').nId++;      
      if(Opciones.length == 1 && Opciones[0].Nombre == '') lMostrar = false;
      
      Nombre = (Opciones[j].Nombre == '' ? 'Varios' : Opciones[j].Nombre);
      oOpc = oTr.cloneNode(true);
      oOpc.Busqueda = Busqueda + (Busqueda == '' ? '' : '&') + Opciones[j].Tipo + '=' + Opciones[j].Codigo;
      oOpc.Raiz = Raiz;
      (oOpc.getElementsByTagName('SPAN')[0]).appendChild(document.createTextNode(Nombre));
      
      if(Opciones[j].Opciones) {
         nRet = OpcionMenuProductos(oOpc.getElementsByTagName('TBODY')[0], oTr, Opciones[j].Opciones, Nivel + 1, oOpc.Busqueda, sId);
         if(nRet > 0) (oOpc.getElementsByTagName('IMG')[0]).setAttribute('src', './images/app/Opcion_Mas.gif');
         if(nRet == Opciones[j].Opciones.length) oOpc.Busqueda = '';
         if(!lMostrar && nRet > 0) lMostrar = true;
      }
      
      if(lMostrar) {
         (oOpc.getElementsByTagName('TD')[1]).Busqueda = oOpc.Busqueda; oOpc.Busqueda = '';
         (oOpc.getElementsByTagName('TD')[1]).Visible = false;
         (oOpc.getElementsByTagName('TD')[1]).setAttribute('id', sId);
         if($('MenuProductos').ListaID != '') $('MenuProductos').ListaID += '&';
         $('MenuProductos').ListaID += sId;
         
         oTbody.appendChild(oOpc);
         Mostrados++;
         if(Nivel == 1) (oOpc.getElementsByTagName('DIV')[0]).style.display='block';
      }
   }
   return Mostrados;
}

function PonerFamilias(Fnc)
{
   if(ExisteId('SelBuscar')) {
      while($('SelBuscar').hasChildNodes()) $('SelBuscar').removeChild($('SelBuscar').lastChild);
      _("app.aspx", "acc=_MENUFAMILIA_", function(oFam) {
         for(var j = -1; j < oFam.Total; j++) {
            opc = document.createElement("option");
            if(j == -1 ) {
               opc.setAttribute('value', '*');
               opc.appendChild(document.createTextNode('Todos los productos'));
               $('SelBuscar').appendChild(opc);
            } else {
               opc.setAttribute('value', oFam.Codigo[j]);
               opc.appendChild(document.createTextNode(oFam.Nombre[j]));
               $('SelBuscar').appendChild(opc);
               for(var k = 0; k < oFam.SubFam[j].Total; k++) {
                  opc = document.createElement("option");
                  opc.setAttribute('value', oFam.Codigo[j] + ">|<" + oFam.SubFam[j].Codigo[k]);
                  opc.appendChild(document.createTextNode("- " + oFam.SubFam[j].Nombre[k]));
                  $('SelBuscar').appendChild(opc);
               }
            }
         }
         $('SelBuscar').show();
         if(ExisteId('SelMarca')) Event.observe('SelBuscar', 'change', function(){PonerMarcas(undefined);});
         PonerMarcas(Fnc)
      });
   } else PonerMarcas(Fnc);
}

function PonerMarcas(Fnc)
{
   if(ExisteId('SelMarca')) {
      var sUrl = "acc=_LISTAR_MARCAS_";
      if(ExisteId('SelBuscar')) {
         var sFam = ($('SelBuscar').value == '*' ? '' : $('SelBuscar').value);
         var sSubFam = '';
         var k = sFam.indexOf('>|<');
         if(k > -1) {
            sSubFam = sFam.substring(k + 3, sFam.length);
            sFam = sFam.substring(0, k);
         }
         if(sFam != '') {
            sUrl += "&param1=" + encodeURIComponent(sFam);
            if(sSubFam != '') sUrl += "&param2=" + encodeURIComponent(sSubFam);
         }
      }
      _("app.aspx", sUrl, function(oMarcas) {
         while($('SelMarca').hasChildNodes()) $('SelMarca').removeChild($('SelMarca').lastChild);         
         for(var j = -1; j < oMarcas.Total; j++) {
            opc = document.createElement("option");
            if(j == -1 ) {
               opc.setAttribute('value', '*');
               opc.appendChild(document.createTextNode('Todas las marcas'));
               $('SelMarca').appendChild(opc);
            } else {
               opc.setAttribute('value', oMarcas.Codigo[j]);
               opc.appendChild(document.createTextNode(oMarcas.Nombre[j]));
               $('SelMarca').appendChild(opc);
            }
         }
         $('SelMarca').show();
         if(Fnc != undefined) Fnc();   
      });
   } else if(Fnc != undefined) Fnc();
}

function VerArticulos(oArt)
{
   var nAltoMaxImagen = null;
   var nAnchoMaxImagen = null;
      
   if($('TblCesta').NumLineas > 0)  HabilitarBoton('SpanComprar', true);
   
   if(oArt.Total == 0) {
      $('TdContenido').innerHTML = oArt.HTML;
   } else {
      $('TdContenido').hide();
      $('TdContenido').innerHTML = oArt.HTML;
      if(oArt.Caption)  {
         var oCaption = $('Marco').getElementsByTagName('CAPTION')[0];
         oCaption.innerHTML = "<p>" + oArt.Caption + "</p>";
      }
      
      if(ExisteId('DivDescArticulo')) $('DivDescArticulo').hide();      
      if(!ExisteId('TblArtNom')) { $('TdContenido').show(); return; }
      
      if(ExisteId('TblArtImg') && ExisteId('AltoMaximoDeImagenes')) nAltoMaxImagen = parseInt($('AltoMaximoDeImagenes').value);
      if(ExisteId('TblArtImg') && ExisteId('AnchoMaximoDeImagenes')) nAnchoMaxImagen = parseInt($('AnchoMaximoDeImagenes').value);
      
      var oTbody;
      if(ExisteId('BodyTblLst')) oTbody = $('BodyTblLst');
      else oTbody = $('Marco').getElementsByTagName('TBODY')[0];
      var oFila = (oTbody.getElementsByTagName('tr')[0]).cloneNode(true);
      oTbody.removeChild(oTbody.getElementsByTagName('tr')[0]);
      for(x = 0; x < oArt.Total; x++) {
         oTbody.appendChild(oFila.cloneNode(true));
         if(ExisteId('TblArtRef')) {
            $('TblArtRef').innerHTML = oArt.Codigo[x];
            $('TblArtRef').setAttribute('id', '');
         }
         if(ExisteId('TblArtBar')) {
            $('TblArtBar').innerHTML = oArt.CodBarras[x];
            $('TblArtBar').setAttribute('id', '');
         }         
         if(ExisteId('TblArtNom')) {
            $('TblArtNom').innerHTML = oArt.Nombre[x];
            $('TblArtNom').setAttribute('id', '');
         }
         if(ExisteId('TblArtMar')) {
            $('TblArtMar').innerHTML = (oArt.Marca[x] == '' ? '&nbsp;' : oArt.Marca[x]);
            $('TblArtMar').setAttribute('id', '');
         }         
         if(ExisteId('TblArtObs')) {         
            $('TblArtObs').innerHTML = (oArt.Obs[x] == '' ? '&nbsp;' : oArt.Obs[x]);
            $('TblArtObs').setAttribute('id', '');
         }

         if(oArt.Pvp[x] == "") {
            if(ExisteId('TblArtPre'))   $('TblArtPre').parentNode.removeChild($('TblArtPre'));
            if(ExisteId('TblArtEuro'))  $('TblArtEuro').parentNode.removeChild($('TblArtEuro'));
            if(ExisteId('TblArtCarro')) $('TblArtCarro').parentNode.removeChild($('TblArtCarro'));
            if(ExisteId('TblArtCan'))   $('TblArtCan').parentNode.removeChild($('TblArtCan'));
            if(ExisteId('TdClasf11'))   $('TdClasf11').parentNode.removeChild($('TdClasf11'));
            if(ExisteId('TdClasf12'))   $('TdClasf12').parentNode.removeChild($('TdClasf12'));
            if(ExisteId('TdClasf21'))   $('TdClasf21').parentNode.removeChild($('TdClasf21'));
            if(ExisteId('TdClasf22'))   $('TdClasf22').parentNode.removeChild($('TdClasf22'));
         }         
         
         if(ExisteId('TblArtPre')) {
            $('TblArtPre').innerHTML = oArt.Pvp[x];
            $('TblArtPre').setAttribute('id', 'Pvp_' + oArt.Codigo[x]);
         }
         if(ExisteId('TblArtEuro')) {
            $('TblArtEuro').setAttribute('id', 'Eur_' + oArt.Codigo[x]);
         }
         if(ExisteId('TlbArtSaldo')) $('TlbArtSaldo').setAttribute('id', 'Sld_' + oArt.Codigo[x]);
         else VerStock = false;

         if(ExisteId('TblArtImg')) {
            if(nAltoMaxImagen != null && oArt.ImgHeight[x] > nAltoMaxImagen) {
               nRel = oArt.ImgHeight[x] / oArt.ImgWith[x];
               oArt.ImgHeight[x] = nAltoMaxImagen;
               oArt.ImgWith[x] = oArt.ImgHeight[x] / nRel;
            }
            if(nAnchoMaxImagen != null && oArt.ImgWith[x] > nAnchoMaxImagen) {
               nRel = oArt.ImgWith[x] / oArt.ImgHeight[x];
               oArt.ImgWith[x] = nAnchoMaxImagen;
               oArt.ImgHeight[x] = oArt.ImgWith[x] / nRel;
            }
            oImg = document.createElement("IMG");
            oImg.setAttribute('src', oArt.Img[x]);
            oImg.setAttribute('border', '0');
            oImg.setAttribute('height', oArt.ImgHeight[x]);
            oImg.setAttribute('width', oArt.ImgWith[x]);
            $('TblArtImg').appendChild(oImg);
            $('TblArtImg').setAttribute('id', '');
            if(oArt.Ampliar[x]) {   
               oImg.setAttribute('id', 'ImgArt');
               oImg.Imagen = oArt.Img[x];
               oImg.Alto = oArt.ImgHeight[x];
               oImg.Ancho = oArt.ImgWith[x];
               $('ImgArt').setStyle('cursor: pointer;');
               ToolTip('ImgArt', 'Ampliar');
               Event.observe('ImgArt', 'click', function() { VerImagen(this); });
               $('ImgArt').setAttribute('id', '');
            }
         } else {
            oArt.Ampliar[x] = false;
         }
 
         if(ExisteId('FichaCompra')) {
            $('FichaCompra').setAttribute('id', 'FichaCompra_' + oArt.Codigo[x]);
            $('FichaCompra_' + oArt.Codigo[x]).Codigo = oArt.Codigo[x];
            $('FichaCompra_' + oArt.Codigo[x]).Plantilla = $('FichaCompra_' + oArt.Codigo[x]).getAttribute('Plantilla');
            Event.observe('FichaCompra_' + oArt.Codigo[x], 'click', function() {
               _("app.aspx", "acc=" + encodeURIComponent("_BUSCAARTICULO_") + "&codigo=" + encodeURIComponent(this.Codigo) + "&plantilla=" + (this.Plantilla == null ? '' : this.Plantilla), VerArticulos);
            });
         }         
         
         if(ExisteId('VerDetalles')) {
            if(oArt.Obs[x] == '') {
               $('VerDetalles').parentNode.removeChild($('VerDetalles'));            
               if(ExisteId('DivDetalles')) $('DivDetalles').parentNode.removeChild($('DivDetalles'));
            } else {
               $('VerDetalles').setAttribute('id', 'VerDetallesArt_' + oArt.Codigo[x]);
               if(ExisteId('DivDetalles')) {
                  $('DivDetalles').setAttribute('id', 'DivDetalles_' + oArt.Codigo[x]);
                  $('DivDetalles_' + oArt.Codigo[x]).hide();
                  if(! $('DivDetalles_' + oArt.Codigo[x]).hasChildNodes()) $('DivDetalles_' + oArt.Codigo[x]).innerHTML = oArt.Obs[x];
                  $('DivDetalles_' + oArt.Codigo[x]).Visible = false;
                  $('DivDetalles_' + oArt.Codigo[x]).Mostrar = function(oBoton) {
                     if(oBoton != undefined) {
                        if(oBoton.TxtMostar == undefined) {
                           oBoton.TxtMostar = oBoton.innerHTML;
                           oBoton.TxtOcultar = (oBoton.getAttribute('TxtOcultar') == null ? oBoton.TxtMostar: oBoton.getAttribute('TxtOcultar'));
                        }
                        if(oBoton.TxtMostar != oBoton.TxtOcultar) oBoton.innerHTML = (this.Visible ? oBoton.TxtMostar : oBoton.TxtOcultar);
                     }
                     if(this.Visible) {
                        this.Visible = false;
                        Effect.BlindUp(this.id, {duration: 0.15});
                     } else {
                        this.Visible = true;
                        Effect.BlindDown(this.id, {duration: 0.15});
                     }
                  }                  
                  $('VerDetallesArt_' + oArt.Codigo[x]).Mostrar = 'DivDetalles_' + oArt.Codigo[x];
               } else $('VerDetallesArt_' + oArt.Codigo[x]).Mostrar = null;
               
               $('VerDetallesArt_' + oArt.Codigo[x]).Titulo = oArt.Nombre[x];
               $('VerDetallesArt_' + oArt.Codigo[x]).Descripcion = oArt.Obs[x];
               $('VerDetallesArt_' + oArt.Codigo[x]).Imagen = oArt.Img[x];
               $('VerDetallesArt_' + oArt.Codigo[x]).ImgWith = oArt.ImgWith[x]
               $('VerDetallesArt_' + oArt.Codigo[x]).ImgHeight = oArt.ImgHeight[x]

               if($('VerDetallesArt_' + oArt.Codigo[x]).className == 'SpanBoton') {
                  Boton('VerDetallesArt_' + oArt.Codigo[x], function() { if(this.Mostrar == null) VerDatosArticulo(this); else $(this.Mostrar).Mostrar(this);}, 'Mostrar detalles');
               } else if($('VerDetallesArt_' + oArt.Codigo[x]).nodeName == 'IMG' || $('VerDetallesArt_' + oArt.Codigo[x]).nodeName == 'A')
                  Event.observe('VerDetallesArt_' + oArt.Codigo[x], 'click', function() { if(this.Mostrar == null) VerDatosArticulo(this);  else $(this.Mostrar).Mostrar(this);});
               else if($('VerDetallesArt_' + oArt.Codigo[x]).nodeName == 'SPAN' || $('VerDetallesArt_' + oArt.Codigo[x]).nodeName == 'DIV') {
                  Event.observe('VerDetallesArt_' + oArt.Codigo[x], 'mouseover', function() { this.Clase = this.className; this.className = this.Clase + 'Sel';});
                  Event.observe('VerDetallesArt_' + oArt.Codigo[x], 'mouseout', function()  { this.className = this.Clase;});
                  Event.observe('VerDetallesArt_' + oArt.Codigo[x], 'click', function() { if(this.Mostrar == null) VerDatosArticulo(this);  else $(this.Mostrar).Mostrar();});
               }
            }
         } else if(ExisteId('DivDetalles')) {
            if(oArt.Obs[x] == '') $('DivDetalles').parentNode.removeChild($('DivDetalles'));
            else $('DivDetalles').setAttribute('id', 'DivDetalles_' + oArt.Codigo[x]);
         }
         
         if(ExisteId('TblArtAmp')) {
            if(oArt.Ampliar[x]) {
               oImg = document.createElement("IMG");
               oImg.setAttribute('src', './images/app/lupa.gif');
               oImg.setAttribute('border', 0);
               oImg.setAttribute('id', 'ImgLupa' );
               oImg.Imagen = oArt.Img[x];
               oImg.Alto = oArt.ImgHeight[x];
               oImg.Ancho = oArt.ImgWith[x];
               $('TblArtAmp').appendChild(oImg);            
               $('ImgLupa').setStyle('cursor: pointer;');
               ToolTip('ImgLupa', 'Ampliar');
               oImg.setAttribute('id', 'ImgLupa' );
               Event.observe('ImgLupa', 'click', function() { VerImagen(this); });
               $('ImgLupa').setAttribute('id', '');
            }
            $('TblArtAmp').setAttribute('id', '');
         }
         
         if(! ExisteId('TdClasf11')) oArt.HayDivisiones[x] = false;
                  
         if(oArt.HayDivisiones[x]) {
            Div1 = oArt.Divisiones1[x];
            Div2 = oArt.Divisiones2[x];
            
            /*
            oSpan = document.createElement("SPAN");
            oSpan.innerHTML = Tit1Div;
            $('TdClasf11').appendChild(oSpan);
            */
            $('TdClasf11').innerHTML = Tit1Div;
            

            oSel = document.createElement("SELECT");
            oSel.setAttribute('id', "Sel1_" + oArt.Codigo[x]);
            oSel.Codigo = oArt.Codigo[x];
            $('TdClasf12').appendChild(oSel);
            for(i = 0; i < Div1.length; i++) {
               opc = document.createElement("option");
               opc.setAttribute('value', Div1[i]);
               opc.innerHTML = Div1[i] + '&nbsp;&nbsp;'
               oSel.appendChild(opc);
            }
            oSel.setAttribute(_ClassName_, 'SelectClasificacion');
            
            /*
            oSpan = document.createElement("SPAN");
            oSpan.innerHTML = Tit2Div;
            $('TdClasf21').appendChild(oSpan);
            */
            $('TdClasf21').innerHTML = Tit2Div;
            
            oSel = document.createElement("SELECT");
            oSel.setAttribute('id', "Sel2_" + oArt.Codigo[x]);
            $('TdClasf22').appendChild(oSel);
            for(i = 0; i < Div2.length; i++) {
               opc = document.createElement("option");
               opc.setAttribute('value', Div2[i]);
               opc.innerHTML = Div2[i] + '&nbsp;&nbsp;'
               oSel.appendChild(opc);
            }
            oSel.setAttribute(_ClassName_, 'SelectClasificacion');

            Event.observe("Sel1_" + oArt.Codigo[x], 'change', function() {
               var CodArt = this.Codigo
               MsjReloj('Obteniendo ' + Tit2Div + '. Espere ...');
               _("app.aspx", "acc=_DIVISIONES_&codigo=" + encodeURIComponent(this.Codigo) + "&division=2&primera=" + $('Sel1_' + this.Codigo).value, function(oVal) {
                  while($('Sel2_' + CodArt).hasChildNodes()) $('Sel2_' + CodArt).removeChild($('Sel2_' + CodArt).lastChild);
                  if(oVal.Total > 0) {
                     for(i = 0; i < oVal.Divisiones.length; i++) {
                        opc = document.createElement("option");
                        opc.setAttribute('value', oVal.Divisiones[i]);
                        opc.appendChild(document.createTextNode(oVal.Divisiones[i]));
                        $('Sel2_' + CodArt).appendChild(opc);
                     }
                     if(VerStock && ExisteId('Sld_' + CodArt)) {
                        Event.observe("Sel2_" + CodArt, 'change', function() {
                           _("app.aspx", "acc=_SALDOALMACEN_&codigo=" + CodArt + $('Sel1_' + CodArt).value + $('Sel2_' + CodArt).value, function(oSaldo) {MostrarSaldo('Sld_' + CodArt, oSaldo.VerSaldo, oSaldo.Saldo, oSaldo.Comprar);});
                        });
                        _("app.aspx", "acc=_SALDOALMACEN_&codigo=" + CodArt + $('Sel1_' + CodArt).value + $('Sel2_' + CodArt).value, function(oSaldo) {MostrarSaldo('Sld_' + CodArt, oSaldo.VerSaldo, oSaldo.Saldo, oSaldo.Comprar);});
                     }
                  }
                });
            });
            
            $('TdClasf11').setAttribute('id', '');
            $('TdClasf12').setAttribute('id', '');
            $('TdClasf21').setAttribute('id', '');
            $('TdClasf22').setAttribute('id', '');
         } else {
            if(ExisteId('TdClasf11')) $('TdClasf11').parentNode.removeChild($('TdClasf11'));
            if(ExisteId('TdClasf12')) $('TdClasf12').parentNode.removeChild($('TdClasf12'));
            if(ExisteId('TdClasf21')) $('TdClasf21').parentNode.removeChild($('TdClasf21'));
            if(ExisteId('TdClasf22')) $('TdClasf22').parentNode.removeChild($('TdClasf22'));
         }
         
         if(TipoDocumento != '') {
            oInput = document.createElement("INPUT");
            oInput.setAttribute('type', (ExisteId('TblArtCan') ? 'TEXT' : 'HIDDEN'));
            oInput.setAttribute('value', '1' + sDecCanInput);
            oInput.setAttribute('size', '4');
            oInput.setAttribute('id', 'Cant_' + oArt.Codigo[x]);
   
            if(ExisteId('TblArtCan')) {
               $('TblArtCan').appendChild(oInput);
               $('Cant_' + oArt.Codigo[x]).addClassName('InputCantidad');
               $('TblArtCan').setAttribute('id', '');
            } else if(ExisteId('TblArtCarro')) {
               $('TblArtCarro').appendChild(oInput);
            }
         }
         
         if(ExisteId('TblArtCarro') && TipoDocumento != '') {
            oImg = document.createElement("IMG");
            oImg.setAttribute('src', 'images/app/carro.png');
            oImg.setAttribute('border', 0);
            oImg.setAttribute('height', 19);
            oImg.setAttribute('width', 24);
            oImg.setAttribute('id', 'ImgAgr_' + oArt.Codigo[x]);
            $('TblArtCarro').appendChild(oImg);
            $('ImgAgr_' + oArt.Codigo[x]).setStyle('cursor: pointer;');
            $('ImgAgr_' + oArt.Codigo[x]).setStyle('border: 10px;');
            ToolTip('ImgAgr_' + oArt.Codigo[x], 'Agregar a la cesta');
            $('ImgAgr_' + oArt.Codigo[x]).Codigo = oArt.Codigo[x];
            $('ImgAgr_' + oArt.Codigo[x]).Descripcion = oArt.Nombre[x];
            $('ImgAgr_' + oArt.Codigo[x]).Pvp = oArt.Pvp[x];
            $('ImgAgr_' + oArt.Codigo[x]).HayDivisiones = oArt.HayDivisiones[x];
            
            $('ImgAgr_' + oArt.Codigo[x]).OnClick = function() {
               if(ObsPorLinea) {
                  var cCodigo = encodeURIComponent(this.Codigo)
                  if(this.HayDivisiones) {
                     cCodigo += encodeURIComponent($('Sel1_' + this.Codigo).value);
                     cCodigo += encodeURIComponent($('Sel2_' + this.Codigo).value);
                  }
                  if(ExisteEnCesta(cCodigo)) AgregarArticulo(this.HayDivisiones, this.Codigo, this.Pvp);
                  else {
                     DivFondo(true);
                     $('DatosArticuloCodigo').innerHTML = this.Codigo;
                     $('DatosArticuloDescripcion').innerHTML = this.Descripcion;
                     if(this.HayDivisiones) {
                        $('DatosArticuloDescripcion').innerHTML += '<br>' + Tit1Div + ':&nbsp;' + $('Sel1_' + this.Codigo).value;
                        $('DatosArticuloDescripcion').innerHTML += '&nbsp;&nbsp;&nbsp;' + Tit2Div + ':&nbsp;' + $('Sel2_' + this.Codigo).value;
                     }
                     $('DatosArticuloCantidad').value = $('Cant_' + this.Codigo).value;
                     $('ArticuloCantidadBorrar').Codigo = this.Codigo;
                     $('ArticuloCantidadAceptar').Codigo = this.Codigo;
                     $('ArticuloCantidadAceptar').Pvp = this.Pvp;
                     $('ArticuloCantidadAceptar').HayDivisiones = this.HayDivisiones;
                     $('DatosArticuloPrecio').innerHTML = this.Pvp + '&nbsp;&euro;';

                     $('ArticuloCantidadBorrar').hide();
                     $('ArticuloCantidadAceptar').innerHTML = 'Agregar';
                     
                     oTh = document.createElement('th');
                     oTh.innerHTML = 'Observ.:';
                     
                     oTd = document.createElement('td');
                     oInp  = document.createElement('input');
                     oInp.setAttribute('type', 'text');
                     oInp.setAttribute('maxLength', '50');
                     oTd.appendChild(oInp);
                     
                     oTr = document.createElement('tr');
                     oTr.appendChild(oTh);
                     oTr.appendChild(oTd);
                     oTr.setAttribute('id', 'LineaObser');
                     
                     ($('TblArticuloCantidad').getElementsByTagName('TBODY')[0]).appendChild(oTr);
                     oInp.setAttribute('id', 'Observaciones'); 
                     
                     Boton('ArticuloCantidadAceptar', function() {
                        var sObs = $('Observaciones').value;
                        $('DivArticuloCantidad').hide();
                        $('ArticuloCantidadAceptar').innerHTML = 'Modificar';           
                        $('LineaObser').parentNode.removeChild($('LineaObser'));
                        DivFondo(false);
                        $('Cant_' + this.Codigo).value = $('DatosArticuloCantidad').value;
                        AgregarArticulo(this.HayDivisiones, this.Codigo, this.Pvp, sObs);
                     }, 'Agregar a la cesta');
                     Boton('ArticuloCantidadCancelar', function() {
                        $('DivArticuloCantidad').hide();
                        $('ArticuloCantidadAceptar').innerHTML = 'Modificar';
                        $('LineaObser').parentNode.removeChild($('LineaObser'));
                        DivFondo(false);
                     }, 'Cancelar operacion');
                     $('DivArticuloCantidad').show();
                     var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivArticuloCantidad').offsetHeight) / 2;
                     var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivArticuloCantidad').offsetWidth) / 2;
                     if(top < 1) top =  1;
                     if(left < 1) left = 1;
                     $('DivArticuloCantidad').style.top  = document.body.scrollTop + top;
                     $('DivArticuloCantidad').style.left = left;
                     OnEsc('DatosArticuloCantidad', function(){$('ArticuloCantidadCancelar').OnClick();});
                     if(ObsPorLinea) {
                        OnEnter('DatosArticuloCantidad', 'Observaciones');
                        OnEsc('Observaciones', function(){$('ArticuloCantidadCancelar').OnClick();});                     
                        OnEnter('Observaciones', function(){$('ArticuloCantidadAceptar').OnClick();});
                     } else {
                        OnEnter('DatosArticuloCantidad', function(){$('ArticuloCantidadAceptar').OnClick();});
                     }
                     $("DatosArticuloCantidad").focus();
                  }
               } else AgregarArticulo(this.HayDivisiones, this.Codigo, this.Pvp);
            }
            
            Event.observe('ImgAgr_' + oArt.Codigo[x], 'click', $('ImgAgr_' + oArt.Codigo[x]).OnClick);
            $('Cant_' + oArt.Codigo[x]).CodArt = oArt.Codigo[x]
            OnEnter('Cant_' + oArt.Codigo[x], function() {$('ImgAgr_' + this.CodArt).OnClick();});
            $('TblArtCarro').setAttribute('id', 'Carr_' + oArt.Codigo[x]);
         }

         MostrarSaldo('Sld_' + oArt.Codigo[x], oArt.VerSaldo[x], oArt.Saldo[x], oArt.Comprar[x]);
         $('TdContenido').show();         
      }

      if(oArt.PaginasTotales > 1) {
         var lPrimero = true;
         (GenArrayPag(oArt.PaginasTotales, oArt.PaginaActual)).each(function(Pag) {
            if(Pag.substring(0, 1) == ".") {
               Pag = Pag.substring(1);
               txPag = "...";
            } else txPag = Pag;
            if(!lPrimero) {
               oSpan = document.createElement("SPAN");
               oSpan.innerHTML = "&nbsp;&nbsp;|&nbsp;&nbsp;";
               $('Paginacion').appendChild(oSpan)
            }
            oSpan = document.createElement("SPAN");
            oSpan.innerHTML = txPag;
            oSpan.Pagina = Pag;
            oSpan.setAttribute('id', 'PAG_' + Pag); 
            $('Paginacion').appendChild(oSpan)
            if(Pag != oArt.PaginaActual) {
               oSpan.style.cursor = 'pointer';
               Event.observe(oSpan, 'mouseover', function(){this.style.textDecoration = 'underline';});
               Event.observe(oSpan, 'mouseout', function(){this.style.textDecoration = 'none';});
               Event.observe(oSpan, 'click', function() { _("app.aspx", "acc=" + encodeURIComponent("_ARTICULOPAGINA_") + "&param1=" + this.Pagina, VerArticulos);});
               ToolTip('PAG_' + Pag, "Pagina " + Pag + " de " + oArt.PaginasTotales);
            } else {
               $('PAG_' + Pag).addClassName('PaginaActual');
            }
            lPrimero = false;
         });
      }
   }
   ScrollUp();
}

function ScrollUp()
{
   if(document.body.scrollTop > 0) 
   if(ExisteId('TblFondo')) Effect.ScrollTo('TblFondo');
   else if(ExisteId('Pagina')) Effect.ScrollTo('Pagina');
}

function AgregarArticulo(lHayDivisiones, cCodArt, Pvp, Observaciones)
{
   MsjReloj('Agregando a la cesta. Espere ...');
   var Cmd = "acc=" + encodeURIComponent("_AGREGARACESTA_");
   Cmd += "&art=" + encodeURIComponent(cCodArt);
   if(lHayDivisiones) {
      Cmd += "&div1=" + encodeURIComponent($('Sel1_' + cCodArt).value);
      Cmd += "&div2=" + encodeURIComponent($('Sel2_' + cCodArt).value);
   } else {
      Cmd += "&div1=&div2=";
   }
   Cmd += "&cantidad=" + encodeURIComponent($('Cant_' + cCodArt).value);
   Cmd += "&obs=" + (Observaciones == undefined ? "" : Observaciones);
   Cmd += "&pvp=" + (Pvp == undefined ? "" : Pvp);
   $('Cant_' + cCodArt).value = '1' + sDecCanInput;
   lMostrarEfectoCesta = true;
   _("app.aspx", Cmd, function(){ActualizarCesta();});
}

function ExisteEnCesta(cCodArt)
{
   if($('TblCesta').NumLineas > 0) {
      oTbody = $('TblCesta').getElementsByTagName('TBODY')[0];
      nFilas = oTbody.getElementsByTagName('TR').length;
      for(x = 0; x < nFilas; x++) if($('CESTA_LIN_' + x).Codigo == cCodArt) return true;
   }
   return false;
}


function MostrarSaldo(sId, VerSaldo, Saldo, Comprar)
{
   if(VerStock && VerSaldo && ExisteId(sId)) {
      if(Saldo == 'Si' || Saldo == 'No') {
         $(sId).innerHTML = "";
         oImagen = document.createElement("IMG");
         oImagen.setAttribute('src', './images/app/' + Saldo + 'Disponible.png');
         oImg.setAttribute('border', 0);
         $(sId).appendChild(oImagen);
      } else {
         $(sId).innerHTML = (VerSaldo ? Saldo : "&nbsp;");
      }
   }

   var CodArt = sId.substring(4);
   if(ExisteId('Cant_' + CodArt)) {
      if(Comprar) $('Cant_' + CodArt).show(); else $('Cant_' + CodArt).hide(); 
   }
   if(ExisteId('Carr_' + CodArt)) {
      if(Comprar) $('Carr_' + CodArt).show(); else $('Carr_' + CodArt).hide(); 
   }
}

function GenArrayPag(Total, Actual)
{
   var sArr = "";
   var nMax = 10;
   var nPrimero = nUltimo = nElementos = 0, j;
  
   nPrimero = Actual;
   for(j = nPrimero; j <= Total && nElementos < nMax; j++) {
      sArr += j + " ";
      nUltimo = j;
      nElementos++;
   }
   
   while(nElementos < nMax && nPrimero > 1) {
      nPrimero--;
      sArr = nPrimero + " " + sArr;
      nElementos++;
   }

   if(nPrimero > 1) { 
      nPrimero--;
      sArr = "." + nPrimero + " " + sArr;
      
      if(nPrimero > 2) sArr = "1 " + sArr;
   }
   
   if(nUltimo < Total) { 
      nUltimo++;
      if(nUltimo == Total)
         sArr = sArr + " " + Total;
      else {
         sArr = sArr + " " + (nUltimo == (Total - 1) ? "" : ".") + nUltimo;
         sArr = sArr + " " + Total;
      }
   }
   
   return $w(sArr);
}

function ActualizarCesta(Fnc)
{
   if(AccederConLogin && $('SpanLogin').visible()) {
      if($('TblCesta').oTbody == undefined) {
         $('TblCesta').oTbody = ($('TblCesta').getElementsByTagName('TBODY')[0]).cloneNode(true);
         $('TblCesta').oTfoot = ($('TblCesta').getElementsByTagName('TFOOT')[0]).cloneNode(true);
      }
      while($('TblCesta').hasChildNodes()) $('TblCesta').removeChild($('TblCesta').lastChild);      
      $('TblCesta').NumLineas = 0;
      $('TblCesta').appendChild($('TblCesta').oTbody.cloneNode(true));      
      var oTbody = $('TblCesta').getElementsByTagName('TBODY')[0];
      var oLinea = (oTbody.getElementsByTagName("TR")[0]).cloneNode(true);
      (oTbody.getElementsByTagName("TR")[0]).removeChild((oTbody.getElementsByTagName("TR")[0]).getElementsByTagName("TD")[0]);
      $('TblCesDes').innerHTML = '<center>La cesta est&aacute; vac&iacute;a</center>';
      Boton('SpanComprar');
      $('TdVaciarCesta').stopObserving('mouseover');
      $('TdVaciarCesta').stopObserving('mouseout');
      $('TdVaciarCesta').stopObserving('click');
   } else {
      MsjReloj('Actualizando cesta. Espere ...');
      _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
         if(lMostrarEfectoCesta) {
            $('TblCesta').shake({duration: 0.5, distance: 5});
            lMostrarEfectoCesta = false;
         }
         if($('TblCesta').oTbody == undefined) {
            $('TblCesta').oTbody = ($('TblCesta').getElementsByTagName('TBODY')[0]).cloneNode(true);
            $('TblCesta').oTfoot = ($('TblCesta').getElementsByTagName('TFOOT')[0]).cloneNode(true);
         }
         while($('TblCesta').hasChildNodes()) $('TblCesta').removeChild($('TblCesta').lastChild);      
         $('TblCesta').NumLineas = 0;
         $('TblCesta').appendChild($('TblCesta').oTbody.cloneNode(true));
         
         var oTbody = $('TblCesta').getElementsByTagName('TBODY')[0];
         var oLinea = (oTbody.getElementsByTagName("TR")[0]).cloneNode(true);
         
         if(oVal.Lineas == 0) {
            (oTbody.getElementsByTagName("TR")[0]).removeChild((oTbody.getElementsByTagName("TR")[0]).getElementsByTagName("TD")[0]);
            $('TblCesDes').innerHTML = '<center>La cesta est&aacute; vac&iacute;a</center>';
            Boton('SpanComprar');
            $('TdVaciarCesta').stopObserving('mouseover');
            $('TdVaciarCesta').stopObserving('mouseout');
            $('TdVaciarCesta').stopObserving('click');
            if(Control1() == 'Pedido') PaginaInicio(false);
         } else {
            oTbody.removeChild(oTbody.getElementsByTagName("TR")[0]);
            $('TblCesta').NumLineas = oVal.Lineas;
            for(x = 0 ; x < oVal.Lineas - (oVal.HayGastos ? 1 : 0) - (oVal.HayGastosEnvio ? 1 : 0) ; x++) {
               if(oVal.Importe[x] != '') {            
                  oTbody.appendChild(oLinea.cloneNode(true));
                  $('CESTA_LIN_').x = x;
                  $('CESTA_LIN_').Codigo = oVal.Codigo[x];
                  $('CESTA_LIN_').CodArt = oVal.Codigo[x].substring(0, oVal.DigCodArt);         
                  $('CESTA_LIN_').Cantidad = oVal.Cantidad[x];
                  $('CESTA_LIN_').Descripcion = oVal.Descripcion[x];
                  $('CESTA_LIN_').Observaciones = oVal.Observaciones[x];
                  $('CESTA_LIN_').Precio = oVal.Precio[x] + '&nbsp;&euro;';
                  if(oVal.Clasificacion[x] != '') $('CESTA_LIN_').Descripcion += ', ' + oVal.Clasificacion[x];
                  
                  $('TblCesCan').innerHTML = "<div class='DivCestaCan'>" + oVal.Cantidad[x] + "</div>";
                  $('TblCesDes').innerHTML = "<div class='DivCestaTit'>" + oVal.Descripcion[x] + "</div>";
                  $('TblCesCan').setAttribute('id', 'TblCesCan_' + x); 
                  $('TblCesDes').setAttribute('id', 'TblCesDes_' + x); 
                  $('CESTA_LIN_').setAttribute('id', 'CESTA_LIN_' + x); 
   
                  Event.observe('CESTA_LIN_' + x, 'mouseover', function() {
                     if(Control1() == 'ConfirmarPedido') return;
                     $('TblCesCan_' + this.x).removeClassName('TblCesCan'); 
                     $('TblCesDes_' + this.x).removeClassName('TblCesDes');
                     $('TblCesCan_' + this.x).addClassName('TblCesCanSel'); 
                     $('TblCesDes_' + this.x).addClassName('TblCesDesSel');
                  });
                  Event.observe('CESTA_LIN_' + x, 'mouseout', function() {
                     if(Control1() == 'ConfirmarPedido') return;
                     $('TblCesCan_' + this.x).removeClassName('TblCesCanSel'); 
                     $('TblCesDes_' + this.x).removeClassName('TblCesDesSel');
                     $('TblCesCan_' + this.x).addClassName('TblCesCan'); 
                     $('TblCesDes_' + this.x).addClassName('TblCesDes');
                  });
                  Event.observe('CESTA_LIN_' + x, 'click', function() {
                     if(Control1() == 'ConfirmarPedido') return;
                     DivFondo(true);
                     $('DatosArticuloCodigo').innerHTML = this.CodArt;
                     $('DatosArticuloDescripcion').innerHTML = this.Descripcion;
                     $('DatosArticuloCantidad').value = this.Cantidad;
                     $('ArticuloCantidadBorrar').Codigo = this.Codigo;
                     $('ArticuloCantidadAceptar').Codigo = this.Codigo;
                     $('DatosArticuloPrecio').innerHTML = this.Precio;
                     $("DatosArticuloCantidad").Valor = $("DatosArticuloCantidad").value
                     
                     if(ObsPorLinea) {
                        oTh = document.createElement('th');
                        oTh.innerHTML = 'Observ.:';
                        
                        oTd = document.createElement('td');
                        oInp  = document.createElement('input');
                        oInp.setAttribute('type', 'text');
                        oInp.setAttribute('size', '22');
                        oInp.setAttribute('maxLength', '50');
                        oTd.appendChild(oInp);
                        
                        oTr = document.createElement('tr');
                        oTr.appendChild(oTh);
                        oTr.appendChild(oTd);
                        oTr.setAttribute('id', 'LineaObser');
                        
                        ($('TblArticuloCantidad').getElementsByTagName('TBODY')[0]).appendChild(oTr);
                        oInp.setAttribute('id', 'Observaciones');
                        oInp.value = this.Observaciones;
                        $('ArticuloCantidadAceptar').Observaciones = this.Observaciones;
                     }
                     
                     Boton('ArticuloCantidadBorrar', function() {
                        $('DivArticuloCantidad').hide();
                        if(ObsPorLinea) $('LineaObser').parentNode.removeChild($('LineaObser'));
                        Boton('ArticuloCantidadBorrar');
                        Boton('ArticuloCantidadAceptar');
                        Boton('ArticuloCantidadCancelar');
                        $('DatosArticuloCantidad').stopObserving('keypress');
                        DivFondo(false);                  
                        _("app.aspx", "acc=" + encodeURIComponent("_BORRARDECESTA_") + "&param1=" + encodeURIComponent(this.Codigo), function(){lMostrarEfectoCesta = true; ActualizarCesta();});
                     }, 'Eliminar articulo de la cesta');
                     Boton('ArticuloCantidadAceptar', function() {
                        $('DivArticuloCantidad').hide();
                        Boton('ArticuloCantidadBorrar');
                        Boton('ArticuloCantidadAceptar');
                        Boton('ArticuloCantidadCancelar');
                        $('DatosArticuloCantidad').stopObserving('keypress');
                        DivFondo(false);                     
                        if(ObsPorLinea) {
                           sObs = $('Observaciones').value;
                           $('LineaObser').parentNode.removeChild($('LineaObser'));
                           if($("DatosArticuloCantidad").Valor != $("DatosArticuloCantidad").value || sObs != this.Observaciones)
                              _("app.aspx", "acc=" + encodeURIComponent("_CABIACANTIDADENCESTA_") + "&param1=" + encodeURIComponent(this.Codigo) + "&param2=" + encodeURIComponent($("DatosArticuloCantidad").value) + "&param3=" + encodeURIComponent(sObs), function(){lMostrarEfectoCesta = true; ActualizarCesta();});
                        } else {
                           if($("DatosArticuloCantidad").Valor != $("DatosArticuloCantidad").value)
                              _("app.aspx", "acc=" + encodeURIComponent("_CABIACANTIDADENCESTA_") + "&param1=" + encodeURIComponent(this.Codigo) + "&param2=" + encodeURIComponent($("DatosArticuloCantidad").value), function(){lMostrarEfectoCesta = true; ActualizarCesta();});
                        }
                     }, 'Cambiar detalles');
                     Boton('ArticuloCantidadCancelar', function() {
                        $('DivArticuloCantidad').hide();
                        if(ExisteId('LineaObser')) $('LineaObser').parentNode.removeChild($('LineaObser'));
                        Boton('ArticuloCantidadBorrar');
                        Boton('ArticuloCantidadAceptar');
                        Boton('ArticuloCantidadCancelar');
                        $('DatosArticuloCantidad').stopObserving('keypress');
                        DivFondo(false);
                     }, 'Cancelar operacion');
                     $('ArticuloCantidadBorrar').show();
                     $('DivArticuloCantidad').show();
                     var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivArticuloCantidad').offsetHeight) / 2;
                     var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivArticuloCantidad').offsetWidth) / 2;
                     if(top < 1) top =  1;
                     if(left < 1) left = 1;
                     $('DivArticuloCantidad').style.top  = document.body.scrollTop + top;
                     $('DivArticuloCantidad').style.left = left;
                     OnEsc('DatosArticuloCantidad', function(){$('ArticuloCantidadCancelar').OnClick();});
                     OnEsc('Observaciones', function(){$('ArticuloCantidadCancelar').OnClick();});
                     OnEnter('DatosArticuloCantidad', 'Observaciones');
                     OnEnter('Observaciones', function(){$('ArticuloCantidadAceptar').OnClick();});
                     $("DatosArticuloCantidad").focus();
                  });            
                  ToolTip('CESTA_LIN_' + x, 'Modificar');
               }
            }
            $('TblCesta').appendChild($('TblCesta').oTfoot.cloneNode(true));
            $('TblCesTot').innerHTML = 'Total:&nbsp;' + oVal.TotalCesta + '&nbsp;&euro;';
            Boton('SpanComprar', function() {
               _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
                  _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                     _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                        MostrarPedido(oHtm, oVal);
                     });
                  });
               });
            }, 'Finalizar compra');
            Event.observe('TdVaciarCesta', 'mouseover', function() {
               if(Control1() == 'ConfirmarPedido') return;
               $('TdVaciarCesta').removeClassName('TdOpcion');
               $('TdVaciarCesta').addClassName('TdOpcionSel');
            });
            Event.observe('TdVaciarCesta', 'mouseout', function() {
               if(Control1() == 'ConfirmarPedido') return;
               $('TdVaciarCesta').removeClassName('TdOpcionSel');
               $('TdVaciarCesta').addClassName('TdOpcion');
            });         
            Event.observe('TdVaciarCesta', 'click', function() {
               if(Control1() == 'ConfirmarPedido') return;
               Confirm('Vaciar el contenido de la cesta', function() {
                  _("app.aspx", "acc=" + encodeURIComponent("_VACIARCESTA_"), function() {
                     lMostrarEfectoCesta = true;
                     ActualizarCesta();
                  });
               });
            });
            if(Control1() == 'Pedido') MostrarPedido(null, oVal);
         }
         
         if(Fnc != undefined) Fnc();
      });
   }
}

function MostrarPedido(oHtm, oVal, lPermitirEditar, FncPie)
{
   if(oVal.Lineas == 0) $('TdContenido').innerHTML = '&nbsp;';
   else {
      HabilitarBoton('SpanComprar', false);
      lPermitirEditar = lPermitirEditar == undefined ? true : lPermitirEditar;
      var oTbody, oLinea;
      if(oHtm == null) {
         var oTbody = $('TblPedido').oTbody;
         var oLinea = $('TblPedido').oLinea;
         while(oTbody.hasChildNodes()) oTbody.removeChild(oTbody.lastChild);
      } else {
         $('TdContenido').innerHTML = oHtm.HTML;
         var oTbody = $('TblPedido').getElementsByTagName('TBODY')[0];
         var oLinea = (oTbody.getElementsByTagName("TR")[0]).cloneNode(true);
         oTbody.removeChild(oTbody.getElementsByTagName("TR")[0]);
         $('TblPedido').oTbody = oTbody;
         $('TblPedido').oLinea = oLinea;
      }
      if(! oVal.Logado) {
         $('SpanPie1').show();
         $('SpanPie2').hide();
      } else {
         $('SpanPie1').hide();
         $('SpanPie2').show();
      }

      var nLineas = 15;
      for(x = 0 ; x < oVal.Lineas ; x++) {
         oTbody.appendChild(oLinea.cloneNode(true));
         $('LineaPedido').setAttribute('id', 'LineaPedido_' + x);
         $('PedCod').setAttribute('id', 'PedCod_' + x);
         $('PedDes').setAttribute('id', 'PedDes_' + x);
         $('PedCan').setAttribute('id', 'PedCan_' + x);
         $('PedPvp').setAttribute('id', 'PedPvp_' + x);
         $('PedImp').setAttribute('id', 'PedImp_' + x);
         $('PedBor').setAttribute('id', 'PedBor_' + x);
         $('PedMod').setAttribute('id', 'PedMod_' + x);

         $('PedBor_' + x).Codigo = oVal.Codigo[x];
         $('PedBor_' + x).CodArt = oVal.Codigo[x].substring(0, oVal.DigCodArt);         
         $('PedBor_' + x).Descripcion = oVal.Descripcion[x];
         if(oVal.Clasificacion[x] != '') $('PedBor_' + x).Descripcion += ', ' + oVal.Clasificacion[x];
         
         $('PedMod_' + x).x = x;
         $('PedMod_' + x).Codigo = oVal.Codigo[x];
         $('PedMod_' + x).CodArt = oVal.Codigo[x].substring(0, oVal.DigCodArt);
         $('PedMod_' + x).Descripcion = oVal.Descripcion[x];
         if(oVal.Clasificacion[x] != '') $('PedMod_' + x).Descripcion += ', ' + oVal.Clasificacion[x];
         $('PedMod_' + x).Precio = oVal.Precio[x] + '&nbsp;&euro;';
         $('PedMod_' + x).Cantidad = oVal.Cantidad[x];

         $('PedCod_' + x).innerHTML = $('PedMod_' + x).CodArt;
         $('PedDes_' + x).innerHTML = oVal.Descripcion[x];
         $('PedCan_' + x).innerHTML = oVal.Cantidad[x];
         $('PedPvp_' + x).innerHTML = oVal.Precio[x];
         $('PedImp_' + x).innerHTML = oVal.Importe[x];
         if(lPermitirEditar && oVal.Importe[x] != '') {
            $('PedBor_' + x).innerHTML = "<img src='./images/app/borrar.gif' border='1'>";
            $('PedMod_' + x).innerHTML = "<img src='./images/app/lapiz.gif' border='1'>";
            $('PedMod_' + x).Observaciones = oVal.Observaciones[x];
         }

         $('PedCod_' + x).addClassName('CodigoSup');
         $('PedDes_' + x).addClassName('DescripcionSup');
         $('PedCan_' + x).addClassName('CantidadSup');
         $('PedPvp_' + x).addClassName('PvpSup');
         $('PedImp_' + x).addClassName('ImporteSup');
         $('PedBor_' + x).addClassName('IconoSup');
         $('PedMod_' + x).addClassName('IconoSup');
         
         if(oVal.Clasificacion[x] == '' && oVal.Observaciones[x] == '') {
            $('PedCod_' + x).addClassName('CodigoSub');
            $('PedDes_' + x).addClassName('DescripcionSub');
            $('PedCan_' + x).addClassName('CantidadSub');
            $('PedPvp_' + x).addClassName('PvpSub');
            $('PedImp_' + x).addClassName('ImporteSub');
            $('PedBor_' + x).addClassName('IconoSub');
            $('PedMod_' + x).addClassName('IconoSub');
         }

         if(lPermitirEditar && oVal.Importe[x] != '') {
            $('PedBor_' + x).setStyle('cursor: pointer');
            $('PedMod_' + x).setStyle('cursor: pointer');
            Event.observe('PedBor_' + x, 'click', function() {
               DivFondo(true);
               $('DatosArticuloCodigoBorrar').innerHTML = this.CodArt;
               $('DatosArticuloDescripcionBorrar').innerHTML = this.Descripcion;
               $('ArticuloBorrarAceptar').Codigo = this.Codigo;
               Boton('ArticuloBorrarAceptar', function() {
                  $('DivArticuloBorrar').hide();
                  DivFondo(false);
                  _("app.aspx", "acc=" + encodeURIComponent("_BORRARDECESTA_") + "&param1=" + encodeURIComponent(this.Codigo), function(){lMostrarEfectoCesta = true; ActualizarCesta();});
               }, 'Eliminar articulo');
               Boton('ArticuloBorrarCancelar', function() {
                  $('DivArticuloBorrar').hide();
                  DivFondo(false);
               }, 'Cancelar operacion');
               $('DivArticuloBorrar').show();
               var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivArticuloBorrar').offsetHeight) / 2;
               var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivArticuloBorrar').offsetWidth) / 2;
               if(top < 1) top =  1;
               if(left < 1) left = 1;
               $('DivArticuloBorrar').style.top  = document.body.scrollTop + top;
               $('DivArticuloBorrar').style.left = left;
            });
            ToolTip('PedBor_' + x, 'Eliminar articulo');
            
            Event.observe('PedMod_' + x, 'click', function() {
               DivFondo(true);
               $('DatosArticuloCodigo').innerHTML = this.CodArt;
               $('DatosArticuloDescripcion').innerHTML = this.Descripcion;
               $('DatosArticuloCantidad').value = this.Cantidad;
               $('ArticuloCantidadAceptar').Codigo = this.Codigo;
               $('DatosArticuloPrecio').innerHTML = this.Precio;
               $("DatosArticuloCantidad").Valor = $("DatosArticuloCantidad").value;

               if(ObsPorLinea) {
                  oTh = document.createElement('th');
                  oTh.innerHTML = 'Observ.:';
                  
                  oTd = document.createElement('td');
                  oInp  = document.createElement('input');
                  oInp.setAttribute('type', 'text');
                  oInp.setAttribute('size', '22');
                  oInp.setAttribute('maxLength', '50');
                  oTd.appendChild(oInp);
                  
                  oTr = document.createElement('tr');
                  oTr.appendChild(oTh);
                  oTr.appendChild(oTd);
                  oTr.setAttribute('id', 'LineaObser');
                  
                  ($('TblArticuloCantidad').getElementsByTagName('TBODY')[0]).appendChild(oTr);
                  oInp.setAttribute('id', 'Observaciones');
                  oInp.value = this.Observaciones;
                  $('ArticuloCantidadAceptar').Observaciones = this.Observaciones;
               }
               
               Boton('ArticuloCantidadAceptar', function() {
                  $('DivArticuloCantidad').hide();
                  DivFondo(false);                     
                  if(ObsPorLinea) {
                     sObs = $('Observaciones').value;
                     $('LineaObser').parentNode.removeChild($('LineaObser'));
                     if($("DatosArticuloCantidad").Valor != $("DatosArticuloCantidad").value || sObs != this.Observaciones)
                        _("app.aspx", "acc=" + encodeURIComponent("_CABIACANTIDADENCESTA_") + "&param1=" + encodeURIComponent(this.Codigo) + "&param2=" + encodeURIComponent($("DatosArticuloCantidad").value) + "&param3=" + encodeURIComponent(sObs), function(){lMostrarEfectoCesta = true; ActualizarCesta();});
                  } else {
                     if($("DatosArticuloCantidad").Valor != $("DatosArticuloCantidad").value)
                        _("app.aspx", "acc=" + encodeURIComponent("_CABIACANTIDADENCESTA_") + "&param1=" + encodeURIComponent(this.Codigo) + "&param2=" + encodeURIComponent($("DatosArticuloCantidad").value), function(){lMostrarEfectoCesta = true; ActualizarCesta();});
                  }
               }, 'Cambiar detalles');                  
               Boton('ArticuloCantidadCancelar', function() {
                  $('DivArticuloCantidad').hide();
                  DivFondo(false);
                  if(ObsPorLinea) $('LineaObser').parentNode.removeChild($('LineaObser'));
               }, 'Cancelar operacion');
               $('ArticuloCantidadBorrar').hide();
               $('DivArticuloCantidad').show();
               var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivArticuloCantidad').offsetHeight) / 2;
               var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivArticuloCantidad').offsetWidth) / 2;
               if(top < 1) top =  1;
               if(left < 1) left = 1;
               $('DivArticuloCantidad').style.top  = document.body.scrollTop + top;
               $('DivArticuloCantidad').style.left = left;
               $("DatosArticuloCantidad").focus();
            });
            ToolTip('PedMod_' + x, 'Modificar cantidad');
         }
         
         nLineas--;
         if(oVal.Clasificacion[x] != '') {
            oTbody.appendChild(oLinea.cloneNode(true));
            $('LineaPedido').setAttribute('id', 'LineaPedido_' + x + '_CL');
            $('PedCod').setAttribute('id', 'PedCod_' + x + '_CL');
            $('PedDes').setAttribute('id', 'PedDes_' + x + '_CL');
            $('PedCan').setAttribute('id', 'PedCan_' + x + '_CL');
            $('PedPvp').setAttribute('id', 'PedPvp_' + x + '_CL');
            $('PedImp').setAttribute('id', 'PedImp_' + x + '_CL');
            $('PedBor').setAttribute('id', 'PedBor_' + x + '_CL');
            $('PedMod').setAttribute('id', 'PedMod_' + x + '_CL');
            
            $('PedCod_' + x + '_CL').innerHTML = '&nbsp;';
            $('PedDes_' + x + '_CL').innerHTML = oVal.Clasificacion[x];
            $('PedCan_' + x + '_CL').innerHTML = '&nbsp;';
            $('PedPvp_' + x + '_CL').innerHTML = '&nbsp;';
            $('PedImp_' + x + '_CL').innerHTML = '&nbsp;';

            if(oVal.Observaciones[x] == '') {
               $('PedCod_' + x + '_CL').addClassName('CodigoSub');
               $('PedDes_' + x + '_CL').addClassName('DescripcionSub');
               $('PedCan_' + x + '_CL').addClassName('CantidadSub');
               $('PedPvp_' + x + '_CL').addClassName('PvpSub');
               $('PedImp_' + x + '_CL').addClassName('ImporteSub');
               $('PedBor_' + x + '_CL').addClassName('IconoSub');
               $('PedMod_' + x + '_CL').addClassName('IconoSub');
            }
            nLineas--;
         }
         
         if(oVal.Observaciones[x] != '') {
            oTbody.appendChild(oLinea.cloneNode(true));
            $('LineaPedido').setAttribute('id', 'LineaPedido_' + x + '_OBS');
            $('PedCod').setAttribute('id', 'PedCod_' + x + '_OBS');
            $('PedDes').setAttribute('id', 'PedDes_' + x + '_OBS');
            $('PedCan').setAttribute('id', 'PedCan_' + x + '_OBS');
            $('PedPvp').setAttribute('id', 'PedPvp_' + x + '_OBS');
            $('PedImp').setAttribute('id', 'PedImp_' + x + '_OBS');
            $('PedBor').setAttribute('id', 'PedBor_' + x + '_OBS');
            $('PedMod').setAttribute('id', 'PedMod_' + x + '_OBS');
            
            $('PedCod_' + x + '_OBS').innerHTML = '&nbsp;';
            $('PedDes_' + x + '_OBS').innerHTML = oVal.Observaciones[x];
            $('PedCan_' + x + '_OBS').innerHTML = '&nbsp;';
            $('PedPvp_' + x + '_OBS').innerHTML = '&nbsp;';
            $('PedImp_' + x + '_OBS').innerHTML = '&nbsp;';

            $('PedCod_' + x + '_OBS').addClassName('CodigoSub');
            $('PedDes_' + x + '_OBS').addClassName('DescripcionSub');
            $('PedCan_' + x + '_OBS').addClassName('CantidadSub');
            $('PedPvp_' + x + '_OBS').addClassName('PvpSub');
            $('PedImp_' + x + '_OBS').addClassName('ImporteSub');
            $('PedBor_' + x + '_OBS').addClassName('IconoSub');
            $('PedMod_' + x + '_OBS').addClassName('IconoSub');
            
            nLineas--;
         }
      }

      k = nLineas;
      while(nLineas > 0) {
         oTbody.appendChild(oLinea.cloneNode(true));
         $('PedCod').setAttribute('id', 'PedCod_' + nLineas + '_BL');
         $('PedDes').setAttribute('id', 'PedDes_' + nLineas + '_BL');
         $('PedCan').setAttribute('id', 'PedCan_' + nLineas + '_BL');
         $('PedPvp').setAttribute('id', 'PedPvp_' + nLineas + '_BL');
         $('PedImp').setAttribute('id', 'PedImp_' + nLineas + '_BL');
         $('PedBor').setAttribute('id', 'PedBor_' + nLineas + '_BL');
         $('PedMod').setAttribute('id', 'PedMod_' + nLineas + '_BL');
         
         $('PedCod_' + nLineas + '_BL').innerHTML = '&nbsp;';
         $('PedDes_' + nLineas + '_BL').innerHTML = '&nbsp;';
         $('PedCan_' + nLineas + '_BL').innerHTML = '&nbsp;';
         $('PedPvp_' + nLineas + '_BL').innerHTML = '&nbsp;';
         $('PedImp_' + nLineas + '_BL').innerHTML = '&nbsp;';
         if(k == nLineas) {
            $('PedCod_' + nLineas + '_BL').addClassName('CodigoSup');
            $('PedDes_' + nLineas + '_BL').addClassName('DescripcionSup');
            $('PedCan_' + nLineas + '_BL').addClassName('CantidadSup');
            $('PedPvp_' + nLineas + '_BL').addClassName('PvpSup');
            $('PedImp_' + nLineas + '_BL').addClassName('ImporteSup');
            $('PedBor_' + nLineas + '_BL').addClassName('IconoSup');
            $('PedMod_' + nLineas + '_BL').addClassName('IconoSup');
         }
         nLineas--;
      }
      
      $('TitBase').innerHTML = 'Base imponible';
      $('ValBase').innerHTML = oVal.Base;
      if(oVal.REE == '') {
         $('TitIVA').innerHTML = 'IVA ' + oVal.DesgloseIVA;
         $('ValIVA').innerHTML = oVal.IVA ;
      } else {
         $('TitIVA').innerHTML = 'IVA ' + oVal.DesgloseIVA + '<br />Rec. Equ. ' + oVal.DesgloseREE;
         $('ValIVA').innerHTML = oVal.IVA + '<br />' + oVal.REE;
      }
      $('TitTOTAL').innerHTML = 'Total';
      $('ValTOTAL').innerHTML = oVal.Total;
      
      if(ExisteId('TblCesTot')) $('TblCesTot').innerHTML = 'Total:&nbsp;' + oVal.Total + '&nbsp;&euro;';

      if(FncPie == undefined) {
         if(lPermitirEditar) {
            if(ReqPago || FormasDeEnvio.Total > 0) {
               while($('SpanPie2').hasChildNodes()) $('SpanPie2').removeChild($('SpanPie2').lastChild);
               if(FormasDeEnvio.Total > 0) {
                  $('SpanPie2').appendChild(document.createElement("DIV"));
                  oDiv = $('SpanPie2').lastChild;
                  oDiv.appendChild(document.createTextNode("Seleccione la forma de envio:"));
                  
                  oSel = document.createElement("SELECT");
                  oSel.setAttribute('id', 'FormaDeEnvio');
                  for(x = 0 ; x < FormasDeEnvio.Total ; x++) {
                     oOpc = document.createElement("option");
                     oOpc.setAttribute('value', FormasDeEnvio.Id[x]);
                     oOpc.appendChild(document.createTextNode(FormasDeEnvio.Nombre[x]));
                     oSel.appendChild(oOpc);
                  }

                  $('SpanPie2').appendChild(document.createElement("DIV"));
                  oDiv = $('SpanPie2').lastChild;
                  oDiv.appendChild(oSel);
                  
                  if(!ReqPago) {
                     oBotSeguir = document.createElement("SPAN")
                     oBotSeguir.appendChild(document.createTextNode('Continuar'));
                     oBotSeguir.setAttribute('id', 'EnvSeleccionado');
                     oBotSeguir.setAttribute(_ClassName_, 'SpanBoton');
                     $('SpanPie2').appendChild(document.createElement("DIV"));
                     oDiv = $('SpanPie2').lastChild;
                     oDiv.appendChild(document.createElement('BR'));
                     oDiv.appendChild(oBotSeguir);
                     Boton('EnvSeleccionado', function() {
                        sFormaDeEnvio = (FormasDeEnvio.Total > 0 ? $('FormaDeEnvio').value : '0');
                        _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=" + sFormaDeEnvio, function() {
                           _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                              _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                 MostrarPedido(oHtm, oVal, false);
                              });
                           });
                        });
                     }, 'Continuar');
                  }
               }
               if(ReqPago) {
                  _("app.aspx", "acc=" + encodeURIComponent("_FORMAS_DE_PAGO_"), function(oFPg) {
                     $('SpanPie2').appendChild(document.createElement("DIV"));
                     oDiv = $('SpanPie2').lastChild;
                     oDiv.appendChild(document.createTextNode("Seleccione la forma de pago:"));
                     
                     oDiv.appendChild(document.createElement("DIV"));
                     oDiv = oDiv.lastChild;
                     oDiv.setAttribute('id', 'FormPago');
                     oDiv.appendChild(document.createElement("UL"));
                     
                     var sIdToolTip, sTxToolTip;
                     for(j = 0 ; j < oFPg.Total; j++) {
                        var oOpc = document.createElement("li");
                        oImg = document.createElement("IMG");
                        switch(oFPg.ID[j]) {
                           case 1:
                              sIdToolTip = 'OpcPag_Transferencia';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/transferenciaicon.png');
                              break;
                              
                           case 2:
                              sIdToolTip = 'OpcPag_TPVSERMEPA';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/SERMEPAICON.png');
                              break;
                              
                           case 3:
                              sIdToolTip = 'OpcPag_ContraReembolso';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/REEMBOLSOICON.png');
                              break;
                              
                           case 4:
                              sIdToolTip = 'OpcPag_PayPal';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/paypalicon.png');
                              break;
                              
                           case 5:
                              sIdToolTip = 'OpcPag_GiroPostal';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/GIROICON.png');
                              break;
                              
                           case 6:
                              sIdToolTip = 'OpcPag_ChequeBancario';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/CHEQUEICON.png');
                              break;
                              
                           case 7:
                              sIdToolTip = 'OpcPag_TPVCECA';
                              sTxToolTip = oFPg.Nombre[j];
                              oImg.setAttribute('src', './images/app/CECAICON.png');
                              break;
                        }
                        if(sIdToolTip != '') {                  
                           oImg.setAttribute('id', sIdToolTip);
                           oOpc.appendChild(oImg);
                           ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
                           ToolTip(sIdToolTip, sTxToolTip);
                           $(sIdToolTip).FormaDePago = oFPg.ID[j];
                           $(sIdToolTip).setStyle('cursor: pointer;');
                           Event.observe(sIdToolTip, 'click', function() {
                              sFormaDeEnvio = (FormasDeEnvio.Total > 0 ? $('FormaDeEnvio').value : '0');
                              _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=" + this.FormaDePago + "&FormaEnvio=" + sFormaDeEnvio, function() {
                                 _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                                    _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                       MostrarPedido(oHtm, oVal, false);
                                    });
                                 });
                              });
                           });
                        }
                     }
                  });   
               }
            } else PieDePedido();
         } else PieDePedido();
      } else {
         FncPie();
      }
   }
}

function PieDePedido()
{
   if(ReqPago) {
      Control1('ConfirmarPedido');
      ActualizarCesta(function() {
         _("app.aspx", "acc=" + encodeURIComponent("_GET_ESTADO_PAGO_"), function(oEst) {
            var EstadoPago = oEst.valor;
            var ErrPagoMsj = oEst.ErrPagoMsj;
            var FormaDePago = oEst.FormaDePago;
            var TextoFormaDepago = oEst.TextoFormaDePago;
      
            $('SpanPie2').innerHTML = '';
            
            if(TextoFormaDepago != '') {
               $('SpanPie2').appendChild(document.createElement("DIV"));
               oDiv = $('SpanPie2').lastChild;
               oDiv.setAttribute('id', 'TextoModoDePago');
               oDiv.innerHTML= TextoFormaDepago;
            }

            if(FormaDePago != 4) {
               $('SpanPie2').appendChild(document.createElement("DIV"));
               oDiv = $('SpanPie2').lastChild;
               oDiv.setAttribute('id', 'ObservacionesPedido');
               oDiv.innerHTML = 'Si lo desea indique sus observaciones antes de finalizar la compra:<br>'
               oObsPed = document.createElement("INPUT");
               oObsPed.setAttribute('type', 'text'); 
               oObsPed.setAttribute('size', '80'); 
               oObsPed.setAttribute('maxLength', '80');
               oDiv.appendChild(oObsPed);
               oObsPed.setAttribute('id', 'ObsPiePedido');
            }
            
            $('SpanPie2').appendChild(document.createElement("DIV"));
            oDiv = $('SpanPie2').lastChild;
            oDiv.appendChild(document.createElement("DIV"));
            oDiv = oDiv.lastChild;
            oDiv.appendChild(document.createElement("UL"));
            oDiv.setAttribute('id', 'FormPago');      
            
            oBoton = document.createElement("SPAN");
            oBoton.setAttribute('id', 'SeguirCompra'); 
            oOpc = document.createElement("li");            
            oOpc.appendChild(oBoton);
            ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
            Control1('ConfirmarPedido');
            HabilitarBoton('SpanComprar', false);
            $('SeguirCompra').addClassName('SpanBoton');
            $('SeguirCompra').innerHTML = 'Atr&aacute;s';
            Boton('SeguirCompra', function() {
               _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
                  ActualizarCesta(function() {
                     _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                        _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                           MostrarPedido(oHtm, oVal);
                        });
                     });
                  });
               });
            }, 'Atr&aacute;s');
      
            if(FormaDePago == 4) {
               oImg = document.createElement("IMG");
               oImg.setAttribute('src', './images/app/ComprarAhora.gif');
               oImg.setAttribute('height', '34px;');
               oImg.setAttribute('id', 'OpcPag_PayPal');             
               oOpc = document.createElement("li");            
               oOpc.appendChild(oImg);
               ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
               $('OpcPag_PayPal').setStyle('cursor: pointer;');
               ToolTip('OpcPag_PayPal', 'Pagar con PayPal');
               Event.observe('OpcPag_PayPal', 'click', function() {
                  _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=4", function() {
                     location.href = 'app.aspx?acc=' + encodeURIComponent('_PAYPAL_PAGAR_');
                  });
               });
            } else {
               oBoton = document.createElement("SPAN");
               oBoton.setAttribute('id', 'FinalizarCompra'); 
               oOpc = document.createElement("li");            
               oOpc.appendChild(oBoton);
               ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
               $('FinalizarCompra').addClassName('SpanBoton');
               $('FinalizarCompra').innerHTML = 'Finalizar compra';
               Boton('FinalizarCompra', function() {
                  AlmacenarPedido($(ObsPiePedido).value, FormaDePago);
               }, 'Finalizar compra');
            }
         });
      });
   } else {
      $('SpanPie2').appendChild(document.createElement("DIV"));
      oDiv = $('SpanPie2').lastChild;
      oDiv.setAttribute('id', 'ObservacionesPedido');
      oDiv.innerHTML = 'Si lo desea indique sus observaciones antes de finalizar la compra:<br>'
      oObsPed = document.createElement("INPUT");
      oObsPed.setAttribute('type', 'text'); 
      oObsPed.setAttribute('size', '80'); 
      oObsPed.setAttribute('maxLength', '80');
      oDiv.appendChild(oObsPed);
      oObsPed.setAttribute('id', 'ObsPiePedido'); 
      
      if(FormasDeEnvio.Total > 0) {
         oDiv = document.createElement("SPAN");
         oDiv.setAttribute('id', 'SeguirCompra');
         $('SpanPie2').appendChild(oDiv);
         $('SeguirCompra').addClassName('SpanBoton');
         $('SeguirCompra').innerHTML = 'Atr&aacute;s';
         Boton('SeguirCompra', function() {
            _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
               ActualizarCesta(function() {
                  _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                     _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                        MostrarPedido(oHtm, oVal);
                     });
                  });
               });
            });
         }, 'Atr&aacute;s');
      }
      
      $('SpanPie2').appendChild(document.createTextNode('   '));
            
      oDiv = document.createElement("SPAN");
      oDiv.setAttribute('id', 'BotonesPago');
      $('SpanPie2').appendChild(oDiv);
      HabilitarBoton('SpanComprar', false);
      $('BotonesPago').addClassName('SpanBoton');
      $('BotonesPago').innerHTML = 'Finalizar compra';
      Boton('BotonesPago', function() {
         AlmacenarPedido($(ObsPiePedido).value, null);
      }, 'Confirmar compra');
   }   
}

function AlmacenarPedido(sObsPed, FPago)
{
   sObsPed = (sObsPed == undefined ? "" : sObsPed);
   MsjReloj('Procesando y almacenado documento. Espere ...');
   _("app.aspx", "acc=" + encodeURIComponent("_REALIZARPEDIDO_") + "&obs=" + encodeURIComponent(sObsPed), function(oDatos) {
      if(FPago != null && (FPago == "2" || FPago == "7")) {
         $('TdContenido').innerHTML = oDatos.Formulario;
         document.forms['FrmTvpVirtual'].submit();
      } else {
         var nIni = (oDatos.EmailBody.toUpperCase()).indexOf('<BODY>') + 6;
         var nFin = (oDatos.EmailBody.toUpperCase()).indexOf('</BODY>');
         $('TdContenido').innerHTML =  "<table id='TblContFinal' class='TblContFinal' cellpadding='0' cellspacing='0'>" +
                                          "<tbody>" +
                                             "<tr>" +
                                                "<td>" + oDatos.EmailBody.substring(nIni, nFin) + "</td>" +
                                             "</tr>" +
                                             "<tr>" +
                                                "<td class='TdContFinal'><span id='Imprimir' class='SpanBoton'>Imprimir</span></td>" +
                                             "</tr>" +
                                          "</tbody>" +
                                       "</table>";
               
         $('TdContenido').EmailBody = oDatos.EmailBody;
         Boton('Imprimir', function() {Imprimir($('TdContenido').EmailBody);}, 'Imprimir documento');
         ActualizarCesta();
      }
   });
}

function Identificarse()
{
   if($('LogEmail').value == '') Alert('No ha especificado email', 'LogEmail');
   else if($('LogClave').value == '') Alert('No ha especificado clave', 'LogClave');
   else _("app.aspx", "acc=" + encodeURIComponent("_LOGIN_") + "&param1=2&param2=" + encodeURIComponent($("LogEmail").value) + "&param3=" + encodeURIComponent($("LogClave").value), function(oVal) {
           if(RecordarUsuarioYClave) { 
              AutoLoginUsuario = $("LogEmail").value; 
              AutoLoginClave = $("LogClave").value;
              SalvarDatosAutoLogin();
           }
           $('SpanLogin').hide();
           $('SpanLogout').show();
           $('email2').innerHTML = oVal.EmlLogado;
           $('usr2').innerHTML = oVal.UsrLogado;
           if(ExisteId('Perfil')) $('Perfil').innerHTML = oVal.Perfil;
           ReqPago = oVal.ReqPago;
           BotonCambiarClave(true);
           if(ExisteId('TblCliente')) {
              if(oVal.AgenteLogado) {
                 $('TblCliente').show();
                 $('TdNomCliente').innerHTML = 'No hay cliente seleccionado';
                 Boton('BotonSelCli', function() {SeleccionarCliente();}, 'Seleccionar cliente');
                 if(ExisteId('TdNuevoCliente')) EnlaceNuevoCliente(oVal.CreaClientes);
              } else {
                 $('TblCliente').hide();
              }
           }
           if(ExisteId('MenuProductos')) $('MenuProductos').show();
           VerBuscador(true);
           if(TipoDocumento != '') $('Tbl_Cesta').show();
           if(MostrarHistoPed && ExisteId('TdHistorico1')) {
              if(oVal.AgenteLogado) {
                 $('TrHistorico2').show();
              } else EnlaceHistorico(1, true);
           }
           if(ExisteId('TdVendido1')) {
              if(oVal.AgenteLogado) {
                 $('TrVendido2').show();
              } else EnlaceVendido(1, true);
           }           
           if(ExisteId('TdMasVendido1')) {
              if(oVal.AgenteLogado) {
                 $('TrMasVendido2').show();
              } else EnlaceMasVendido(1, true);
           }           
           Destacados(true);
           Novedades(true);
           ActualizarCesta();
           if(!ExisteId('TblPedido')) {
              $('TdContenido').innerHTML = sHtmInicio;
              ScrollUp();
              if(document.onPaginaInicio != undefined) document.onPaginaInicio();
           }
        });
}

function BotonCambiarClave(lActivo)
{
   if(lActivo) {
      if(ExisteId('TdCambiarClave')) {
         Event.observe('TdCambiarClave', 'mouseover', function() {
            $('TdCambiarClave').removeClassName('TdOpcion');
            $('TdCambiarClave').addClassName('TdOpcionSel');
         });
         Event.observe('TdCambiarClave', 'mouseout', function() {
            $('TdCambiarClave').removeClassName('TdOpcionSel');
            $('TdCambiarClave').addClassName('TdOpcion');
         });         
         Event.observe('TdCambiarClave', 'click', function() { CambiarClave(); });
      } else if(ExisteId('LnkCambiarClave')) {
         if($('LnkCambiarClave').Inicializado) ;
         else {
            $('LnkCambiarClave').Inicializado = true;
            BotonLink('LnkCambiarClave', CambiarClave);
         }
         $('LnkCambiarClave').removeAttribute(_ClassName_);
      }
   } else {
      if(ExisteId('TdCambiarClave')) {
         $('TdCambiarClave').stopObserving('mouseover');
         $('TdCambiarClave').stopObserving('mouseout');
         $('TdCambiarClave').stopObserving('click');
      } else if(ExisteId('LnkCambiarClave')) {
         $('LnkCambiarClave').setAttribute(_ClassName_, 'Disabled');
      }
   }
}

function CambiarClave()
{
   if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=cambiarclave", function(oVal) {
      $('TdContenido').innerHTML = oVal.HTML;
      Boton('BotCambiar', function() {
         _("app.aspx", "acc=" + encodeURIComponent("_CAMBIAR_CLAVE_") + "&param1=" + encodeURIComponent($("clv1").value) + "&param2=" + encodeURIComponent($("clv2").value) + "&param3=" + encodeURIComponent($("clv3").value),
            function() {
               var sTbl = "<table class='TblAviso' 'cellpadding'='0' 'cellspacing'='0'>";
               sTbl    +=    "<tbody>";
               sTbl    +=       "<tr>";
               sTbl    +=          "<td>Su clave ha cambiado.</td>";
               sTbl    +=       "</tr>";
               sTbl    +=    "</tbody>";
               sTbl    += "</table>";
               $('TdContenido').innerHTML = sTbl;
            }
         );
      }, 'Cambiar clave');
      OnEnter('clv1', 'clv2');
      OnEnter('clv2', 'clv3');
      OnEnter('clv3', $('BotCambiar').OnClick);
      $('clv1').focus();
   });
}

function ValidEmail(sEml)
{
   var regex=/^\w+([\.\-\_]?\w+)*@\w+([\.-]?\w+)*(\.\D{2,4})+$/;
   return(sEml != null && sEml.length != 0 && regex.test(sEml));
}

function PaginaInicio(PonerMenus)
{
   if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=inicio", function(oVal) {
      sHtmInicio = oVal.HTML;
      if(PonerMenus) {
           PonerMenuProductos(function() {
            _("app.aspx", "acc=" + encodeURIComponent("_GET_ESTADO_PAGO_"), function(oEst) {
               var EstadoPago = oEst.valor;
               var ErrPagoMsj = oEst.ErrPagoMsj;
               var FormaDePago = oEst.FormaDePago;
               var TextoFormaDepago = oEst.TextoFormaDePago;
               if(FormaDePago == 2 || FormaDePago == 7) {
                  if(EstadoPago == "CANCELADO") {
                     _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
                        ActualizarCesta(function() {
                           _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                              _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                 MostrarPedido(oHtm, oVal);
                              });
                           });
                        });
                     });
                  } else if(EstadoPago == "FINALIZADO") {
                     _("app.aspx", "acc=" + encodeURIComponent("_GET_TPV_PEDIDOFINAL_"), function(oDatos) {
                        var nIni = (oDatos.EmailBody.toUpperCase()).indexOf('<BODY>') + 6;
                        var nFin = (oDatos.EmailBody.toUpperCase()).indexOf('</BODY>');
                        $('TdContenido').innerHTML =  "<table id='TblContFinal' class='TblContFinal' cellpadding='0' cellspacing='0'>" +
                                                         "<tbody>" +
                                                            "<tr>" +
                                                               "<td>" + oDatos.EmailBody.substring(nIni, nFin) + "</td>" +
                                                            "</tr>" +
                                                            "<tr>" +
                                                               "<td class='TdContFinal'><span id='Imprimir' class='SpanBoton'>Imprimir</span></td>" +
                                                            "</tr>" +
                                                         "</tbody>" +
                                                      "</table>";
                              
                        $('TdContenido').EmailBody = oDatos.EmailBody;
                        Boton('Imprimir', function() {Imprimir($('TdContenido').EmailBody);}, 'Imprimir documento');
                        ActualizarCesta();
                     });
                  }
               }else if(FormaDePago == 4 && (EstadoPago == "ERROR" || EstadoPago == "CONFIRMACIONENESPERA" || EstadoPago == "FINALIZADO")) {
                  _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                     if(EstadoPago == "ERROR") {
                        _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
                           ActualizarCesta(function() {
                              _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                                 _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                    MostrarPedido(oHtm, oVal, false, function() {
                                       $('SpanPie2').appendChild(document.createElement("DIV"));
                                       oDiv = $('SpanPie2').lastChild;
                                       oDiv.appendChild(document.createElement("DIV"));
                                       oDiv = oDiv.lastChild;
                                       oDiv.appendChild(document.createElement("UL"));
                                       oDiv.setAttribute('id', 'FormPago');
                                                         
                                       oBoton = document.createElement("SPAN");
                                       oBoton.setAttribute('id', 'SeguirCompra'); 
                                       oOpc = document.createElement("li");            
                                       oOpc.appendChild(oBoton);
                                       ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
                                       $('SeguirCompra').addClassName('SpanBoton');
                                       $('SeguirCompra').innerHTML = 'Atr&aacute;s';
                                       Boton('SeguirCompra', function() {
                                          _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                                             _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                                MostrarPedido(oHtm, oVal);
                                             });
                                          });
                                       }, 'Atr&aacute;s');
                                       Alert(ErrPagoMsj);
                                    });
                                 });
                              });
                           });
                        });
                     } else if(EstadoPago == "CONFIRMACIONENESPERA") {
                        ActualizarCesta(function() {
                           _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                              _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                 MostrarPedido(oHtm, oVal, false, function() {
                                    $('SpanPie2').appendChild(document.createElement("DIV"));
                                    oDiv = $('SpanPie2').lastChild;
                                    oDiv.setAttribute('id', 'ObservacionesPedido');
                                    oDiv.innerHTML = 'Si lo desa indique sus observaciones antes de finalizar la compra:<br>'
                                    oObsPed = document.createElement("INPUT");
                                    oObsPed.setAttribute('type', 'text'); 
                                    oObsPed.setAttribute('size', '80'); 
                                    oObsPed.setAttribute('maxLength', '80');
                                    oDiv.appendChild(oObsPed);
                                    oObsPed.setAttribute('id', 'ObsPiePedido'); 
         
                                    $('SpanPie2').appendChild(document.createElement("DIV"));
                                    oDiv = $('SpanPie2').lastChild;
                                    oDiv.appendChild(document.createElement("DIV"));
                                    oDiv = oDiv.lastChild;
                                    oDiv.appendChild(document.createElement("UL"));
                                    oDiv.setAttribute('id', 'FormPago');      
                                    
                                    oBoton = document.createElement("SPAN");
                                    oBoton.setAttribute('id', 'SeguirCompra'); 
                                    oOpc = document.createElement("li");            
                                    oOpc.appendChild(oBoton);
                                    ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
                                    $('SeguirCompra').addClassName('SpanBoton');
                                    $('SeguirCompra').innerHTML = 'Atr&aacute;s';
                                    Boton('SeguirCompra', function() {
                                       _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
                                          ActualizarCesta(function() {
                                             _("app.aspx", "acc=" + "_PLANTILLA_&documento=pedido", function(oHtm) {
                                                _("app.aspx", "acc=" + encodeURIComponent("_DATOSCESTA_"), function(oVal) {
                                                   MostrarPedido(oHtm, oVal);
                                                });
                                             });
                                          });
                                       });
                                    }, 'Atr&aacute;s');
                              
                                    oBoton = document.createElement("SPAN");
                                    oBoton.setAttribute('id', 'FinalizarCompra'); 
                                    oOpc = document.createElement("li");            
                                    oOpc.appendChild(oBoton);
                                    ($('FormPago').getElementsByTagName('UL')[0]).appendChild(oOpc);
                                    $('FinalizarCompra').addClassName('SpanBoton');
                                    $('FinalizarCompra').innerHTML = (FormaDePago == 4 ? 'Finalizar pago' : 'Finalizar compra');
                                    Boton('FinalizarCompra', function() {
                                       location.href = 'app.aspx?acc=' + encodeURIComponent('_PAYPAL_FINALIZAR_PAGO_') + "&obs=" + $(ObsPiePedido).value;
                                    }, 'Finalizar compra');         
                                 });
                              });
                           });
                        });
                     } else if(EstadoPago == "FINALIZADO") {
                        AlmacenarPedido(ErrPagoMsj, null);
                     }
                  });
               } else {
                  $('TdContenido').innerHTML = sHtmInicio;
                  if(ExisteId('ImgInicio')) {
                     $('ImgInicio').hide();
                     Effect.Appear('ImgInicio', {duration: 0.9});
                  }
                  ScrollUp();
                  if(document.onPaginaInicio != undefined) document.onPaginaInicio();
                  _("app.aspx", "acc=" + encodeURIComponent("_SET_FORMA_DE_PAGO_") + "&FormaPago=0&FormaEnvio=0", function() {
                     if(AutoLogin && RecordarUsuarioYClave)  ActualizarCesta(function() {
                                                                                           $('LogEmail').value = AutoLoginUsuario;
                                                                                           $('LogClave').value = AutoLoginClave;
                                                                                           Identificarse();
                                                                                        });
                     else ActualizarCesta();
                  });
               }
            });
         });
      } else {
         $('TdContenido').innerHTML = sHtmInicio;
         ScrollUp();
         if(document.onPaginaInicio != undefined) document.onPaginaInicio();
         DivReloj(false);
      }
      DivFondo(false);
      DoHttpProcLock = function() {DivReloj(HttpProcLock);}
      if(oVal.MsjInicio != '') Alert(oVal.MsjInicio);
   });
   
}

function PaginaEmpresa()
{
   if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=Empresa", function(oVal) {
      $('TdContenido').innerHTML = oVal.HTML;
      ScrollUp();
      if(document.onPaginaEmpresa != undefined) document.onPaginaEmpresa();
   });
}

function PaginaContacto()
{
   if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=contacto", function(oVal) {
      $('TdContenido').innerHTML = oVal.HTML;
      ScrollUp();
      Boton('ConEnviar', function() {
         _("app.aspx", "acc=" + encodeURIComponent("_SOLICITAR_INFO_") + "&Empresa=" + encodeURIComponent($("ConEmpresa").value)
                                                                       + "&Persona=" + encodeURIComponent($("ConPersona").value)
                                                                       + "&Direccion=" + encodeURIComponent($("ConDireccion").value)
                                                                       + "&Poblacion=" + encodeURIComponent($("ConPoblacion").value)
                                                                       + "&Codpostal=" + encodeURIComponent($("ConCodpostal").value)
                                                                       + "&Pais=" + encodeURIComponent($("ConPais").value)
                                                                       + "&Provincia=" + encodeURIComponent($("ConProvincia").value)
                                                                       + "&Telefono=" + encodeURIComponent($("ConTelefono").value)
                                                                       + "&EMail=" + encodeURIComponent($("ConEMail").value)
                                                                       + "&Obs=" + encodeURIComponent($("ConObs").value),
            function() {
               var sTbl = "<table class='TblAviso' 'cellpadding'='0' 'cellspacing'='0'>";
               sTbl    +=    "<tbody>";
               sTbl    +=       "<tr>";
               sTbl    +=          "<td>Su solicitud se ha cursado.</td>";
               sTbl    +=       "</tr>";
               sTbl    +=    "</tbody>";
               sTbl    += "</table>";
               $('TdContenido').innerHTML = sTbl;
            }
         );
     }, 'Enviar solicitud');
     if(document.onPaginaContacto != undefined) document.onPaginaContacto();
   });
}

function PaginaLegal()
{
   if($('TblCesta').NumLineas > 0) HabilitarBoton('SpanComprar', true);
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=legal", function(oVal) {
      $('TdContenido').innerHTML = oVal.HTML;
      ScrollUp();
      if(document.onPaginaLegal != undefined) document.onPaginaLegal();
   });
}

function PaginaDestacados()
{
   MsjReloj('Buscando ofertas. Espere ...'); 
   _("app.aspx", "acc=" + "_ARTICULOSDESTACADOS_", VerArticulos);
}

function PaginaNovedades()
{
   MsjReloj('Buscando novedades. Espere ...');
   _("app.aspx", "acc=" + "_ARTICULOSNOVEDAD_", VerArticulos);
}

function SesionExpirada()
{
   var sMsj = "Se ha excedido el tiempo de inactividad y se volver&aacute; a la p&aacute;gina de inicio."
   if($('SpanLogout').visible())   sMsj += "<br />Deber&aacute; identificarse de nuevo.";
   if($('TblCesta').NumLineas > 0) sMsj += "<br />El pedido actual ha sido cancelado.";
   DivFondo(true);
   $('TextoAtencion').innerHTML = sMsj;
   Boton('AtencionAceptar', function(){
      $('DivAtencion').hide(); 
      DivFondo(false);
      window.location.reload();
   }, 'Aceptar y cerrar');   
   $('DivAtencion').show();
   var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivAtencion').offsetHeight) / 2;
   var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivAtencion').offsetWidth) / 2;
   if(top < 1) top =  1;
   if(left < 1) left = 1;
   $('DivAtencion').style.top  = document.body.scrollTop + top;
   $('DivAtencion').style.left = left;
}

var oLstPed = null;
var oCabPed = null;
var oLinPed = null;
function EnlaceHistorico(nEnlace, lActivo)
{
   if(ExisteId('TdHistorico' + nEnlace)) {   
      if(lActivo) {
         Event.observe('TdHistorico' + nEnlace, 'mouseover', function() {
            $('TdHistorico' + nEnlace).removeClassName('TdOpcion');
            $('TdHistorico' + nEnlace).addClassName('TdOpcionSel');
         });
         Event.observe('TdHistorico' + nEnlace, 'mouseout', function() {
            $('TdHistorico' + nEnlace).removeClassName('TdOpcionSel');
            $('TdHistorico' + nEnlace).addClassName('TdOpcion');
         });         
         Event.observe('TdHistorico' + nEnlace, 'click', function() {
            _("app.aspx", "acc=" + "_PLANTILLA_&documento=Historico", function(oVal) {
               $('TdContenido').innerHTML = oVal.HTML;
               HistoricoDePedidos();
            });
         });
         if(nEnlace == 1) $('TrHistorico1').show();
         if(nEnlace == 2) $('TdHistorico2').EventosAsignados = true;
      } else {
         $('TdHistorico' + nEnlace).stopObserving('mouseover');
         $('TdHistorico' + nEnlace).stopObserving('mouseout');
         $('TdHistorico' + nEnlace).stopObserving('click');
         $('TrHistorico' + nEnlace).hide();
         if(nEnlace == 2) $('TdHistorico2').EventosAsignados = false;
      }
   }
}

function EnlaceVendido(nEnlace, lActivo)
{
   if(ExisteId('TdVendido' + nEnlace)) {   
      if(lActivo) {
         Event.observe('TdVendido' + nEnlace, 'mouseover', function() {
            $('TdVendido' + nEnlace).removeClassName('TdOpcion');
            $('TdVendido' + nEnlace).addClassName('TdOpcionSel');
         });
         Event.observe('TdVendido' + nEnlace, 'mouseout', function() {
            $('TdVendido' + nEnlace).removeClassName('TdOpcionSel');
            $('TdVendido' + nEnlace).addClassName('TdOpcion');
         });         
         Event.observe('TdVendido' + nEnlace, 'click', function() {
            _("app.aspx", "acc=" + encodeURIComponent("_ARTICULOSVENDIDOS_"), VerArticulos);
         });
         if(nEnlace == 1) $('TrVendido1').show();
         if(nEnlace == 2) $('TdVendido2').EventosAsignados = true;
      } else {
         $('TdVendido' + nEnlace).stopObserving('mouseover');
         $('TdVendido' + nEnlace).stopObserving('mouseout');
         $('TdVendido' + nEnlace).stopObserving('click');
         $('TrVendido' + nEnlace).hide();
         if(nEnlace == 2) $('TdVendido2').EventosAsignados = false;
      }
   }
}


function EnlaceMasVendido(nEnlace, lActivo)
{
   if(ExisteId('TdMasVendido' + nEnlace)) {
      if(lActivo) {
         Event.observe('TdMasVendido' + nEnlace, 'mouseover', function() {
            $('TdMasVendido' + nEnlace).removeClassName('TdOpcion');
            $('TdMasVendido' + nEnlace).addClassName('TdOpcionSel');
         });
         Event.observe('TdMasVendido' + nEnlace, 'mouseout', function() {
            $('TdMasVendido' + nEnlace).removeClassName('TdOpcionSel');
            $('TdMasVendido' + nEnlace).addClassName('TdOpcion');
         });         
         Event.observe('TdMasVendido' + nEnlace, 'click', function() {
            _("app.aspx", "acc=" + encodeURIComponent("_ARTICULOSMASVENDIDOS_"), VerArticulos);
         });
         if(nEnlace == 1) $('TrMasVendido1').show();
         if(nEnlace == 2) $('TdMasVendido2').EventosAsignados = true;
      } else {
         $('TdMasVendido' + nEnlace).stopObserving('mouseover');
         $('TdMasVendido' + nEnlace).stopObserving('mouseout');
         $('TdMasVendido' + nEnlace).stopObserving('click');
         $('TrMasVendido' + nEnlace).hide();
         if(nEnlace == 2) $('TdMasVendido2').EventosAsignados = false;
      }
   }
}

function HistoricoDePedidos()
{
   oLstPed = $('Historico').getElementsByTagName('TBODY')[0];
   oCabPed = (oLstPed.getElementsByTagName("TR")[0]).cloneNode(true);
   oLinPed = (oLstPed.getElementsByTagName("TR")[1]).cloneNode(true);
   
   BorrarLstPed();   

   $('DatosOpcEntrFec').hide();
   $('DatosOpcEntrFec').Visible = false;
   
   var oFecha = new Date();
   var sDia  = '' + oFecha.getDate(); sDia = (sDia.length == 1 ? '0' : '') + sDia;
   var sMes  = '' + (oFecha.getMonth() + 1); sMes = (sMes.length == 1 ? '0' : '') + sMes;
   var sAnno = '' + oFecha.getFullYear();
   $('FecIni').value = '01/01/' + sAnno
   $('FecFin').value = sDia  + '/' + sMes + '/' + sAnno;
   
   Event.observe('OpcUltPed', 'mouseover', function()  { this.addClassName('OpcSel'); });
   Event.observe('OpcUltPed', 'mouseout',  function()  { this.removeClassName('OpcSel'); });
   Event.observe('OpcUltPed', 'click',  function() { 
      ConsultarHistoricoDePedidos('acc=_ULTIMOS_PEDIDOS_');
   });
   
   Event.observe('OpcEntreFec', 'mouseover', function()  { this.addClassName('OpcSel'); });
   Event.observe('OpcEntreFec', 'mouseout',  function()  { this.removeClassName('OpcSel'); });
   Event.observe('OpcEntreFec', 'click',  function() { 
      if(! $('DatosOpcEntrFec').Visible) {
         this.removeClassName('OpcSel');
         $('OpcEntreFec').stopObserving('mouseover');
         $('OpcEntreFec').stopObserving('mouseout');
         $('DatosOpcEntrFec').Visible = true;
         $('OpcUltPed').hide();
         Effect.BlindDown('DatosOpcEntrFec', {duration: 0.3});
      }
   });
   Boton('SpanAtrasConsultaPed', function() {
      $('OpcUltPed').show();
      Effect.BlindUp('DatosOpcEntrFec', {duration: 0.3});
      $('DatosOpcEntrFec').Visible = false;
      Event.observe('OpcEntreFec', 'mouseover', function()  { this.addClassName('OpcSel'); });
      Event.observe('OpcEntreFec', 'mouseout',  function()  { this.removeClassName('OpcSel'); });
   });
   Boton('SpanConsultarPed', function() {
      ConsultarHistoricoDePedidos('acc=_PEDIDOS_ENTRE_FECHAS_&FecIni=' + $('FecIni').value + '&FecFin=' + $('FecFin').value);
   });
}

function ConsultarHistoricoDePedidos(sVal)
{
   _("app.aspx", sVal, function(oVal) {
      UltDesp = null;
      BorrarLstPed();
      if(oVal.Total > 0) {
         for(x = 0; x < oVal.Total; x++) AgregaLstPed(oVal.Numero[x], oVal.Fecha[x], oVal.Importe[x], oVal.Base[x], oVal.Iva[x], oVal.FPg[x], oVal.Obs[x]);
      } else {
         var oTr = document.createElement('TR');
         var oTd = document.createElement('TD');
         oTd.setAttribute('colspan', '6');
         oTd.innerHTML = 'No existen operaciones de venta.';
         oTr.appendChild(oTd);
         oLstPed.appendChild(oTr);
      }
   });
}

function BorrarLstPed()
{
   while(oLstPed.hasChildNodes()) oLstPed.removeChild(oLstPed.lastChild);
}

var UltDesp = null;
function AgregaLstPed(Numero, Fecha, Importe, Base, IVA, FPg, Obs)
{
   oLin = oCabPed.cloneNode(true);
   oLstPed.appendChild(oLin);
   aTd = oLin.getElementsByTagName('TD');
   var j;
   for(j = 0 ; j < aTd.length; j++) {
      sClass = aTd[j].className;
      if(sClass == 'ColNum') aTd[j].innerHTML = Numero;
      else if(sClass == 'ColFec') aTd[j].innerHTML = Fecha;
      else if(sClass == 'ColImp') aTd[j].innerHTML = Importe;
      else if(sClass == 'ColBas') aTd[j].innerHTML = Base;
      else if(sClass == 'ColIVA') aTd[j].innerHTML = IVA;
      else if(sClass == 'ColFPg') aTd[j].innerHTML = FPg;
      else if(sClass == 'ColDat') {
         aTd[j].Numero = Numero;
         aTd[j].Detallado = false;
         aTd[j].setAttribute('id', '_' + Numero);
         
         $('_' + Numero).Observaciones = Obs;
         
         Event.observe('_' + Numero, 'click', function()  {
            var oImg = this.getElementsByTagName('img')[0];
            if(!this.Detallado) {
               if(UltDesp != null) {
                  oImg2 = $(UltDesp).getElementsByTagName('img')[0];
                  oImg2.src = oImg2.src.replace('opcion_menos.gif','opcion_mas.gif');
                  aTr = oLstPed.getElementsByTagName("TR");
                  for(x = 0; x < aTr.length; x++) {
                     if(("_" + (aTr[x].getElementsByTagName("TD")[0]).Numero) == UltDesp) {
                        oLstPed.removeChild(aTr[x + 1]);
                     }
                  }
                  $(UltDesp).Detallado = false;
                  UltDesp = null;
               }
               this.Detallado = true;               
               oImg.src = oImg.src.replace('opcion_mas.gif','opcion_menos.gif');
               NumeroPedido = this.Numero
               _("app.aspx", "acc=_DETALLE_DE_PEDIDO_&NumPedido=" + NumeroPedido, function(oLin) {
                  if(oLin.Total > 0)  {
                     LineasDetalle = oLinPed.cloneNode(true);
                     oTBodyLinPed = LineasDetalle.getElementsByTagName('TBODY')[0];
                     oTrLinPed = (oTBodyLinPed.getElementsByTagName("TR")[0]).cloneNode(true);
                     while(oTBodyLinPed.hasChildNodes()) oTBodyLinPed.removeChild(oTBodyLinPed.lastChild);
                     
                     for(y = 0; y < oLin.Total; y++) {
                        oLinea = oTrLinPed.cloneNode(true);
                        aTdLinea = oLinea.getElementsByTagName("TD")
                        aTdLinea[0].innerHTML = (oLin.Articulo[y] == '' ? '&nbsp;' : oLin.Articulo[y]);
                        aTdLinea[1].innerHTML = (oLin.Descripcion[y] == '' ? '&nbsp;' : oLin.Descripcion[y]);
                        aTdLinea[2].innerHTML = (oLin.Cantidad[y] == '' ? '&nbsp;' : oLin.Cantidad[y]);
                        aTdLinea[3].innerHTML = (oLin.Precio[y] == '' ? '&nbsp;' : oLin.Precio[y]);
                        oTBodyLinPed.appendChild(oLinea);
                     }

                     var sObs = $('_' + NumeroPedido).Observaciones;
                     if(sObs != '') {
                        oLinea = oTrLinPed.cloneNode(true);
                        oTBodyLinPed.appendChild(oLinea);
                        oLinea = oTrLinPed.cloneNode(true);
                        aTdLinea = oLinea.getElementsByTagName("TD")
                        aTdLinea[0].innerHTML = '&nbsp;';
                        aTdLinea[1].innerHTML = (sObs == '' ? '&nbsp;' : sObs);
                        aTdLinea[2].innerHTML = '&nbsp;';
                        aTdLinea[3].innerHTML = '&nbsp;';
                        oTBodyLinPed.appendChild(oLinea);
                     }

                     aTr = oLstPed.getElementsByTagName("TR");
                     for(x = 0; x < aTr.length; x++) {
                        if((aTr[x].getElementsByTagName("TD")[0]).Numero == NumeroPedido) {
                           if(x == (aTr.length - 1)) oLstPed.appendChild(LineasDetalle.cloneNode(true));
                           else oLstPed.insertBefore(LineasDetalle.cloneNode(true), aTr[x + 1]);
                        }
                     }
                  }
               });
               UltDesp = this.getAttribute('id');
            } else {
               this.Detallado = false;               
               oImg.src = oImg.src.replace('opcion_menos.gif','opcion_mas.gif');               
               aTr = oLstPed.getElementsByTagName("TR");
               for(x = 0; x < aTr.length; x++) {
                  if((aTr[x].getElementsByTagName("TD")[0]).Numero == this.Numero) {
                     oLstPed.removeChild(aTr[x + 1]);
                  }
               }
               UltDesp = null;
            }
         });
      }
   }
}

function CuentaNoActivada()
{
   Confirm('La cuenta no esta activada.&nbsp;Revise su correo.<br>Desea que se le reenvie el correo de activacion.', function() {
      _("app.aspx", "acc=" + encodeURIComponent("_REENVIAR_ACTIVACION_") + "&param1=" + encodeURIComponent($("LogEmail").value), function(oVal) {
         Alert('Correo reenviado.');
      });
   });
}

function SeleccionarCliente()
{
   _("app.aspx", "acc=" + "_PLANTILLA_&documento=SeleccionarCliente", function(oVal) {
      $('TdContenido').innerHTML = oVal.HTML;

      var oTbody = $('LstCli').getElementsByTagName('TBODY')[0];
      
      var oTr  = document.createElement('TR');
      var oTd1 = document.createElement('TD');
      var oTd2 = document.createElement('TD');
      var oTd3 = document.createElement('TD');
      
      oTd1.setAttribute(_ClassName_, 'ColDat');
      oTd2.setAttribute(_ClassName_, 'ColNom');
      oTd3.setAttribute(_ClassName_, 'ColNif');
      oTd1.setAttribute('valign', 'middle'); 
      
      Boton('BotonBuscarCliente', function() {
            _("app.aspx", "acc=" + encodeURIComponent("_BUSCACLIENTES_") + "&param1=" + encodeURIComponent($("NomCli").value), function(oVal) {
               while(oTbody.hasChildNodes()) oTbody.removeChild(oTbody.lastChild);
               var oTrCli, oTdFlc, oTdNom, oTdNif
               if(oVal.Total == 0) {
                  oTrCli = oTr.cloneNode(true);
                  oTdFlc = oTd1.cloneNode(true);
                  oTdNom = oTd2.cloneNode(true);
                  oTdNif = oTd3.cloneNode(true);
                  oTdFlc.innerHTML = '&nbsp;';
                  oTdNom.innerHTML = 'No se encontraron clientes';
                  oTdNif.innerHTML = '&nbsp;';
                  oTrCli.appendChild(oTdFlc);
                  oTrCli.appendChild(oTdNom);
                  oTrCli.appendChild(oTdNif);
                  oTbody.appendChild(oTrCli);
               } else for(var x = 0; x < oVal.Total; x++) {
                  oTrCli = oTr.cloneNode(true);
                  oTdFlc = oTd1.cloneNode(true);
                  oTdNom = oTd2.cloneNode(true);
                  oTdNif = oTd3.cloneNode(true);

                  oImg = document.createElement('IMG');
                  oImg.setAttribute('border', '0');
                  oImg.setAttribute('style', 'padding:0 0 2px 0;');
                  oImg.setAttribute('src', './images/app/flecha1.gif'); 
                  oTdFlc.appendChild(oImg);

                  oTdNom.innerHTML = oVal.Nombre[x];
                  oTdNif.innerHTML = (oVal.NIF[x] == '' ? '&nbsp;' : oVal.NIF[x]);
                  
                  oTdNom.style.cursor = 'pointer';
                  oTdNom.setAttribute('id', 'NomCli_' + x);
                  oTdNom.Codigo = oVal.Codigo[x];
                  
                  oTrCli.appendChild(oTdFlc);
                  oTrCli.appendChild(oTdNom);
                  oTrCli.appendChild(oTdNif);
                  oTbody.appendChild(oTrCli);
                  
                  Event.observe('NomCli_' + x, 'mouseover', function() { this.addClassName('Underline'); });
                  Event.observe('NomCli_' + x, 'mouseout', function() { this.removeClassName('Underline'); });
                  Event.observe('NomCli_' + x, 'click', function() { 
                     _("app.aspx", "acc=" + encodeURIComponent("_ASIGNARCLIENTE_") + "&param1=" + encodeURIComponent(this.Codigo), function(oRes) {
                        $('TdContenido').innerHTML = oRes.HTML;
                        $('TdNomCliente').innerHTML = oRes.Cliente;
                        if(MostrarHistoPed && ExisteId('TdHistorico1') && !$('TdHistorico2').EventosAsignados) EnlaceHistorico(2, true);
                        if(ExisteId('TdVendido1') && !$('TdVendido1').EventosAsignados) EnlaceVendido(2, true);
                        if(ExisteId('TdMasVendido1') && !$('TdMasVendido2').EventosAsignados) EnlaceMasVendido(2, true);
                        ActualizarCesta();
                     });
                  });
               }
            });
      }, 'Buscar cliente');
      $('NomCli').focus();
      OnEnter('NomCli', function() {$('NomCli').focus(); $('BotonBuscarCliente').OnClick();} )
      if(ExisteId('LstVis')) ActualizarVisitar();
   });
}

function VerBuscador(lMostrar)
{
   if(lMostrar) {
      if(ExisteId('DivCabBuscador')) $('DivCabBuscador').show();
      else if(ExisteId('TblBuscador')) $('TblBuscador').show();
   } else {
      if(ExisteId('DivCabBuscador')) $('DivCabBuscador').hide();
      else if(ExisteId('TblBuscador')) $('TblBuscador').hide();
   }
}

function EnlaceNuevoCliente(lActivo)
{
   if(lActivo) {
      Event.observe('TdNuevoCliente', 'mouseover', function() {
         $('TdNuevoCliente').removeClassName('TdOpcion');
         $('TdNuevoCliente').addClassName('TdOpcionSel');
      });
      Event.observe('TdNuevoCliente', 'mouseout', function() {
         $('TdNuevoCliente').removeClassName('TdOpcionSel');
         $('TdNuevoCliente').addClassName('TdOpcion');
      });         
      Event.observe('TdNuevoCliente', 'click', function() {
         _("app.aspx", "acc=" + "_PLANTILLA_&documento=NuevoCliGes", function(oVal) {
            $('TdContenido').innerHTML = oVal.HTML;
            Boton('NuevoCliente', function() {
               _("app.aspx", "acc=" + encodeURIComponent("_NUEVO_CLIENTE_") +
                                          "&nombre=" + encodeURIComponent($("nombre").value) +
                                          "&subnombre=" + encodeURIComponent($("subnombre").value) +
                                          "&nif=" + encodeURIComponent($("nif").value) +
                                          "&direccion=" + encodeURIComponent($("direccion").value) +
                                          "&codpostal=" + encodeURIComponent($("codpostal").value) +
                                          "&poblacion=" + encodeURIComponent($("poblacion").value) +
                                          "&provincia=" + encodeURIComponent($("provincia").value) +
                                          "&telefono=" + encodeURIComponent($("telefono").value) +
                                          "&movil=" + encodeURIComponent($("movil").value) +
                                          "&fax=" + encodeURIComponent($("fax").value) +
                                          "&email=" + encodeURIComponent($("email").value) +
                                          "&tipoiva=" + encodeURIComponent($("tipoIva").value) +
                                          "&tarifa=" + encodeURIComponent($("tarifa").value) +
                                          "&dt1=" + encodeURIComponent($("dt1").value) +
                                          "&dt2=" + encodeURIComponent($("dt2").value) +
                                          "&fpr=" + encodeURIComponent($("fpr").value) +
                                          "&req=" + encodeURIComponent($("req").value),
                                          function(oVal) {$('TdContenido').innerHTML = oVal.HTML;});
            }, 'Crear cliente');
            OnEnter('nombre', 'subnombre');
            OnEnter('subnombre', 'nif');
            OnEnter('nif', 'direccion');
            OnEnter('direccion', 'codpostal');
            OnEnter('codpostal', 'poblacion');
            OnEnter('poblacion', 'provincia');
            OnEnter('provincia', 'telefono');
            OnEnter('telefono', 'movil');
            OnEnter('movil', 'fax');
            OnEnter('fax', 'email');
            OnEnter('email', 'tipoIva');
            OnEnter('tipoIva', 'tarifa');
            OnEnter('tarifa', 'dt1');
            OnEnter('dt1', 'dt2');
            OnEnter('dt2', 'fpr');
            OnEnter('fpr', 'req');
            OnEnter('req', function() {$('NuevoCliente').OnClick();});            
            $('nombre').focus();
         });
      });
      $('TrNuevoCliente').show();
   } else {
      $('TdNuevoCliente').stopObserving('mouseover');
      $('TdNuevoCliente').stopObserving('mouseout');
      $('TdNuevoCliente').stopObserving('click');
      $('TrNuevoCliente').hide();
   }
}

function PaginaDocumentacion()
{
   _("app.aspx", "acc=" + "_DOCUMENTACION_", function(oVal) { 
      $('TdContenido').innerHTML = oVal.HTML;
      var oTbody = $('Marco').getElementsByTagName('TBODY')[0];
      aTr = oTbody.getElementsByTagName('TR');
      var oTrCategoria = aTr[0].cloneNode(true);
      var oTrTitulo    = aTr[1].cloneNode(true);
      
      oTbody.removeChild(aTr[1]);
      oTbody.removeChild(aTr[0]);

      var sCat = "";
      if(oVal.Documentos.length > 0) {
         for(x = 0; x < oVal.Documentos.length; x++) {
            if(oVal.Documentos[x].Categoria != sCat) {
               sCat = oVal.Documentos[x].Categoria;
               oTr = oTrCategoria.cloneNode(true);
               (oTr.getElementsByTagName('TD')[0]).innerHTML= sCat;
               oTbody.appendChild(oTr);
            }
            oTr = oTrTitulo.cloneNode(true);
            oA = oTr.getElementsByTagName('A')[0];
            oA.innerHTML = oVal.Documentos[x].Titulo;
            oA.Documento = './data/docs/' + oVal.Documentos[x].Fichero;
            oA.onclick = function() { this.blur(); window.open(this.Documento, "Documentacion"); } 
            oTbody.appendChild(oTr);
         }
      } else {
         oTr = oTrCategoria.cloneNode(true);
         (oTr.getElementsByTagName('TD')[0]).innerHTML= "No hay documentaci&oacute;n disponible.<br /><br />";
         oTbody.appendChild(oTr);
      }
   });
}


var NomCookie = "FsWeb";

function CargarDatosAutoLogin()
{
   AutoLoginUsuario = LeeCookie(NomCookie + "Usr");
   AutoLoginClave = LeeCookie(NomCookie + "Pwd");
}

function SalvarDatosAutoLogin()
{
   GrabaCookie(NomCookie + "Usr", AutoLoginUsuario, 90);
   GrabaCookie(NomCookie + "Pwd", AutoLoginClave, 90);
}

function LeeCookie(Nombre)
{
   var Valor = "";
   if(document.cookie.length > 0) {
      var nPosIni = document.cookie.indexOf(Nombre);
      if(nPosIni != -1) {
         nPosIni += Nombre.length + 1;
         Valor = document.cookie.substring(nPosIni);
         nPosFin = Valor.indexOf(";");
         if(nPosFin > -1) Valor = Valor.substring(0, nPosFin);
      }
   }
   return Valor;
}

function GrabaCookie(Nombre, Valor, Dias)
{
   var dtsec = new Date();
   dtsec.setSeconds(dtsec.getSeconds() + (60 * 30 * 60 * Dias));
   document.cookie = Nombre + "=" + Valor + "; expires=" + dtsec.toGMTString();
}

function ActualizarVisitar()
{
   _("app.aspx", "acc=" + encodeURIComponent("_CLIENTESAVISITAR_"), function(oVal) {      
      var oTbody = $('LstVis').getElementsByTagName('TBODY')[0];
      while(oTbody.hasChildNodes()) oTbody.removeChild(oTbody.lastChild);
      for(x = 0; x < oVal.TotPdt; x++) {
         oTd = document.createElement('TD');
         oTd.appendChild(document.createTextNode(oVal.NomPdt[x]));
         oTd2 = document.createElement('TD');
         oTd2.appendChild(document.createTextNode(oVal.FecPdt[x]));
         oTr = document.createElement('TR');
         oTr.appendChild(oTd);
         oTr.appendChild(oTd2);
         oTbody.appendChild(oTr);
         oTd.setAttribute(_ClassName_, 'Pendiente');
         
         oTd.setAttribute('id', oVal.CodPdt[x]); 
         oTd.Planning = oVal.PlanPdt[x];
         oTd.Codigo = oVal.CodPdt[x];
         $(oVal.CodPdt[x]).style.cursor = 'pointer';
         Event.observe(oVal.CodPdt[x], 'click', function() {
            Planning = this.Planning;
            Codigo = this.Codigo;
            Confirm("Seleccionar este cliente", function() {
               _("app.aspx", "acc=" + encodeURIComponent("_ASIGNARCLIENTE_") + "&param1=" + encodeURIComponent(Codigo), function(oRes) {
                  $('TdContenido').innerHTML = oRes.HTML;
                  $('TdNomCliente').innerHTML = oRes.Cliente;
                  if(MostrarHistoPed && ExisteId('TdHistorico1') && !$('TdHistorico2').EventosAsignados) EnlaceHistorico(2, true);
                  if(ExisteId('TdVendido1') && !$('TdVendido1').EventosAsignados) EnlaceVendido(2, true);
                  if(ExisteId('TdMasVendido1') && !$('TdMasVendido2').EventosAsignados) EnlaceMasVendido(2, true);
                  ActualizarCesta();
               });
             }, function() {
               Confirm("Marcar como visitado este cliente", function() {
                  DivFondo(true);
                  $('TextoPregunta').innerHTML = "Indique el motivo por el que lo marca como visitado:<br><input type=\'text\' id=\'MotVisCli\' size='40' >";
                  Boton('PreguntaAceptar', function() {
                     $('DivPregunta').hide();
                     DivFondo(false);
                     _("app.aspx", "acc=" + encodeURIComponent("_MARCARCOMOVISITADO_") + "&planning=" + encodeURIComponent(Planning) + "&cliente=" + encodeURIComponent(Codigo) + "&observaciones=" + encodeURIComponent($('MotVisCli').value), function(oVal) {ActualizarVisitar();});
                  }, 'Aceptar y cerrar');
                  Boton('PreguntaCancelar', function() {
                     $('DivPregunta').hide();
                     DivFondo(false);
                  }, 'Cancelar y cerrar');
                  $('DivPregunta').show();
                  var top  = ((document.layers ? window.innerHeight : document.body.clientHeight)  - $('DivPregunta').offsetHeight) / 2;
                  var left = ((document.layers ? window.innerWidth : document.body.clientWidth) - $('DivPregunta').offsetWidth) / 2;
                  if(top < 1) top = 1;
                  if(left < 1) left = 1;
                  $('DivPregunta').style.top  = document.body.scrollTop + top;
                  $('DivPregunta').style.left = left;      
               });
            });
         });
      }
      for(x = 0; x < oVal.TotVis; x++) {
         oTd = document.createElement('TD');
         oTd.appendChild(document.createTextNode(oVal.NomVis[x]));
         oTd2 = document.createElement('TD');
         oTd2.appendChild(document.createTextNode(oVal.FecVis[x]));
         oTr = document.createElement('TR');
         oTr.appendChild(oTd);
         oTr.appendChild(oTd2);
         oTbody.appendChild(oTr);
         oTd.setAttribute(_ClassName_, 'Visitado');
      }      
   });
}
