﻿//////////////////////////////
///// VARIABLES GLOBALES /////
//////////////////////////////
var CodCliente = '';
var Codcliente = '';
CodigoDecliente = '';
var IdNoteolvides = '';
var Path_Imagenes = 'Imagenes/';
var IDDivPintarResultdos = '';
//////////////////////////////
//////////////////////////////

/////////////////////////////
///   FUNCIONES COMUNES   ///
/////////////////////////////

function Start() { CodigoDecliente = $get('ctl00_CodClienteJS').value; }
function getTime() {var d = new Date();return d.getTime();}
function PintarFecha(obj) {
    var dt = new Date(); var Hora = dt.getHours(); var Minutos = dt.getMinutes(); var Segundos = dt.getSeconds()
    $get('HoraSistema').innerHTML = " (" + Formatear(Hora) + ":" + Formatear(Minutos) + ":" + Formatear(Segundos) + ")"; setTimeout("PintarFecha(this)", 1000)
    var fecha = new Date(); var diames = fecha.getDate(); var diasemana = fecha.getDay(); var mes = fecha.getMonth() + 1; var ano = fecha.getFullYear();
    var textosemana = new Array(7); textosemana[0] = "Domingo"; textosemana[1] = "Lunes"; textosemana[2] = "Martes"; textosemana[3] = "Miércoles"; textosemana[4] = "Jueves"; textosemana[5] = "Viernes"; textosemana[6] = "Sábado";
    var textomes = new Array(12); textomes[1] = "Enero"; textomes[2] = "Febrero"; textomes[3] = "Marzo"; textomes[4] = "Abril"; textomes[5] = "Mayo"; textomes[6] = "Junio"; textomes[7] = "Julio"; textomes[8] = "Agosto"; textomes[9] = "Septiembre"; textomes[10] = "Octubre"; textomes[11] = "Noviembre"; textomes[12] = "Diciembre";
    try { $get(obj).innerHTML = "Fecha: " + textosemana[diasemana] + ", " + diames + " de " + textomes[mes] + " de " + ano; } catch (Error) { }
}
function Formatear(Obj) { if (Obj == 0) { return '00' } if (Obj == 1) { return '01' } if (Obj == 2) { return '02' } if (Obj == 3) { return '03' } if (Obj == 4) { return '04' } if (Obj == 5) { return '05' } if (Obj == 6) { return '06' } if (Obj == 7) { return '07' } if (Obj == 8) { return '08' } if (Obj == 9) { return '09' } return Obj; }

// Redondea una cantidad en javascript
function Right(str, n) {if (n <= 0)return "";else if (n > String(str).length)return str;else {var iLen = String(str).length;return String(str).substring(iLen, iLen - n);}}
function redondea(sVal, nDec) {var n = parseFloat(sVal);var s;n = Math.round(n * Math.pow(10, nDec)) / Math.pow(10, nDec);s = String(n) + "." + String(Math.pow(10, nDec)).substr(1);s = s.substr(0, s.indexOf(".") + nDec + 1);if (Right(s, 1) == '.') {return s.substring(0, s.length - 1);} else {return s;}}

//function MostrarCargando() { try { $get('CapaCargando').style.visibility = 'visible'; } catch (error) { } }
function LLamarAlCargador(txt) {$get('MPCapaCargando_div').style.visibility = 'visible';$get('MPCapaCargando_label').innerHTML = txt;}
function QuitarCargador() {$get('MPCapaCargando_div').style.visibility = 'hidden';}
function ComprobarElNavegador() {if (typeof document.body.style.maxHeight != "undefined") {} else {if (document.URL != "http://www.dmi.es/FRMLectorHTML.aspx?Pagina=Recomendaciones.htm") {document.location.href = "FRMLectorHTML.aspx?Pagina=Recomendaciones.htm";}}}
function LimpiarInput(obj) { $get(obj).value = ''; }
function Redirect(Pagina) {location.href = Pagina; }
function ValidarCIF(cajadetexto, boton) {var text1 = $get(cajadetexto).value; var longitud = text1.length; var primeraletra = text1.charAt(0); if (longitud < 9) { $get(boton).disabled = true; } else { $get(boton).disabled = false; }}
function PonerImaSubCategoria(Img) {$get('IMGRecomendacionBA').src = Img;}
function MostrarImgSubCat(Img) {
    if (parseInt($get('CapaImgSubCategoria').style.left = event.clientX) >= parseInt('700')) { $get('CapaImgSubCategoria').style.left = event.clientX - 20; }
    else { $get('CapaImgSubCategoria').style.left = event.clientX + 30; }
    $get('CapaImgSubCategoria').style.top = (event.clientY + document.documentElement.scrollTop + document.body.scrollTop + 7); $get('CapaImgSubCategoria').style.display = 'block'; $get('ImgSubCategoriaProducto').src = Img;
}
function ExpandireNoticias(Estado) {
    if (Estado == "True") {
        for (i = 0; i < 200; i++) {
            try { $get('ctl00_ContentPlaceHolder1_noticia_' + String(i)).style.display = 'block'; } catch (err) {
                return
            }
        }
    }
    else {
        for (i = 0; i < 200; i++) {
            try { $get('ctl00_ContentPlaceHolder1_noticia_' + String(i)).style.display = 'none'; }
            catch (err) {
                return
            }
        }
    }
}

