var ListaProducto = new Array;
var porcentajeDescuento = 0;
const importe_iva = 0.18;
const total_iva = 1.18;

function getDescuento(numInserciones) {
    if (numInserciones>=52)
       return 25;
    else if (numInserciones>=26)
       return 15;
    else if (numInserciones>=13)
       return 10;
    else
       return 0;
}


function round_decimals(original_number, decimals) {
    var result1 = original_number * Math.pow(10, decimals);
    var result2 = Math.round(result1);
    var result3 = result2 / Math.pow(10, decimals);
    return (result3);
}


function thounsandPoints(valor) {
    var residual = valor.length % 3;
    if (residual==0) residual=3;

    var result = valor.substr(0,residual);
    for (var i=residual; i<valor.length; i+=3)
        result += '.' + valor.substr(i,3);

    return result;
}


function pad_with_zeros(rounded_value, decimal_places) {

    //Convertimos el numero a cadena
    var value_string = rounded_value.toString();
    
    //Buscamos el punto decimal
    var decimal_location = value_string.indexOf(".");

    //Hay punto?
    if (decimal_location == -1)
        {
        //No, entonces no tenemos ninguna cifra decimal
        decimal_part_length = 0;
        
        //Ponemos la coma si es que el numero de cifras decimales es positivo
        value_string = thounsandPoints(value_string) + (decimal_places > 0 ? "," : "");
        }
    else
        {
        //Si, entonces miramos el numero de cifras decimales que tenemos.
        decimal_part_length = value_string.length - decimal_location - 1;

        parteEntera = thounsandPoints(value_string.substring(0,decimal_location));
        partedecimal = value_string.substr(decimal_location+1,decimal_places);
        value_string = parteEntera + ',' + partedecimal;
        }
    
    //Calculemos el numero de cifras a cero que debemos incluir
    var pad_total = decimal_places - decimal_part_length;
    
    //Pad con 0s
    if (pad_total > 0)
        {
        for (var counter = 1; counter <= pad_total; counter++) 
            value_string += "0"
        }

    return value_string
}


function limpiaClasificado() {
    //Limpiamos espacios seguidos, retornos de carro, etc
    //Mayuscula al principio de la Frase.
    var miTexto = document.fPresupuesto.pTxt.value;
    if (miTexto) {
        //Separacion de palabras por comas, puntos, ...
        miTexto=miTexto.replace(/([,\.:])(\D)/gi,"$1 $2");
        //Ummmm ... puede ser que pase si ponen la separacion de comas mal
        miTexto=miTexto.replace(/\s([,\.:])\s/gi,"$1 ");
        //Evitamos: Tel:971971071
        miTexto=miTexto.replace(/(\w):(\d)/gi,"$1: $2");
        //quitamos guiones entre numeros y palabras. Evitamos trampas de la forma 2-habitaciones
        miTexto=miTexto.replace(/(\d)[_-](\w)/gi,"$1 $2");
        //Limpiamos espacios seguidos, retornos de carro, etc ...
        miTexto=miTexto.replace(/\s+/gi," ");

        //Contar los espacios en blanco en la cadena 2
        aPalabras = miTexto.split(" ");
        var palabras = aPalabras.length;
        if (aPalabras[palabras-1]=="") palabras -= 1;

        document.fPresupuesto.pTxt.value = miTexto;
    }
    else palabras = 0;

    if (palabras<10) palabras=10;

    //Mostramos palabras contadas.
    var palabrasBis = document.getElementById('numPalSpan');
    if (palabrasBis) palabrasBis.innerHTML = palabras;

    var modulaje = document.fPresupuesto.modulaje;
    if (modulaje) modulaje.value=palabras;

    recalculaPrecio();
}


