﻿function llamarPagina(nombre) {
    limpiarPagina();
    var x=$("#Centro");
    var pagina;
//    if (elIdCirculo != 0)
//        elCirculo.remove();
    if (pagActual != nombre) {
        x.html('');
        $(".divPagina").css('visibility', 'hidden');
        if (nombre != 'principal') {
            pararAnimacion();
        }
        switch (nombre) {
            case "principal":
                elCentro('ocultar');
                posicionarMostrarPagina($("#nuestraPropuesta"));
                leerNovedades();
                auxFondoPaginas.attr({y: arrayBordeNovedades[0].getBBox().y});
                break;
            case "default.aspx":
                elCentro('mostrar');
                laPagina = 1;
                filtroGral = "0";
                $('.file').css('background-color', 'Transparent'); // borra resaltado de elección Rubro
                iniciarCentro();
                break;
            case "quienesSomos":
                elCentro('ocultar');
                posicionarMostrarPagina($("#quienesSomos"));
                break;
            case "ingresarDatos":
                elCentro('ocultar');
                posicionarMostrarPagina( $("#contDatos"));
                break;
            case "contactenos":
                elCentro('ocultar');
                posicionarMostrarPagina( $("#contactenos"));
                break;
            case "pagosEnvios":
                elCentro('ocultar');
                posicionarMostrarPagina($("#pagosEnvios"));
                break;
            case "ayuda":
                elCentro('ocultar');
                posicionarMostrarPagina($("#ayuda"));
                break;
            default:
                elCentro('ocultar');
                posicionarMostrarPagina( $("#quienesSomos"));
                break;
        }
        if (nombre != 'principal') 
                limpiarPagina();
    }
    return false;
}
function posicionarMostrarPagina(laPagina) {
    if (laPagina.attr('id') == 'nuestraPropuesta') 
        mitadWidth = (_browserWidth - parseInt(laPagina.css('width'))) / 2;
    else {
        mitadWidth = ((_browserWidth - lineaV.getBBox().x) - parseInt(laPagina.css('width'))) / 2;
        mitadWidth += lineaV.getBBox().x;
    }
    mitadHeight = $("#divBuscadorPorRubro").offset().top;
    
    laPagina.css('left', mitadWidth);
    laPagina.css('top', mitadHeight);
    $("#mensajeFiltros").css('visibility', 'hidden');
    auxFondoPaginas.attr({ 'x': parseInt(laPagina.css('left')), 
                           'y': parseInt(laPagina.css('top')), 
                           'width': laPagina.width(), 
                           'height': laPagina.height(), 
                           'fill': '#676767',
                           'stroke': '#ff0000',
                           'stroke-width': 3
                           }).show();
    laPagina.css('visibility', 'visible');
}
function elCentro(queHacer) {
    auxFondoPaginas.hide();
    $(".divPagina").css('visibility', 'hidden');
    switch (queHacer) {
        case "mostrar":
            $("#divBarraPaginas").css('visibility', 'visible');
            auxRectPaginas.show();
            break;
        case "ocultar":
            $("#divBarraPaginas").css('visibility', 'hidden');
            auxRectPaginas.hide();
            break;
    }
}
function seleccionarColores(elColor) {
    var auxiliar; 
    auxiliar = "App_Themes/" + elColor + "/ui.theme.css";
    return auxiliar;
}
function loadjscssfile(filename, filetype) {
    var fileref;
    if (filetype=="js") { 
        fileref=document.createElement('script');
        fileref.setAttribute("type","text/javascript");
        fileref.setAttribute("src", filename);
    }
    else if (filetype=="css") { 
            fileref=document.createElement("link");
            fileref.setAttribute("rel", "stylesheet");
            fileref.setAttribute("type", "text/css");
            fileref.setAttribute("href", filename);
        }
    if (typeof fileref != "undefined")
        document.getElementsByTagName("head")[0].appendChild(fileref);
    return false;
}
function redondear2(numero) {
	var original=parseFloat(numero);
	var result=Math.round(original) ;
	return result;
}
function redondear(cantidad, decimales) {
    cantidad = parseFloat(cantidad);
    decimales = parseFloat(decimales);
    decimales = (!decimales ? 2 : decimales);
    return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales); 0
} 
function leerMenuHorizontal() {
    /**** Buscar Datos ****/
    empresaActual = 1;
    var datos = { accion: 'leerMenu', empresa: empresaActual, posicion:'H1' };
    $.ajax({
        type: "GET",
        url: "generales.ashx",
        async: false, 
        data: datos,
        dataType: "json",
        cache: false, 
        success: function(data) {
                   elMenu = jQuery.extend(true, {}, data);
                 }
        });
    return false;
}
function armarElMenu() {
    if ($("#menuHorizontal").length > 0)
        $("#menuHorizontal").remove(); 
    var anchoMenu = (elMenu.cantItems * parseInt(elMenu.anchoItem)) + (elMenu.cantItems * parseInt(elMenu.distEntreItems));
    anchoMenu = anchoMenu + (3 * 2 * elMenu.cantItems); // calculo 3px borde * 2 bordes de cada Item
    var altoMenu = parseInt(elMenu.altoItem);
    o = "<div id='menuHorizontal' style='width:" + anchoMenu + "px; height: " + altoMenu + "; ";
    o += "position:absolute; top: " + elMenu.top + "; left: " + elMenu.left + "; ";
    o += "z-index:50";
    if (elMenu.bordeGral.length > 0)
        o += "; border: " + elMenu.bordeGral;
    o += "'/>";
    agregarObjeto(o, 'elBody');

    /**** Items ****/
    for (i=0; i<elMenu.cantItems; i++) {
        nombreItem = 'mnu' + elMenu.items[i].leye;
        o ="<div id='" + nombreItem + "' class='losItemsMenu' onclick=\"llamarPagina('" + elMenu.items[i].pag + "')\" ";
        o +="style='float:left;";
        o +="width:" + elMenu.anchoItem + "; height:" + elMenu.altoItem;  
        if (elMenu.bordeItem.length > 0) 
            o += "; border:" + elMenu.bordeItem;
        if (elMenu.distEntreItems.length > 0)
            o +="; margin-left:" + elMenu.distEntreItems;
        o +="; cursor:pointer'>";
        
        o += "<table width='100%'>";
        o += "<tr valign='middle' align='center' style='height:" + elMenu.altoItem + "'>";
        o += "<td>";
        if (elMenu.configItem == 2 || elMenu.configItem == 3) {
            o += "<img src='Imagenes/" + elMenu.items[i].img + "' alt='' />";
        }
        var fontYColor="";
        if (elMenu.font.length > 0)
            fontYColor += "font:" + elMenu.font + '; ';
        if (elMenu.colorFrente.length > 0)
            fontYColor += "color:" + elMenu.colorFrente;
//        if (elMenu.configItem == 1 || elMenu.configItem == 3) {
//            o += "<span ";
//            if (fontYColor.length > 0)
//                o += "style='" + fontYColor + "'";
//            o += ">" + elMenu.items[i].leye + "</span>";
//        }
        o += "</td>";
        o += "</tr></table>";
        o += "<table><tr > <td style='width:" + elMenu.anchoItem + "' align=center>";
        o += "<span class='leyendaMenu' style='font:normal 10px arial; font-weight:bold;'>" + elMenu.items[i].leye + "</span>";
        o += "</td></tr></table>";
        o += "</div>";
    
        agregarObjeto(o, 'menuHorizontal');
        auxO = $("#" + nombreItem);
        medioLeft = auxO.offset().left + (parseInt(auxO.width()) / 2);
        medioTop = auxO.offset().top + (parseInt(auxO.height()) / 2);
        arrayItemsMenu[i] = paper.circle(medioLeft, medioTop, (parseInt(auxO.width()) / 2) * .8);
        arrayItemsMenu[i].attr({ "stroke-width": 3, "stroke": "#FF0000", "fill": "#ffffff", "fill-opacity": "0.3" });
    }
    return false;
}    
function agregarObjeto(elObjeto, padre) { 
      elPadre = "#" + padre;
      $(elPadre).append(elObjeto);
      return false;
}
function isNumeric(valor) {
    if (valor.match(/^\d+$/) == null) {
        alert('El Valor ingresado debe ser Numérico');
        return false;
    }
    else
        return true; 
}
function devolverValorDropDown(elObjeto, valorTexto) {
    var text;
    if (valorTexto == '')
        valorTexto = 'texto';
    var ix = $("#" + elObjeto).attr("selectedIndex");
    if (valorTexto == 'texto')
        text = $("#" + elObjeto).find("option:eq(" + ix + ")").text(); 
    else
        text = $("#" + elObjeto).find("option:eq(" + ix + ")").val();
    return text;
}
function buscarParamEmpresa() {
    var datos = { accion: 'leerEmpresa', empresa: empresaActual };
    $.ajax({
        type: "GET",
        url: "generales.ashx",
        async: false, 
        data: datos,
        dataType: "json",
        cache: false,
        success: function(data) {
                   laEmpresa = jQuery.extend(true, {}, data);
                 }
        });
    return false;
}
function hoverImagen(elObjeto, imagen, imagenHover) {
     $(elObjeto).hover(function() { $(elObjeto).attr('src', imagenHover) },
                       function() { $(elObjeto).attr('src', imagen) })
}
function tratarOverTreeview(elObjeto) {
    $(".file").css('color', '#ffffff');
    $(".folder").css('color', '#ffffff');
    $(elObjeto).css('color', '#00ff00');
}
function llenarComboDesdeTabla(tabla, elCombo, elMensajeSeleccion) {
    var d = leerTablaParaCombo(tabla);
    var ar = new Array();
    ar = d.split('|');
    llenarCombo(ar, elCombo, elMensajeSeleccion);
}
function leerTablaParaCombo(tabla) {
    var datos = { accion: 'leer' + tabla, empresa: empresaActual };
    var d;
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "jsondata",
        cache: false,
        success:  function(data) {
                d = data;
            }
    });
    return d;
}
function llenarCombo(elArray, elCombo, elMensajeSeleccion) {
    if (elMensajeSeleccion != null) {
        o = "<option value ='Seleccione'>" + elMensajeSeleccion + "</option>";
        agregarObjeto(o, elCombo);
    }
    var resto;
    for (i = 1; i < elArray.length; i++) {
        resto = i % 2;
        if (resto == 0) {
            o = "<option value =" + elArray[i - 1] + ">" + elArray[i] + "</option>";
            agregarObjeto(o, elCombo);
        }
    }
}
function regrabarBoton(elBoton, elTop, elLeft) {
    var datos = { accion: 'regrabarBoton', boton: elBoton, top: elTop, left: elLeft };
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "jsondata",
        cache: false
    });
}
function carac(elCaracter) {
    var c;
    switch (elCaracter) {
        case 'a':
            c = String.fromCharCode(225);     
            break;
        case 'e':
            c = String.fromCharCode(233);     
            break;
        case 'i':
            c = String.fromCharCode(237);     
            break;
        case 'o':
            c = String.fromCharCode(243);     
            break;
        case 'u':
            c = String.fromCharCode(250);     
            break;
        case 'n':
            c = String.fromCharCode(241);     
            break;    
        case 'N':
            c = String.fromCharCode(209);     
            break;
    }
    return c;
}
function tratarClickRubro(elObjeto, tipoArticulo) {
    pararAnimacion();
    $('.file').css('background-color', 'Transparent');
    $(elObjeto).css('background-color', '#3C576C');
    $(".redon").remove();
    descrTipoArticulo="";
    $("#cmbTipoArticulo option").each(
        function(){
            if ($(this).attr('value') == tipoArticulo)
                descrTipoArticulo = $(this).text();
    });
    filtroGral = 'tipoArticulo: ' + tipoArticulo;
    filtroGralDisplay = "Filtrado por... Tipo de Art" + carac('i') + "culo: " + descrTipoArticulo;
    laPagina = 1;
    armarPagina(1);
}
function mandarMail() {
   control = true;
   mensaje = "";
   if ($("#t2").val().length == 0) {
       mensaje += "El Nombre es Obligatorio - ";
       control = false;
   }
   if ($("#t1").val().length == 0) {
        mensaje += "El eMail es Obligatorio - ";
        control = false;
   }
   ok = validarEmail($("#t1").val());
   if (!ok) {
        mensaje += "La direccion de Email es incorrecta - ";
        control = false;
   }
   if (control) {
        var carri = "";
        for(i=0; i<elCarrito.length; i++) {
            if (carri != "")
                carri += "|";
            carri += elCarrito[i];
        }
       
        var datos = {accion: 'mandarMail',
                     nombre: $("#t2").val(),
                     direccion: $("#t3").val(),
                     provincia: $("#t4").val(),
                     eMail: $("#t1").val(),
                     telefono: $("#t6").val(),
                     mensaje: $("#ta1").val(),
                     carrito: carri
                    };
        var d = 'EL MAIL NO PUDO SER ENVIADO';
        $.ajax({
            type: "GET",
            url: "generales.ashx",
            async: false,
            data: datos,
            dataType: "jsondata",
            cache: false,
            success: function() {
                        d = 'El  Mail  ha  sido  Enviado\n\nGracias por su consulta';
                     }
        });
        alert(d);
   }
   else alert(mensaje);
   return control;}