function Mid(s, n, c) {
    var numargs = Mid.arguments.length; if (numargs < 3)
        c = s.length - n + 1; if (c < 1)
        c = s.length - n + 1; if (n + c > s.length)
        c = s.length - n + 1; if (n > s.length)
        return ""; return s.substring(n - 1, n + c - 1);
}

function LimpiarSearchbox(obj) {if (document.getElementById(obj).value == 'B\u00fasqueda r\u00e1pida') {document.getElementById(obj).value = '';}}
function EnQueURLEstoy(localhost) {
    if (localhost == 'true') {
        var urlactual = window.location.href.substring(33, window.location.href.length);
        var urlactualpartida = urlactual.split('.');
        return urlactualpartida[0]; 
    } else {
        var urlactual = window.location.href.substring(18, window.location.href.length);
        var urlactualpartida = urlactual.split('.');
        return urlactualpartida[0]; 
    }
}

function IraURL(url) {try {location.href = url;} catch (Error) { }}

///////////////////////////////////
///// ALTERACIONES DEL ESTILO /////
///////////////////////////////////

function CambiarBGPosition(obj, nuevapos) { $get(obj).style.backgroundPosition = nuevapos; }
function CambiarCssEnDiv(objeto, nuevocss) { $get(objeto).className = nuevocss; }
function RolloverImagen(imagen, nuevaimagen) { $get(imagen).src = nuevaimagen; }
function SET_bgcolor(obj, color) {try { $get(obj).style.backgroundColor = color; } catch (Error) { }  }
function RolloverBackground(obj, color) { $get(obj).style.backgroundColor = color; }
function ROver_BackgroundPosition(obj, alto, ancho) { document.getElementById(obj).style.backgroundPosition = alto + ' ' + ancho; }

function CambiarImagen(obj, ruta) { $get(obj).src = ruta; }
function IluminarTexto(Span, color) { try { $get(Span).style.color = color; } catch (Error) { } }

function MostrarPanel(Panel) { $get(Panel).style.display = 'block'; }
function PonerBlock(obj) { $get(obj).style.display = 'block'; }
function OcultarPanel(panel) { $get(panel).style.display = 'none'; }
function PonerOculto(obj) { $get(obj).style.display = 'none'; }

function HacerVisible(obj) { $get(obj).style.visibility = 'visible'; }
function HacerInvisible(obj) { $get(obj).style.visibility = 'hidden'; }

function MostraryOcultarRetardo(obj) { $get(obj).style.display = 'block'; setTimeout("PonerOculto('" + obj + "')", 5000); }

function MostrarCapa_y_OcultarOtra(capavisible, capaoculta) {
    try { $get(capaoculta).style.display = 'none'; } catch (Error) { }
    try { $get(capavisible).style.display = 'block'; } catch (Error) { }
}
function MostrarCapa(capavisible) {
    try {
        if ($get(capavisible).style.display != 'block') { $get(capavisible).style.display = 'block'; }
        else { $get(capavisible).style.display = 'none'; } 
    } catch (Error) { }
}

function bajar(oj) { window.scrollTo(0, oj); }
function MostrarOcultarCapa(Panel) { if ($get(Panel).style.display == 'block') { $get(Panel).style.display = 'none'; } else { $get(Panel).style.display = 'block'; } }
function MostrarOcultarPanel(Panel) { if ($get(Panel).style.display == 'block') { $get(Panel).style.display = 'none'; } else { $get(Panel).style.display = 'block'; } }
function MostrarOcultarPanelconCambiodeImagen(PanelVisible, PanelOculto, BotonVisible, BotonOculto, RutaON, RutaOFF)
{ $get(PanelVisible).style.display = 'block'; $get(PanelOculto).style.display = 'none'; $get(BotonVisible).src = RutaON; $get(BotonOculto).src = RutaOFF; }
function MostrarPaneles(Panel, Panel2, Boton, RutaON, RutaOFF) {
    if (($get(Panel).style.display == 'block') || ($get(Panel2).style.display == 'block')) {
        try
{ $get(Panel).style.display = 'none'; $get(Panel2).style.display = 'none'; $get(Boton).src = RutaOFF; }
        catch (Err) { }
    }
    else {
        try { $get(Panel).style.display = 'block'; $get(Boton).src = RutaON; }
        catch (Err) { }
    }
}
function MostrarOcultar3Objetos(obj1, obj2, obj3) {
    if ($get(obj1).style.display == 'block')
    { $get(obj1).style.display = 'none'; }
    else
    { $get(obj1).style.display = 'block'; }

    if ($get(obj2).style.display == 'block')
    { $get(obj2).style.display = 'none'; }
    else
    { $get(obj2).style.display = 'block'; }

    if ($get(obj3).style.display == 'block')
    { $get(obj3).style.display = 'none'; }
    else
    { $get(obj3).style.display = 'block'; }
}
function Mostrar3Objetos(obj1, obj2, obj3, estado) { $get(obj1).style.display = estado; $get(obj2).style.display = estado;try { $get(obj3).style.display = estado; } catch (Error) { }  }

