var arrayBeginRequest = new Array();
var arrayEndRequest = new Array();
var arrayPageLoad = new Array();
var ventanaActiva = false;
var preciosProductos = { "codigoCliente" : null, "codigoProducto" : new Array(), "panelId":new Array(), "precio" : new Array(), "ofertaWS":new Array() };
var correccionAlturaMenuIzq = 51;
var clienteActivo = true;
var MundialPath = '/MundialB2B/';

function pageLoad(sender, args) {
    arrayBeginRequest.each( function(f){ f(); } );
    arrayBeginRequest = new Array();
    // Realizar consulta de precios al finalizar cada actualizacion de pagina
    cargarPreciosWS();
}
function addOnloadEvent(fnc){
  if ( typeof window.addEventListener != "undefined" )
    window.addEventListener( "load", fnc, false );
  else if ( typeof window.attachEvent != "undefined" ) {
    window.attachEvent( "onload", fnc );
  }
  else {
    if ( window.onload != null ) {
      var oldOnload = window.onload;
      window.onload = function ( e ) {
        oldOnload( e );
        window[fnc]();
      };
    }
    else
      window.onload = fnc;
  }
}
function load()
{
    Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(BeginRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
    arrayPageLoad.each( function(f){ f(); } );
    arrayPageLoad = new Array();
    ajustarAlturaMenuIzquierdo();    
}
function BeginRequestHandler(sender, args)
{
    arrayBeginRequest.each( function(f){ f(); } );
    arrayBeginRequest = new Array();
    try { if(panelLoading != null) panelLoading.show(); } catch(e) { }
}
function EndRequestHandler(sender, args)
{    
    responseError = args.get_error();
    if (responseError && responseError.name == "Sys.WebForms.PageRequestManagerTimeoutException")
        location.href = MundialPath + "HomeB2b.aspx";
    if (responseError && responseError.name == "Sys.WebForms.PageRequestManagerServerErrorException")
        args.set_errorHandled(true);
    try
    {
        if(panelLoading != null) 
        {
            panelLoading.hide();
            document.getElementById('panelLoading_c').style.top = '0px';
            //document.getElementById('panelLoading_mask').style.height='1px'
        }
    }
    catch(e) { }
    arrayEndRequest.each( function(f){ f(); } );
    arrayEndRequest = new Array();
    ajustarAlturaMenuIzquierdo();
    
    // Realizar consulta de precios al finalizar cada actualizacion de pagina
    cargarPreciosWS();    
}
function pageLoaded(sender, args)
{
    arrayPageLoad.each( function(f){ f(); } );
    arrayPageLoad = new Array();
}
function registerEndRequest(f)
{
    arrayEndRequest[arrayEndRequest.length] = f;
}
function registerBeginRequest(f)
{
    arrayBeginRequest[arrayBeginRequest.length] = f;
}
function registerPageLoaded(f)
{
    arrayPageLoad.push(f);
}
function ajustarAlturaMenuIzquierdo()
{
    if($("menu_izquierdo"))
    {
        $("menu_izquierdo").style.height = ""
        if ($("rightcolumn") && $("menu_izquierdo").scrollHeight < $("rightcolumn").scrollHeight)
        {
            $("menu_izquierdo").style.height = ($("rightcolumn").scrollHeight - correccionAlturaMenuIzq) + "px";
            if($("menu_izquierdo_banner") != null)
                $("menu_izquierdo_banner").style.top = ($("menu_izquierdo").clientHeight - $("menu_izquierdo_banner").clientHeight - $("identificador").clientHeight - $("categorias_relacionadas").clientHeight - 10) + "px";
        }
    }
}

function getIFrameDocument(aID){ 
var rv = null; 

// if contentDocument exists, W3C compliant (Mozilla) 
if (document.getElementById(aID).contentDocument){ 
rv = document.getElementById(aID).contentDocument; 
} else { 
// IE 
rv = document.frames[aID].document; 
} 

return rv; 
} 

// Esta funcion solicita el precio para el producto 'codigoProducto' y lo escribe en el panel 'paenlId'. Si el precio no existe,
// sera cargado al momento de recuperar los precios (cargarPrecios)
function mostrarPrecioCatalogo(panelId, codigoProducto, codigoCliente, ofertaWS)
{
    var productoExiste = false;
    for(var i=0; i<preciosProductos.codigoProducto.length; i++)
    {
        if(preciosProductos.codigoProducto[i] == codigoProducto)
        {
            if(preciosProductos.panelId[i] == null || preciosProductos.panelId[i] == panelId)
            {
                productoExiste = true;
                preciosProductos.panelId[i] = panelId;
                if(preciosProductos.precio[i] != null && panelId != null)
                    if(preciosProductos.ofertaWS[i])
                        document.getElementById(panelId).innerHTML = "<span class='precio_tachado'><span class='precio'>" + preciosProductos.precio[i] + "</span></span>";
                    else
                        document.getElementById(panelId).innerHTML = "<span class='precio'>" + preciosProductos.precio[i] + "</span>";

            }
        }
    }
    if(!productoExiste)
    {
        preciosProductos.codigoProducto.push(codigoProducto);
        preciosProductos.panelId.push(panelId);
        preciosProductos.precio.push(null);
        preciosProductos.ofertaWS.push(ofertaWS == null ? false : ofertaWS);
    }
    preciosProductos.codigoCliente=codigoCliente;
}

// Funcion que consulta los precios de los productos registrados en el objeto 'preciosProductos'. Solo se invoca una vez al cargar la
// pagina (body.onload). Debe ser invocada por el control o pagina que contiene a todos los productos (p.e.:CatalogoProductosGrid, etc)
function cargarPreciosWS()
{
    if(!clienteActivo)
        return;
    var faltanPrecios = false;
    for(var i=0;i<preciosProductos.precio.length;i++)
    {
        if(preciosProductos.precio[i]==null)
            faltanPrecios=true;
    }
    if(!faltanPrecios)  return;
    var parametros = preciosProductos.codigoCliente + "@" + preciosProductos.codigoProducto.toString();
    cargarPreciosWS_Complete = function(args)
    {
        // Guardar precios en preciosProductos
        var preciosFormateados = args.split(',');
        for(var i=0; i<preciosFormateados.length; i++)
        {
            preciosProductos.precio[i] = preciosFormateados[i];
            if(preciosProductos.panelId[i] != null && document.getElementById(preciosProductos.panelId[i])!=null)
            {
                if(preciosProductos.ofertaWS[i])
                    document.getElementById(preciosProductos.panelId[i]).innerHTML = "<span class='precio_tachado' style='font-size:20px;'><span class='precio'>" + preciosProductos.precio[i] + "</span></span>";
                else
                    document.getElementById(preciosProductos.panelId[i]).innerHTML = "<span class='precio' style='font-size:20px;'>" + preciosProductos.precio[i] + "</span>";
            }
        }
    }
    Mundial.ScriptServices.GetPreciosProductos(parametros, cargarPreciosWS_Complete, function(args) { }, function(args) { });
}

function actualizarBotonAgregar(idbtn, idtxt)
{
    if(document.getElementById(idbtn) != null && document.getElementById(idtxt) != null)
        document.getElementById(idbtn).className = (document.getElementById(idtxt).value.replace(/^\\s+|\\s+$/g,'').length == 0) ? 'button' : 'button_enabled';
}

// 48 - 57 Números
// 8 Backspace
// 37 Flecha Izquierda
// 39 Flecha Derecha
// 46 Delete
// 13 Enter
// 96 - 105 Números desde Panel Numérico
function btnCantidad_KeyDown(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);
    if(ev.which != undefined) 
        aux = !(codes.indexOf(ev.which) < 0);
    if(ev.keyCode != undefined) 
        aux = !(codes.indexOf(ev.keyCode) < 0);
        
    if (ev.shiftKey || ev.altKey || ev.ctrlKey) 
        return false;

    return aux;        
}

