function sleep(milliseconds) {
    var start = new Date().getTime();
    for (var i = 0; i < 1e7; i++) {
        if ((new Date().getTime() - start) > milliseconds){
            break;
        }
    }
}


function validarEmail(valor) {
    if (/^\w+([\.-ñ\+]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(valor)){
        //alert(”La dirección de email ” + valor + ” es correcta.”)
        return (true)
    } else {
        //alert(”La dirección de email es incorrecta.”);
        return (false);
    }
}

function str_replace(cadena, cambia_esto, por_esto) {
    return cadena.split(cambia_esto).join(por_esto);
}

function redondear(num)
{
    var original=parseFloat(num);
    if ((original*100%100)>=0.5){
        var result=Math.round(original*100)/100+0.01;
        return result;
    }
    result=Math.round(original*100)/100;
    return result;
}

function redondeo(cantidad, decimales) {
    var cantidad = parseFloat(cantidad);
    var decimales = parseFloat(decimales);
    decimales = (!decimales ? 2 : decimales);
    return Math.round(cantidad * Math.pow(10, decimales)) / Math.pow(10, decimales);
    
}



function valida_login(formulario, f_email){
    if (f_email.length > 0){
        if (f_email != formulario.username.value && formulario.username.value.length > 0 ){
            jAlert("El email introducido no coincide con el del pedido");
            return false;
        }

    }
    
    var resultado = true;
    var num_array = 2;
    var errores = new Array(num_array);
    if (formulario.username.value.length == 0){
        errores[0] = "Introduzca un nombre de usuario";
        resultado = false;
    }
    if (formulario.password.value.length == 0){
        errores[1] = "Introduzca una contraseña";
        resultado = false;
    }
    var errores_str = errores.toString();
    if (!resultado){
        jAlert(str_replace(errores_str, ',','\n'));
    }
    var mode = document.getElementById('id_mode').value;
    mode = 'login';
    return resultado;
}

function valida_promo(promotion, formulario){
    var resultado =true;
    var num_array = 1;
    var errores = new Array(num_array);

    if (promotion.value.length == 0){
        errores[0] = "Introduzca un código de promoción";
        resultado = false;
    }
    var errores_str = errores.toString();
    if (!resultado){
        jAlert(str_replace(errores_str, ',','\n'));
    }else{
        formulario.mode.value = 'promocode';
        formulario.submit();
    }
    
}

function valida_email_form(formulario){
    var resultado = true;
    var i = 0;
    var errores = new Array();
    if (formulario.email.value.length == 0){
        errores[i] = "Introduzca un email";
        i++;
        resultado = false;
    }else{
        var correcto = validarEmail(formulario.email.value);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
            resultado = false;
        }
    }
    var errores_str = errores.toString();

    if (errores == '' || errores == null){


        //formulario.submit();
        var urlpage = location.href;

            if (formulario.ptf.value == 'lnx'){
                window.open('/static/programa/thinkinphoto_x11.deb?utm_source=Enlaces_internos&utm_medium=Web&utm_campaign=Download');

            //location.href = '{{ MEDIA_URL }}/programa/customfoto_x11.deb';
            }else if (formulario.ptf == 'mac'){
                window.open('/static/programa/thinkinphoto_mac.dmg');
            }else{
                window.open('/static/programa/thinkinphoto_win.exe');
            }
        
        //formulario.submit();

        this.submit();
        window.parent.location.reload(true);
    //return true;
    //return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;

    }
    return false;
}

function validar_suggest(formulario){
    var resultado = true;
    var errores = new Array();
    var i = 0;
    if (formulario.asunto.value == 0){
        errores[i] = "Seleccione un asunto";
        i++;
        resultado = false;
    }

    if (formulario.mensaje.value.length == 0 || formulario.mensaje == null){
        errores[i] = "Introduza un mensaje";
        i++;
        resultado = false;
    }

    var errores_str = errores.toString();
        if (!resultado){
            jAlert(str_replace(errores_str, ',','\n'));
            return false;
        //alert(resultado);
        }else{
            resultado = true;
            return true;

        }

}