function validarEmail(valor) {
    ok = true;
    if (!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)) 
            ok = false;
    return ok;   
}
function chequearExtension(nombreArchivo) {
    var ok = true;
    var ext = nombreArchivo.split('.').pop().toLowerCase();
    var allow = new Array('gif', 'png', 'jpg', 'jpeg', 'ico');
    if (jQuery.inArray(ext, allow) == -1) {
        alert('Extensi' + carac('o') + 'n de Archivo NO permitida \n\n Aceptamos (.gif, .png, .jpg, .jpeg, .ico)');
        ok = false;
    }
    return ok;
}
function leerBotonesFormulario(nombreFormulario) {
    var datos = { accion: 'leerBotonesFormulario', formulario: nombreFormulario };
    var auxiliar = {};
    var i;
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "json",
        cache: false,
        success: function(data) {
                    auxiliar = jQuery.extend(true, {}, data);
                 }
    });
    for (i = 0; i < auxiliar.totalRegistros; i++) { 
        armarBoton(auxiliar.reg[i]);
    }

    $("#btnNovedades").css('top', lineaH.getBBox().y - 20);
}
function armarBoton(btn) {
    leftBoton = _browserWidth * parseInt(btn.elLeft) / 100;
    topBoton = _browserHeight * parseInt(btn.elTop) / 100;
    o = "<div id='" + btn.id + "' style='position:absolute; z-index:50; ";
    o += "top:" + topBoton + "px; left:" + leftBoton + "px";
    if (btn.anchoBoton.length > 0) 
        o += "; width:" + btn.anchoBoton;
    if (btn.altoBoton.length > 0) 
        o += "; height:" + btn.altoBoton;
    if (btn.cursor.length > 0)
        o += "; cursor:" + btn.cursor + "; ";
    o += "'>";
    o += "<table>";
    if (btn.imagen.length > 0) {
        o += "<tr align='center' ><td>";
        var path = 'Imagenes/' + btn.imagen;
        o += "<img alt='" + btn.id_boton + "' " + "src='" + path + "' " + " title='" + btn.tip + "'/> ";
        o += "</td></tr>";
    }
    if (btn.descripcion.length > 0) {
        o += "<tr align=center><td>";
        o += "<span ";
        o += "style='";
        if (btn.fontFamily.length > 0)
            o += "font-family: " + btn.fontFamily + "; ";
        if (btn.fontWeight.length > 0)
            o += "font-weight: " + btn.fontWeight + "; ";
        if (btn.fontSize.length > 0)
            o += "font-size: " + btn.fontSize + "; ";
        if (btn.fontColorFrente.length > 0)
            o += "color: " + btn.fontColorFrente + "; ";
        o += "'>" + btn.descripcion + "</span>";
        o += "</td></tr>";
        unObjeto = "#" + btn.id_boton;
        if (btn.fontColorResaltado.length > 0) {
            $(unObjeto).hover(function() { $(unObjeto).css('color', btn.fontColorResaltado) },
                              function() { $(unObjeto).css('color', btn.fontColorFrente) });
        }
    }
    o += "</table>";
    o += "</div>";
    
    if (btn.descripcionBorde.length > 0) {
        rec = paper.rect(leftBoton, topBoton, parseInt(btn.anchoBoton), parseInt(btn.altoBoton), 5).attr({ 'stroke-width': 2, 'stroke': '#676767' });
        if (btn.id_boton == 'btnBusquedas') {
            txt = 'B' + carac('u') + 'squeda';
            textoR = paper.text(0, 0, txt);
            textoR.attr({ 'font-family':'Arial', 'font-size':11, 'font-weight':'bold', 'text-anchor':'start', 'fill':'#0000FF'});
//            largoTexto = redondear(texto.getBBox().width, 2);
            textoR.attr({ x: rec.getBBox().x, y: rec.getBBox().y + rec.getBBox().height + 8 });
        }
    }

    if (btn.link.length > 0) { // borra todo lo hecho anteriormente
        if (btn.imagen != '') {
            indice = btn.link.indexOf('http');
            if (indice != -1) { // es decir, es un http://sitio
                o = "<a target='_blank' style='position:absolute; top:" + btn.elTop + "; left:" + btn.elLeft + "; z-index:50' ";
                o += "href=\"" + btn.link + "\"> ";
                o += "<img alt='' src='Imagenes/" + btn.imagen + "' style='border:none' />";
                o += "</a>";
            }
            else {
                o = "<img alt='' style='border:none; position:absolute; top:" + btn.elTop;
                o += "; left:" + btn.elLeft + "; z-index:50; cursor: " + btn.cursor + "' ";
                o += "src='Imagenes/" + btn.imagen + "' ";
                o += "onclick=\"llamarPagina('" + btn.link + "')\"/>";
            }
        }
        else { // es un link pero con palabras, SIN imágenes
             o = "<a id='" + btn.id_boton + "' target='_blank' style='position:absolute; text-decoration:none; ";
             o += "top:" + btn.elTop + "; left:" + btn.elLeft + "; z-index:50' href=\"" + btn.link + "\"> ";
             o += "<span style='font-family: ";
             if (btn.fontFamily.length > 0)
                    o += btn.fontFamily + "; ";
             else   o += "Arial";
             if (btn.fontWeight.length > 0)
                o += "font-weight: " + btn.fontWeight + "; ";
             if (btn.fontSize.length > 0)
                o += "font-size: " + btn.fontSize + "; ";
             if (btn.fontColorFrente.length > 0)
                o += "color: " + btn.fontColorFrente;
             o += "'>" + btn.descripcion;
             o += "</span>";
             o += "</a>";
        }
    }
    agregarObjeto(o, 'elBody');
    
    if (btn.dragable == 1) {
        $("#" + btn.id_boton).draggable({
            stop: function(event, ui) {
                if (donde == 'elBody') {
                    elTop = redondear2(ui.position.top * 100 / $(window).height());
                    elLeft = redondear2(ui.position.left * 100 / $(window).width());
                }
                else {
                    elDonde = $("#" + donde);
                    elTop = redondear2(ui.position.top * 100 / $(elDonde).height());
                    elLeft = redondear2(ui.position.left * 100 / $(elDonde).width());
                }
                regrabarBoton($(this).attr('id'), elTop, elLeft);
            }
        });
    }
}
$.ctrl = function(key, callback, args) {
    var isCtrl = false;
    $(document).keydown(function(e) {
        if (!args) args = []; // IE barks when args is null

        if (e.ctrlKey) isCtrl = true;
        if (e.keyCode == key.charCodeAt(0) && isCtrl) {
            callback.apply(this, args);
            return false;
        }
    }).keyup(function(e) {
        if (e.ctrlKey) isCtrl = false;
    });
};
function iconosBarraPaginas() {
    $("#pagPrimera").hover(function() { $(this).attr('src', 'Imagenes/primeroAzul.ico') },
                                     function() { $(this).attr('src', 'Imagenes/primeroGris.ico') });
    $("#pagAnterior").hover(function() { $(this).attr('src', 'Imagenes/anteriorAzul.ico') },
                                     function() { $(this).attr('src', 'Imagenes/anteriorGris.ico') });
    $("#pagSiguiente").hover(function() { $(this).attr('src', 'Imagenes/siguienteAzul.ico') },
                                     function() { $(this).attr('src', 'Imagenes/siguienteGris.ico') });
    $("#pagUltima").hover(function() { $(this).attr('src', 'Imagenes/ultimoAzul.ico') },
                                     function() { $(this).attr('src', 'Imagenes/ultimoGris.ico') });
}
function modal(inicia) {
    if (inicia == true) {
        o = "<div id='divModal' style='width:100%; height:100%; position:absolute; top:0%; left:0%; background-color:white; z-index:200' >";
        o += "</div>";
        agregarObjeto(o, 'elBody');
        $("#divModal").fadeTo(0, 0.7);
    }
    else {
        $("#divModal").remove(); 
    }
}
function buscarDescripcionExtendida(art) {
    var datos = { accion: 'leerDescripcionExtendidaArticulo', artic: art };
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "html",
        cache: false,
        success: function(data) {
            descrHTML = data;
        }
    });
    return descrHTML;
}
function leerFotosArticulo(art) {
    var auxiliar = {};
    var datos = { accion: 'leerFotosArticulo', empresa: empresaActual, articulo: art };
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "json",
        cache: false,
        success: function(data) {
                    auxiliar = jQuery.extend(true, {}, data);
                 }
    });
    return auxiliar;
}
/****** Filtro de Busquedas ******/
function busquedas() {
    modal(true);
    $("#btnBusquedas").css('visibility', 'hidden');
    auxBusqueda = $("#divBusqueda");
    var leftBusqueda = (_browserWidth - auxBusqueda.width()) / 2;
    var topBusqueda = 30 * _browserHeight / 100;
    /*** Recuadro y Fondo ***/
    dm = document.getElementById('divModal');   
    paperModal = Raphael(dm, $(dm).width(), $(dm).height());
    auxDivBusqueda = paperModal.rect(leftBusqueda - 10, topBusqueda - 10, auxBusqueda.width() +  20, auxBusqueda.height() + 20, 10);
    auxDivBusqueda.attr({ 'fill': '#000000', 'stroke-width': 2, 'stroke':'#ff0000', 'fill-opacity': 1 });
    /************************/
    auxBusqueda.css('top', topBusqueda ).css('left', leftBusqueda);
    auxBusqueda.css('visibility', 'visible').focus();
    $("#cmbTipoArticulo").val("Seleccione");
    $("#inputDescripcion").val("");
    auxBusqueda.keypress( function(event) {
                                    if (event.keyCode == 27) {
                                            salirBusqueda(); 
                                            llamarPagina('principal');
                                    }
                                    if (event.keyCode == 13) $("#btnOk").click();
                            })
}
function salirBusqueda() {
    limpiarPagina();
    modal(false);
    $("#divBusqueda").css('visibility', 'hidden');
    $("#mensajeFiltros").css('visibility', 'hidden');
    $("#btnBusquedas").css('visibility', 'visible');
    $(".divPagina").css('visibility', 'hidden');
    elCentro('ocultar');
    auxDivBusqueda.remove();
    pararAnimacion();
}
function buscarPorFiltro() {
    var auxFiltros = "";
    filtroGralDisplay = "Filtrado por... ";
    
    if ($("#cmbTipoArticulo").val() == 'Seleccione' &&
        $("#inputDescripcion").val() == '') {
        pararAnimacion();
        llamarPagina('principal');
        return false;
    }
    if ($("#cmbTipoArticulo").val() != 'Seleccione') {
        auxFiltros += "tipoArticulo: " + $("#cmbTipoArticulo").val();
        filtroGralDisplay += "Tipo de Art" + carac('i') + "culo: " + $("#cmbTipoArticulo option:selected").text();
    }
    if ($("#inputDescripcion").val() != '') {
        if (auxFiltros.length > 0) {
                auxFiltros += ",subString: " + $("#inputDescripcion").val();
                filtroGralDisplay += "," 
        }
        else    {
                auxFiltros += "subString: " + $("#inputDescripcion").val();
        }
        filtroGralDisplay += " Descripci" + carac('o') + "n: " + $("#inputDescripcion").val();
    }
    filtroGral = auxFiltros;
    
    if (filtroGral != '')
        armarPagina(1); ;
}
function iniciarCentro() {
    iconosBarraPaginas();
    armarPagina(laPagina);
    $("#elBody").bind("contextmenu", function(e) { return false; });
}
function locationVars (vr) {
    var src = String( window.location.href ).split('?')[1];
    var vrs = src.split('&');

    for (var x = 0, c = vrs.length; x < c; x++) 
    {
    	if (vrs[x].indexOf(vr) != -1)
    	{
    		return decodeURI( vrs[x].split('=')[1] );
    		break;
    	};
    };
};