// Agregada por Diego Eusse
// 48 - 57 Números
// 8 Backspace
// 37 Flecha Izquierda
// 39 Flecha Derecha
// 46 Delete
// 13 Enter
// 65 - 90 Letras
// 96 - 105 Números desde Panel Numérico
// 110 Punto desde Panel Numérico
// 190 Punto
// 9 - TAB
function IsAlphaNumeric(ev) 
{
   if(ev.which || ev.keyCode)
    {
        if ((ev.which == 13) || (ev.keyCode == 13)) {return false;}
    } else {return true};
    var codes = new Array(9,45,48,49,50,51,52,53,54,55,56,57,8,37,39,46,13,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,96,97,98,99,100,101,102,103,104,105,109);
    if(ev.which != undefined) 
        aux = !(codes.indexOf(ev.which) < 0);
    if(ev.keyCode != undefined) 
        aux = !(codes.indexOf(ev.keyCode) < 0);
        
    if (ev.shiftKey || ev.altKey || ev.ctrlKey) 
        return false;
        
    return aux;
}


// 48 - 57 Números
// 8 Backspace
// 37 Flecha Izquierda
// 39 Flecha Derecha
// 46 Delete
// 13 Enter
// 65 - 90 Letras
// 96 - 105 Números desde Panel Numérico
// 110 Punto desde Panel Numérico
// 190 Punto
// 9 - TAB
function IsAlphaNumericCarro(ev) 
{
   if(ev.which || ev.keyCode)
    {
        if ((ev.which == 13) || (ev.keyCode == 13)) {return false;}
    } else {return true};
    var codes = new Array(9,32,48,49,50,51,52,53,54,55,56,57,8,37,39,46,13,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,96,97,98,99,100,101,102,103,104,105);
    if(ev.which != undefined) 
        aux = !(codes.indexOf(ev.which) < 0);
    if(ev.keyCode != undefined) 
        aux = !(codes.indexOf(ev.keyCode) < 0);
        
    if (ev.shiftKey || ev.altKey || ev.ctrlKey) 
        return false;
        
    return aux;
}

// Agregada por Diego Eusse
// 48 - 57 Números
// 8 Backspace
// 37 Flecha Izquierda
// 39 Flecha Derecha
// 46 Delete
// 13 Enter
// 96 - 105 Números desde Panel Numérico
// 110 Punto desde Panel Numérico
// 190 Punto
// 9 - TAB
// 109 - Resta
function btnDescuento_KeyDown(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,110,190,109);
    if(ev.which != undefined) 
        aux = !(codes.indexOf(ev.which) < 0);
    if(ev.keyCode != undefined) 
        aux = !(codes.indexOf(ev.keyCode) < 0);

    if (ev.shiftKey || ev.altKey || ev.ctrlKey) 
        return false;

    return aux;
 
}

// Agregada por Diego Eusse
function btnDescuento_OnFocus(ob)
{
    oDcto = document.getElementById(ob);
    if(parseFloat(oDcto.value) == 0)
        oDcto.value = "";
}

function btnDescuento_OnBlur(e)
{
    if(e.value=="")
        e.value="00.00";
    return false;
}

var timerDescuento = null, primeraEjecucionTimerDescuento = false;
var postbackActualizarNoAplicado = '';
function actualizar(objetoDescuento, objetoPrecio, objetoPrecio2, precio, valorMaximo, label1, label2, idProducto, codcliente, codMundial, ddMotivo, postback)
{
    postbackActualizarNoAplicado = postback;
    if(timerDescuento != null)
        clearTimeout(timerDescuento);
    if(!primeraEjecucionTimerDescuento)
        timerDescuento = setTimeout(function() {actualizarDescuento(objetoDescuento, objetoPrecio, objetoPrecio2, precio, valorMaximo, label1, label2, idProducto, codcliente, codMundial, ddMotivo)}, 500);
    primeraEjecucionTimerDescuento = false;
}