function recalculaPrecio() {
    //Obtenemos la info del producto
    var producto = document.fPresupuesto.refProducto;

    //Obtenemos las inserciones
    var inserciones = parseInt(document.fPresupuesto.inserciones.value,10);
    if (isNaN(inserciones)) inserciones=0;

    //obtenemos el precio
    var precio = parseFloat(document.fPresupuesto.precio.value,10);
    if (isNaN(precio)) precio=0;

    //Obtenemos el modulaje, si no es fijo
    var modulaje=1;
    if ((producto.value!='') && (ListaProducto[producto.value]['modulosfijo']!='S'))
        {
        modulaje = parseInt(document.fPresupuesto.modulaje.value,10);
        if (isNaN(modulaje)) modulaje=0;
        }

    //Calculamos el importe bruto (y redondeamos).
    var importeBruto = round_decimals(modulaje * inserciones * precio,2);

    //calculo del recargo. Hay que tener en cuenta si el producto permite tintas.
    var importeRecargo = 0;
    if ((producto.value!='') && (ListaProducto[producto.value]['permitetintas']=='S'))
        {
        var importeRecargo = round_decimals(document.fPresupuesto.tintas.value*importeBruto/100,2);
        var tdImporteRecargo = document.getElementById('tdImporteRecargo');
        tdImporteRecargo.innerHTML = pad_with_zeros(importeRecargo,2);
        }

    //Faltan los descuentos
    var importeDescuento = 0;
    if ((producto.value!='') && (ListaProducto[producto.value]['permitedescuento']=='S'))
    	importeDescuento = round_decimals((importeBruto+importeRecargo) * porcentajeDescuento / 100,2);

    var tdImporteDescuento = document.getElementById('tdImporteDescuento');
    tdImporteDescuento.innerHTML = pad_with_zeros(importeDescuento,2);

    //Mostramos base imponible
    var base = round_decimals(importeBruto + importeRecargo - importeDescuento, 2);
    var tdImporteBaseImponible = document.getElementById('tdImporteBaseImponible');
    tdImporteBaseImponible.innerHTML = pad_with_zeros(base,2);

    //Mostramos importe IVA
    var tdImporteIVA = document.getElementById('tdImporteIVA');
    tdImporteIVA.innerHTML = pad_with_zeros(round_decimals(base*importe_iva, 2),2);

    //Mostramos total
    var tdImporteTotal = document.getElementById('tdImporteTotal');
    tdImporteTotal.innerHTML = pad_with_zeros(round_decimals(base*total_iva, 2),2);
}


function toggleRecargos() {
    var porcentajeRecargo = document.fPresupuesto.tintas.value;

    var tdRecargo = document.getElementById('tdRecargo');
    tdRecargo.innerHTML = porcentajeRecargo + '%';

    recalculaPrecio();
}


function toggleDescuentos() {
    var inserciones = parseInt(document.fPresupuesto.inserciones.value,10);
    if (isNaN(inserciones)) inserciones=0;

    var producto = document.fPresupuesto.refProducto;
    var permitedescuento = document.fPresupuesto.permitedescuento;
    
    if ((producto.value!='') && (ListaProducto[producto.value]['permitedescuento']=='S')) {
        porcentajeDescuento = getDescuento(inserciones);
	permitedescuento.value = 'S';
    }
    else {
        porcentajeDescuento = 0;
	permitedescuento.value = 'N';
    }

    //Mostramos ocultamos la fila de porcentaje de descuento
    var trDescuento = document.getElementById('trDescuento');
    if (trDescuento)
        {
        if (porcentajeDescuento>0)
            {
            if (document.all)
                {
                trDescuento.style.display = 'inline';
                }
            else
                {
                trDescuento.style.display = 'table-row';
                }
            }
        else
            {
            trDescuento.style.display = 'none';
            }
        }
    //Mostramos ocultamos la fila de importe  de descuento
    var trImporteDescuento = document.getElementById('trImporteDescuento');
    trImporteDescuento.style.display = trDescuento.style.display;

    //Ponemos el descuento
    var tdDescuento = document.getElementById('tdDescuento');
    tdDescuento.innerHTML = porcentajeDescuento+'%';

    recalculaPrecio();
}


function arrangeForm() {
    if (document.fPresupuesto) {
    var pantalla = document.fPresupuesto.pantalla;
    if (pantalla.value=='producto')
        {
        var product = document.fPresupuesto.refProducto;
        if ( (!isNaN(product.value)) && (typeof(ListaProducto[product.value]) !='undefined')  )
            resetPointer(product.value);

        toggleDescuentos();
        }
    else if (pantalla.value=='dias')
        {
        printDayList();
        }   
    }
}