function MostrarPanelconCambiodeImagen(Panel, Boton, RutaON, RutaOFF) {
    if ($get(Panel).style.display == 'block') {
        try
{ $get(Panel).style.display = 'none'; $get(Boton).src = RutaOFF; }
        catch (Err)
{ }
    }
    else {
        try
{ $get(Panel).style.display = 'block'; $get(Boton).src = RutaON; }
        catch (Err)
{ }
    }
}

function CopiarTextBox_a_otro(origen, destino) {
    try { $get(destino).value = $get(origen).value; } catch (Error) { }
}

function bloquear_caracteres(elEvento, elemento) { //Devuelve true o false

    var evento = elEvento || window.event;
    var codigoCaracter = evento.charCode || evento.keyCode;
    var caracter = String.fromCharCode(codigoCaracter);

    if (codigoCaracter == 32) {
        return false;
    } else {
        return true;
    }

    
}

//function HabilitarBoton(Boton) {BTNEnviar = $get(Boton); if (BTNEnviar.disable == false) { BTNEnviar.disabled = true; } else { BTNEnviar.disabled = false; }}

//function openPanel() { try { $find("Feles")._doOpen(); } catch (err) { } }


function cambiaFoco(cajadestino){var key = window.event.keyCode; if (key == 13)$get(cajadestino).focus();}

function IsNumeric(sText) {var ValidChars = "0123456789.";var IsNumber = true;var Char;for (i = 0; i < sText.length && IsNumber == true; i++) {Char = sText.charAt(i);if (ValidChars.indexOf(Char) == -1) {IsNumber = false;}}return IsNumber;}