function actualizarDescuento(objetoDescuento, objetoPrecio, objetoPrecio2, precio, valorMaximo, label1, label2, idProducto, codcliente, codMundial, ddMotivo)
{
    oDcto = document.getElementById(objetoDescuento);
    var dctoLabel = (oDcto.value.replace(/^\\s+|\\s+$/g,''));
    var dcto = isNaN(parseFloat(dctoLabel)) ? 0 : parseFloat(dctoLabel);
    
    continuar = function(args){
        valorMaximo = parseFloat(args);
        if(dcto > 100)
        {
            dcto = 100;
            oDcto.value = 100;
        }
        
        if(dcto > valorMaximo)
        {
            $(label1).style.display = 'block'; 
            $(label2).style.display = 'block'; 
        }
        else
        {        
            $(label1).style.display = 'none'; 
            $(label2).style.display = 'none'; 
        }
        
        if(objetoPrecio == '' && precio == '')
        {
            for(var i=0; i<preciosProductosCarro.codigoProducto.length; i++)
            {
                if(preciosProductosCarro.IdSKU[i] == idProducto)
                {
                    precio = preciosProductosCarro.precio[i].split('@')[2];
                    objetoPrecio = preciosProductosCarro.IdLabelUnitario[i];
                }
            }
        }
        
        if(objetoPrecio != '' && precio != '')
        {
            if(document.getElementById(objetoPrecio) != null)
            {
                var precioLabel = document.getElementById(objetoPrecio);
                var aux = precioLabel.innerHTML;
                precio = precio.replace(',','.');
                precio = parseFloat(precio);
                if(!isNaN(precio) && !isNaN(dcto))
                {
                    var valorTotal = precio - (precio * (dcto / 100));
                    precioLabel.innerHTML = CurrencyFormatted(valorTotal);
                    if(objetoPrecio2 != '')
                        document.getElementById(objetoPrecio2).style.display=((precioLabel.innerHTML != document.getElementById(objetoPrecio2).innerHTML) ? 'inline' : 'none');
                }
            }
        }
    
     }
     Mundial.ScriptServices.ActualizarDescuento(idProducto, dcto, $(ddMotivo).value, function(args) { }, function(args) { }, function(args) { });
     Mundial.ScriptServices.GetDescuentoMaximo(codcliente + "@" + codMundial, continuar, function(args) { }, function(args) { });
//    eval(postbackActualizarNoAplicado);
//    valorMaximo = parseFloat(valorMaximo);
}

function actualizarPrecios( precio, label1, label2, codcliente, codMundial, cantidad)
{   
    valorcantidad = $(cantidad).value;
    continuar = function(args){
        
        preciocondescuento = parseFloat(args.split('@')[0]);
        descuento = parseFloat(args.split('@')[1]);        
        if(preciocondescuento != -1)
        {
            $(label1).style.display = 'block'; 
            $(label2).style.display = ''; 
            $(label1).innerHTML = CurrencyFormatted(preciocondescuento);
            if(isNaN(descuento))
                descuento = 0;
            $(label2).innerHTML = descuento.toString().replace(".",",") + " %";
        }  
     }

     Mundial.ScriptServices.GetDescuentoxVolumen(codcliente + "@" + codMundial + "@" + precio + "@" + valorcantidad, continuar, function(args) { }, function(args) { });
}

function actualizarPreciosAcompanamiento( precio, lblPrecioDescuento, lblDescuento, codcliente, codMundial, cantidad)
{
    valorcantidad = $(cantidad).value;
    continuar = function(args){
        
        preciocondescuento = parseFloat(args.split('@')[0]);
        descuento = parseFloat(args.split('@')[1]);        
        if(preciocondescuento != -1)
        {
            $(lblPrecioDescuento).style.display = 'block'; 
            $(lblDescuento).style.display = ''; 
            $(lblPrecioDescuento).innerHTML = CurrencyFormatted(preciocondescuento);
            if(isNaN(descuento))
                descuento = 0;
            $(lblDescuento).value = descuento.toString();
        }  
     }
     Mundial.ScriptServices.GetDescuentoxVolumen(codcliente + "@" + codMundial + "@" + precio + "@" + valorcantidad, continuar, function(args) { }, function(args) { });
}


function CurrencyFormatted(num)
{
    num = num.toString().replace(/\$|\,/g,'');
    if(isNaN(num))
    num = "0";
    sign = (num == (num = Math.abs(num)));
    num = Math.floor(num*100+0.50000000001);
    centsA = num%100;
    num = Math.floor(num/100).toString();
    if(centsA<10)
    centsA = "0" + centsA;
    for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
    num = num.substring(0,num.length-(4*i+3))+'.'+
    num.substring(num.length-(4*i+3));
    return (((sign)?'':'-') + '$ ' + num + ',' + centsA);
}   


function getMouseCoords(e)
{
    var ev=(!e)?window.event:e;//Moz:IE
    if (ev.pageX){posx=ev.pageX;posy=ev.pageY}//Mozilla or compatible
    else if(ev.clientX){posx=ev.clientX;posy=ev.clientY}//IE or compatible
    else{return false}//old browsers
    
    var mouse = {x:posx, y:posy};
    return mouse;
}