/******** Efecto Blink ********/
function blink(laClase) {
    $("." + laClase).fadeTo(1000, 0.2).fadeTo(1000, 1, function(){blink(laClase)});
}
function frenar() {
    $(".foto").removeClass().addClass('fotos');
}
function continuarBlink(laClase) {
    $(".blinkearAux").addClass(laClase);
    blink('foto');
}
/******** Efecto Marquesina ********/
function marquesina() {
    arrayMarquesina[0].animate({
        left: '+=800'
    }, 3000, marquesinaForEver)
}
function marquesinaForEver() {
    arrayMarquesina[0].css('left', 0);
    arrayMarquesina[0].animate({
        left: '+=500'
    }, 3000, marquesinaForEver)
}
function leerNovedades() {
    var datos = { accion: 'leerArticulosUltimosIngresados' };
    var auxiliar = {};
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "json",
        cache: false,
        success: function(data) {
                      auxiliar = jQuery.extend(true, {}, data);
                 }
    });
    armarNovedades(auxiliar);
}
function armarNovedades(aux) {
    var nombre;
    var nombreAux;
    var nombreFoto;
    var elTop = $("#divBuscadorPorRubro").offset().top - 20;
    var elLeft = redondear(78 * _browserWidth / 100, 2);
    var elWidth = redondear(_browserWidth - elLeft - 10, 2);
    o = "<div style='position:absolute; top:" + elTop + "px; left:" + elLeft + "px; width: " + elWidth + "px; font-size:13px'";
    o += "align='center' class='descripcionItemsNovedades tituloNovedades'>Ultimas Novedades";
    o += "</div>";
    agregarObjeto(o, 'elBody');
    elTop += 20;
    var rectaLeft; 
    var rectaTop;
    var rectaWidth;
    var rectaHeight;
    var j;
    for (j = 0; j < aux.totalRegistros; j++) {
        nombre = "novedad" + j;
        nombreFoto = "novedadFoto" + j;
        o = "<div id='" + nombre + "' style='position:absolute; top:" + elTop + "px; left:" + elLeft + "px; width: " + elWidth + "px; ";
        o += "z-index:150; min-height:90px; max-height:90px' class='novedades' >";
        o += "<table width='100%' >";
        o += "<tr valign='middle' >";
        o += "<td>";
        o += "<img id='" + nombreFoto + "' src='Fotos/" + aux.artic[j].foto + "' alt='' style='max-width:64px; max-height:64px; width:64px; border:none' />";
        o += "</td>";
        o += "<td valign='top'>";
        o += "<div align='center'>";
        o += "<span class='descripcionItemsNovedades' >" + aux.artic[j].descr.substr(0, 40) + "</span>";
        o += "<p class='descripcionItemsNovedades' >" + obtenerDescrRubroTipoArticulo(aux.artic[j].id_tipo_articulo, 'Rubro') + " - " + obtenerDescrRubroTipoArticulo(aux.artic[j].id_tipo_articulo, 'TipoArt') + "</p>";
//        o += "<br/>";
//        o += "<a href='#' onclick=\"armarModal(" + aux.artic[j].id + ", '" + aux.artic[j].cod + "', '" + aux.artic[j].descr + "', '";
//        o += aux.artic[j].precio + "', '" + aux.artic[j].foto + "')\" style='color:#FFFFFF'>Ver Ficha</a>&nbsp";
        o += "<a href=\"../ficha.aspx?id=" + aux.artic[j].id + "&cod=" + aux.artic[j].cod + "&descr=" + aux.artic[j].descr;
        o += "&precio=" + aux.artic[j].precio + "&foto=" + aux.artic[j].foto + "\"";
        o += " style='color:#1058A0; text-decoration:none; font-size:11px; font-weight:bold'>Ver Ficha</a>&nbsp";
        o += "<span style='color:#FFFFFF; float:right' class='descripcionItemsNovedades'>Precio " + aux.artic[j].precio + "</span>";
        o += "<br /></div>";
        o += "</td>";
        o += "</tr>";
        o += "</table>";
        o += "</div>";
        agregarObjeto(o, 'elBody');
        
        nombreAux = $("#" + nombre);
        elTop = nombreAux.offset().top + nombreAux.height() + 6;
        rectaLeft = nombreAux.offset().left - 1; 
        rectaTop = nombreAux.offset().top - 1;
        rectaWidth =  nombreAux.width() + 2;
//        rectaHeight = nombreAux.height() + 2;
        rectaHeight = 90;
        nombreAux = $("#" + nombreFoto);
        if($("#" + nombreFoto).height() > $("#" + nombreFoto).width())
            $("#" + nombreFoto).height(64);
        else
            $("#" + nombreFoto).width(64);
        if (j < 5)
            arrayBordeNovedades[j] = paper.rect(rectaLeft, rectaTop, rectaWidth, rectaHeight, 10).attr({ 'stroke-width': 2, 'stroke': '#000000', 'fill': '#FFB871' }); 
    }
    armarMarquesinaNovedades();
} 
function armarMarquesinaNovedades() {
    var arrayAux = $(".novedades");
    arrayNovedades = [];
    for (var i=0; i<arrayAux.length; i++) {
        arrayNovedades.push($(arrayAux[i])); // acá están las novedades       
    }
    arrayAux = [];
    puntoInicial = 0;
    elTop = $("#novedad0").offset().top;
    elAlto = arrayBordeNovedades[0].getBBox().height;
    arrayNovedadesMuestra = armarArrayMostrar(puntoInicial);
    marquesina();
}
function armarArrayMostrar(inicio) {
    var array = new Array(5);
    var color = "";
    for(var i=0; i < arrayNovedades.length; i++) {
        arrayNovedades[i].css('visibility', 'hidden');
    }
    
    for (var i=0; i<5; i++) {
        arrayNovedades[inicio].css('visibility', 'visible');
        array[i] = arrayNovedades[inicio];
        arrayBordeNovedades[i].attr({ "fill": "#FFB871" })
        switch (inicio) {
            case 0:
                color = '#FF7777';
                break;
            case 1:
                color = '#FFFF64';
                break;
            case 2:
                color = '#FF9E3E';
                break;
            case 3:
                color = '#FF7777';
                break;
            case 4:
                color = '#FFFF64';
                break;
            case 5:
                color = '#FF9E3E';
                break;
            case 6:
                color = '#FF7777';
                break;
            case 7:
                color = '#FFFF64';
                break;
            case 8:
                color = '#FF9E3E';
                break;
            case 9:
                color = '#FFFF64';
                break;
        }
        arrayBordeNovedades[i].attr({ "fill": color });
        
        $(array[i]).css('top', elTop + (i * (elAlto + 5)) );
        inicio++;
        if (inicio >= arrayNovedades.length)
            inicio = 0;
    }
    return array;
}
function marquesina() {
    for (var i=0; i < 4; i++) {
        arrayNovedadesMuestra[i].animate({ 
                       'top' : "+=0"
                       }, 2000)
    }
    arrayNovedadesMuestra[4].animate({ 
                       'top' : "+=0"
                       }, 2000 , marquesinaForEver)
}
function marquesinaForEver() {
    puntoInicial += 1;
    if (puntoInicial >= arrayNovedades.length)
        puntoInicial = 0;
    arrayNovedadesMuestra = armarArrayMostrar(puntoInicial);
    for (var i=0; i < 4; i++) {
        arrayNovedadesMuestra[i].animate({ 
                            "top": "+=0"    
                        }, 2000)
    }
    arrayNovedadesMuestra[4].animate({ 
                       'top' : "+=0"
                       }, 2000 , marquesinaForEver)

}
function pararAnimacion() {
   for (var i = 0; i < 5; i++) {
       arrayNovedadesMuestra[i].stop();
   }
}
/****** Tipos de Artículo y Rubros ******/
function armarTiposArticuloyRubros() {
    var datos = { accion: 'leerTiposArticuloRubro' };
    var auxiliar = {};
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "json",
        cache: false,
        success: function(data) {
                    auxiliar = jQuery.extend(true, {}, data);
        }
    });
    if ($("#cmbTipoArticulo").length > 0) 
        llenarComboTipoArticulo(auxiliar);
    return auxiliar;
}
function llenarComboTipoArticulo(aux) {
    for (i=0; i<aux.totalRegistros; i++) {
        o = "<option value =" + aux.reg[i].id_tipo_articulo + ">" + aux.reg[i].descripcion + "</option>";
        agregarObjeto(o, 'cmbTipoArticulo');
    }
    o = "<option value = 'Seleccione'" + ">Seleccione</option>";
    agregarObjeto(o, 'cmbTipoArticulo');  
}
function obtenerDescrRubroTipoArticulo(tipoArt, que) {
    var descrip = "";
    var i;
    limite = TiposArticuloRubros.totalRegistros;
    for (i=0; i < limite; i++) {
        if (tipoArt == TiposArticuloRubros.reg[i].id_tipo_articulo) {
                switch (que) {
                    case 'Rubro':
                        descrip = TiposArticuloRubros.reg[i].descripcionRubro;
                        break;
                    case 'TipoArt':
                        descrip = TiposArticuloRubros.reg[i].descripcion;
                        break;
                    case 'Ambos':
                        descrip = TiposArticuloRubros.reg[i].descripcionRubro;
                        if (TiposArticuloRubros.reg[i].descripcionRubro != TiposArticuloRubros.reg[i].descripcion)
                            descrip += " - " + TiposArticuloRubros.reg[i].descripcion;
                        break;
                }
                i = limite;
        }
    }
    return descrip;
}
/****************************************/
function armarRubrosTiposArticulos() {
    var datos = { accion: 'leerRubrosTipoArticuloAgrupados'  };
    var auxiliar = "";
    $.ajax({
        type: "GET",
        url: "maestros.ashx",
        async: false,
        data: datos,
        dataType: "jsondata",
        cache: false,
        success: function(data) {
                    auxiliar = data;
        }
    });
    return auxiliar;
}
/**********************************************************/

