
function passwordStrength(password1, username, password2) {
	var shortPass = 1, badPass = 2, goodPass = 3, strongPass = 4, mismatch = 5, symbolSize = 0, natLog, score;

	// password 1 != password 2
	if ( (password1 != password2) && password2.length > 0)
		return mismatch

	//password < 4
	if ( password1.length < 4 )
		return shortPass

	//password1 == username
	if ( password1.toLowerCase() == username.toLowerCase() )
		return badPass;

	if ( password1.match(/[0-9]/) )
		symbolSize +=10;
	if ( password1.match(/[a-z]/) )
		symbolSize +=26;
	if ( password1.match(/[A-Z]/) )
		symbolSize +=26;
	if ( password1.match(/[^a-zA-Z0-9]/) )
		symbolSize +=31;

	natLog = Math.log( Math.pow(symbolSize, password1.length) );
	score = natLog / Math.LN2;

	if (score < 40 )
		return badPass

	if (score < 56 )
		return goodPass

    return strongPass;
}

function check_pass_strength() {
    var pass1 = jQuery('#pass1').val(), user = jQuery('#user_login').val(), pass2 = jQuery('#pass2').val(), strength;

    jQuery('#pass-strength-result').removeClass('short bad good strong');
    if ( ! pass1 ) {
        jQuery('#pass-strength-result').html( pwsL10n.empty );
        return;
    }

    strength = passwordStrength(pass1, user, pass2);

    switch ( strength ) {
        case 2:
            jQuery('#pass-strength-result').addClass('bad').html( pwsL10n['bad'] );
            break;
        case 3:
            jQuery('#pass-strength-result').addClass('good').html( pwsL10n['good'] );
            break;
        case 4:
            jQuery('#pass-strength-result').addClass('strong').html( pwsL10n['strong'] );
            break;
        case 5:
            jQuery('#pass-strength-result').addClass('short').html( pwsL10n['mismatch'] );
            break;
        default:
            jQuery('#pass-strength-result').addClass('short').html( pwsL10n['short'] );
    }
}