function ScrollPanel(divPaneles, totalPaneles, imgDown, imgUp, imgPath)
{
    this.velocidad = 2;                // Tamaño del paso del movimiento
    this.divPaneles = divPaneles;       // Nombre del div que contiene los div's de combos
    this.totalPaneles = totalPaneles;   // Cantidad de combos (no se usa)
    this.imgDown = imgDown;             // ID de la imagen de bajada del scroll
    this.imgUp = imgUp;                 // ID de la imagen de subida del scroll
    this.imgPath = imgPath;             // Ruta de las imagenes del scroll
    this.top = 0;                       // Top del divPaneles
    this.topAnterior = 0;               // Valor del top justo antes de iniciar el movimiento
    this.Activo = false;                // true si el panel esta en movimiento
    this.panelActual = 1;               // Panel (producto) visible en el momento. Varia entre 1 y totalPaneles
    // Este metodo actualiza el top del divPaneles a partir del atributo top        
    this.actualizarTop = function()
    {
        document.getElementById(this.divPaneles).style.top = this.top + "px";
    }
    
    this.actualizarFlechas = function()
    {
        $(this.imgUp).src = this.imgPath + ((this.panelActual == 1) ? 'carrusel_combos_up_arrow.jpg' :  'carrusel_combos_up_arrow_enabled.jpg');
        $(this.imgDown).src = this.imgPath + ((this.panelActual == this.totalPaneles) ? 'carrusel_combos_down_arrow.jpg' :  'carrusel_combos_down_arrow_enabled.jpg');
    }
    this.actualizarFlechas();
    
    // Metodo ejecutado por el link o boton para subir el panel
    this.upClick = function()
    {
        if(this.Activo)
            return;
        this.Activo = true;
        this.up();
    }   
    
    // Metodo ejecutado por el link o boton para bajar el panel
    this.downClick = function()
    {
        if(this.Activo)
            return;
        this.Activo = true;
        this.down();
    }

    // Este metodo desplaza hacia arriba el listado de combos. Al llegar al final, no permite subir mas
    this.up = function()
    {
        // Si llego al final del listado, finalizar
        if(Math.abs(this.top - document.getElementById(this.divPaneles).parentNode.clientHeight) >= document.getElementById(this.divPaneles).clientHeight)
        {
            this.Activo = false;
            return;
        }
        // Calcular la nueva posicion del top
        this.top -= (this.top - this.velocidad) >= (this.topAnterior - document.getElementById(this.divPaneles).parentNode.clientHeight) ? this.velocidad : 0;
        this.actualizarTop();
        thisObj = this;
        if((this.top - this.velocidad) >= (this.topAnterior - document.getElementById(this.divPaneles).parentNode.clientHeight))
            setTimeout(function() { thisObj.up() } , 20);  // WTF?!? .. Volver a llamar up() al pasar 100ms (no pregunte)
        else
        {
            this.top = this.topAnterior - document.getElementById(this.divPaneles).parentNode.clientHeight; // Corregir top
            this.actualizarTop();                           // Aplicar cambio del top al panel divPaneles
            this.topAnterior = this.top;
            this.Activo = false;
            this.panelActual++;
            this.actualizarFlechas();
        }
    }
    
    this.down = function()
    {
        if(this.top >= 0)
        {
            this.Activo = false;
            return;
        }
        this.top += (this.top + this.velocidad) <= (this.topAnterior + document.getElementById(this.divPaneles).parentNode.clientHeight) ? this.velocidad : 0;
        this.actualizarTop();
        thisObj = this;
        if((this.top + this.velocidad) <= (this.topAnterior + document.getElementById(this.divPaneles).parentNode.clientHeight))
            setTimeout(function() { thisObj.down() } , 20);
        else
        {
            this.top = this.topAnterior + document.getElementById(this.divPaneles).parentNode.clientHeight; // Corregir top
            this.actualizarTop();                           // Aplicar cambio del top al panel divPaneles
            this.topAnterior = this.top;
            this.Activo = false;
            this.panelActual--;
            this.actualizarFlechas();
        }
    }
}

var carruseles = new Array();

function Carrusel(GUID, divItems, divItemsBuffer, divLoading, ancho, anchoItem, tooltipWidth, itemPorPagina, URL, Path, carruselLoading, carruselPublicaciones, tipo, carruselNovedadesHomes, anchoImagen, altoImagen)
{
    this.GUID = GUID;
    this.divItems = divItems;
    this.divItemsBuffer = divItemsBuffer;
    this.divLoading = divLoading;
    this.ancho = ancho;
    this.anchoItem = anchoItem;
    this.tooltipWidth = tooltipWidth;
    this.itemPorPagina = itemPorPagina;
    this.URL = URL;
    this.Path = Path;
    this.carruselLoading = carruselLoading;
    this.ultimoItem = 0;
    this.buffer = "";
    this.AnchoImagen = anchoImagen;
    this.AltoImagen = altoImagen;
    if (carruselNovedadesHomes)
        this.wsActualizar = Mundial.ScriptServices.ActualizarCarruselPublicacionesHome; 
    else
        this.wsActualizar = (carruselPublicaciones ? Mundial.ScriptServices.ActualizarCarruselPublicaciones : Mundial.ScriptServices.ActualizarCarrusel);
    //this.wsActualizar = Mundial.ScriptServices.ActualizarCarruselPublicacionesHome; 
    this.tipo = tipo;
    this.swap = function()
    {
        $get(this.divItemsBuffer).innerHTML=this.buffer;
        $get(this.divItemsBuffer).style.display='block';
        new Effect.Fade(this.divItems, {from:1.0,to:0.0,duration:0.5});
        setTimeout("$get('" + this.divItems + "').innerHTML=$get('" + this.divItemsBuffer + "').innerHTML;$get('" + this.divItems + "').style.display='block';", 600);
    }
    
    this.onComplete = function(args)
    {
        try
        {
            var params = args.split('@');
            var aux = eval('carrusel' + params[0].replace(/-/g,'_'));
            aux.buffer = params[1];
            aux.swap();
            $get(aux.carruselLoading).style.display = 'none';
        }
        catch(e) { }
    }
    
    this.actualizar = function()
    {
        if($(this.divItems) == null)
            return;
        var parametros = this.GUID + ',' + this.tooltipWidth + ',' + this.itemPorPagina + ',' + this.ultimoItem + ',' + this.URL + ',' + this.Path + ',' + this.AnchoImagen + ',' + this.AltoImagen;
        var onComplete = this.onComplete;
        this.wsActualizar(parametros, onComplete, function(args){}, function(args){});
    }
    
    this.iniciar = function()
    {
        this.ultimoItem = 0;
        this.actualizar();
    }
    
    this.siguiente = function()
    {
        $get(this.carruselLoading).style.display = 'block';
        this.ultimoItem += this.itemPorPagina;
        this.actualizar();
    }
    
    this.anterior = function()
    {
        $get(this.carruselLoading).style.display = 'block';
        this.ultimoItem -= this.itemPorPagina;
        this.actualizar();
    }

    this.actualizarDataSource = function(idSKU)
    {
        var aux = this;
        Mundial.ScriptServices.CarruselActualizarDataSource(this.tipo, idSKU, this.GUID, function(args) { aux.iniciar(); }, function(args) { }, function(args) { });
    }
}

function getUrlParam(name)
{
    name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
    var regexS = "[\\?&]"+name+"=([^&#]*)";
    var regex = new RegExp( regexS );
    var results = regex.exec( window.location.href );
    return (results == null) ? "" : results[1];
}

//*************************************************************************************************

/* Inicio - Funciones del control de busqueda */
var Buscador = {};
Buscador.MarcasCargadas = false;

