// Avoid `console` errors in browsers that lack a console.
(function () {
    var method;
    var noop = function () {};
    var methods = [
        'assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error',
        'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log',
        'markTimeline', 'profile', 'profileEnd', 'table', 'time', 'timeEnd',
        'timeStamp', 'trace', 'warn'
    ];
    var length = methods.length;
    var console = (window.console = window.console || {});

    while (length--) {
        method = methods[length];

        // Only stub undefined methods.
        if (!console[method]) {
            console[method] = noop;
        }
    }
}());

// Place any jQuery/helper plugins in here.
/*
(function() {
  $('a[data-aspm]').each(function() {
    var aSplit = $(this).attr('data-aspm').split('#');
    if(aSplit.length != 2) return true;
    $(this).text(aSplit[1]+'@'+aSplit[0]);
    $(this).attr('href', "mailto:"+aSplit[1]+'@'+aSplit[0]);
  });
}());*/
(function () {
    $("a[data-aspm]").each(function () {
        var e = $(this).attr("data-aspm").split("#");
        if (e.length != 2) return true;
        $(this).text(e[1] + "@" + e[0]);
        $(this).attr("href", "mailto:" + e[1] + "@" + e[0])
    })
})();

/**
 * jquery.matchHeight-min.js v0.5.2
 * http://brm.io/jquery-match-height/
 * License: MIT
 */
(function (b) {
    b.fn.matchHeight = function (a) {
        if ("remove" === a) {
            var d = this;
            this.css("height", "");
            b.each(b.fn.matchHeight._groups, function (b, a) {
                a.elements = a.elements.not(d)
            });
            return this
        }
        if (1 >= this.length) return this;
        a = "undefined" !== typeof a ? a : !0;
        b.fn.matchHeight._groups.push({
            elements: this,
            byRow: a
        });
        b.fn.matchHeight._apply(this, a);
        return this
    };
    b.fn.matchHeight._apply = function (a, d) {
        var c = b(a),
            e = [c];
        d && (c.css({
            display: "block",
            "padding-top": "0",
            "padding-bottom": "0",
            "border-top-width": "0",
            "border-bottom-width": "0",
            height: "100px"
        }), e = k(c), c.css({
            display: "",
            "padding-top": "",
            "padding-bottom": "",
            "border-top-width": "",
            "border-bottom-width": "",
            height: ""
        }));
        b.each(e, function (a, c) {
            var d = b(c),
                e = 0;
            d.each(function () {
                var a = b(this);
                a.css({
                    display: "block",
                    height: ""
                });
                a.outerHeight(!1) > e && (e = a.outerHeight(!1));
                a.css({
                    display: ""
                })
            });
            d.each(function () {
                var a = b(this),
                    c = 0;
                "border-box" !== a.css("box-sizing") && (c += g(a.css("border-top-width")) + g(a.css("border-bottom-width")), c += g(a.css("padding-top")) + g(a.css("padding-bottom")));
                a.css("height", e - c)
            })
        });
        return this
    };
    b.fn.matchHeight._applyDataApi = function () {
        var a = {};
        b("[data-match-height], [data-mh]").each(function () {
            var d = b(this),
                c = d.attr("data-match-height");
            a[c] = c in a ? a[c].add(d) : d
        });
        b.each(a, function () {
            this.matchHeight(!0)
        })
    };
    b.fn.matchHeight._groups = [];
    b.fn.matchHeight._throttle = 80;
    var h = -1,
        f = -1;
    b.fn.matchHeight._update = function (a) {
        if (a && "resize" === a.type) {
            a = b(window).width();
            if (a === h) return;
            h = a
        } - 1 === f && (f = setTimeout(function () {
            b.each(b.fn.matchHeight._groups, function () {
                b.fn.matchHeight._apply(this.elements,
                    this.byRow)
            });
            f = -1
        }, b.fn.matchHeight._throttle))
    };
    b(b.fn.matchHeight._applyDataApi);
    b(window).bind("load resize orientationchange", b.fn.matchHeight._update);
    var k = function (a) {
            var d = null,
                c = [];
            b(a).each(function () {
                var a = b(this),
                    f = a.offset().top - g(a.css("margin-top")),
                    h = 0 < c.length ? c[c.length - 1] : null;
                null === h ? c.push(a) : 1 >= Math.floor(Math.abs(d - f)) ? c[c.length - 1] = h.add(a) : c.push(a);
                d = f
            });
            return c
        },
        g = function (a) {
            return parseFloat(a) || 0
        }
})(jQuery);