jQuery(document).ready(function(){
    
    jQuery('.inicio .solicitar a').click(function(e){
        
    });
    
    jQuery('form').html5form({
        
        async : false,
        responseDiv : '#respuesta',
        allBrowsers: true
        
    });

    jQuery('.inicio .solicitar form').submit(function(){

        jQuery.ajax({
            type: "POST",
            url: jQuery(".inicio .solicitar form").attr("action"),
            data: "ajax=true&page=" + jQuery('.inicio .solicitar form #page').attr("value")
                + "&nom=" + jQuery('.inicio .solicitar form #nom').attr("value")
                + "&mail=" + jQuery('.inicio .solicitar form #mail').attr("value")
                + "&telf=" + jQuery('.inicio .solicitar form #telf').attr("value"),
            beforeSend: function(){
                    jQuery('.inicio .solicitar form .exit').hide();
                    jQuery('.inicio .solicitar form .error').hide();
            },
            success: function(msg){
                if(msg == 'EXITO'){
                    jQuery('.inicio .solicitar form .exit').show();
                }else{
                    jQuery('.inicio .solicitar form .error').show();
                }
            }
        });
        
        return false;
        
    });

    jQuery('input.cantidad').each(function(index) {

        var cantidad = jQuery(this);

        cantidad.onChange(function(){

            jQuery.ajax({
                type: "POST",
                url: jQuery("#carrito").attr("action"),
                data: "ajax=true&action=cantidad&cantidad=" + cantidad.attr("value")
                    + "&prod=" + cantidad.parent().children('input.producto').attr("value")
                    + "&id=" + cantidad.parent().children('input.id').attr("value"),
                beforeSend: function(){
                    cantidad.parent().children('img.loader').show();
                },
                success: function(msg){
                    myData = JSON.parse(msg, function (key, value) {
                        if(key == 'subtotal'){
                            cantidad.parent().parent().children('td.subtotal').html(value);
                        }else if(key == 'total_iva'){
                            cantidad.parent().parent().parent().children('tr').children('td.total_iva').html(value);
                        }else if(key == 'final'){
                            cantidad.parent().parent().parent().children('tr').children('td.final').html(value);
                        }else if(key == 'total'){
                            cantidad.parent().parent().parent().children('tr').children('td.total').html(value);
                        }else if(key == 'gastos'){
                            cantidad.parent().parent().parent().children('tr').children('td.gastos').html(value);
                        }else if(key == 'final_descuento'){
                            cantidad.parent().parent().parent().children('tr').children('td.final_descuento').html(value);
                        }
                    });
                    cantidad.parent().children('img.loader').hide();
                }
            });

        });
    });

    jQuery('a.eliminar').click(function(e) {

        e.preventDefault();

        var cantidad = jQuery(this).parent().parent().parent().parent().children('td.cantidad');

        jQuery.ajax({
            type: "POST",
            url: jQuery("#carrito").attr("action"),
            data: "ajax=true&action=eliminar&prod=" + cantidad.children('input.producto').attr("value")
                + "&id=" + cantidad.children('input.id').attr("value"),
            beforeSend: function(){

            },
            success: function(msg){
                myData = JSON.parse(msg, function (key, value) {
                    if(key == 'total_iva'){
                        cantidad.parent().parent().children('tr').children('td.total_iva').html(value);
                    }else if(key == 'final'){
                        cantidad.parent().parent().children('tr').children('td.final').html(value);
                    }else if(key == 'total'){
                        cantidad.parent().parent().children('tr').children('td.total').html(value);
                    }else if(key == 'gastos'){
                        cantidad.parent().parent().children('tr').children('td.gastos').html(value);
                    }else if(key == 'final_descuento'){
                        cantidad.parent().parent().children('tr').children('td.final_descuento').html(value);
                    }
                });
                cantidad.parent().remove();
            }
        });
    });

    
    jQuery.ajax({
        type: "POST",
        url: icl_home,
        data: "ajax=true&action=anadir&prod=0",
        beforeSend: function(){

        },
        success: function(msg){
            myData = JSON.parse(msg, function (key, value) {
                if(key == 'prods'){
                    jQuery('#carrito p.prod span').html(value);
                    jQuery('#carrito .carro p').html(value);
                }else if(key == 'precio'){
                    jQuery('#carrito p.precio span').html(value);
                }
            });
        }
    });

    jQuery('a.anadir').click(function(e) {

        e.preventDefault();

        var link = jQuery(this);

        jQuery.ajax({
            type: "POST",
            url: link.attr('href'),
            data: "ajax=true&action=anadir&prod=" + link.parent().children('form').children('input.prod-id').attr("value"),
            beforeSend: function(){

            },
            success: function(msg){
                myData = JSON.parse(msg, function (key, value) {
                    if(key == 'prods'){
                        jQuery('#carrito p.prod span').html(value);
                        jQuery('#carrito .carro p').html(value);
                    }else if(key == 'precio'){
                        jQuery('#carrito p.precio span').html(value);
                    }
                });
            }
        });
    });
    

    jQuery("#recovery_pass").click(function(event){
        event.preventDefault();
        event.stopPropagation();
        jQuery("#lostpasswordform").toggle();
        var top = parseInt(jQuery(this).position().top) - 10;
        top = top + 'px';
        var left = parseInt(jQuery(this).position().left) +  parseInt(jQuery(this).width()) + 10;
        left = left + 'px';
        jQuery('#lostpasswordform').css('top', top).css('left', left)
    });

    jQuery('html').click(function() {
        jQuery("#lostpasswordform").hide();
    });

    jQuery('#lostpasswordform').click(function(event){
        event.stopPropagation();
    });


    jQuery('#lostpasswordform #user_login_recovery').focus(function() {
        if(jQuery(this).attr("value") == lostpass){
            jQuery(this).attr("value", "");
        }
    });

    jQuery('#lostpasswordform #user_login_recovery').blur(function() {
        if(jQuery(this).attr("value") == ""){
            jQuery(this).attr("value", lostpass);
        }
    });


    jQuery("#lostpasswordform").submit(function(){
        var ok = true;

        if(jQuery("input#user_login_recovery").attr("value") == ""){
            ok = false;
        }

        if(ok == false){
            alert("Por favor, rellena los campos");
            return false;
        }

        jQuery.ajax({
            type: "POST",
            url: jQuery("#lostpasswordform").attr('action'),
            data: "ajax=true&user_login=" + jQuery("input#user_login_recovery").attr("value"),
            beforeSend: function(){
                jQuery("#lostpasswordform p.img").show();
            },
            success: function(msg){
                if(msg == 'EXITO'){
                    jQuery("#lostpasswordform p.img").hide();
                    jQuery("#lostpasswordform p.success").show();
                }else{
                    jQuery("#lostpasswordform p.img").hide();
                    jQuery("#lostpasswordform p.error").show();
                }
            }
        });

        return false;

    });

    jQuery("#lostpasswordform p.error").click(function() {
        jQuery(this).hide();
    });

    jQuery("#lostpasswordform p.success").click(function() {
        jQuery(this).hide();
    });

    if(jQuery('#factura').is(':checked') == true){
        jQuery('#empresa').removeAttr('disabled').removeClass('disabled');
        jQuery('#cif').removeAttr('disabled').removeClass('disabled');
    }else{
        jQuery('#empresa').attr('disabled', 'disabled').addClass('disabled');
        jQuery('#cif').attr('disabled', 'disabled').addClass('disabled');
    }

    jQuery('#factura').click(function(e) {

        if(jQuery('#factura').is(':checked') == true){
            jQuery('#empresa').removeAttr('disabled').removeClass('disabled');
            jQuery('#cif').removeAttr('disabled').removeClass('disabled');
        }else{
            jQuery('#empresa').attr('disabled', 'disabled').addClass('disabled');
            jQuery('#cif').attr('disabled', 'disabled').addClass('disabled');
        }
        
        jQuery(':submit').each(function(index) {
            jQuery(this).unbind('click');
        });
        jQuery('form').html5form({

            async : false, // cancela el método de envío por defecto.
            responseDiv : '#respuesta', // define un contenedor para mostrar el resultado de la petición Ajax.
            allBrowsers: true

        });

    });


    jQuery('#pass1').val('').keyup( check_pass_strength );
    jQuery('#pass2').val('').keyup( check_pass_strength );


    jQuery('a.privacidad').click(function(event){
        event.stopPropagation();
        event.preventDefault();
        jQuery('.priv-content').toggle();
    });

    jQuery('a.close').click(function(event){
        event.preventDefault();
        jQuery('.priv-content').hide();
    });

    jQuery('.priv-content').click(function(event){
        event.stopPropagation();
    });

    jQuery('html').click(function() {
        jQuery(".priv-content").hide();
    });

    jQuery('a.ampliar').click(function(event){
        event.preventDefault();
        var id = jQuery(this).attr('id').substr(5);
        jQuery('a.ampliar').removeClass('active');
        jQuery(this).addClass('active');
        jQuery('a.grande').hide();
        jQuery('a.grande').css('margin-left', '0');
        var marginLeft = jQuery('.izq').width()
            - jQuery('.izq .block .miniaturas').width()
            - parseInt(jQuery('.izq .block .miniaturas').css('margin-right'))
            - jQuery('a#maxi-' + id).width();
        if(marginLeft > 0)
            jQuery('a#maxi-' + id).css('margin-left', parseInt(marginLeft/2));
        jQuery('a#maxi-' + id).fadeIn('fast');
    });
    
    
    $("a[rel=fancy]").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : ''
	});
    
    $("a.ampliar-ficha").fancybox({
		'transitionIn'		: 'none',
		'transitionOut'		: 'none',
		'titlePosition' 	: 'over',
		'titleFormat'       : ''
	});
    
    $('#referencia').change(function(e){
        if($("#referencia option:selected").val() != 0)
            document.location = $("#referencia option:selected").val()
    });
    
    $('#categoria').change(function(e){
        if($("#categoria option:selected").val() != 0)
            document.location = $("#categoria option:selected").val()
    });
    
    $('#precio-buscar').change(function(e){
        $('#buscar-form').submit();
    });

});


jQuery(window).load(function() {
        
    var marginLeft = jQuery('.izq').width()
        - jQuery('.izq .block .miniaturas').width()
        - parseInt(jQuery('.izq .block .miniaturas').css('margin-right'))
        - jQuery('a#maxi-0').width();
    if(marginLeft > 0)
        jQuery('a#maxi-0').css('margin-left', parseInt(marginLeft/2));
    
});