//*************************************************************************************************

Buscador.Init = function()
{
    if (document.getElementsByTagName) {
        var inputElements = document.getElementsByTagName("input");
        for (i=0; inputElements[i]; i++) {
            if (inputElements[i].className && (inputElements[i].className.indexOf("disableAutoComplete") != -1)) {
                inputElements[i].setAttribute("autocomplete","off");
            }
        }
    }
    new Tooltip($('btnBusquedaBasica'), {mouseFollow: true, backgroundColor: '#F5F5F5', borderColor: '#D7D4D4', textColor: '#4A4E60', textShadowColor: '#F5F5F5', delay: 500, opacity: 0.9});
    new Tooltip($('txtBusquedaAvanzada'), {mouseFollow: true, backgroundColor: '#F5F5F5', borderColor: '#D7D4D4', textColor: '#4A4E60', textShadowColor: '#F5F5F5', delay: 500, opacity: 0.9});
    new Tooltip($('btnBusquedaAvanzada'), {mouseFollow: true, backgroundColor: '#F5F5F5', borderColor: '#D7D4D4', textColor: '#4A4E60', textShadowColor: '#F5F5F5', delay: 500, opacity: 0.9});
    // Registrar listener para buscar al presionar enter sobre el textbox
    var klBusquedaBasica = new YAHOO.util.KeyListener('txtBusquedaBasica',  { keys : YAHOO.util.KeyListener.KEY.ENTER }, Buscador.BusquedaBasica);
    var klBusquedaAvanzada = new YAHOO.util.KeyListener('txtBusquedaAvanzada',  { keys : YAHOO.util.KeyListener.KEY.ENTER }, Buscador.BusquedaAvanzada);
    klBusquedaBasica.enable();
    klBusquedaAvanzada.enable();
    // Inicializar datasource del autocomplete
    var dsBusquedaAutocompletar = new YAHOO.util.XHRDataSource("/MundialB2B/ScriptServices.asmx/BusquedaBasicaAutocompletar");
    dsBusquedaAutocompletar.connMethodPost = true;
    dsBusquedaAutocompletar.responseType = YAHOO.util.XHRDataSource.TYPE_JSON;
    dsBusquedaAutocompletar.responseSchema = { resultsList : "productos", fields : ["nombre"] };
    // Inicializar autocomplete basica
    var autocompleteBasica = new YAHOO.widget.AutoComplete("txtBusquedaBasica", "txtBusquedaBasicaContainer", dsBusquedaAutocompletar, 
    { 
        maxResultsDisplayed:10,
        allowBrowserAutocomplete:false,
        animVert:false,
        animSpeed:0.0,
        autoHighlight:false,
        queryDelay:0.0,
        useShadow:false,
        prehighlightClassName:'yui-ac-prehighlight',
        resultTypeList:false
    });
    autocompleteBasica.generateRequest = function(cadena) { return "cadena=" + cadena; };
    // Inicializar autocomplete avanzada
    // Inicializar autocomplete basica
    var autocompleteAvanzada = new YAHOO.widget.AutoComplete("txtBusquedaAvanzada", "txtBusquedaAvanzadaContainer", dsBusquedaAutocompletar, 
    { 
        maxResultsDisplayed:10,
        allowBrowserAutocomplete:false,
        animVert:false,
        animSpeed:0.0,
        autoHighlight:false,
        queryDelay:0.0,
        useShadow:false,
        prehighlightClassName:'yui-ac-prehighlight',
        resultTypeList:false
    });
    autocompleteAvanzada.generateRequest = function(cadena) { return "cadena=" + cadena; };
}

//*************************************************************************************************

Buscador.BusquedaBasica = function(type, args)
{
    var cadena = $('txtBusquedaBasica').value.replace(/^\\s+|\\s+$/g,'');
    if(cadena.length == 0)
    {
        ModalDialog.Show("Error", "Se requiere al menos parte de una la palabra, descripci&oacute;n del art&iacute;culo o TAG, o la referencia (SKU) de un producto", ModalDialog.OK);
        return;
    }
    if(args != null)
    {
        YAHOO.util.Event.preventDefault(args[1]);
        YAHOO.util.Event.stopPropagation(args[1]);
    }
    var BusquedaBasica_OnSuccess = function(idMarca)
    {
        if(idMarca > 0)
            location.href = MundialPath + 'HomeMarca.aspx?mnd1=' + idMarca + '&mndb1=' + encodeBase64(cadena);
        else
            location.href = MundialPath + 'resultadosBusqueda.aspx?mnd1=0&mnd2=' + encodeBase64(cadena);
    }
    Mundial.ScriptServices.BusquedaAvanzadaGetMarcaByNombre(cadena, BusquedaBasica_OnSuccess, function() { }, function() { });
}

//*************************************************************************************************