$("#ord_name").bind("change keyup", function () {
    if ($('#checkfactura').prop("checked")) {

        $('#eres_cliente input').prop('required', true);
        $("#fac_address").val($("#ord_address").val());
        $("#fac_pcode").val($("#ord_pcode").val());
        $("#fac_city").val($("#ord_city").val());
        $("#fac_name").val($("#ord_name").val());

    } else {
        $('#eres_cliente input').prop('required', false);
        $("#fac_address").val("");
        $("#fac_pcode").val("");
        $("#fac_city").val("");
        $("#fac_name").val("");
    }
});


$(document).ready(function () {


    if ($('#checkregistrarse').prop("checked")) {
        $('#eres_registrado input').prop('required', true);
    } else {
        $('#eres_registrado input').prop('required', false);

    }

    if ($('#checkfactura').prop("checked")) {
        $('#eres_cliente input').prop('required', true);
    } else {

        $("#fac_address").val("");
        $("#fac_pcode").val("");
        $("#fac_city").val("");
        $("#fac_name").val("");

        $('#eres_cliente input').prop('required', false);
    }


    $(".accordion .titulo_faq:first").addClass("active");
    $(".accordion .desarrollo:not(:first)").hide();




    $(".accordion .titulo_faq").click(function () {
        $(this).next(".desarrollo").slideToggle("slow").siblings(".desarrollo:visible").slideUp("slow");
        $(this).toggleClass("active");
        $(this).siblings(".titulo").removeClass("active");

    });

    $('#checkfactura').click(function () {

        if ($('#checkfactura').prop("checked")) {

            $('#eres_cliente input').prop('required', true);
            $("#fac_address").val($("#ord_address").val());
            $("#fac_pcode").val($("#ord_pcode").val());
            $("#fac_city").val($("#ord_city").val());
            $("#fac_name").val($("#ord_name").val());

        } else {
            $('#eres_cliente input').prop('required', false);
            $("#fac_address").val("");
            $("#fac_pcode").val("");
            $("#fac_city").val("");
            $("#fac_name").val("");
        }
        $('#eres_cliente').toggle("slow");

    });

    $('#checkregistrarse').click(function () {

        if ($('#checkregistrarse').prop("checked")) {
            $('#eres_registrado input').prop('required', true);
        } else {

            $('#eres_registrado input').prop('required', false);

        }

        $('#eres_registrado').toggle("slow");
    });

    $('#formIdentificarse').click(function () {
        $('#login').val($("#log").val());
        $('#pass').val($("#pass1").val());
        $("#Formlogin").submit();
    });


    if ($('#checkfactura').prop("checked")) $("#eres_cliente").css("display", "block");
    if ($('#checkregistrarse').prop("checked")) $("#eres_registrado").css("display", "block");



    // Show Menu Smooth
    $('.dropdown').hover(function () {
        $(this).find('.dropdown-menu').first().stop(true, true).fadeIn(200)
    }, function () {
        $(this).find('.dropdown-menu').first().stop(true, true).fadeOut(200)
    });

    $('.topheadrow .dropdown ul li').click(function () {
        $(this).parent().prev('a').html($(this).text());
        $(".dropdown ul").hide();
    });



    $("#ord_pcode").change(function () {
        $.post("select_poblacion_cp.php", {
            id: $(this).val()
        }, function (data) {
            $("#poblacion_select").html(data);
        })
        $.post("select_provincia_cp.php", {
            id: $(this).val()
        }, function (data) {
            $("#provincia_select").html(data);
        })
    });

    $("#ord_pcode").on("change keyup blur input", function () {

        if ($("#ord_pcode").val() != '') {
            $.post("select_poblacion_cp.php", {
                id: $(this).val()
            }, function (data) {
                $("#poblacion_select").html(data);
            })
            $.post("select_provincia_cp.php", {
                id: $(this).val()
            }, function (data) {
                $("#provincia_select").html(data);
            })
        }

    });

    $("#fac_pcode").change(function () {
        $.post("select_poblacion_cp.php", {
            id: $(this).val()
        }, function (data) {
            $("#poblacion_select_fac").html(data);
        })
    });


    $('a.btnPedidoDesplegar').click(function () {
        var pedido = $(this).attr('data-url');
        $(pedido).slideToggle("slow");
        return false;
    });

    $('a.btnSearch').click(function () {
        $(".form-buscador-movil").css("display", "block");
        return false;
    });

    $('a.btnCloseForm').click(function () {
        $(".form-buscador-movil").css("display", "none");
        return false;
    });


    $('.btnIncrementar').click(function () {
        var id = $(this).attr("id");
        var valor = $(id).val();
        $(id).val(parseInt(valor) + 1);
        // $("#basket").submit();

        $.ajax({ // create an AJAX call...
            data: $('form#basket').serialize(), // get the form data
            type: "POST", // GET or POST
            url: "basket_ajax.php?bktop=3", // the file to call
            success: function (response) { // on success..
                recargar("resumen_cesta_ajax.php", "#resumen-cesta");
                $('#cesta_compra').html(response);

            }
        });


        return false;

    });

    $('.btnDisminuir').click(function () {
        var id = $(this).attr("id");
        var valor = $(id).val();
        if (valor > 0) $(id).val(parseInt(valor) - 1);
        //$("#basket").submit();
        //

        $.ajax({ // create an AJAX call...
            data: $('form#basket').serialize(), // get the form data
            type: "POST", // GET or POST
            url: "basket_ajax.php?bktop=3", // the file to call
            success: function (response) { // on success..
                recargar("resumen_cesta_ajax.php", "#resumen-cesta");
                $('#cesta_compra').html(response);


            }
        });

        return false;

    });



});

