// Archivo JScript
var QuickLookPopUp = {};

QuickLookPopUp.IdSKU = [];
QuickLookPopUp.Visible = false;
QuickLookPopUp.TopOffset = 50;      // FIXME: reemplazar en archivos 'mlpTopOffset' por 'MisListasPopup.TopOffset'
QuickLookPopUp.Posicion;            // array de la forma [0:X,1:Y]
QuickLookPopUp.Autenticado = false; // Indica si el usuario se encuentra autenticado
QuickLookPopUp.ClienteActivo = true;
QuickLookPopUp.Acompanamiento = false;
QuickLookPopUp.NOM_MAX_LENGTH = 40; // Constante que define el máximo número de caracteres del nombre.
  
QuickLookPopUp.ZoomVisible = false; // Indica si el zoom está visible.
QuickLookPopUp.TimerDescuento = null;
QuickLookPopUp.TimerCantidad = null;
QuickLookPopUp.MostrarMotivo = false;
//*************************************************************************************************

QuickLookPopUp.Mostrar = function(id, titulo, opciones)
{
    if(id != null && !QuickLookPopUp.Visible)
    {
        QuickLookPopUp.Visible = true;
        if($('quicklookloader_' + id) != null)
            $('quicklookloader_' + id).style.visibility = 'visible';
        var nombre = "";
        
        QuickLookPopUp.IdSKU = id;
        CallMe.IdSKU = id;
        if(opciones != null && opciones.ev != null)
            QuickLookPopUp.Posicion = YAHOO.util.Event.getXY(opciones.ev);
        if(opciones != null && opciones.el != null)
            QuickLookPopUp.Posicion = YAHOO.util.Dom.getXY(opciones.el);
        if(opciones != null && opciones.posicion != null)
            QuickLookPopUp.Posicion = YAHOO.util.Event.getXY(opciones.ev);
        if(opciones != null && opciones.offsetLeft != null)
            QuickLookPopUp.Posicion[0] -= opciones.offsetLeft;
        if(opciones != null && opciones.offsetTop != null)
            QuickLookPopUp.Posicion[1] -= opciones.offsetTop;
        if(titulo != null)
            nombre = titulo;
        

        var divBackground = document.createElement('div');
        document.body.insertBefore(divBackground, document.body.firstChild);
        divBackground.setAttribute('id', 'quicklookBackground');
        divBackground.style.position = 'absolute';
        divBackground.style.zIndex = $('pnlDetProdContainer').style.zIndex - 1;
        YAHOO.util.Dom.setStyle(divBackground, 'opacity', 0);
        YAHOO.util.Dom.setStyle(divBackground, 'background-color', '#ffffff');
        var viewWidth = YAHOO.util.Dom.getViewportWidth();
        var viewHeight = YAHOO.util.Dom.getViewportHeight();
        if (divBackground.offsetHeight > viewHeight)
        {
            divBackground.style.height = viewHeight + "px";
        }
        if (divBackground.offsetWidth > viewWidth)
        {
            divBackground.style.width = viewWidth + "px";
        }
        divBackground.style.height = YAHOO.util.Dom.getDocumentHeight() + "px";
        divBackground.style.width = YAHOO.util.Dom.getDocumentWidth() + "px";
        YAHOO.util.Event.addListener(divBackground, 'click', QuickLookPopUp.Cerrar);
        
        var panelDetProd = $('pnlDetalleProducto');
        YAHOO.util.Dom.setStyle(panelDetProd, 'opacity', 0);
        panelDetProd.style.display='block';
        panelDetProd.style.visibility='visible';
        $('lblNombreProd').style.fontSize = QuickLookPopUp.GetTitleSize(463, 24, nombre);
        QuickLookPopUp.Posicion[0] = (YAHOO.util.Dom.getViewportWidth() - panelDetProd.clientWidth)/2;
        QuickLookPopUp.Posicion[1] = YAHOO.util.Dom.getDocumentScrollTop() + ((YAHOO.util.Dom.getViewportHeight() - panelDetProd.clientHeight)/2);
        YAHOO.util.Dom.setXY(panelDetProd, QuickLookPopUp.Posicion);
        var animObj = new YAHOO.util.Anim('pnlDetalleProducto', { opacity: { from: 0, to: 1 } }, 1, YAHOO.util.Easing.easeOut);
        animObj.animate();
    }
}