function armarModal(id, codigo, descripcion, precio, foto, proviene) {
        o = "<div id='telon' ";
        o += "style='position:absolute; top:0%; left:0%; width:100%; height:100%; background:#000000; ";
        o += "z-index:150'>";    
        o += "</div>";
        agregarObjeto(o, 'elBody');
        
        tln = document.getElementById('telon');
        paperTelon = Raphael(tln, $(tln).width(), $(tln).height());
        
        rectTop = redondear(_browserHeight * 20 / 100, 2);
        rectLeft = redondear(_browserWidth * 10/ 100, 2);
        rectHeight = redondear(_browserHeight * 60 / 100, 2);
        rectWidth = redondear(_browserWidth * 80 / 100, 2);
        auxRectTelon = paperTelon.rect(rectLeft, rectTop, rectWidth, rectHeight, 25).attr({ fill: "#FFFFFF", "stroke-width": 3, "stroke": "#00FF00" }); 
        
        /**** Icono para Cerrar Modal ****/
        iconoTop = rectTop;;
        iconoLeft = rectLeft + rectWidth;
        o = "<img id='cerrarPopUp' src= 'Imagenes/close.png' class='btn_close' alt='' ";
        o += "style='cursor:pointer; position:absolute; top:" + iconoTop + "px; left: " + iconoLeft + "px' "; 
        o += "onclick=\"cerrarModal('" + proviene + "')\" />";
        agregarObjeto(o, 'telon');
        
        /**** Foto Modal ****/
        fotoTop = redondear(_browserHeight * 25 / 100, 2);
        fotoLeft = redondear(_browserWidth * 12 / 100, 2);
        fotoMaxHeight = redondear(_browserHeight * 50 / 100, 2);
        fotoMaxWidth = redondear(_browserWidth * 50 / 100, 2); 
        $("#imagenAux").attr('src', 'Fotos/' + foto);
        
        if ($("#imagenAux").height() < fotoMaxHeight) 
            fotoTop += (fotoMaxHeight - $("#imagenAux").height() ) / 2;
        if ($("#imagenAux").width() < fotoMaxWidth) 
            fotoLeft += (fotoMaxWidth - $("#imagenAux").width()) / 2;
        
        o ="<img id='fotoModal' src='Fotos/" +  foto + "' alt='' ";
        o += "style='position:absolute; top:" + fotoTop + "px; left:" + fotoLeft + "px; ";
        o += "max-height:" + fotoMaxHeight + "px; max-width:" + fotoMaxWidth + "px' />";
        agregarObjeto(o, 'telon');

        /**** Esta es la columna donde finaliza la foto ****/
        leftHtml = parseInt($('#fotoModal').css('left')) + $('#fotoModal').width();
        
        o = "<span style='position:absolute; top:20%; left:" + (leftHtml + 25) + "px; max-width:25%'>"
        o += buscarDescripcionExtendida(id);
        o += "</span>";
        agregarObjeto(o, 'telon');

        codigoLeft = auxRectTelon.getBBox().x + (_browserWidth * 1 / 100);
        codigoTop = auxRectTelon.getBBox().y + (auxRectTelon.getBBox().height / 2);
        elTextoCodigoModal = paperTelon.text(codigoLeft, codigoTop, 'C' + carac('o') + 'digo: ' + codigo).attr({ 'font-size': 18, 'fill': '#FF0000', 'font-weight': 'bold' }).rotate(270);
        codigoLeft = auxRectTelon.getBBox().x + (_browserWidth * 20 / 100);
        codigoTop = auxRectTelon.getBBox().y + 20;
        elTextoPrecioModal = paperTelon.text(codigoLeft, codigoTop, 'Precio: ' + precio).attr({ 'font-size': 18, 'fill': '#FF0000', 'font-weight': 'bold' });

        arrayFotosModal = leerFotosArticulo(id);
        if (arrayFotosModal.cantidad > 1) {
                if ($("#barraControlesFoto").length == 0)
                    armarBarraControlesFoto();
                topBarra = auxRectTelon.getBBox().y + auxRectTelon.getBBox().height - 24;
                leftBarra = auxRectTelon.getBBox().x + (_browserWidth * 17 / 100);
                $("#barraControlesFoto").css('top', topBarra).css('left', leftBarra).css('visibility', 'visible');
                arrayFotos = new Array(arrayFotosModal.cantidad);
                for (i = 0; i < arrayFotosModal.cantidad; i++) {
                    arrayFotos[i] = 'Fotos/' + arrayFotosModal.reg[i].nombre;
                }
                corriente = 0;
                pausa();
                play();
        }
        else    $("#barraControlesFoto").css('visibility', 'hidden');
    }
    function pausa() {
        laPausa = $("#fotoPausa").attr('src');
        if (laPausa == 'Imagenes/fotoContinuar.ico') {
            play();
            $("#fotoPausa").attr('src', 'Imagenes/fotoPausa.ico');
        }
        else {
            clearInterval(intervalo); //Paramos el intervalo
            $("#fotoPausa").attr('src', 'Imagenes/fotoContinuar.ico');
        }
    }
    function play() { //Generamos de nuevo el intervalo
        intervalo = setInterval(cargaImagen, 2000); //Creamos el intervalo con un refresco de 2 segundos
        $("#fotoPausa").attr('src', 'Imagenes/fotoPausa.ico');
        $("#numerosBarraFoto").html('Foto ' + (corriente + 1) + ' de ' + arrayFotosModal.cantidad);
    }
    function siguienteFoto() {
        cargaImagen();
    }
    function anteriorFoto() {
        corriente = corriente - arrayFotosModal.cantidad;
        cargaImagen();
    }
    function cargaImagen() {
        corriente++;
        if (corriente > arrayFotosModal.cantidad - 1)
            corriente = 0;
        if (corriente < 0)
            corriente = arrayFotosModal.cantidad - 1;
        $("#fotoModal").attr('src', arrayFotos[corriente]);
        $("#numerosBarraFoto").html('Foto ' + (corriente + 1) + ' de ' + arrayFotosModal.cantidad);
    } 
    function cerrarModal(proviene) {
        $("#barraControlesFoto").css('visibility', 'hidden');
        auxRectTelon.remove();
        $("#telon").remove();
        $("#cerrarPopUp").remove();
        clearInterval(intervalo);
        if (proviene == 'novedad')
            history.back();
    }
    function armarBarraControlesFoto() {
        o = "<div id='barraControlesFoto' style='position:absolute; visibility:hidden; z-index:201; border:none'>";
            o += "<table>";
                o += "<tr valign='middle'>";
                    o += "<td>";
                        o += "<span id='numerosBarraFoto' style='font:bold 10px Arial'>Foto 1 de 1</span>";
                    o += "</td>";
                    o += "<td style='margin-left:15px'>";
                        o += "<img id='fotoAnterior' src='Imagenes/fotoAnterior.ico' alt=''";
                                 o += "style='cursor:pointer' onclick='anteriorFoto()'/>&nbsp;";
                        o += "<img id='fotoPausa' src='Imagenes/fotoPausa.ico' alt='' ";
                                 o += "style='cursor:pointer' onclick='pausa()'/>&nbsp;";
                        o += "<img id='fotoSiguiente' src='Imagenes/fotoSiguiente.ico' alt='' ";
                                 o += "style='cursor:pointer' onclick='siguienteFoto()' />";
                    o += "</td>";
                o += "</tr>";
            o += "</table>";
        o += "</div>";
        agregarObjeto(o, 'elBody');
    }