function resetPointer(theRowNum) {
    var product = document.fPresupuesto.refProducto;

    if ((!isNaN(product.value)) && (typeof(ListaProducto[product.value]) !='undefined') ) 
        {
        document.getElementById('trProducto'+product.value).className = 'defaultProducto';
        //ListaProducto[product.value]['fila'].className = 'defaultProducto';
        var checkOff = document.getElementById('Check-'+product.value);
        if (checkOff) checkOff.checked=false;
        }

    if (product) product.value=theRowNum;

    toggleDescuentos();

    var checkOn = document.getElementById('Check-'+theRowNum);
    if (checkOn) checkOn.checked=true;

    //Tipo de modulaje!
    var tipoModulaje = document.fPresupuesto.modulosfijo;
    if (tipoModulaje) tipoModulaje.value = ListaProducto[theRowNum]['modulosfijo'];

    //Si el modulaje es fijo ... lo metemos a 1
    if ((ListaProducto[theRowNum]['modulosfijo']=='S') && (document.fPresupuesto.modulaje.value==''))
            document.fPresupuesto.modulaje.value=1;

    //Ponemos el precio
    document.fPresupuesto.precio.value = ListaProducto[theRowNum]['precio'];
    var tdPrecio = document.getElementById('tdPrecio');
    tdPrecio.innerHTML = pad_with_zeros(ListaProducto[theRowNum]['precio'],2);

    var modulaje = document.getElementById('trModulaje');
    if (modulaje)
        {
        if (ListaProducto[theRowNum]['modulosfijo']=='N') 
            {
            if (document.all)
                modulaje.style.display = 'inline';
            else
                modulaje.style.display = 'table-row';
            }
        else 
            {
            modulaje.style.display = 'none';
            }
        }
    else 
        {
        alert('No puedo encontrat trModulaje');
        }


    var palabras = document.getElementById('trPalabras');
    var trTextoClasificado = document.getElementById('trTextoClasificado');
    var menuFicheros = document.getElementById('menuficheros');
    if (trTextoClasificado) {
        if (ListaProducto[theRowNum]['modulosfijo']=='P')
            {
            if (document.all)
                {
                palabras.style.display = 'inline';
                trTextoClasificado.style.display = 'inline';
                }
            else
                {
                palabras.style.display = 'table-row';
                trTextoClasificado.style.display = 'table-row';
                }
            
            menuFicheros.style.display = 'none';
            limpiaClasificado();
            }
        else
            {
            palabras.style.display = 'none';
            trTextoClasificado.style.display = 'none';
            menuFicheros.style.display = 'inline';
            }
    }

    var trTintas = document.getElementById('trTintas');
    if (ListaProducto[theRowNum]['permitetintas']=='S') 
        {
        if (document.all)
            trTintas.style.display = 'inline';
        else
            trTintas.style.display = 'table-row';
        }
    else
        {
        trTintas.style.display = 'none';
        }

    var recargo = document.getElementById('trRecargo');
    if (recargo) recargo.style.display = trTintas.style.display;

    recargo = document.getElementById('trImporteRecargo');
    if (recargo) recargo.style.display = trTintas.style.display;

    recalculaPrecio();
    //var theForm = findObj('fPresupuesto');
    //if (theForm) theForm.submit();
}


function setPointer(theRow, theRowNum, theAction)
{
    var currentStyle = null;
    var newStyle     = null;

    currentStyle = theRow.className;
    var product = findObj('refProducto').value;
    

    // 4. Defines the new color
    // 4.1 Current color is the default one
    if (currentStyle == '' || currentStyle.toLowerCase() == 'defaultproducto') {
        if (theAction == 'over') 
            newStyle              = 'pointerProducto';
        else if (theAction == 'click') {
            newStyle = 'markProducto';
            resetPointer(theRowNum);
        }
    }
    // 4.1.2 Current color is the pointer one
    else if (currentStyle.toLowerCase() == 'pointerproducto' && (theRowNum!=product)) {
        if (theAction == 'out') {
            newStyle              = 'defaultProducto';
        }
        else if (theAction == 'click') {
            newStyle              = 'markProducto';
            //checkPresupuestoModulos2(theRowNum);
            resetPointer(theRowNum);
        }
    }
    // 4.1.3 Current color is the marker one
 /*   else if (currentStyle.toLowerCase() == 'markproducto') {
        if (theAction == 'click') {
            newStyle  = 'pointerProducto';
            resetPointer( theRowNum);
        }
    } // end 4
*/
    // 5. Sets the new color...
    if (newStyle) theRow.className= newStyle;

    return true;

}


function LimpiaDias() {
    var dias  = findObj('dias');
    if (dias) dias.value='';

    var form = findObj('fPresupuesto');
    if (form) form.submit();
}


//Establece el tipo de publicidad: General/Calsificados
function setTipo(aTipo) {
    document.fPresupuesto.tipo.value=aTipo;
    document.fPresupuesto.pantalla.value='producto';
    document.fPresupuesto.submit();
}