//*************************************************************************************************

QuickLookPopUp.Zoom = function(e, opciones)
{
    QuickLookPopUp.IdSKU = opciones.id;
    
    if(opciones.id != null && !QuickLookPopUp.ZoomVisible)
    {
        QuickLookPopUp.ZoomVisible = true;
        var panelDetProd = $('pnlZoomProduct');        
        $('lblAmpNombreProd').innerHTML = opciones.nombre;
        $('lblAmpNombreProd').style.fontSize = QuickLookPopUp.GetTitleSize(280, 24, opciones.nombre);
        YAHOO.util.Dom.setStyle(panelDetProd, 'opacity', 0);
        panelDetProd.style.display='block';
        panelDetProd.style.visibility='visible';
        // Posición en X de la ventana de Zoom.
        QuickLookPopUp.Posicion[0] = (YAHOO.util.Dom.getXY('aHrefZoom')[0] - ((panelDetProd.offsetWidth - $('aHrefZoom').offsetWidth) / 2));
        // Posición en Y de la ventana de Zoom con respecto al link de ampliar de la ventana de detalle.
        QuickLookPopUp.Posicion[1] = YAHOO.util.Dom.getXY('aHrefZoom')[1] - 340;
        YAHOO.util.Dom.setXY(panelDetProd, QuickLookPopUp.Posicion);
        var animObj = new YAHOO.util.Anim('pnlZoomProduct', { opacity: { from: 0, to: 1 } }, 1, YAHOO.util.Easing.easeOut);
        animObj.animate();
    }
}

//*************************************************************************************************

QuickLookPopUp.Restore = function()
{
    if($('pnlZoomProduct') != null)
        var animObj = new YAHOO.util.Anim('pnlZoomProduct', { opacity: { from: 1, to: 0 } }, 1, YAHOO.util.Easing.easeOut);
        animObj.onComplete.subscribe(function()
        {
            this.getEl().style.display='none';
            this.getEl().style.visibility='hidden';
            QuickLookPopUp.ZoomVisible=false;
        });
        animObj.animate();
}

//*************************************************************************************************

QuickLookPopUp.Cerrar = function()
{
    if(QuickLookPopUp.ZoomVisible)
        QuickLookPopUp.Restore();
    if($('pnlDetalleProducto') != null)
        var animObj = new YAHOO.util.Anim('pnlDetalleProducto', { opacity: { from: 1, to: 0 } }, 1, YAHOO.util.Easing.easeOut);
        animObj.onComplete.subscribe(function()
        {
            this.getEl().style.display='none';
            this.getEl().style.visibility='hidden';
            if($('quicklookBackground') != null)
            {
                document.body.removeChild($('quicklookBackground'));
            }
            if($('quicklookloader_' + QuickLookPopUp.IdSKU) != null)
            {
                $('quicklookloader_' + QuickLookPopUp.IdSKU).style.visibility = 'hidden';
            }
            if($('QuickLook' + QuickLookPopUp.IdSKU) != null)
            {
                $('QuickLook' + QuickLookPopUp.IdSKU).style.display='none';
                $('QuickLook' + QuickLookPopUp.IdSKU).style.visibility='hidden';
            }
            QuickLookPopUp.Visible=false;
        });
        animObj.animate();
}

//*************************************************************************************************

QuickLookPopUp.GetTitleSize = function(maxContTitleSize, titleSize, title)
{
    var tag_nobr = $('hiddenNoBr');
    var size = titleSize;
    
    tag_nobr.innerHTML = title;
    tag_nobr.style.fontSize = titleSize + "px";
    
    while(tag_nobr.offsetWidth > maxContTitleSize)
    {
        size = size - 1;
        tag_nobr.style.fontSize = size + "px";        
    }
    
    return size + "px";
}

//*************************************************************************************************