function playPause() {
    if (myVideo.paused) {
        myVideo.play();
    } else
        myVideo.pause();
}




var $contactForm = $('#inscribirseForm');

$contactForm.on('submit', function (ev) {
    ev.preventDefault();
    $.ajax({
        url: "form-registro-email.php",
        type: 'POST',
        data: $contactForm.serialize(),
        success: function (data) {
            if (data == "true") {
                $("#imageOK").show().delay(1000).fadeOut();
                $("#email").val("");
            }
            if (data == "false") {
                alert('El correo ' + $("#email").val() + ' ya se encuentra en nuestra base de datos');
            }
        }
    });
});


// JavaScript Document
function recargar(pag, div) {
    $.ajax({
        type: 'GET',
        url: pag,
        success: function (msg) {
            $(div).html(msg);
        }
    });

}

function cargaURL(codiproducte, id) {
    var val2;
    var val;
    //val = document.getElementById('tam_id').value;

    if ((document.getElementById('tam_id')) != null) val = document.getElementById('tam_id').value;
    if ((document.getElementById('op_id')) != null) val2 = document.getElementById('op_id').value;

    var d = new Date();
    var time = d.getMilliseconds();
    recargar('cargar_precio.php?art_id=' + codiproducte + '&tam_id=' + val + '&op_id=' + val2 + '&time=' + time, id);
}

function cargaURL1(codiproducte, id) {

    var val2;
    var val;
    //val = document.getElementById('tam_id').value;

    if ((document.getElementById('tam_id')) != null) val = document.getElementById('tam_id').value;

    var d = new Date();
    var time = d.getMilliseconds();
    recargar('cargar_precio_popup.php?art_id=' + codiproducte + '&tam_id=' + val + '&time=' + time, id);
}

$(".tamano_radio").click(function () {
    var valor = $(this).val();
    recargar('cargar_precio_popup.php?tam_id=' + valor, "#cambiar_precio1");
});

function gastosEnvio(total, id) {

    $("#Portes").css("border", "1px solid #BEBAB4");


    val = document.getElementById('Portes').value;

    var d = new Date();
    var time = d.getMilliseconds();
    recargar('gastosenvio.php?total_price=' + total + '&Portes=' + val + '&time=' + time, id);
}



function incrementar() {
    var valor = $("#art_stock1").val();

    var incrementar = parseInt(valor) + 1;

    $("#art_stock1").val(incrementar);
    $("#art_stock").val(incrementar);

}

function disminuir() {
    var valor = $("#art_stock1").val();

    var incrementar = parseInt(valor) - 1;

    if (incrementar < 1) incrementar = 1;

    $("#art_stock1").val(incrementar);
    $("#art_stock").val(incrementar);

}

$('.btn-number').click(function (e) {


    e.preventDefault();

    fieldName = $(this).attr('data-field');


    type = $(this).attr('data-type');
    var input = $("." + fieldName);

    var currentVal = parseInt(input.val());

    if (!isNaN(currentVal)) {
        if (type == 'minus') {

            if (currentVal > 1) {
                input.val(currentVal - 1).change();
            }
            if (parseInt(input.val()) == 1) {
                //$(this).attr('disabled', true);
            }

        } else if (type == 'plus') {

            if (currentVal < 99999) {

                input.val(currentVal + 1).change();
            }
            if (parseInt(input.val()) == 99999) {
                $(this).attr('disabled', true);
            }

        }
    } else {
        input.val(0);
    }

    return false;
});
$('.input-number').focusin(function () {
    $(this).data('oldValue', $(this).val());
});
$('.input-number').change(function () {

    minValue = 1;
    maxValue = 999;
    valueCurrent = parseInt($(this).val());

    name = $(this).attr('name');
    if (valueCurrent >= minValue) {
        $(".btn-number[data-type='minus'][data-field='" + name + "']").removeAttr('disabled')
    } else {
        alert('Sorry, the minimum value was reached');
        $(this).val($(this).data('oldValue'));
    }
    if (valueCurrent <= maxValue) {
        $(".btn-number[data-type='plus'][data-field='" + name + "']").removeAttr('disabled')
    } else {
        alert('Sorry, the maximum value was reached');
        $(this).val($(this).data('oldValue'));
    }
});