function CountDown(year, m, d, obj) {
    var montharray = new Array("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
    var today = new Date()
    var todayy = today.getFullYear()
    var todaym = today.getMonth()
    var todayd = today.getDate()
    var todayh = today.getHours()
    var todaymin = today.getMinutes()
    var todaysec = today.getSeconds()
    var todaystring = montharray[todaym] + " " + todayd + ", " + todayy
    var paststring = montharray[m - 1] + " " + d + ", " + year
    var difference = (Math.round((Date.parse(paststring) - Date.parse(todaystring)) / (24 * 60 * 60 * 1000)) * 1)

    var Dias = difference - 1;
    var Horas = difference * 24;
    var Minutos = Horas * 60;
    var Segundos = Minutos * 60;
    var TiempoHoras = Horas - todayh;
    var TiempoHorasRestantes = (Horas - todayh) % 24;
    var TiempoMinutos = (Minutos - todaymin) % 60;
    var TiempoSegundos = (Segundos - todaysec) % 60;
    
    try {
        if (Dias == 0) {
            document.getElementById(obj).innerHTML = "<span class='hot'>"+TiempoHorasRestantes + ":" + TiempoMinutos + ":" + TiempoSegundos+"</span>";
        } else {
            if (Dias == 1) {
                document.getElementById(obj).innerHTML = "<span class='near'>"+Dias + "D " + TiempoHorasRestantes + ":" + TiempoMinutos + ":" + TiempoSegundos+"</span>";
            } else {
            document.getElementById(obj).innerHTML = "<span class='cold'>" + Dias + " Días</span>";
            }
        }
    } catch (Error) { }
    
    CountDown_Restante(year, m, d, obj);
}

function CountDown_Restante(year, m, d, obj) {
    setTimeout("CountDown(" + year + "," + m + "," + d + ",'" + obj + "')", 1000);
}


/****************/
/***** HOME *****/
/****************/

//-> Muestro / Oculto los divs de fabricantes
function iShow(obj) {$(obj).fade('in');}
function iHideFabricantes(modo) {for (i = 0; i < 200; i++) {try {$('H_Fabricantediv_' + i).fade(modo);} catch (Error) { break; }}}

function MuestraSubCatID_AutoCompletar(SubCatID) {

    try {
        if ($get('ctl00_ContentPlaceHolder1_EstoyEnBusqueda').value == "true") {
            GuardarCatid(SubCatID);
            Filtrar('');
            $get("searchbox_resultados").style.display = 'none';
            $get("H_searchbox_input").value = ''
            ActivarGoSw = false;
        }
    }
    catch (Error) {
        document.location.href = 'http://www.dmi.es/FRMBusquedaAvanzada.aspx?Subcatid=' + SubCatID;
    }

}

//////////////////////////////////////////////////////////////////////////////////////////
//////////////////////          COMPARADOR DE PRODUCTOS          /////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////
shortcut.add("Esc", function() { $get("searchbox_resultados").style.display = 'none'; $get("H_searchbox_input").value = ''; ActivarGoSw = false; });

function VerComparador() {
    Codcliente = $get('ctl00_CodClienteJS').value;
    var Productos = ProductosParaComparar('comparar', '');
    if (Productos == false) {
    } else {
        ConexionSW.VerComparador(Codcliente, CodigoUltimaSubcategoriaPinchada, Productos, Path_Imagenes, VerComparador_OK, VerComparador_FAIL);
    }
}

function VerComparadorRequest(Productos, CodSubCat) {
    Codcliente = $get('ctl00_CodClienteJS').value;
    if (Productos == false) {
    } else {
        ConexionSW.VerComparador(Codcliente, CodSubCat, Productos, Path_Imagenes, VerComparador_OK, VerComparador_FAIL);
    }
}

function VerComparador_OK(resultado) {
    PonerBlock('DIV_Comparador');
    $get('DIV_Comparador').innerHTML = resultado;
}

function VerComparador_FAIL(Error) {
}

function ProductosParaComparar(accion, quality) {

    var ProductIDCheckado = '';
    ProductsIDParaComparar = '';
    var CuantosSeleccionados = 0;

    //  1º) Recorro los checks
    //  2º) Si esta checkado, entro
    //  3º) Si es el primero, lo inserto sin ;
    //  4º) Si es el cuarto, le impido que coga mas
    //  5º) Control si no hay ninguno o solo 1 checkados

    //º1)
    for (i = 1; i < 1000; i++) {
        //2º)
        try {

            if ($get('CompararProducto' + i).checked == true) {

                if (quality == 'manuales' || quality == 'dmi') {
                    alert('Este producto no tiene habilitada la comparativa. Lamentamos las molestias.');
                    $get('CompararProducto' + i).checked = false;
                    return false;
                }

                ProductIDCheckado = $get('CompararProducto' + i).value;
                CuantosSeleccionados = ProductsIDParaComparar.split(";");
                //3º)
                if (ProductsIDParaComparar == '') {
                    ProductsIDParaComparar = ProductIDCheckado;
                } else {
                    //4º)
                    if (CuantosSeleccionados.length == 4) {
                        alert('Solo puedes seleccionar 4 productos para comparar');
                        $get('CompararProducto' + i).checked = false;
                        return false;
                    } else {
                        ProductsIDParaComparar = ProductsIDParaComparar + ';' + ProductIDCheckado;
                    }
                }
            } //Fin del if

        } catch (Error) { break; }

    } //Fin del for

    if (accion == 'comparar') {
        //5º)
        if (CuantosSeleccionados == 0 || CuantosSeleccionados.length < 1) {
            alert('Debes seleccionar al menos 2 productos para comparar');
            return false;
        } else {
            return ProductsIDParaComparar;
        }
    }
}

function SearchBoxObtenerProductos(NCat, catid) {
    var Cuantos = 0;
    var ProductosAcomparar = '';

    for (i = 0; i < 1000; i++) {
        try {
            if ($get('SB_chkcomparar_' + NCat + '_' + i).checked == true) {

                if (Cuantos > 4) {
                    alert('Solo puedes comparar 4 productos a la vez.');
                    break;
                } else {
                    Cuantos = Cuantos + 1;

                    if (ProductosAcomparar == '') {
                        ProductosAcomparar = $get('SB_chkcomparar_' + NCat + '_' + i).value;
                    } else {
                        ProductosAcomparar = ProductosAcomparar + ';' + $get('SB_chkcomparar_' + NCat + '_' + i).value;
                    }
                }
            }
        }
        catch (Error) { break; }
    }

    if (Cuantos == 0 || Cuantos == 1) {
        alert('Debes seleccionar al menos 2 productos para comparar.');
    } else {
        if (Cuantos > 4) {
            alert('Solo puedes comparar 4 productos a la vez.');} else {VerComparadorRequest(ProductosAcomparar, catid);
        }
    }

}