function validar_login_app(formulario){
    var resultado = true;
    var errores= new Array();

    var i = 0;
    if (formulario.name.value.length == 0 || formulario.name == null){
        errores[i] = "Introduzca un nombre";
        i++;
        resultado = false;
    }

    if (formulario.email.value.length == 0){
        errores[i] = "Introduzca un email";
        i++;
        resultado = false;
    }else{
        var correcto = validarEmail(formulario.email.value);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
            resultado = false;
        }
    }

    var errores_str = errores.toString();
        if (!resultado){
            jAlert(str_replace(errores_str, ',','\n'));
            return false;
        //alert(resultado);
        }else{
            resultado = true;
            return true;

        }


}

function valida_registro(formulario){
    
    var resultado = true;
    var errores = new Array();
    
    var i = 0;
    if (formulario.name.value.length == 0){
        errores[i] = "Introduzca un nombre";
        i++;
        resultado = false;
    }
    if (formulario.email.value.length == 0){
        errores[i] = "Introduzca un email";
        i++;
        resultado = false;
    }else{
        var correcto = validarEmail(formulario.email.value);
        if (correcto == false){
            errores[i] = "Introduzca un email correcto";
            i++;
            resultado = false;
        }
    }

    if (formulario.repemail.value.length == 0){
        errores[i] = "Introduzca una repetición de email";
        i++;
        resultado = false;
    }else{
        var correcto = validarEmail(formulario.repemail.value);
        if (correcto == false){
            errores[i] = "Introduzca una repetición de email correcto";
            i++;
            resultado = false;
        }
    }

    if (formulario.repemail.value != formulario.email.value){
        errores[i] = "Los emails no coinciden";
        i++;
        resultado = false;
    }
    var errores_str = errores.toString();

    if (errores == '' || errores == null){
                
                
        //formulario.submit();
        var urlpage = location.href;
        var result = urlpage.indexOf('thinkinphoto');
        if (result == -1){ //No es tip,es cuf
            if (formulario.radio1[0].checked){
                        
                var nuevaVentana = window.open('/static/programa/customfoto_x11.deb');
                
            }else if (formulario.radio1[1].checked){
                window.open('/static/programa/customfoto_mac.dmg');
            }else{
                window.open('/static/programa/customfoto_win32.exe');
            }

                    
        }else{
            if (formulario.radio1[0].checked){
                window.open('/static/programa/thinkinphoto_x11.deb');

            }else if (formulario.radio1[1].checked){
                window.open('/static/programa/thinkinphoto_mac.dmg');
            }else{
                window.open('/static/programa/thinkinphoto_win.exe');
            }
        }
        //formulario.submit();
        
        this.submit();
        window.parent.location.reload(true);
    //return true;
    //return true;

    }else{
        alert(str_replace(errores_str, ',','\n'));
        return false;
                
    }
    return false;
//return resultado;


}

function valida_todo(formulario){
    
    var resultado = true;
    //var num_array = 11;
    var errores = new Array();
    var acepto = document.getElementById('id_eleccion');
    var valor_unidades = document.getElementById('id_unidades_nuevo').value;    
    var unidades = document.getElementById('id_unidades').value;    
    unidades = valor_unidades;
    var i = 0;
    if (acepto.checked){
        if (formulario.envio[0].checked){
            if (formulario.address.value.length == 0){
                errores[i] = "Introduzca una direccion de envio";
                i++;
                resultado = false;
            }
            if (formulario.cp.value.length == 0){
                errores[i] = "Introduzca un código postal";
                i++;
                resultado = false;
            }
            if (formulario.town.value.length == 0){
                errores[i] = "Introduzca una localidad";
                i++;
                resultado = false;
            }
            if (formulario.province_envio.value.length == 0){
                errores[i] = "Introduzca una provincia";
                i++;
                resultado = false;
            }
        }
        if (formulario.name.value.length == 0){
            errores[i] = "Introduzca un nombre";
            i++;
            resultado = false;
        }
        if (formulario.surnames.value.length == 0){
            errores[i] = "Introduzca apellidos";
            i++;
            resultado = false;
        }
        if (formulario.mobile.value.length == 0){
            errores[i] = "Introduzca móvil";
            i++;
            resultado = false;
        }
        if (formulario.email.value.length == 0){
            errores[i] = "Introduzca email";
            i++;
            resultado = false;
        }

        /*var long_username = document.getElementById('id_username').value.length;
        var long_password = document.getElementById('id_password').value.length;
        if (long_username == 0 && long_password == 0){
            if (formulario.contrasena.value.length == 0){
                errores[i] = "Introduzca contraseña";
                i++;
                resultado = false;
            }
            if (formulario.confirm.value.length == 0){
                errores[i] = "Introduzca confirmación de la contraseña";
                i++;
                resultado = false;
            }
        }*/
        
        var errores_str = errores.toString();
        if (!resultado){
            jAlert(str_replace(errores_str, ',','\n'));
        //alert(resultado);
        }else{
            resultado = true;
            formulario.mode.value = 'todo';
            formulario.submit();
           /* jConfirm('Vamos a proceder a enviar tu pedido, una vez finalizado accederás a la pantalla de pago', 'Confirmar pedido', function(r) {
                //jAlert('Confirmed: ' + r, 'Confirmation Results');
                formulario.mode.value = 'todo';
                resultado = true;
                if (r){
                    formulario.submit();
                }

            });*/
        }

        return resultado;
    }else{
        jAlert("Debe aceptar las condiciones generales");
        return false;
    }
}