Buscador.BusquedaAvanzada = function(type, args)
{
    var cadena = $('txtBusquedaAvanzada').value.replace(/^\\s+|\\s+$/g,'');
    if((cadena.length == 0 || (cadena.length > 0 &&
        $('rbBusquedaAvanzadaDescripcion').checked == false && 
        $('rbBusquedaAvanzadaReferencia').checked == false && 
        $('rbBusquedaAvanzadaCodigo').checked == false)) && 
        $('chkBusquedaOfertas').checked == false && 
        $('chkBusquedaProductosNuevos').checked == false && 
        $('chkBusquedaCombos').checked == false && 
        $('busquedaMarca').selectedIndex == 0)
    {
        ModalDialog.Show("Error", "Debe ingresar algún criterio de búsqueda", ModalDialog.OK);
        return;
    }
    if(cadena.length > 0 &&
       $('rbBusquedaAvanzadaDescripcion').checked == false && 
       $('rbBusquedaAvanzadaReferencia').checked == false && 
       $('rbBusquedaAvanzadaCodigo').checked == false)
    {
        ModalDialog.Show("Error", "Debe seleccionar al menos un filtro: Descripción, Referencia, Código", ModalDialog.OK);
        return;
    }

    if(args != null)
    {
        YAHOO.util.Event.preventDefault(args[1]);
        YAHOO.util.Event.stopPropagation(args[1]);
    }
    var BusquedaAvanzada_OnSuccess = function(idMarca)
    {
        var parametros = 0;
        parametros += $('rbBusquedaAvanzadaDescripcion').checked ? 1 : 0;
        parametros += $('rbBusquedaAvanzadaReferencia').checked ? 2 : 0;
        parametros += $('rbBusquedaAvanzadaCodigo').checked ? 4 : 0;
        parametros += $('chkBusquedaOfertas').checked ? 8 : 0;
        parametros += $('chkBusquedaProductosNuevos').checked ? 16 : 0;
        parametros += $('chkBusquedaCombos').checked ? 32 : 0;
        if(idMarca > 0)
            location.href = MundialPath + 'HomeMarca.aspx?mnd1=' + idMarca + '&mndb2=' + parametros;
        else
        {
            if($('busquedaMarca').selectedIndex > 0)
            {
                idMarca = parseInt($('busquedaMarca')[$('busquedaMarca').selectedIndex].value);
                location.href = MundialPath + 'HomeMarca.aspx?mnd1=' + idMarca + '&mndb1=' + encodeBase64(cadena) + '&mndb2=' + parametros;
            }
            else
                location.href = MundialPath + 'resultadosBusqueda.aspx?mnd1=1&mnd2=' + encodeBase64(cadena) + '&mnd3=' + parametros + '&mnd4=' + idMarca;
        }
    }
    Mundial.ScriptServices.BusquedaAvanzadaGetMarcaByNombre(cadena, BusquedaAvanzada_OnSuccess, function() { }, function() { });
}

//*************************************************************************************************

Buscador.MostrarBusquedaAvanzada = function()
{
    Effect.Appear('busqueda_avanzada', { duration: 0.3 });
    var BusquedaAvanzadaMarcas_OnSuccess = function(args)
    {
        var respuesta = eval('(' + args + ')');
        if(!respuesta.resultado)
        {
            ModalDialog.Show("Error", respuesta.mensajeError, ModalDialog.OK);
            return;
        }
        $('busquedaMarca').remove(0);
        for(var i=0; i < respuesta.marcas.length; i++)
            $('busquedaMarca')[i] = new Option(respuesta.marcas[i].nombre, respuesta.marcas[i].id);
        $('busquedaMarca').disabled = false;
        Buscador.MarcasCargadas = true;
    }
    if(!Buscador.MarcasCargadas)
        Mundial.ScriptServices.BusquedaAvanzadaMarcas(BusquedaAvanzadaMarcas_OnSuccess, function(args) { }, function(args) { });
}

//*************************************************************************************************

Buscador.CerrarBusquedaAvanzada = function()
{
    Effect.Fade('busqueda_avanzada', { duration: 0.3 });
    setTimeout("(function(){document.getElementById('busqueda_avanzada').style.top='0px';document.getElementById('busqueda_avanzada').style.left='0px';})()", 400);
}

//*************************************************************************************************

Buscador.Limpiar = function()
{
    $('txtBusquedaBasica').value = '';
    $('txtBusquedaAvanzada').value = '';
    $('rbBusquedaAvanzadaDescripcion').checked = false;
    $('rbBusquedaAvanzadaReferencia').checked = false;
    $('rbBusquedaAvanzadaCodigo').checked = false;
    $('chkBusquedaOfertas').checked = false;
    $('chkBusquedaProductosNuevos').checked = false;
    $('chkBusquedaCombos').checked = false;
    $('busquedaMarca')[0].selected = true;
}
/* Fin - Funciones del control de busqueda */
//*************************************************************************************************

/* Inicio - Funciones del toolbox */
var ToolBox = {};

ToolBox.Formulario = null;
ToolBox.FormularioError = true;

//*************************************************************************************************

ToolBox.Ayuda = function()
{
    window.open('http://www.mundial.com.co/web/Default.aspx?tabid=77',null,'height=600,width=800,toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=yes');
}

//*************************************************************************************************

ToolBox.ReportarError = function()
{
    // Titulo y descripcion
    $('toolboxFormulario').style.display='';
    $('toolboxFormularioTitulo').innerHTML = 'Reportar un error';
    $('toolboxFormularioDescripcion').innerHTML = 'Para Mundial las observaciones sobre su contenido son importantes, perm&iacute;tanos conocerlas para, si es el caso, tomar los correctivos necesarios, o darle trámite ante las instancias pertinentes dentro de Mundial<br />Por favor, incluya su nombre y correo electr&oacute;nico para informarle del seguimiento que le hemos dado a su observaci&oacute;n.';
    // Ocultar campos de amigo
    $('toolboxFormularioNombreAmigo').style.display='none';
    $('toolboxFormularioEmailAmigo').style.display='none';
    // Cambiar boton
    $('toolboxFormularioEnviar').src = 'images/botones/bt_reportar.png';
    // Tipo de formulario
    ToolBox.FormularioError = true;
    // Mostrar
    ToolBox.Formulario.show();
    $('toolboxFormulario_mask').style.zIndex='1000';
}

//*************************************************************************************************

ToolBox.RecomendarAmigo = function()
{
    // Titulo y descripcion
    $('toolboxFormulario').style.display='';
    $('toolboxFormularioTitulo').innerHTML = 'Recomendar a un amigo';
    $('toolboxFormularioDescripcion').innerHTML = 'Para recomendar el sitio Web de Mundial, ingrese la siguiente informaci&oacute;n';
    // Ocultar campos de amigo
    $('toolboxFormularioNombreAmigo').style.display='';
    $('toolboxFormularioEmailAmigo').style.display='';
    // Cambiar boton
    $('toolboxFormularioEnviar').src = 'http://images2.mundial.com.co/MundialB2B/images/botones/bt_recomendar.png';
    // Tipo de formulario
    ToolBox.FormularioError = false;
    // Mostrar
    ToolBox.Formulario.show();
    $('toolboxFormulario_mask').style.zIndex='1000';
}

//*************************************************************************************************

ToolBox.AgregarFavoritos = function()
{
    if (window.sidebar)
    { // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title, location.href,"");
    } else if( window.external ) 
    { // IE Favorite
           window.external.AddFavorite( location.href, document.title); 
    }
    else if(window.opera && window.print) 
    { // Opera Hotlist
           return true; 
    }
}