QuickLookPopUp.ObtenerDetalle = function(idSKU, GUID, opciones)
{
     var MostrarDetalleProducto_OnSuccess = function(args)
            {
                var respuesta = eval('(' + args + ')');
                
                if(!respuesta.resultado)
                {
                    ModalDialog.Show("Error", respuesta.mensajeError, ModalDialog.OK);
                    return;
                }
                
                $('lblNombreProd').innerHTML = respuesta.nom;
                    
                $('lblCodigo').innerHTML = respuesta.cod;
                $('lblRef').innerHTML = respuesta.ref;
                $('lblEAN').innerHTML = respuesta.ean;
                $('lblMarca').innerHTML = respuesta.mar;
                var marca_OnSuccess = function(args2)
                {
                    $('hlkMarca').href = "Homemarca.aspx?mnd1=" + args2    
                }
                Mundial.ScriptServices.Encriptar(respuesta.idmar, marca_OnSuccess, function(args2) { return null; }, function(args2) { });
                $('lblPUM').innerHTML = respuesta.pum;
                $('lblPrecioUnitario').innerHTML = respuesta.pu;
                $('lblDescuento').innerHTML = respuesta.des;
                
                if(respuesta.des != "0%")
                {
                    $('lblPrecioUnitario').className = "Scratchout";
                }
                else
                {
                    $('lblPrecioUnitario').className = "detalle_producto_precio";
                }
                var oncli = $('pnlDetalleProducto').innerHTML;
                oncli = oncli.replace(/__CATALOGO_IDSKU__/g, idSKU);
                $('pnlDetalleProducto').innerHTML = oncli; 
                
                $('lblPrecioDescuento').className = "detalle_producto_precio";
                $('lblPrecioDescuento').innerHTML = respuesta.pdes;
                $('lblUnidadVenta').innerHTML = respuesta.uv;
                $('lblUnidadEmpaque').innerHTML = respuesta.ue;
                $('imgProd96').src = respuesta.img;
                $('imgOferta').style.display = (respuesta.oferta ? 'inline' : 'none');
                $('imgNuevo').style.display = (respuesta.nuevo ? 'inline' : 'none');
                $('imgCombo').style.display = (respuesta.combo ? 'inline' : 'none');
                $('lblDescripcion').innerHTML = respuesta.desc;
                $('lblEspecTec').innerHTML = respuesta.espec;
                $('lblTablaDescuentos').innerHTML = respuesta.tdes;
                
                $('lbPrecio').innerHTML = respuesta.pdes;
                
                
                $('idVerInformacion').href = respuesta.vi;
               
                
                var ampliarJsonObj = {id:idSKU, nombre:respuesta.nom};
                
                if(YAHOO.util.Event.getListeners("aHrefZoom", "click") != null)
                {
                    YAHOO.util.Event.removeListener("aHrefZoom", "click");
                    YAHOO.util.Event.addListener('aHrefZoom', "click", QuickLookPopUp.Zoom, ampliarJsonObj);
                }
                else
                {
                    YAHOO.util.Event.addListener('aHrefZoom', "click", QuickLookPopUp.Zoom, ampliarJsonObj);
                }
                $('imgProductZoom').src = respuesta.zoom;
                
                if(!Catalogo.Autenticado)
                {
                    $('idQtyQuickLook').style.display = "none";
                    $('SpanQty').style.display = "none";
                    $('idPrecioUnitario').style.display = "none";
                    $('idDescuento').style.display = "none";
                    $('PrecioDescuento').style.display = "none";
                    $('lbPrecio').style.display = "none";
                    $('lbPrecio').style.visibility = "hidden";
                    $('idPUM').style.display = 'none';
                }
                else
                {
                    $('idQtyQuickLook').value = respuesta.uv;
                }
                var tabView = new YAHOO.widget.TabView('tabs_detalle_producto');
                 if(respuesta.tdes == "")
                {
                    $('li3').style.display = "none";
                    if($('li3').style.display == "none")
                    {
                        tabView.set('activeIndex', 0);
                    }
                }
                else
                {
                    $('li3').style.display = '';
                    tabView.set('activeIndex', 2);
                }
                // Descuento adicional
                if(QuickLookPopUp.Acompanamiento)
                {
                    $('idMotivoDescuento').style.display = 'none';
                    $('idPUM').style.display = '';
                    $('idDescuento').style.display = 'none';
                    $('idDescuentoAdicional').style.display = '';
                    $('idDescuentoMax').style.display = '';
                    $('lblDescuentoMax').innerHTML = respuesta.descuentoMaximo + '%';
                    // Cargar descuento por volumen
                    if(respuesta.descuentoVolumen > 0)
                    {
                        $('txtDescuentoAdicional').value = respuesta.descuentoVolumen;
                        if(respuesta.descuentoVolumen > respuesta.descuentoMaximo)
                        {
                            $('idMotivoDescuento').style.display = '';
                            $('motivoDescuento').value = '-1';                            
                        }
                    }
                    else
                    {
                        $('txtDescuentoAdicional').value = '00.00';
                        $('idMotivoDescuento').style.display = 'none';
                    }
                }
                // Usuario inactivo
                if(!QuickLookPopUp.ClienteActivo)
                {
                    $('idPUM').style.display = 'none';
                    $('idDescuento').style.display = 'none';
                    $('idDescuentoAdicional').style.display = 'none';
                    $('PrecioDescuento').style.display = 'none';
                    $('lblPrecioUnitario').className = "detalle_producto_precio";
                    $('idDescuentoMax').style.display = 'none';
                }

                QuickLookPopUp.Mostrar(idSKU, respuesta.nom, opciones);
            }

            Mundial.ScriptServices.DetallePedidosRapidos(idSKU, GUID, MostrarDetalleProducto_OnSuccess, function(args) { }, function(args) { });
}