/*


                alert(1);
                formulario.mode.value = 'todo';
                resultado = true;
                alert(resultado);
*/

function calcular(){
    var seleccion_unidad = document.getElementById('id_unidades_nuevo').value;
    var unidad_sin_iva_1 = document.getElementById('unidad_sin_iva').innerHTML;
    var unidad_sin_iva_2 = str_replace(unidad_sin_iva_1, "€","");
    var unidad = parseFloat(unidad_sin_iva_2);
    var subtotal = document.getElementById('subtotal');
    var subtotal_valor = unidad * seleccion_unidad;
    subtotal_valor = parseFloat(subtotal_valor);
    subtotal.innerHTML = redondeo(subtotal_valor) + ' €';
    base_imponible = subtotal_valor;
    gastos_envio_show = document.getElementById('gastos-selected').style.display;
    if (gastos_envio_show != 'none'){
        var gastos = document.getElementById('gastos_envio').innerHTML;        
        var gastos_envio_1 = str_replace(gastos, "€","");
        var gastos_envio_1 = str_replace(gastos_envio_1, "+", "");
    }else{
        gastos_envio_1 = 0;
    }


    try {
        descuento = document.getElementById('promotion').innerHTML;
        if (descuento != 'none'){
            if (descuento.indexOf("%") > -1){
                descuento = str_replace(descuento, "-","");
                descuento = str_replace(descuento, "%","");
                descuento = parseFloat(descuento);
                descuento = (base_imponible * descuento) /100;
                base_imponible = base_imponible - descuento;
                
            }else{
                descuento = str_replace(descuento, "-","");
                descuento = str_replace(descuento, "€","");
                descuento = parseFloat(descuento);
                base_imponible = (base_imponible - descuento);
                

            }

            var descuentohtml = document.getElementById('descuento');
            descuentohtml.innerHTML = '-'+redondeo(descuento)+ ' €';

        }
    }
    catch (e){


    } finally {
        var total = document.getElementById('total');
        var iva_valor = document.getElementById('iva');
        var iva = base_imponible * 0.16;        
        var total_valor = base_imponible + parseFloat(gastos_envio_1);        
        var total_redondeado = redondeo(total_valor,2);
        total.innerHTML = total_redondeado + ' €';
    }
   
  
}
function cambio_unidades(seleccion){
    var unidades = document.getElementById('id_unidades');
    unidades.value = seleccion.value;
    calcular();
}

function cambioenvio(seleccion, error){
    var select = seleccion.value;
    if (select == 1){       
        $('#dir-imprenta').hide();
        $('#dir-cliente').show();
        select.checked = true;
        $('#gastos-selected').show();
        var gastos = document.getElementById('gastos-selected');
        calcular();
    }else{
        jConfirm('¿Esta seguro que desea venir a recogerlo?', 'Confirmation Dialog', function(r) {
            if (r == true){
                if (error){
                    jAlert(error);
                }
                $('#dir-cliente').hide();
                $('#dir-imprenta').show();
                select.checked = true;
                $('#gastos-selected').hide();
                var gastos = document.getElementById('gastos-selected');
                calcular();
            }else{
                seleccion.checked = false;
                nueva_seleccion = document.getElementById('id_envio_0');
                nueva_seleccion.checked = true;
            }
        });

    }

}


function up_login(){
    var div = document.getElementById('login-up');    
    if (div.style.display == "none"){
        div.style.display = "block";
    }else{
        div.style.display = "none";
    }
}

function enviar_paso(view_url){
    $.post(view_url, {}, function(data){
        //$('#masinfo').html(data);
        return false;
    });
}