//*************************************************************************************************

ToolBox.EnviarFormulario = function()
{
    var nombre = $('toolboxNombre').value.replace(/^\\s+|\\s+$/g,'');
    var email = $('toolboxEmail').value.replace(/^\\s+|\\s+$/g,'');
    var nombreAmigo = $('toolboxNombreAmigo').value.replace(/^\\s+|\\s+$/g,'');
    var emailAmigo = $('toolboxEmailAmigo').value.replace(/^\\s+|\\s+$/g,'');
    var comentario = $('toolboxComentario').value.replace(/^\\s+|\\s+$/g,'');
    var emailRegex = new RegExp(/^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+[a-zA-Z0-9]{2,4}$/);
    var ltrURL = location.href;
    
     
    if(ToolBox.FormularioError)
    {
        // Validar campos
       
            $('spanNombre').style.display = ((nombre == '') ? "" : "none");              
            $('spanEmail').style.display = ((email == '') ? "" : "none");
            $('spanEmail').innerHTML = ((email == '') ? " Ingrese correo " : "");            
            if(email != '')
            {                
                $('spanEmail').style.display = ((!emailRegex.test(email)) ? "" : "none");
                $('spanEmail').innerHTML = ((!emailRegex.test(email)) ? " Correo inválido " : "");
            }                
            $('spanComentario').style.display = ((comentario == '') ? "" : "none");
       
             
        if(nombre == '' || email == '' || comentario == '' || !emailRegex.test(email))
            return;
            
        // Enviar reporte de error
        var ReportarError_OnSuccess = function(args)
        {
            var respuesta = eval('(' + args + ')');
            if(!respuesta.resultado)
            {
                ModalDialog.Show('Error', respuesta.mensajeError, ModalDialog.OK);
                return;
            }
            ToolBox.Cancelar();
        }
        Mundial.ScriptServices.ToolBoxReportarError(nombre, email, comentario, ltrURL, ReportarError_OnSuccess, function(args) { }, function(args) { });
    }
    else
    {
        // Validar campos        
        
            $('spanNombre').style.display = ((nombre == '') ? "" : "none");                  
            $('spanEmail').style.display = ((email == '') ? "" : "none");
            $('spanEmail').innerHTML = ((email == '') ? " Ingrese correo " : "");         
            $('spanNombreAmigo').style.display = ((nombreAmigo == '') ? "" : "none");           
            $('spanEmailAmigo').style.display = ((emailAmigo == '') ? "" : "none");
            $('spanEmailAmigo').innerHTML = ((emailAmigo == '') ? " Ingrese correo amigo " : "");               
            if(email != '')
            {                
                $('spanEmail').style.display = ((!emailRegex.test(email)) ? "" : "none");
                $('spanEmail').innerHTML = ((!emailRegex.test(email)) ? " Correo inválido " : "");
            }
         
            if(emailAmigo != '')
            {  
                $('spanEmailAmigo').style.display = ((!emailRegex.test(emailAmigo)) ? "" : "none");
                $('spanEmailAmigo').innerHTML = ((!emailRegex.test(emailAmigo)) ? " Correo inválido " : "");
            }
        
        if(nombre == '' || email == '' || nombreAmigo == '' || emailAmigo == '' || !emailRegex.test(email) || !emailRegex.test(emailAmigo))
            return;
        
        // Enviar recomendar amigo
        var RecomendarAmigo_OnSuccess = function(args)
        {
            var respuesta = eval('(' + args + ')');
            if(!respuesta.resultado)
            {
                ModalDialog.Show('Error', respuesta.mensajeError, ModalDialog.OK);
                return;
            }
            ToolBox.Cancelar();
        }
        Mundial.ScriptServices.ToolBoxRecomendarAmigo(nombre, email, nombreAmigo, emailAmigo, comentario, ltrURL, RecomendarAmigo_OnSuccess, function(args) { }, function(args) { });
    }
}

//*************************************************************************************************

ToolBox.Limpiar = function()
{
    $('toolboxNombre').value = '';
    $('toolboxEmail').value = '';
    $('toolboxNombreAmigo').value = '';
    $('toolboxEmailAmigo').value = '';
    $('toolboxComentario').value = '';
    
    $('spanNombre').style.display = "none";          
    $('spanEmail').style.display = "none";
    $('spanComentario').style.display = "none"; 
    if(!ToolBox.FormularioError)
    {
        $('spanNombreAmigo').style.display = "none";   
        $('spanEmailAmigo').style.display = "none";       
    }     
}

//*************************************************************************************************

ToolBox.Cancelar = function()
{
    ToolBox.Limpiar();
    ToolBox.Formulario.hide();
}


ToolBox.ValidarNombre = function()
{
     var nombre = $('toolboxNombre').value.replace(/^\\s+|\\s+$/g,'');
    $('spanNombre').style.display = ((nombre == '' && $('spanNombre').style.display=='') ? "" : "none");
}

ToolBox.ValidarEmail = function()
{
     var email = $('toolboxEmail').value.replace(/^\\s+|\\s+$/g,'');
      $('spanEmail').style.display = ((email == '' && $('spanEmail').style.display=='') ? "" : "none");
}

ToolBox.ValidarNombreAmigo = function()
{
     var nombreAmigo = $('toolboxNombreAmigo').value.replace(/^\\s+|\\s+$/g,'');
     $('spanNombreAmigo').style.display = ((nombreAmigo == ''&& $('spanNombreAmigo').style.display=='') ? "" : "none");
}

ToolBox.ValidarEmailAmigo = function()
{
     var emailAmigo = $('toolboxEmailAmigo').value.replace(/^\\s+|\\s+$/g,'');
     $('spanEmailAmigo').style.display = ((emailAmigo == ''&& $('spanEmailAmigo').style.display=='') ? "" : "none");
}

ToolBox.ValidarComentario = function()
{
     var comentario = $('toolboxComentario').value.replace(/^\\s+|\\s+$/g,'');
     $('spanComentario').style.display = ((comentario == ''&& $('spanComentario').style.display=='') ? "" : "none");
}