$(".tamano_radio1").click(function () {

    var val = $(this).val();
    recargar('cargar_precio.php?tam_id=' + val, "#cambiar_precio");

});

/*
$("#menu-toggle-2").click(function () {

    var height = $('body').height();

    var position = $('.navbar').offset();

    $('.navbar').height(height);

    var selected = $(this).hasClass('slide-active');

    if (selected) {
        jQuery('#menu-toggle-2 .fa').removeClass("fa-times").addClass("fa-bars");
        jQuery('.cover').hide();
    } else {
        jQuery('#menu-toggle-2 .fa').removeClass("fa-bars").addClass("fa-times");
        jQuery('.cover').show();
    }


    $('.navbar').stop().animate({
        left: selected ? '-220px' : '0px'
    });

    $('#menu-toggle-2').stop().animate({
        left: selected ? '0px' : '215px'
    });

    $(this).toggleClass('slide-active', !selected);

    return false;

});
*/

jQuery("button.closeMenu").click(function(){
  jQuery("#menu-toggle-2").trigger("click");
})
jQuery(".btnshow").click(function(){
  jQuery(".description-categoria .panel").css("max-height","100%");
  jQuery(this).addClass("hide");
  jQuery(".btnhide").removeClass("hide");
  return false;
});
jQuery(".btnhide").click(function(){
  jQuery(".description-categoria .panel").css("max-height","50px");
  jQuery(this).addClass("hide");
  jQuery(".btnshow").removeClass("hide");
  return false;
});


jQuery.event.special.scrolldelta = {
    // from http://learn.jquery.com/events/event-extensions/
    delegateType: "scroll",
    bindType: "scroll",
    handle: function (event) {
        var handleObj = event.handleObj;
        var targetData = jQuery.data(event.target);
        var ret = null;
        var elem = event.target;
        var isDoc = elem === document;
        var oldTop = targetData.top || 0;
        targetData.top = isDoc ? elem.documentElement.scrollTop + elem.body.scrollTop : elem.scrollTop;
        event.scrollTopDelta = targetData.top - oldTop;
        event.scrollTop = targetData.top;
        event.type = handleObj.origType;
        ret = handleObj.handler.apply(this, arguments);
        event.type = handleObj.type;
        return ret;
    }
};


if (jQuery(window).width() > 1023) {
    jQuery(document).ready(function () {
        var top = jQuery(".izquierda .navbar").offset().top;
        var width = jQuery(".izquierda").width();
        var position = jQuery(".lst-productos").position();
        var current = 0;


        jQuery(".subcategoria").width(jQuery(".lst-productos").width() + 33);
        jQuery(".subcategoria").css("top", position.top);
        jQuery(".subcategoria").css("left", position.left - 18);

        jQuery(window).on('scrolldelta', function (e) {
            var topScroll = e.scrollTop;
            var topDelta = e.scrollTopDelta;

            var y = jQuery(this).scrollTop();
            jQuery(".subcategoria").css("top", position.top - y);


            if (y >= top) {
                jQuery(".subcategoria").css("top", -1);
                jQuery(".izquierda .navbar").css("position", "fixed");
                jQuery(".izquierda .navbar").css("width", width);
                jQuery(".izquierda .navbar").css("top", -1);
                jQuery(".resumen-compra").width(jQuery(".lst-productos").width());
                jQuery(".resumen-compra").addClass("fixed");



                var fixed_position = $(".izquierda .navbar").offset().top;
                var fixed_height = $(".izquierda .navbar").height();

                var toCross_position = $("#pie").offset().top;
                var toCross_height = $("#pie").height();


                if (fixed_position + fixed_height + 60 < toCross_position) {
                    current = 0;

                } else {
                    jQuery(".izquierda .navbar").css("top", current);
                    current -= topDelta;
                }

            } else {
                jQuery(".izquierda .navbar").css("position", "relative");
                jQuery(".izquierda .navbar").css("width", "100%");
                jQuery(".resumen-compra").removeClass("fixed");
            }
        });
    });
}