//*************************************************************************************************

QuickLookPopUp.AgregarCarro = function()
{
    if(QuickLookPopUp.TimerDescuento != null)
        return;
    var cantidad = $('idQtyQuickLook').value.replace(/^\\s+|\\s+$/g,'');
    var descuento = $('txtDescuentoAdicional').value.replace(/^\\s+|\\s+$/g,'');
    var motivo = $('motivoDescuento').value;
    // Validar cantidad
    if(cantidad.length == 0 || !IsNumeric(cantidad) || !IsInt(cantidad) || parseInt(cantidad) <= 0)
    {
        ModalDialog.Show("Error", "La cantidad no es válida", ModalDialog.OK);
        return;
    }
    // Validar motivo
    if(descuento == '')
        descuento = -1000;
    else
    {
        if(!IsNumeric(descuento) || parseFloat(descuento) <= -100 || parseFloat(descuento) >= 100)
        {
            ModalDialog.Show("Error", "El descuento debe ser un valor numérico entre -100 y 100", ModalDialog.OK);
            return;
        }
    }
    // Validar motivo
    if(QuickLookPopUp.MostrarMotivo && motivo == '-1')
    {
        ModalDialog.Show("Error", "El motivo de descuento es requerido", ModalDialog.OK);
        return;
    }
    var AgregarCarro_OnSuccess = function(args)
    {
        if(typeof(vistaCarroCompra)!="undefined" && vistaCarroCompra)
        {
            listaRefrescarProducto(QuickLookPopUp.IdSKU);
        }
        panelLoading.hide();
        var respuesta = eval('(' + args + ')');
        if(!respuesta.resultado)
        {
            ModalDialog.Show("Error", respuesta.mensajeError, ModalDialog.OK);
            return;
        }
        
        if(typeof(vistaCarroCompra) == "undefined" || !vistaCarroCompra)
        {
            mostrarSliderCarroCompra(respuesta.datosSlider);
        }
        actualizarContadorCarro(respuesta.totalCarro);
        QuickLookPopUp.Cerrar();
    }
    panelLoading.show();
    $('panelLoading_mask').style.zIndex=1001;
    $('panelLoading_c').style.zIndex=1002;
    if(!QuickLookPopUp.Acompanamiento)
        Mundial.ScriptServices.AgregarCarro(QuickLookPopUp.IdSKU, cantidad, AgregarCarro_OnSuccess, Catalogo.WS_OnError, Catalogo.WS_OnTimeout);
    else
        Mundial.ScriptServices.AgregarCarroAcompanamiento(QuickLookPopUp.IdSKU, cantidad, descuento, motivo, AgregarCarro_OnSuccess, Catalogo.WS_OnError, Catalogo.WS_OnTimeout);
}

//*************************************************************************************************

QuickLookPopUp.descuentoOnKeyUp = function(ev, el)
{
//    var teclaValida = QuickLookPopUp.descuentoOnKeyDown(ev);
//    if(!teclaValida)
//        return false;
    if(QuickLookPopUp.TimerDescuento != null)
        clearTimeout(QuickLookPopUp.TimerDescuento);
    QuickLookPopUp.TimerDescuento = setTimeout(function() { QuickLookPopUp.ActualizarDescuento($('idQtyQuickLook').value, el.value, QuickLookPopUp.IdSKU); }, 1000);
}