function zoomText(Accion,Elemento)
{
    //inicializacion de variables y parámetros 
    var obj=document.getElementById('wrapper');
    //alert(obj);
    var max = 200 //tamaño máximo del fontSize
    var min = 70 //tamaño mínimo del fontSize
    if (obj.style.fontSize=="")
    {
        obj.style.fontSize="100%";
    }
    actual=parseInt(obj.style.fontSize); //valor actual del tamaño del texto 
    incremento=10;// el valor del incremento o decremento en el tamaño 
        
    //accion sobre el texto 
    if( Accion=="reestablecer" )
    {
        obj.style.fontSize="100%"
    }
    if( Accion=="aumentar" && ((actual+incremento) <= max ))
    {
        valor=actual+incremento;
        //alert(valor);
        obj.style.fontSize=valor+"%"          
    }
    if( Accion=="disminuir" && ((actual+incremento) >= min ))
    {
        valor=actual-incremento;
        obj.style.fontSize=valor+"%"
    }
} 

function AgregaraFavoritos()
{
     if (window.sidebar) 
     {
        window.sidebar.addPanel("Mundial", "http://www.mundial.com.co",'');
     } 
     else if( window.external ) 
     {
        window.external.AddFavorite("http://www.mundial.com.co","Mundial");
     } 
     else if( window.opera && window.print ) 
     {
        return true;
     }     
}
    
function SystemPrintPreview(OLECMDID) 
{ 
//var OLECMDID = 10; 
/* OLECMDID values: 
* 6 - print 
* 7 - print preview 
* 8 - page setup (for printing) 
* 1 - open window 
* 4 - Save As 
* 10 - properties 
*/
    try
    {
        var PROMPT = 1; // 1 PROMPT & 2 DONT PROMPT USER 
        var oWebBrowser = document.getElementById("WebBrowser1");
        if(oWebBrowser == null)
        {
            var sWebBrowser = '<OBJECT ID="WebBrowser1" WIDTH=0 HEIGHT=0 CLASSID="CLSID:8856F961-340A-11D0-A96B-00C04FD705A2"></OBJECT>'; 
            document.body.insertAdjacentHTML('beforeEnd', sWebBrowser); 
            alert(document.getElementById("WebBrowser1"));
            oWebBrowser = document.getElementById("WebBrowser1");
        }
        oWebBrowser.ExecWB(OLECMDID,PROMPT);
    }
    catch(e){alert("Printing failed! " + e.message);}
} 
/* Fin - Funciones del toolbox */
//************************************************************************************************

function imprimir(img1, img2)
{
    var ventanaImprimir = window.open("print.htm", "ventanaImprimira", "toolbar=0,status=0,location=0,menubar=0,scrollbars=1,width=800,height=600");
    if(ventanaImprimir == null)
    {
        alert("Para imprimir, debe permitir el uso de ventanas emergentes para www.mundial.com.co");
        return;
    }
    ventanaImprimir.document.write("<html><body onload='window.print();window.close()'>");
    if(img1 != null)
        ventanaImprimir.document.write("<img src='" + img1 + "' border=0 />");
    if(img2 != null)
        ventanaImprimir.document.write("<br /><img src='" + img2 + "' border=0 />");
    ventanaImprimir.document.write("</body></html>");
    ventanaImprimir.document.close();
}

//************************************************************************************************

function cerrarSesion()
{
    cerrarSesion_Complete = function(args)
    {
        if(args)
            location.href = MundialPath + "HomeB2B.aspx";
    }
    Mundial.ScriptServices.CerrarSesion(cerrarSesion_Complete, function(args) { }, function(args) { });
}

//************************************************************************************************

function esIE6()
{
    var isIE6 = ((navigator.userAgent.indexOf("MSIE 6.") != -1) && (navigator.userAgent.indexOf("Opera") == -1));
    if (isIE6 == true)
    {
        var mensaje = 'Para visualizar correctamente el sitio www.mundial.com.co le sugerimos actualizar la versión de su navegador.';
        mensaje+= 'Haga click sobre el icono del navegador de su preferencia para descargar la ultima versión del mismo.';
        mensaje+= '<br><br><table border=0><tr><td><a href="http://www.google.com/chrome"> <img border=0 src="images/botones/compatible_chrome.gif" title="Google Chrome" /> </a></td>'; 
        mensaje+= '<td><a href="http://www.mozilla-europe.org/es/firefox/"> <img border=0 src="images/botones/compatible_firefox.gif" title="Mozilla Firefox" /> </a></td>'; 
        mensaje+= '<td><a href="http://www.apple.com/es/safari/download/"> <img border=0 src="images/botones/compatible_safari.gif" title="Safari" /> </a></td>'; 
        mensaje+= '<td><a href="http://www.opera.com/"> <img border=0 src="images/botones/compatible_opera.gif" title="Opera" /> </a></td>'; 
        mensaje+= '<td><a href="http://www.microsoft.com/latam/windows/internet-explorer/"> <img border=0 src="images/botones/compatible_ie.gif" title="Internet Explorer" /> </a></td>'; 
        mensaje+= '</tr></table>';
        ModalDialog.Show('Navegador desactualizado',mensaje,ModalDialog.OK); 
    }
} 

/**************************************************************************************************************/
/**************************************************************************************************************/
actualizarEstadoLoginTop = function(estaAutenticado)
{
   if(estaAutenticado.toLowerCase() == 'true'){
     $('content_usuario_autenticado').style.display = 'block';
     $('content_usuario_autenticado').style.visibility = 'visible';
     $('content_usuario_no_autenticado').style.display = 'none';
     $('content_usuario_no_autenticado').style.visibility = 'hidden';
     
     datosUsuario_OnSuccess = function(args)
     {
        actualizarNombreUsuarioLoginTop(args[0], args[1]);
     }         
         
     Mundial.ScriptServices.obtenerDatosUsuario(datosUsuario_OnSuccess);    
   }
   else {
     $('content_usuario_autenticado').style.display = 'none';
     $('content_usuario_autenticado').style.visibility = 'hidden';
     $('content_usuario_no_autenticado').style.display = 'block';
     $('content_usuario_no_autenticado').style.visibility = 'visible';
   }
}