window.onresize = function () {
    //var current = jQuery(".izquierda .navbar").offset().top;

    if (jQuery(window).width() > 1023) {
        var top = jQuery(".izquierda .navbar").offset().top;
        var width = jQuery(".izquierda").width();
        var position = jQuery(".lst-productos").position();


        jQuery(".subcategoria").width(jQuery(".lst-productos").width() + 33);
        jQuery(".subcategoria").css("top", position.top);
        jQuery(".subcategoria").css("left", position.left - 18);


        jQuery(window).on('scrolldelta', function (e) {
            var topScroll = e.scrollTop;
            var topDelta = e.scrollTopDelta;

            var y = jQuery(this).scrollTop();
            jQuery(".subcategoria").css("top", position.top - y);

            if (y >= top) {
                jQuery(".subcategoria").css("top", -1);
                jQuery(".izquierda .navbar").css("position", "fixed");
                jQuery(".izquierda .navbar").css("width", width);
                jQuery(".izquierda .navbar").css("top", -1);
                jQuery(".resumen-compra").width(jQuery(".lst-productos").width());
                jQuery(".resumen-compra").addClass("fixed");

                var fixed_position = $(".izquierda .navbar").offset().top;
                var fixed_height = $(".izquierda .navbar").height();

                var toCross_position = $("#pie").offset().top;
                var toCross_height = $("#pie").height();


                if (fixed_position + fixed_height + 60 < toCross_position) {
                    current = 0;

                } else {
                    jQuery(".izquierda .navbar").css("top", current);
                    current -= topDelta;
                }


            } else {
                jQuery(".izquierda .navbar").css("position", "relative");
                jQuery(".izquierda .navbar").css("width", "100%");
                jQuery(".resumen-compra").removeClass("fixed");
            }
        });
    }else{
        jQuery(".izquierda .navbar").css("width", "auto");
        jQuery(".izquierda .navbar").css("top", 0);

    }
}
var end = 0;

jQuery(window).scroll(function (e) {

    //Not always the pos == h statement is verified, expecially on mobile devices, that's why a 300px of margin are assumed.
    if (
        (jQuery(window).scrollTop() + jQuery(window).height() >= jQuery(document).height() - 300)
        ||
        (jQuery(window).scrollTop() >= jQuery("#scroll-container").height())
    )
    {
        var url = jQuery("a.btnCargarMas:last").attr("data-url");
        var start = jQuery("a.btnCargarMas:last").attr("data-start");


        $("a.btnCargarMas:last").remove();

        if (url != undefined) $.post(url, {
            id: jQuery("a.btnCargarMas:last").val()
        }, function (data) {
            jQuery('#scroll-container').append(data).fadeIn(900);
        })

    }
});


$(window).scroll(function () {


});




if (jQuery(window).width() < 768) {

    jQuery('a.submenu').click(function () {
        var $this = jQuery(this);
        //jQuery('.subcategoria').slideUp();
        //jQuery('.submenu i').removeClass("fa-angle-up").removeClass("fa-angle-down").addClass("fa-angle-down");
        jQuery(this).next().css("display", "block");
        return false;
    });
    jQuery('a.close').click(function () {
        var $this = jQuery(this);
        //jQuery('.subcategoria').slideUp();
        //jQuery('.submenu i').removeClass("fa-angle-up").removeClass("fa-angle-down").addClass("fa-angle-down");
        jQuery(this).parent().parent().css("display", "none");
        return false;
    });
}



(function () {
    $('.carousel-showmanymoveone .item').each(function () {
        var itemToClone = $(this);

        for (var i = 1; i < 4; i++) {
            itemToClone = itemToClone.next();


            if (!itemToClone.length) {
                itemToClone = $(this).siblings(':first');
            }


            itemToClone.children(':first-child').clone()
                .addClass("cloneditem-" + (i))
                .appendTo($(this));
        }
    });
}());





$("a.btnNewsletter").click(function () {
    $("html, body").animate({
        scrollTop: $('#suscribete').offset().top
    }, 1000);


    return false;
});


$(".btnSubmenu").click(function () {
  $(".btnSubmenu").removeClass("active");
  $(this).next().next("div").slideToggle("slow");
  $(this).toggleClass("active");
  return false;
});

/** BOTON ARRIBA **/
$('.scrollup').click(function(){

  var height= 0;

    $("html, body").animate({
        scrollTop: height
    }, 1000);
    return false;
});


  /** SCROLL AL ENTRAR A LA SECCION **/
  $(window).scroll(function(){

    if ($(this).scrollTop() > 500) {

        $('.scrollup').fadeIn();
    } else {
        $('.scrollup').fadeOut();
    }

});