//*************************************************************************************************

QuickLookPopUp.descuentoOnFocus = function(el)
{
    if(el.value=="00.00")
        el.value="";
}

//*************************************************************************************************

QuickLookPopUp.descuentoOnBlur = function(el)
{
    if(el.value=="")
    {
        el.value="00.00";
        return true;
    }
    return false;
}

//*************************************************************************************************

QuickLookPopUp.descuentoOnKeyDown = function(ev)
{
    if(ev.which || ev.keyCode)
    {
        if ((ev.which == 13) || (ev.keyCode == 13)) {return false;}
    } else {return true}
    var codes = new Array(9,48,49,50,51,52,53,54,55,56,57,8,37,39,46,13,96,97,98,99,100,101,102,103,104,105,109,110,190);
    if(ev.which != undefined) 
    {
        aux = !(codes.indexOf(ev.which) < 0);
    }
    else
    if(ev.keyCode != undefined) 
    {
        aux = !(codes.indexOf(ev.keyCode) < 0);
    }
    if (ev.shiftKey || ev.altKey || ev.ctrlKey)
        return false;
    return aux;
}

//*************************************************************************************************

QuickLookPopUp.ActualizarDescuento = function(cantidad, descuento, idsku)
{
    QuickLookPopUp.TimerDescuento = null;
    descuento = descuento.replace(/^\\s+|\\s+$/g,'');
    cantidad = cantidad.replace(/^\\s+|\\s+$/g,'');
    // Validar cantidad
    if(cantidad.length == 0 || !IsNumeric(cantidad) || !IsInt(cantidad) || parseInt(cantidad) <= 0)
    {
        ModalDialog.Show("Error", "La cantidad no es válida", ModalDialog.OK);
        return;
    }

    $('motivoDescuento').value = '-1';
    motivo = $('motivoDescuento').value;
    var i;
    if(isNaN(parseFloat(descuento)))
        return;
    var actualizarDescuento_OnSuccess = function(result, eventargs)
    {
        panelLoading.hide();
        respuesta =  eval("(" + result + ")");
        if(!respuesta.resultado)
        {
            ModalDialog.Show("Error", respuesta.mensajeError , ModalDialog.OK);
            $('idMotivoDescuento').style.display = "none";
            $('txtDescuentoAdicional').value = "00.00";
            return;
        }
        QuickLookPopUp.MostrarMotivo = (QuickLookPopUp.Acompanamiento && respuesta.mostrarMotivo);
        $('idMotivoDescuento').style.display = (QuickLookPopUp.MostrarMotivo ? "" : "none");
        $('lblPrecioDescuento').innerHTML = respuesta.valorUnitario;
        $('lblDescuento').innerHTML = respuesta.descuento + ' %';
        if(QuickLookPopUp.Acompanamiento)
            $('txtDescuentoAdicional').value = respuesta.descuento;
    }
    var actualizarDescuento_OnError = function(error)
    {
        panelLoading.hide();
        ModalDialog.Show("Error", "Verifique que el descuento sea un valor numérico", ModalDialog.OK);
    }
    panelLoading.show();
    $('panelLoading_mask').style.zIndex=1001;
    $('panelLoading_c').style.zIndex=1002;
    Mundial.ScriptServices.ActualizarDescuentoQuickLook(idsku, descuento, cantidad, actualizarDescuento_OnSuccess, actualizarDescuento_OnError, function(args) { });
}

//*************************************************************************************************

QuickLookPopUp.cantidadOnBlur = function(el)
{
    if(el.value=="")
    {
        el.value="0";
        return true;
    }
    return false;
}

//*************************************************************************************************

QuickLookPopUp.cantidadOnKeyUp = function(ev, el)
{
    if(QuickLookPopUp.TimerCantidad != null)
        clearTimeout(QuickLookPopUp.TimerCantidad);
    QuickLookPopUp.TimerCantidad = setTimeout(function() { QuickLookPopUp.ActualizarDescuento(el.value, '-1000', QuickLookPopUp.IdSKU); }, 1000);
}


