﻿//Variables para controlar popover cantidad 0
var idNew = "";
var idVar = "";
var idList = "";
var provAct = "";
var elementosTemporalesCarrito = [];

jQuery(function () {
    Eshop.SetColorsActive();
    Eshop.SetEshop();
    Eshop.ToggleFilters();
    Eshop.OpenFirstTab();
    Eshop.ChangeTab();
    Eshop.DeleteItem();
    Eshop.ClearShopCart();
    Eshop.IncrementDecrement();
    Eshop.IncrementDecrementLib();
    Eshop.Marista.Init();
    Eshop.GetShoppingCart();
    Eshop.GetNumElementsShopCart();
    //Eshop.GetNumElementsWishList();
    Eshop.ChageParticular();
    Eshop.InicialiceInfoSizes();
    Eshop.SetStep1();


    $("body").on("click", "#applycupon", Eshop.RegisterPromotionCode);
    //$(".landing").mCustomScrollbar({ theme: "dark" });
    $("body").on("click", ".method-payment input", Eshop.ChangePaymentMethod); //Desactivamos esta comprobación porque no tiene gastos adicionales la forma de pago elegida

    LoginPopUp.SetModalParameter();

    Tglobe.InicialiceDataSlider();
    //$("img.lazy.image-hover.yit-image.attachment-shop_catalog, img.lazy.attachment-shop_catalog.wp-post-image").lazyload({
    //    effect: "fadeIn",
    //    skip_invisible: false
    //});

    $("#query").keypress(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            if ($('#query').val().length > 3) {
                var form = $("#form_search");
                $(form).submit();
            }
        }
    });

    $("#query2").keypress(function (event) {
        if (event.which == 13) {
            event.preventDefault();
            if ($('#query2').val().length > 3) {
                var form = $("#form_search2");
                $(form).submit();
            }
        }
    });

    $('#pass_loginLib').keypress(function (e) {
        var key = e.which;
        if (key == 13)  // the enter key code
        {
            e.preventDefault();
            LoginLib.LoginLib();
        }
    });

    $('body').on('click', '.compra-rapida-enlace', function (e) {
        $('#tab2').click();
    });

    $('.selector').click(function () {

        var item = $(this);

        $(item).next('div').children('ul').find('li[data-available="true"]').each(function () {
            $(this).attr('style', 'display:block!important');
        });

        if (item.hasClass("open")) {
            $(item).next('div').children('ul').find('li[data-available="true"]').each(function () {
                if ($(this).attr('data-selected') != true) {
                    $(this).removeAttr('style');
                }
            });
        }

        $(this).toggleClass("open");
        //if ($('.selector').next('ul').length > 0)
        //{
        //    $(this).attr('class', "selector_open");        
        //}
        //else
        //{
        //    $(this).attr('class', "selector");
        //}


    });

    $(".mini-cart-wrapper").on("mouseleave", function () {
        $(".mini-cart-wrapper").hide();
    });

    if ($('#shiptobilling-checkbox').length > 0 && $('#shiptobilling-checkbox').attr('checked') == 'checked') {

        if (Eshop.bDatFact == 1) {
            $('#DireccionMismosDatos').removeAttr('disabled');
            $('#labdirec').removeAttr('disabled');
            $('#factaddressCliente').show();
            if ($('#ClienteFacturacion_id_i').val() != 0) {
                $('#factaddress').hide();
                $('#hiddeonsamedata').hide();
            }
            else {
                $('#factaddress').show();
                $('#hiddeonsamedata').show();
            }
            if ($('#DireccionMismosDatos').length > 0 && $('#DireccionMismosDatos').attr('checked') == 'checked') {
                $('#factaddressCliente').hide();
                $('#factaddress').hide();
                $('#hiddeonsamedata').hide();
            }
        }
        else {
            // SRP: como siempre 'queremos factura' se habilita el checkbox de MismosDatos
            $('#DireccionMismosDatos').removeAttr('disabled');

            //$('#factaddress').show();
            if ($('#DireccionMismosDatos').length > 0 && $('#DireccionMismosDatos').attr('checked') == 'checked') {
                $('#DireccionMismosDatos').removeAttr('disabled');
                $('#labdirec').removeAttr('disabled');
                $('#factaddressCliente').hide();
                $('#factaddress').hide();
                $('#hiddeonsamedata').hide();
            }
        }
    }

    if ($('#rdbAgenda').length > 0 && $('#rdbAgenda').val() == '2') {
        $('#DirCliEnv').show();
    }

    window.setInterval(testPopUp3min, 500);
});

jQuery(window).resize(function () {
    Eshop.SizeOnResize();
});

jQuery(window).load(function () {
    Eshop.SizeOnResize();
});

jQuery(window).scroll(function () {
    Eshop.Fixed();
});
jQuery('body').scroll(function () {
    Eshop.Fixed();
});

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function getUrlParameter(sParam) {
    var sPageURL = window.location.search.substring(1);
    var sURLVariables = sPageURL.split('&');
    for (var i = 0; i < sURLVariables.length; i++) {
        var sParameterName = sURLVariables[i].split('=');
        if (sParameterName[0] == sParam) {
            return sParameterName[1];
        }
    }
}

(function ($) {
    $.fn.hasScrollBar = function () {
        return this.get(0).scrollHeight > this.height();
    }
})(jQuery);

var Eshop = {

    LstFilters: "",
    Order: "",
    Tr: new Object(),
    MaxPrice: 0,
    MinPrice: 0,
    MaxPriceSelected: 0,
    MinPriceSelected: 0,
    Itemspp: "",
    QuiereFact: "-1",
    MismosDatos: "-1",
    bDatFact: 0,
    bDatEnv: 0,
    numTransports: 0,


    // JCA: Métodos para controlar la variedad seleccionada en la ficha de producto.
    InitItemSelector: function () {
        // comprobamos el núm de variedades.
        var itemNo = 0;
        var var_id = 0;
        var jsonDic = jQuery.parseJSON(var_items);
        $.each(jsonDic, function (idx, obj) {
            if (!isNaN(idx)) { itemNo++; var_id = idx; }
        });

        // Inicializamos hash de selección de variedad para ficha de producto
        if (itemNo > 1) {
            for (var i = 0; i < $('.atr_clickable div ul').length; i++) {
                var table = $('.atr_clickable div ul')[i];
                var td = $(table).find('li').first();
                var valor_atr = td.data("id");
                hash_vals_items["" + valor_atr + ""] = 0;
            }

            // Comprobamos que la variedad está cargada
            var variedad_url = 0;
            try { variedad_url = location.pathname.substring(location.pathname.lastIndexOf('/') + 1); }
            catch (ex) { }

            if (variedad_url != 0 && !isNaN(variedad_url)) {

                if (Object.keys(hash_vals_items).length == 0) {
                    $("#var_id_selected").val(variedad_url);
                    $("#variedad_id_selected_remember").val(variedad_url);
                }

                initialize(variedad_url);
                search_item_var();
            }
            else {
                // No determinamos la variedad por URL, solicitamos la predeterminada.
                var id_pred = 0;

                // buscamos la variedad predeterminada
                var jsonDic = jQuery.parseJSON(var_items);
                $.each(jsonDic, function (idx, obj) {
                    if (obj.$values != null) {
                        $.each(obj.$values, function (ind, val) {
                            if (val.Key == "pred_b" && val.Value == "1") {
                                id_pred = idx;
                                return false;
                            }
                        });
                    }
                });

                // si no aparece ninguna usamos la primera por defecto.
                if (id_pred == 0) {
                    $.each(jsonDic, function (idx, obj) {
                        id_pred = idx;
                        return false;
                    });
                }
                $("#var_id_selected").val(id_pred);
                $("#variedad_id_selected_remember").val(id_pred);
                initialize(id_pred);
                search_item_var();
            }
        }
        else {
            $("#var_id_selected").val(var_id);
            $("#variedad_id_selected_remember").val(id_pred);
            initialize(var_id);
            var jsonDic = jQuery.parseJSON(var_items);
            $.each(jsonDic, function (idx, obj) {
                if (idx == $("#var_id_selected").val()) {
                    $.each(obj.$values, function (ind, val) {
                        // actualizamos datos en ficha de producto.
                        //if (val.Key == "nom_var_full") { $("div.details h1").html(val.Value); }
                        //if (val.Key == "ean") { $("div.sku span").html(val.Value); $("div.sku span").data('original-title', val.Value); }
                        if (val.Key == "prec") {
                            $("input[name='prec_unit']").html(val.Value);
                            showPrice();
                        }

                        if (val.Key == "stock") {
                            $("#stock_variedad").val(val.Value);
                            if (val.Value == 0) { $("#btnComprar").prop("disabled", true); $("#AvisoStock").show(); }
                            else { $("#btnComprar").prop("disabled", false); $("#AvisoStock").hide(); }
                        }

                        if (val.Key == "prec_div") {
                            $("div.prices del span").first().html(val.Value);
                        }

                        if (val.Key == "descuento" && val.Value != "") {
                            if (val.Value != "true") $("span.badge.main").addClass("badge-sale").html(val.Value);
                            if (val.Value != "2x1") $("del.base").removeAttr("hidden");
                        }

                        if (val.Key == "info_extra_descuento" && val.Value != "") {
                            $('.discount-message').removeAttr("hidden").html(val.Value);
                        }
                        else if (val.Key == "info_extra_descuento" && val.Value == "") {
                            if (typeof $('.discount-message').attr("hidden") !== typeof undefined && $('.discount-message').attr("hidden") !== false) {
                                $('.discount-message').addAttr("hidden");
                            }
                        }

                        //  COMENTAMOS ESTA LLAMADA PORQUE LA DESCRIPCIÓN LARGA VA A NIVEL DE PRODUCTO
                        //if (val.Key == "desc_editor") {
                        //    var product_id = $("input[name='pro_id']").val();
                        //    $.ajax({
                        //        url: "/product/getLongDescription",
                        //        async: true,
                        //        dataType: "json",
                        //        data: { ProductID: product_id, fichero: val.Value },
                        //        success: function (data) {
                        //            $("#description p").html(data.html);
                        //        },
                        //        complete: function () {

                        //        }
                        //    });
                        //}

                        if (val.Key == "desc_corta_nv") { $("div.short-description p").html(val.Value); }
                    });

                    // una vez hemos actualizado la información de la ficha, abandonamos la búsqueda.
                    return false;
                }
            });
        }

        // Evento de modificación de var_items
        $(".atr_clickable div ul li").click(function () {

            var atr_select = $(this).data('id');
            var val_select = $(this).data('value-id');
            var selected = ($(this).attr('data-selected') == "true");
            var available = ($(this).attr('data-available') == "true");

            //if (selected && available) return false;

            // quitamos la opción de seleccionado.
            if (selected) {
                $(this).removeAttr('data-selected');
                val_select = 0;
            }
            else {
                $(this).attr('data-selected', 'true');
            }


            // marcamos los atributos data-selected = ''
            var changeOption = select_item_var($(this), atr_select, val_select);
            // var checkAvailability = check_item_var_full(atr_select.toString());

            // if (!checkAvailability || changeOption) {
            //if (changeOption) {
            var jsonDic = jQuery.parseJSON(dic_atr_val);
            var check_val_items = [];
            $.each(jsonDic, function (idx, obj) {
                var idx_variedad = idx;
                var dic_item_vals = obj;
                if (dic_item_vals.$values != null) {
                    for (var i = 0; i < dic_item_vals.$values.length; i++) {
                        if (dic_item_vals.$values[i].Key == atr_select && dic_item_vals.$values[i].Value == val_select) {
                            check_val_items.push(dic_item_vals.$values);
                        }
                    }
                }
            });
            //}

            search_item_var(atr_select, val_select);


            // JCA. Responsive trick... cuando en modo móviles seleccionamos uno cerramos el selector.
            if ($(this).parent().parent().parent().find("label").hasClass("open")) {
                try {
                    var item = $(this).parent().parent().parent().find("label");
                    $(item).trigger("click");
                }
                catch (ex) { }
            }
        });

        $('input[name="cantidad"]').bind('input', function (e) {
            if (isNaN($(this).val()) || $(this).val() == "") { $('input[name="cantidad"]').val(''); return false; }
            showPrice();
        });

        $('input[name="cantidad"]').change(function () {
            if (isNaN($(this).val()) || $(this).val() == "") { $('input[name="cantidad"]').val(''); return false; }
            showPrice();
        });

    },

    showFormAvailableReminder: function () {
        $("#modalReminder").dialog({
            modal: true,
            title: '',
            zIndex: 10000,
            autoOpen: true,
            width: 'auto',
            resizable: false
        });
    },

    showFormAvailableReminderWhish: function (idVariedad) {
        $("#variedad_id_selected_remember").val(idVariedad);
        $("#modalReminder").dialog({
            modal: true,
            title: '',
            zIndex: 10000,
            autoOpen: true,
            width: 'auto',
            resizable: false
        });
    },

    ///Old-inactivo
    SetColorsActive: function () {
        //jQuery('body').on("click", ".mnu-color ul li a", function () {
        //    jQuery(this).toggleClass("mnu-active");
        //});
    },

    SetEshop: function () {
        jQuery('body').on("click", "div.sbHolder .sbOptions li", function () {
            jQuery("#lstorderby").next("div.sbHolder").children('.sbOptions').children('li').removeClass('orderselected');
            jQuery(this).addClass('orderselected');
            jQuery("#lstnumitems").next("div.sbHolder").children('.sbOptions').children('li').removeClass('orderselected');
            jQuery(this).addClass('orderselected');
        });

        jQuery("body").on("click", ".mnu-filtros ul li a input", function () {
            $(this).children("input").attr("checked", !$(this).children("input").prop("checked"));
            Eshop.GetEshop();
        });

        jQuery('body').on("click", "div.sbHolder .sbOptions li", function () {
            Eshop.GetEshop();
        });

        // SMARTKIOSK: Obtnemos mas productos cuando se pulse el boton en el smartkiosk
        jQuery("body").on("click", ".mostrar_mas_productos", function () {
            Eshop.LoadMoreProducts();
        });

        //jQuery('body').on("click", function () {
        //    $(".w-sms-alert").hide();
        //});
        //jQuery('body').on("mouseenter", ".identi-background", function () {
        //    $(".indenti-main").hide();
        //});

        if ($("#rangeprice").length) {
            // SMARTKIOSK: comprobamos la existencia de un objeto de la clase mostrar_mas_productos para diferenciar el listado de 
            // productos normales del de el smartkiosk
            if ($(".mostrar_mas_productos").length == 0) {
                $("#rangeprice").slider({
                    range: true,
                    min: parseInt(Eshop.MinPrice),
                    max: parseInt(Eshop.MaxPrice),
                    values: [parseInt(Eshop.MinPriceSelected), parseInt(Eshop.MaxPriceSelected)],
                    stop: function (event, ui) {
                        Eshop.GetEshop();
                    },
                    slide: function (event, ui) {
                        $("#spanstart").text(ui.values[0]);
                        $("#spanstop").text(ui.values[1]);
                    }
                });
                $("#spanstart").text($("#rangeprice").slider("values", 0));
                $("#spanstop").text($("#rangeprice").slider("values", 1));
            } else {
                $("#rangeprice").noUiSlider({
                    start: [parseInt(Eshop.MinPrice), parseInt(Eshop.MaxPrice)],
                    step: 1,
                    connect: true,
                    range: {
                        'min': parseInt(Eshop.MinPrice),
                        'max': parseInt(Eshop.MaxPrice)
                    },
                    format: wNumb({
                        decimals: 0,
                        thousand: ''
                    })
                });
                $("#rangeprice").on({
                    slide: function () {
                        $("#spanstart").text($("#rangeprice").val()[0]);
                        $("#spanstop").text($("#rangeprice").val()[1]);
                    },
                    change: function () {
                        Eshop.GetEshop();
                    }
                });
                $("#spanstart").text($("#rangeprice").val()[0]);
                $("#spanstop").text($("#rangeprice").val()[1]);
            }
        }

        //jQuery("body").on("click", "div.widget-1.widget-first.widget.yith-woo-ajax-navigation.trackglobe-woo.widget_layered_nav > h3", function () {
        //    if (!$(this).children().hasClass("toggled")) {
        //        $(this).parent().children().show();
        //    } else {
        //        $(this).parent().children().hide();
        //        $(this).show();
        //    }
        //    $(this).children().toggleClass("toggled");
        //});

        jQuery
    },

    SetStep1: function () {
        ////si existe
        if ($(".transport-container").length > 0) {
            //    $(".transport-container label,.gastosenviodel").hide();
            //    setTimeout(function () {
            //        $(".transport-container img,.gastosenviocont img").remove();
            //        $(".transport-container label,.gastosenviodel").show(300);
            //    }, 2500);

            //Eshop.St1CalculaTransporte();

            if (Eshop.bDatFact == 1) {
                if (Eshop.QuiereFact == "1") {
                    $('#factaddressCliente').show();
                    if (Eshop.MismosDatos == "1") {
                        $('#factaddress').hide();
                        $('#hiddeonsamedata').hide();
                        $('#factaddressCliente').hide();
                    } else {
                        $('#factaddress').show();
                        $('#hiddeonsamedata').show();
                    }
                } else {
                    $('#factaddressCliente').hide();
                }
            }
            else {
                if (Eshop.QuiereFact == "1") {
                    if (Eshop.MismosDatos == "1") {
                        $('#factaddress').hide();
                        $('#hiddeonsamedata').hide();
                    } else {
                        $('#factaddress').show();
                        $('#hiddeonsamedata').show();
                    }
                } else {
                    $('#factaddress').hide();
                }
            }
        }
    },

    GetEshop: function () {
        var dMap = jQuery(".mnu-filtros ul li a input:checked").map(function () {
            return jQuery(this).data('id');
        });

        Eshop.LstFilters = dMap.get();
        Eshop.Order = jQuery(".shorting div.sbHolder .sbOptions li.orderselected a").attr("rel");
        Eshop.Itemspp = jQuery(".ipp div.sbHolder .sbOptions li.orderselected a").attr("rel");

        // SMARTKIOSK: comprobamos la existencia de un objeto de la clase mostrar_mas_productos para diferenciar el listado de 
        // productos normales del de el smartkiosk
        if ($(".mostrar_mas_productos").length == 0) {
            Eshop.LoadFilters();
        } else {
            Eshop.LoadFiltersSK();
        }
    },

    LoadFilters: function () {
        if (!$(document).data("filtering")) {
            $(document).data("filtering", true);
            jQuery('ul.product-list.isotope li').hide();
            jQuery('#paginator').hide()
            jQuery('ul.product-list').addClass("yith-wcan-loading");
            $("html, body").animate({ scrollTop: 0 }, "slow");
            jQuery.ajax({
                cache: false,
                url: "/Filter",
                type: "post",
                asyn: true,
                data: { filtros: JSON.stringify(Eshop.LstFilters), order: Eshop.Order, preciomin: $("#rangeprice").slider("values", 0), preciomax: $("#rangeprice").slider("values", 1), itemspp: Eshop.Itemspp },
                success: function (data) {
                    if (data.valid == true) {
                        jQuery('ul.product-list.isotope').html(data.data);
                        jQuery('#paginator').html(data.pages);
                    }
                    jQuery('#paginator').show();
                    jQuery('ul.product-list.isotope li').show();
                    jQuery('ul.product-list').removeClass("yith-wcan-loading");
                    Eshop.SizeOnResize();
                    $(document).data("filtering", false);
                },
                error: function (data) {
                    jQuery('ul.product-list.isotope li').show();
                    jQuery('#paginator').show();
                    jQuery('ul.product-list').removeClass("yith-wcan-loading");
                    Eshop.SizeOnResize();
                    $(document).data("filtering", false);
                    //$("img.lazy.image-hover.yit-image.attachment-shop_catalog, img.lazy.attachment-shop_catalog.wp-post-image").lazyload({
                    //    effect: "fadeIn",
                    //    skip_invisible: false
                    //});
                }
            });
        }
    },

    // SMARTKIOSK: Metodo de cargar filtros para el smartkiosk
    // lo pongo aqui porque dependiendo de si estamos en el listado de productos del smartkiosk o de la web hay que cargar uno u otro
    LoadFiltersSK: function () {
        if (!$(document).data("filtering")) {
            $(document).data("filtering", true);
            jQuery('ul.product-list.isotope li').hide();

            // inicializamos los valores de loadmoreproducts
            jQuery('ul.product-list.more-products').html("");
            jQuery("#currpag").text("1");
            $(".mostrar_mas_productos").css("display", "none");
            // ---------------------------------------------

            jQuery('#paginator').hide()
            jQuery('ul.product-list').not('.more-products').addClass("yith-wcan-loading");
            $("html, body").animate({ scrollTop: 0 }, "slow");

            jQuery.ajax({
                cache: false,
                url: "/FilterSK",
                type: "post",
                asyn: true,
                data: { filtros: JSON.stringify(Eshop.LstFilters), order: Eshop.Order, preciomin: $("#rangeprice").val()[0], preciomax: $("#rangeprice").val()[1], itemspp: Eshop.Itemspp, urlsk: $("#permSmk").text() },
                success: function (data) {
                    if (data.valid == true) {
                        jQuery('ul.product-list.isotope').html(data.data);
                        jQuery('#paginator').html(data.pages);
                    }
                    // para la carga de loadmoreproducts
                    if (data.mas_prod) {
                        $(".mostrar_mas_productos").css("display", "block");
                    }
                    // ---------------------------------

                    jQuery('#paginator').show();
                    jQuery('ul.product-list.isotope li').show();
                    jQuery('ul.product-list').removeClass("yith-wcan-loading");
                    Eshop.SizeOnResize();
                    $(document).data("filtering", false);
                },
                error: function (data) {
                    jQuery('ul.product-list.isotope li').show();
                    jQuery('#paginator').show();
                    jQuery('ul.product-list').removeClass("yith-wcan-loading");
                    Eshop.SizeOnResize();
                    $(document).data("filtering", false);
                    //$("img.lazy.image-hover.yit-image.attachment-shop_catalog, img.lazy.attachment-shop_catalog.wp-post-image").lazyload({
                    //    effect: "fadeIn",
                    //    skip_invisible: false
                    //});
                }
            });
        }
    },

    // SMARTKIOSK: metodo para cargar los productos sin necesidad del paginador en el smartkiosk
    LoadMoreProducts: function () {
        if (!$(document).data("loadingmoreproducts")) {
            $(document).data("loadingmoreproducts", true);
            $(".mostrar_mas_productos").css("display", "none");
            $("#carg_mas_productos").addClass("yith-wcan-loading");
            $("#carg_mas_productos").addClass("height-40-imp");

            jQuery.ajax({
                cache: true,
                url: "/MoreProductsSK",
                type: "post",
                asyn: true,
                data: { filtros: JSON.stringify(Eshop.LstFilters), order: Eshop.Order, preciomin: $("#rangeprice").val()[0], preciomax: $("#rangeprice").val()[1], itemspp: Eshop.Itemspp, pageIndex: $("#currpag").text(), urlsk: $("#permSmk").text() },
                success: function (data) {
                    console.log("mas_prod: '" + data.mas_prod + "'");
                    if (data.valid) {
                        if (data.mas_prod) {
                            var npag = parseInt($("#currpag").text()) + 1;
                            $("#currpag").text(npag);

                            $(".mostrar_mas_productos").css("display", "block");
                        } else {
                            $(".mostrar_mas_productos").css("display", "none");
                        }

                        jQuery('ul.product-list.more-products').append(data.data);
                        Eshop.SizeOnResize();
                        //$('.product-list.isotope').append(data.data);
                    }
                    $(document).data("loadingmoreproducts", false);

                    $("#carg_mas_productos").removeClass("yith-wcan-loading");
                    $("#carg_mas_productos").removeClass("height-40-imp");
                },
                error: function (data) {
                    console.log("error: '" + data + "'");

                    $(document).data("loadingmoreproducts", false);

                    $("#carg_mas_productos").removeClass("yith-wcan-loading");
                    $("#carg_mas_productos").removeClass("height-40-imp");
                }
            });
        }
    },

    ChangeTab: function () {
        jQuery(".reviews_tab a").click(function (e) {
            e.preventDefault();
            jQuery(".reviews_tab").removeClass("active");
            jQuery("div.panel.customentry-content").hide();

            jQuery(this).parent().addClass("active");
            jQuery("#" + jQuery(this).attr("href")).show();
        });
    },

    ScrollToTab: function () {
        $($('.reviews_tab')[0]).children().click();
        $('html, body').animate({
            scrollTop: $($('.reviews_tab')[0]).children().offset().top - 70
        }, 200);
    },

    ScrollToTop: function () {
        $("html, body").animate({ scrollTop: 0 }, "slow");
    },

    OpenFirstTab: function () {
        jQuery(jQuery(".reviews_tab a")[0]).parent().addClass("active");
        jQuery("#" + jQuery(jQuery(".reviews_tab a")[0]).attr("href")).show();
    },

    SizeOnResize: function () {
        var si = 0;

        jQuery('li.product').css("height", "auto");

        jQuery('li.product').each(function (i, e) {
            if (jQuery(e).height() > si)
                si = jQuery(e).height();
        });

        jQuery('li.product').height(si);

        var $container = jQuery('.yit-wcan-container-p .products');

        $container.isotope('destroy');

        $container.isotope({
            filter: '*',
            animationOptions: {
                duration: 200,
                easing: 'linear',
                queue: false
            }
        });

        var selector = "li.product.type-product";
        $container.isotope({
            filter: selector,
            animationOptions: {
                duration: 200,
                easing: 'linear',
                queue: false
            }
        }, function () {
            $("img.lazy.image-hover.yit-image.attachment-shop_catalog, img.lazy.attachment-shop_catalog.wp-post-image").lazyload({
                //effect: "fadeIn",
                skip_invisible: true
            });
        });

        $("#featured-products-4").height($("#text-6").height());

        //Fix para resoluciones 1200 y 1024
        //liclassdynamic

        var wid = jQuery("body").width();

        if (wid <= 1200) {
            $(".liclassdynamic").attr("css", "menu-item menu-item-type-post_type menu-item-object-page dropdown menu-item-children-8");
            $(".menu-item.menu-item-type-custom.menu-item-object-custom.menu-item-children-0.menu-item-custom-content").hide();
        }
        if (wid <= 1024) {
            $(".liclassdynamic").attr("css", "menu-item menu-item-type-post_type menu-item-object-page dropdown menu-item-children-8");
            $(".menu-item.menu-item-type-custom.menu-item-object-custom.menu-item-children-0.menu-item-custom-content").hide();
        }
    },

    DeleteItem: function () {
        jQuery("body").on("click", ".col_remove .remove", function (event) {
            var ou = jQuery(this);
            Eshop.DeleteItemShoppingCarr($(ou).data("va"), -1, event);
        });
    },

    ClearShopCart: function () {
        jQuery("body").on("click", ".clear_shopping_cart", function (event) {
            Eshop.ClearShoppingCart(event);
        });
    },

    IncrementDecrement: function () {
        //jQuery("body").on("click", ".col_remove .remove", function (event) {
        //    var ou = jQuery(this);
        //    Eshop.IncrementItemShoppingCarr($(ou).data("va"), -1, event);
        //});

        var cant_min = parseInt($('input[name="cant_min_b2b"]').val());

        jQuery("body").on("click", ".cart.plus.cart-plus", function (event) {
            var stock = 9999;
            if ($("#stock_variedad").val() >= 0) {
                stock = $("#stock_variedad").val();
            }
            if (jQuery(this).prev().val() < stock) {
                jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);

                var ou = jQuery(this);
                Eshop.IncrementItemShoppingCarr($(ou).data("va"), jQuery(this).prev().val(), event);
                showPrice();
            }
        });

        jQuery("body").on("click", ".cart.plus.cart-plus-virtual", function (event) {
            Loading('show');
            jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
            var ou = jQuery(this);
            var newOld = $(ou).data("soc");
            if (newOld) idNew = newOld;
            idList = $(ou).data("code");
            idVar = $(ou).data("va");
            Eshop.IncrementItemShoppingCart($(ou).data("va"), $(ou).data("code"), $(ou).data("soc"), $(ou).data("tipo"), jQuery(this).prev().val(), event);

            ////Gestión libros socializados
            //if (newOld) {                
            //    idNew = newOld;
            //    $("#cart-minus-" + newList + "-" + newOld).trigger('click');
            //}

            //showPrice();
            //}
        });

        jQuery("body").on("click", "#btnAddCarr", function (event) {
            Eshop.AddToCar(false);
        });

        jQuery("body").on("click", "#btn-AddCarr-Buy", function (event) {
            Eshop.AddToCar(true);
        });

        jQuery("body").on("click", "#cd-cart-trigger", function (event) {
            if (window.innerWidth <= 767) {
                window.location.href = "/es/micesta";
            } else {
                Eshop.GetMiniCart();
                event.preventDefault();
            }
        });

        jQuery("body").on("click", ".cd-item-remove", function (event) {

            var variedad = $(this).data('variedad');
            var codigo = $(this).data('codigo');

            var name = $(this).data('name');
            var price = $(this).data('price');
            var brand = $(this).data('brand');
            var centro = $(this).data('centro');
            var etapa = $(this).data('etapa');
            var curso = $(this).data('curso');
            var ean = $(this).data('isbn');

            if (!variedad) {
                return false;
            }

            //Eshop.DeleteItemShoppingCarrNew(variedad, codigo).then(function () {
            Eshop.DeleteItemShoppingCarrNew(variedad, codigo, name, price, brand, centro, etapa, curso, ean).then(function () {
                Eshop.GetAlwaysNumElementsShopCart();
            });

            event.preventDefault();
        });

        jQuery("body").on("click", ".cart.minus.cart-minus", function (event) {

            if (jQuery(this).next().val() > 1) {
                if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                    jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                }

                var ou = jQuery(this);
                Eshop.IncrementItemShoppingCarr($(ou).data("va"), jQuery(this).next().val(), event);
                showPrice();
            }
        });

        jQuery("body").on("click", ".cart.minus.cart-minus-virtual", function (event) {
            try {

                if (jQuery(this).next().val() <= 0) {
                    return false;
                }

                Loading('show');
                if (jQuery(this).next().val() > 0) {
                    if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                        jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                    }

                    var ou = jQuery(this);
                    var newOld = $(ou).data("soc");
                    idList = $(ou).data("code");
                    idVar = $(ou).data("va");
                    Eshop.IncrementItemShoppingCart($(ou).data("va"), $(ou).data("code"), "", 0, jQuery(this).next().val(), event);

                    //showPrice();
                }
            } catch (e) {
                Loading('hide');
            }

        });

        jQuery("body").on("click", ".cart.add.cart-plus", function (event) {
            if (jQuery(this).prev().val() < parseInt(jQuery(this).prev().prop('max'))) {
                jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
            }
        });

        jQuery("body").on("click", ".cart.remove.cart-minus", function (event) {
            if (jQuery(this).next().val() > 1) {
                if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                    jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                }
            }
        });

        //jQuery("body").on("click", "input.instock.plus:not(.cart-plus)", function () {
        //    if (jQuery(this).prev().val() <= 20)
        //        jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
        //});

        //jQuery("body").on("click", "input.instock.minus:not(.cart-minus)", function () {
        //    if (jQuery(this).next().val() > 0)
        //        jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
        //});
        /*
        jQuery("input.plus_ref").on("click", function () {
        if (jQuery(this).prev().val() < parseInt(jQuery(this).prev().prop('max')))
        jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
        });
        jQuery("input.minus_ref").on("click", function () {
        if (jQuery(this).next().val() > 0)
        jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
        });
        */
    },

    IncrementDecrementLib: function () {
        var cant_min = parseInt($('input[name="cant_min_b2b"]').val());

        jQuery("body").on("click", ".cart.plus.cart-plus-lib-virtual", function (event) {

            jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
            var ou = jQuery(this);
            var newOld = $(ou).data("soc");
            var newList = $(ou).data("code");
            Eshop.IncrementItemShoppingCartLib($(ou).data("va"), $(ou).data("code"), jQuery(this).prev().val(), event);

            //Gestión libros socializados
            if (newOld) {
                $("#cart-minus-" + newList + "-" + newOld).trigger('click');
            }
        });

        jQuery("body").on("click", ".cart.minus.cart-minus-lib-virtual", function (event) {
            if (jQuery(this).next().val() > 0) {
                if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                    jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                }

                var ou = jQuery(this);
                var newOld = $(ou).data("soc");
                Eshop.IncrementItemShoppingCartLib($(ou).data("va"), $(ou).data("code"), jQuery(this).next().val(), event);

            }
        });

        jQuery("body").on("click", ".cart.add.cart-plus", function (event) {
            if (jQuery(this).prev().val() < parseInt(jQuery(this).prev().prop('max'))) {
                jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
            }
        });

        jQuery("body").on("click", ".cart.remove.cart-minus", function (event) {
            if (jQuery(this).next().val() > 1) {
                if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                    jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                }
            }
        });
    },

    AddItemShoppingCarrFloat: function (va) {
        var cantidad = $('input[name="item_quantity[' + va + ']"]').val();
        $("#multiCart").removeClass("ui-state-active ui-state-hover ui-state-focus");
        $("#multiCart").closest(".ui-dialog-content").dialog("close");
        $("#multiCart").remove();
        Eshop.AddItemShoppingCarr(va, cantidad);
    },

    AddItemShoppingCarr: function myfunction(va, ca, b) {
        console.log(va + " " + ca);
        var struct = [];
        var int = 0;

        $("#AvisoAsync").hide();

        if (va === undefined || ca === undefined) {
            struct.push(new Object({
                Variedad: $("#var_id_selected").val(),
                Cant: $('input[name="cantidad"]').val(),
            }))
        }
        else {
            struct.push(new Object({
                Variedad: va,
                Cant: ca,
                Optativa: b,
            }));
        }

        var cantTotal = 0;
        for (var i = 0; i < struct.length; i++) {
            cantTotal += parseInt(struct[i]["Cant"]);
        }

        if (cantTotal == 0) {
            var mensaje = Eshop.Literal.DebesSelVariedad
            $('<div class="dialog-custom"></div>').appendTo('body')
                .html('<div><h6 class="no-margin">' + mensaje + '</h6></div>')
                .dialog({
                    modal: true,
                    title: '',
                    zIndex: 10000,
                    autoOpen: true,
                    width: 'auto',
                    resizable: false,
                    buttons: {
                        'Aceptar': function () {
                            $(this).dialog("close");
                        }
                    }
                });
            return true;
        }

        $(".loading-comprar").show().css("visibility", "visible");  // Icono al lado del botón comprar
        var confirm = true;

        if (ca < 1) {
            $('<div class="dialog-custom"></div>').appendTo('body')
                .html('<div><h6 class="no-margin">' + Eshop.Literal.Delete + '</h6></div>')
                .dialog({
                    modal: true,
                    title: '',
                    zIndex: 10000,
                    autoOpen: true,
                    width: 'auto',
                    draggable: false,
                    resizable: false,
                    buttons: {
                        'Si':
                            function () {
                                $.ajax({
                                    url: "/Buy/AddItemBuyCart",
                                    type: "post",
                                    asyn: true,
                                    dataType: "json",
                                    data: { vm: JSON.stringify(struct) },
                                    success: function (data) {
                                        $(".mini-cart-content").html('<img class="loadercart" src="/Assets/img/loader.gif" />');
                                        $.post("/buy/get-mini-cart", function (data) {
                                            $(".mini-cart-content").html(data.Data);
                                            if (data.Show == "1") {
                                                $(".mini-cart-wrapper").show();
                                                $(".mini-cart-content").show();
                                                $("html, body").animate({ scrollTop: 0 }, "slow");
                                            }

                                            Eshop.GetNumElementsShopCart();
                                        });
                                        if (data.Result == 0) {
                                            window.dataLayer = window.dataLayer || [];
                                            dataLayer.push({
                                                'event': 'removeFromCart',
                                                'ecommerce': {
                                                    'remove': {                               // 'remove' actionFieldObject measures.
                                                        'products': [{                          //  removing a product to a shopping cart.
                                                            'name': data.Nombre.replace('\'', '\\\''),
                                                            'id': data.Id,
                                                            'price': data.Precio.toString().replace(',', '.'),
                                                            'quantity': data.Cantidad
                                                        }]
                                                    }
                                                }
                                            });
                                        }
                                    },
                                    complete: function () {
                                        $(".ajax-loading").hide();
                                    }
                                });
                                $(this).dialog("close");
                            },
                        'No': function () {
                            confirm = false;
                            $(this).dialog("close");
                        }
                    },
                    open: function () {
                        $(".ui-dialog-buttonpane").find('button').addClass('btn btn-violet')
                    },
                    close: function (event, ui) {
                        confirm = false;
                        $(this).remove();
                    }
                });
        } else if (confirm) {
            $("#btnComprar").addClass("disabled loading");
            $.ajax({
                url: "/Buy/AddItemBuyCart",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { vm: JSON.stringify(struct) },
                success: function (data) {
                    if (data.Result == 0) {
                        $(".mini-cart-content").html('<img class="loadercart" src="/Assets/img/loader.gif" />');
                        $.post("/buy/get-mini-cart", function (data) {
                            $(".mini-cart-content").html(data.Data);
                            if (data.Show == "1") {
                                $(".mini-cart-wrapper").show();
                                $(".mini-cart-content").show();
                                $("html, body").animate({ scrollTop: 0 }, "slow");
                            }
                            Eshop.GetNumElementsShopCart();
                        });
                        window.dataLayer = window.dataLayer || [];
                        dataLayer.push({
                            'event': 'addToCart',
                            'ecommerce': {
                                'add': {
                                    'products': [{
                                        'name': data.Nombre.replace(/['"]+/g, ''),
                                        'id': data.Id,
                                        'price': data.Precio.toString().replace(',', '.'),
                                        //'category': $("ul.breadcrumb li:last-child a").html(),
                                        //'variant': va.toString(),
                                        'quantity': data.Cantidad
                                    }]
                                }
                            }
                        });

                        if (data.RiesgoStock == true) {
                            new PNotify({
                                title: 'Stock limitado',
                                text: data.MsgRiesgoStock
                            });
                        }

                    } else {
                        $(data.Data).each(function (i, item) {
                            $("#AvisoAsync").text(item.Value);
                            $("#AvisoAsync").show();
                        });
                    }
                },
                complete: function () {
                    $(".ajax-loading").hide();
                    $("#btnComprar").removeClass("disabled loading");
                }
            });
        }
    },

    //AddItemFromWishlist: function myfunction(vartalla) {

    //    var valorCantidad = $("input[name='item_quantity[" + vartalla + "]']").val();

    //    return $.ajax({
    //        url: "/Buy/AddItemFromWish",
    //        type: "post",
    //        asyn: true,
    //        dataType: "json",
    //        data: { variedad: vartalla, cantidad: valorCantidad },
    //        success: function (data) {
    //            if (data.Result == 0) {

    //                $("#wish_" + data.IdVar).html(data.Data);
    //                $("#wish_" + data.IdVar).show();
    //                Eshop.GetNumElementsShopCart();
    //                Eshop.GetNumElementsWishList();
    //            } else {
    //                $("#wish_" + data.IdVar).html(data.Data);
    //                $("#wish_" + data.IdVar).show();
    //            }
    //        },

    //    });
    //},

    //AddAllItemsFromWishlist: function myfunction(url) {
    //    url = url || "";
    //    $("#spinnerWishlistProducts").show();

    //    var results = [];
    //    $('.track-wishlist .filaArticulo').each(function () {
    //        if ($(this).data('id') != null && $(this).data('stock') != 0) {
    //            results.push(Eshop.AddItemFromWishlist($(this).data('id')));
    //        }
    //    });

    //    $.when.apply(this, results).done(function () {
    //        $("#spinnerWishlistProducts").hide();
    //        $("html, body").animate({ scrollTop: 0 }, "slow");
    //        if (url != "") window.location.href = url;
    //    });
    //},

    //RemoveItemFromWishlist: function myfunction(varr, wish) {

    //    $.ajax({
    //        url: "/Buy/RemItemFromWish",
    //        type: "post",
    //        asyn: true,
    //        dataType: "json",
    //        data: { wish: wish, varr: varr },
    //        success: function (data) {
    //            if (data.Result == 0) {
    //                $("#bodyw_" + data.IdWish + " #wish_row_" + data.IdVar).remove();
    //            } else {
    //                $("#bodyw_" + data.IdWish + " #wish_" + data.IdVar).html(data.Data);
    //                $("#bodyw_" + data.IdWish + " #wish_" + data.IdVar).show();
    //            }
    //        },
    //        complete: function (data) {
    //            location.href = location.href;
    //        }

    //    });

    //},

    ClearShoppingCart: function (event) {
        $("#spinnerCarrito").show();
        $('<div class="dialog-custom">' + Resources.TXT_BORRAR + '</div>').appendTo('body')
            .html('<div><h6 class="no-margin">' + Resources.TXT_VaciarCarrito + '</h6></div>')
            .dialog({
                modal: true,
                title: Resources.TXT_BORRAR,
                zIndex: 10000,
                autoOpen: true,
                width: 'auto',
                resizable: false,
                draggable: false,
                buttons: {
                    'SÍ': function () {
                        $("#spinnerCarrito").show();
                        $.ajax({
                            url: "/buy/ClearShoppingCart",
                            type: "post",
                            asyn: true,
                            dataType: "json",
                            data: {},
                            success: function (data) {
                                if (data.Result == 0) {
                                    //window.localtion.href = data.Url;
                                    $(location).attr('href', data.Url);
                                } else if (data.Result == -4) {
                                    $("#msgRecurso").show();
                                    $("#_recurso").html("<div class='alert alert-danger'><span>" + Resources.TXT_CarritoVaciadoKO.toUpperCase() + "</span></div>")
                                    setTimeout(function () {
                                        $("#_recurso").html("");
                                    }, 10000)
                                }
                            },
                            complete: function () {
                                $(".loading-carrito").hide();
                            }
                        });
                        $(this).dialog("close");
                    },
                    'NO': function () {
                        confirm = false;
                        $(this).dialog("close");
                        $("#spinnerCarrito").hide();
                    }
                },
                open: function () {
                    $(".ui-dialog-buttonpane").find('button').addClass('btn btn-black')
                },
                close: function (event, ui) {
                    confirm = false;
                    $(this).remove();
                    $("#spinnerCarrito").hide();
                }
            });
    },

    DeleteItemShoppingCarr: function myfunction(va, ca, e, b) {
        var struct = [];
        var int = 0;
        var eo = e;

        $("#spinnerCarrito").show();
        //$(".loading-carrito").show();
        //$(".span3 .cart-details").animate({ opacity: 0.2 }, 200);
        //$(".loader").animate({ opacity: 0.2 }, 200, function () {
        struct.push(new Object({
            Variedad: va,
            Cant: ca,
            Optativa: b,
        }));

        $('<div class="dialog-custom">' + Resources.TXT_BORRAR + '</div>').appendTo('body')
            .html('<div><h6 class="no-margin">' + Eshop.Literal.Delete + '</h6></div>')
            .dialog({
                modal: true,
                title: Resources.TXT_BORRAR,
                zIndex: 10000,
                autoOpen: true,
                width: 'auto',
                resizable: false,
                draggable: false,
                buttons: {
                    'SÍ': function () {
                        //$(".loader").animate({ opacity: 0.2 }, 200);
                        $("#spinnerCarrito").show();
                        $.ajax({
                            url: "/buy/DeleteItemBuyCart",
                            type: "post",
                            asyn: true,
                            dataType: "json",
                            data: { vm: JSON.stringify(struct) },
                            success: function (data) {
                                if (data.Result == 0) {
                                    $.when(Eshop.GetFullCart()).done(function () {
                                        $("#spinnerCarrito").hide();
                                        $("#msgRecurso").show();
                                        $("#_recurso").html("<div class='alert alert-success'><span>" + Resources.TXT_ProductoEliminadoOK.toUpperCase() + "</span></div>")
                                        setTimeout(function () {
                                            $("#_recurso").html("");
                                        }, 10000)
                                        MaristasNuevo.ComprobarRadioButtonEnvio();
                                    });
                                    window.dataLayer = window.dataLayer || [];
                                    dataLayer.push({
                                        'event': 'removeFromCart',
                                        'ecommerce': {
                                            'remove': { // 'remove' actionFieldObject measures.
                                                'products': [{ // removing a product to a shopping cart.
                                                    'name': data.Nombre.replace('\'', '\\\''),
                                                    'id': data.Id,
                                                    'price': data.Precio.toString().replace(',', '.'),
                                                    'quantity': data.Cantidad
                                                }]
                                            }
                                        }
                                    });
                                }
                                if (data.Result == -4) {
                                    $("#msgRecurso").show();
                                    $("#_recurso").html("<div class='alert alert-danger'><span>" + Resources.TXT_ProductoEliminadoKO.toUpperCase() + "</span></div>")
                                    setTimeout(function () {
                                        $("#_recurso").html("");
                                    }, 10000)
                                } else {
                                    $(".mini-cart-content").html('<img class="loadercart" src="/Assets/img/loader.gif" />');
                                    $.post("/buy/get-mini-cart", function (data) {
                                        $(".mini-cart-content").html(data.Data);
                                        if (data.Show == "1") {
                                            $(".mini-cart-content").show();
                                            $("html, body").animate({ scrollTop: 0 }, "slow");
                                        }
                                        Eshop.GetNumElementsShopCart();
                                    });
                                }
                            },
                            complete: function () {
                                $(".loading-carrito").hide();
                            }
                        });
                        $(this).dialog("close");
                    },
                    'NO': function () {
                        confirm = false;
                        $(this).dialog("close");
                        //$(".span3 .cart-details").animate({ opacity: 1 }, 200);
                        //$(".loader").animate({ opacity: 1 }, 200);
                        //$(".loading-carrito").hide();
                        $("#spinnerCarrito").hide();
                    }
                },
                open: function () {
                    $(".ui-dialog-buttonpane").find('button').addClass('btn btn-black')
                },
                close: function (event, ui) {
                    confirm = false;
                    $(this).remove();
                    //$(".span3 .cart-details").animate({ opacity: 1 }, 200);
                    //$(".loader").animate({ opacity: 1 }, 200);
                    //$(".loading-carrito").hide();
                    $("#spinnerCarrito").hide();
                }
            });
        //});
    },

    IncrementItemShoppingCart: function myfunction(va, co, soc, tip, ca, e) {
        var struct = [];
        var int = 0;
        var eo = e;
        Loading('show');

        let solicitudId = $('#SolicitudLista')[0]
            ? $('#SolicitudLista').data('value')
            : null;

        struct.push(new Object({
            Variedad: va,
            Cant: ca,
            Codigo: co,
            VariedadNewSoc: soc,
            Tipo: tip
        }));

        if (ca < 0) { ca = 0; }

        var esCarritoTemporal = $('#carritoTemporal')[0] && $('#carritoTemporal').data('val') == 1;

        if (esCarritoTemporal) {
            elementosTemporalesCarrito = elementosTemporalesCarrito.filter(function (obj) {
                return obj.Variedad != va;
            });
            elementosTemporalesCarrito.push(new Object({
                Variedad: va,
                Cant: ca,
                Codigo: co,
                VariedadNewSoc: soc,
                Tipo: tip,
                SolicitudId: solicitudId,
            }));
            $.post('CambiarCantidadCestaTemporal', { codLista: co, vm: JSON.stringify(elementosTemporalesCarrito) }, function (partialView) {

                if (partialView) {
                    if (!partialView.Error) {
                        $('#postVirtual-8').empty().html(partialView);
                        CalcularAhorro();
                        obtenerVentaCruzada();
                    }
                }

            }).then(function () {
                Loading('hide');
            })

            return;
        }

        $.ajax({
            url: "/Buy/ChangeItemBuyCart",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { vm: JSON.stringify(struct) },
            success: function (data) {
                if (data.Result == 0) {
                    $.when(Eshop.GetFullCart()).done(function () {
                        CalcularAhorro();
                        ModalProductDetail();
                        Loading('hide');
                    });
                }
                // Hay errores
                if (data.Result == 1) {
                    $(data.Data).each(function (i, item) {
                        Loading('hide');
                        ////Inicialización de popover de la línea en específico.
                        //$(appendedPrependedInputButtons).popover({ placement: 'bottom', content: item.Value, template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>' });
                        ////Corrección del valor
                        //$(appendedPrependedInputButtons).val($(appendedPrependedInputButtons).val() - 1);
                        ////Mostramos popover, espera 3 segundos, destruye el elemento
                        //$(appendedPrependedInputButtons).popover('show');
                        //setTimeout(function () { $(appendedPrependedInputButtons).popover('destroy') }, 3000);
                    });
                } else {
                    // ACTUALIZAMOS BURBUJA CARRITO
                    $(".mini-cart-content").html('<img class="loadercart" src="/Assets/img/loader.gif" />');
                    $.post("/buy/get-mini-cart", function (data) {
                        $(".mini-cart-content").html(data.Data);
                        if (data.Show == "1") {
                            $(".mini-cart-content").show();
                            //$("html, body").animate({ scrollTop: 0 }, "slow"); //Deshabilitamos que se haga scroll hacia arriba
                        }
                        Eshop.GetNumElementsShopCart();
                    });
                }
            },
            complete: function () {
                // $(".loading-carrito").hide();
                //$("#spinnerCarrito").hide();
            }
        });

    },

    //AddToCar: function (finalizarPago) {
    AddToCar: function (finalizarPago) {
        var productItems = $('.product-item');
        var elementosParaAgregarCarrito = [];

        let solicitudId = $('#SolicitudLista')[0]
            ? $('#SolicitudLista').data('value')
            : null;

        $.each(productItems, function (idx, item) {
            var cantidad = parseInt($(item).data('cant'));
            if (cantidad > 0) {
                let va = $(item).data('var');
                let ca = $(item).data('cant');
                var co = $(item).data('code');
                var cl = $(item).data('chequelibro');

                elementosParaAgregarCarrito.push(new Object({
                    Variedad: va,
                    Cant: ca,
                    Codigo: co,
                    SolicitudId: solicitudId,
                    ChequeLibro: cl
                }));
            }
        });

        if (elementosParaAgregarCarrito == null || elementosParaAgregarCarrito.length <= 0) {
            return;
        }

        Loading('show');

        $.post('AgregarElementoCarrito', { elementosCarrito: JSON.stringify(elementosParaAgregarCarrito) }, function (result) {

            if (result.Success) {
                if (finalizarPago) {
                    var step = 2;

                    location.href = 'finasistente?step=' + step;
                    //location.href = 'finasistente';
                } else {
                    //location.href = '/';
                    var step = 1; //Añadir y seguir comprando
                    Swal.fire({
                        title: '',
                        text: 'Se ha agregado la lista al carrito',
                        icon: 'success',
                        showCloseButton: true,
                        backdrop: true,
                        allowOutsideClick: false,
                        closeOnClickOutside: false,
                    }).then((result) => {
                        location.href = 'centro?step=' + step;
                    });

                }
            } else {
                if (result.ErrorCode && result.ErrorCode > 0) {
                    location.href = 'centro?numError=' + result.ErrorCode;
                } else {
                    alert(result.ErrorMessage);
                    location.href = 'centro';
                }
            }

        }).then(function () {
            Loading('hide');
        });
    },

    GetMiniCart: function () {

        $.get('/buy/minicesta', null, function (partialView) {
            if (partialView) {
                $('#cd-cart').empty().html(partialView);
            }
        });
    },

    IncrementItemShoppingCartLib: function myfunction(va, co, ca, e) {
        var struct = [];
        var int = 0;
        var eo = e;
        $("#spinner").show();

        struct.push(new Object({
            Variedad: va,
            Cant: ca,
            Codigo: co,
        }));

        if (ca < 0) { ca = 0; }

        $.ajax({
            url: "/Libreria/ChangeItemBuyCart",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { vm: JSON.stringify(struct) },
            success: function (data) {
                if (data.Result == 0) {
                    $.when(Eshop.GetFullCartLib()).done(function () {
                        $("#spinner").hide();
                        //Quitamos ya que da error en tiempo de ejecución
                        //Eshop.CalcularAhorroLib();
                    });
                }
                // Hay errores
                if (data.Result == 1) {
                    $(data.Data).each(function (i, item) {
                        $("#spinner").hide();
                    });
                } else {
                }
            },
            complete: function () {
            }
        });

    },

    //CalcularAhorroLib() {
    //    var ahorro = 0;
    //    $("#dISBNs").find('.sumahorro').each(function () {
    //        ahorro = parseFloat(ahorro) + parseFloat($(this).data("valor").replace(',', '.'));
    //    })
    //    ahorro = ahorro.toFixed(2);
    //    $("#ahorroTotal").val("-" + ahorro + " €");
    //    $("#ahorroTotal").text("-" + ahorro + " €");
    //},

    IncrementItemShoppingCarr: function myfunction(va, ca, e) {
        var struct = [];
        var int = 0;
        var eo = e;
        var appendedPrependedInputButtons = "#appendedPrependedInputButtons_" + va;
        //$(".loading-carrito").show();
        //$(".span3 .cart-details").animate({ opacity: 0.2 }, 200);
        $("#spinnerCarrito").show();
        //$(".loader").animate({ opacity: 0.2 }, 200, function () {
        struct.push(new Object({
            Variedad: va,
            Cant: ca,
        }));

        if (ca < 1) { ca = 1; }

        $.ajax({
            url: "/Buy/ChangeItemBuyCart",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { vm: JSON.stringify(struct) },
            success: function (data) {
                if (data.Result == 0) {
                    $.when(Eshop.GetFullCart()).done(function () {
                        $("#spinnerCarrito").hide();
                        MaristasNuevo.ComprobarRadioButtonEnvio();
                    });
                }
                // Hay errores
                if (data.Result == 1) {
                    $(data.Data).each(function (i, item) {
                        $("#spinnerCarrito").hide();
                        //$(".loading-carrito").hide();
                        //$(".span3 .cart-details").animate({ opacity: 1 }, 200);
                        //$(".loader").animate({ opacity: 1 }, 200);
                        //Inicialización de popover de la línea en específico.
                        $(appendedPrependedInputButtons).popover({ placement: 'bottom', content: item.Value, template: '<div class="popover"><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>' });
                        //Corrección del valor
                        $(appendedPrependedInputButtons).val($(appendedPrependedInputButtons).val() - 1);
                        //Mostramos popover, espera 3 segundos, destruye el elemento
                        $(appendedPrependedInputButtons).popover('show');
                        setTimeout(function () { $(appendedPrependedInputButtons).popover('destroy') }, 1000);
                    });
                } else {
                    // ACTUALIZAMOS BURBUJA CARRITO (LO HEMOS COMENTADO, PORQUE HEMOS QUITADO EL CARRITO EN EL PROCESO DE COMPRA)
                    //$(".mini-cart-content").html('<img class="loadercart" src="/Assets/img/loader.gif" />');
                    //$.post("/buy/get-mini-cart", function (data) {
                    //    $(".mini-cart-content").html(data.Data);
                    //    if (data.Show == "1") {
                    //        $(".mini-cart-content").show();
                    //        $("html, body").animate({ scrollTop: 0 }, "slow");
                    //    }
                    //    Eshop.GetNumElementsShopCart();
                    //});
                }
            },
            complete: function () {
                // $(".loading-carrito").hide();
                //$("#spinnerCarrito").hide();
            }
        });
        //});
    },

    DeleteItemShoppingCarrNew: function (variedad, codigo, name, price, brand, centro, etapa, curso, ean) {
        var struct = [];
        $("#spinnerCarrito").show();
        struct.push(new Object({
            Variedad: variedad,
            Cant: 0,
            Codigo: codigo,
            VariedadNewSoc: "",
            EliminandoDesdeMiniCesta: true,
            Name: name,
            Price: price,
            Brand: brand,
            Centro: centro,
            Etapa: etapa,
            Curso: curso,
            Ean: ean
        }));

        Loading('show');

        return $.ajax({
            url: "/Buy/ChangeItemBuyCart",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { vm: JSON.stringify(struct) },
            success: function (data) {
                if (data.Result == 0) {
                    $.get('/buy/minicesta', null, function (partialView) {
                        if (partialView) {
                            $('#cd-cart').empty().html(partialView);
                        }
                    });

                    Swal.fire({
                        position: 'top-end',
                        icon: 'success',
                        title: 'Se ha eliminado exitosamente el articulo de la cesta.',
                        timer: 2000,
                        showConfirmButton: true,
                        confirmButtonText: `OK`,
                    });

                    if (location.href.includes('finasistente')) {
                        window.location.reload();
                    }
                }
                // Hay errores
                if (data.Result == 1) {
                    $(data.Data).each(function (i, item) {
                        alert('Error al intentar remover el elemento de la cesta.');
                    });
                } else {
                }
            },
            complete: function () {
                Loading('hide');
            }
        });
    },

    GetShoppingCart: function () {
        var i = 0;
        var x = 0;
        //$(".mini-cart").on("mouseenter", function () {
        //    //$('.megamenu-sub-menu.span2').stop(true, true);
        //    $(".mini-cart-wrapper").show();
        //    if (!$(document).data("isCheckingCart")) {
        //        $(document).data("isCheckingCart", true);
        //        $(".mini-cart-content").html('<img class="loadercart" src="/Assets/img/loader.gif" />');
        //        $.post("/buy/get-mini-cart", function (data) {
        //            $(".mini-cart-content").html(data.Data);
        //            if (data.Show == "1") {
        //                $(".mini-cart-content").show();
        //            }
        //            Eshop.GetNumElementsShopCart();
        //        }).done(function () {
        //            $(document).data("isCheckingCart", false);
        //        });
        //    }
        //});
    },

    GetNumElementsShopCart: function () {
        if (!$(document).data("isCheckingCartNumber")) {
            $(document).data("isCheckingCartNumber", true);
            return $.post("/buy/get-num-cart", function (data) {
                $("#cart-items-number").text(data);
                $("#cart-mini-edv").attr("data-title", data);
                $("#cart-mini-edv2").attr("data-title", data);
                if (data == "0") {
                    $("#liBorrarCarrito").hide();
                } else {
                    $("#liBorrarCarrito").show();
                }
            }).done(function () {
                $(document).data("isCheckingCartNumber", false);
            });
        }

        return null;
    },

    GetAlwaysNumElementsShopCart: function () {
        return $.post("/buy/get-num-cart", function (data) {
            $("#cart-items-number").text(data);
            $("#cart-mini-edv").attr("data-title", data);
            $("#cart-mini-edv2").attr("data-title", data);
        });
    },

    //GetNumElementsWishList: function () {
    //    if (!$(document).data("isCheckingWLNumber")) {
    //        $(document).data("isCheckingWLNumber", true);
    //        $.post("/buy/get-num-wl", function (data) {
    //            $("#wl-mini-edv").attr("data-title", data);
    //        }).done(function () {
    //            $(document).data("isCheckingWLNumber", false);
    //        });
    //    }
    //},

    ChageParticular: function () {
        $(".transport-label.envio-persona").click(function () {
            if ($(this).children("input").val() == "0") {
                $("#shiptobilling").show();
                $("#h3_factr").show();
                $(".name_social").show();
                $(".documento").show();
            } else {
                $("#shiptobilling").hide();
                $("#h3_factr").hide();
                $(".documento").hide();
                $(".name_social").hide();
            }
        });
    },

    CheckSendForm: function () {
        var parti = $($(".transport-label.envio-persona input")[1]).attr("checked");
        if (parti == undefined || parti != "checked") {
            if ($("#ClienteFacturacion_NIF").val() = "") {
                $('*[data-valmsg-for="ClienteFacturacion.NIF"]').addClass('field-validation-error');
                $('*[data-valmsg-for="ClienteFacturacion.NIF"]').text($("#ClienteFacturacion_NIF").data("data-val-length"));
            }
        }
    },

    AddToWishlist: function (p, w) {
        $($('*[data-product-id="' + p + '"]').next()).css("display", "block").css("visibility", "visible");
        $.ajax({
            url: "/Buy/AddProductWish",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { p: p, w: -1 },
            success: function (data) {
                if (data.Result == 0) {
                    $($('*[data-product-id="' + data.IdVar + '"]').parent().parent().children(".w-ok")).show(0).delay(5000).hide(0);
                    //$($('*[data-product-id="' + data.IdVar + '"]').parent().parent().children(".w-ok")).css("display", "block").css("visibility", "visible");
                } else {
                    $($('*[data-product-id="' + data.IdVar + '"]').parent().parent().children(".w-ko")).show(0).delay(5000).hide(0);
                    //$($('*[data-product-id="' + data.IdVar + '"]').parent().parent().children(".w-ko")).css("display", "block").css("visibility", "visible");
                }
            },
            complete: function () {
                $('.action.wishlist .ajax-loading').css("display", "none").css("visibility", "hidden");
            }
        });
    },
    AddToWishlistP: function (p, w, element) {
        //$($('.summary.customentry-summary .product-meta-wrapper *[data-product-id="' + p + '"]').next()).css("display", "block").css("visibility", "visible");
        $($(element).next()).css("display", "block").css("visibility", "visible");
        $.ajax({
            url: "/Buy/AddProductWish",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { p: p, w: -1 },
            success: function (data) {
                if (data.Result == 0) {
                    $($('div.summary.customentry-summary .yith-wcwl-add-to-wishlist').children()[1]).css("display", "block").css("visibility", "visible");
                } else {
                    $($('div.summary.customentry-summary .yith-wcwl-add-to-wishlist').children()[2]).css("display", "block").css("visibility", "visible");
                }
            },
            complete: function () {
                $($('div.summary.customentry-summary .yith-wcwl-add-to-wishlist').children()[0]).children('.ajax-loading').css("display", "none").css("visibility", "hidden");
            }
        });
    },
    LAsyn: function myfunction() {
        var struct = new Object({
            Email: $("form#lasyn2 input#Cliente_Email").val(),
            Clave: $("form#lasyn2 input#Cliente_Clave").val()
        });
        var g = $('.col-1 *[name="__RequestVerificationToken"]').val();
        $(".sms-alert-login").hide();
        $.ajax({
            url: "/Access/LAsyn",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { clave: $("form#lasyn2 input#Cliente_Clave").val(), email: $("form#lasyn2 input#Cliente_Email").val(), __RequestVerificationToken: g },
            success: function (data) {
                if (data.data == true) {
                    location.href = location.href;
                } else {
                    $(".sms-alert-login").show();
                }
            }

        });
    },

    RAsyn: function myfunction() {
        var struct = new Object({
            Email: $("#ClienteR_Email").val(),
            Clave: $("#ClienteR_Clave").val(),
            Nombre: $("#ClienteR_Nombre").val()
        });
        var g = $('#regasyn *[name="__RequestVerificationToken"]').val();
        $(".sms-alert-login").hide();
        $.ajax({
            url: "/Access/RAsyn",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { nombre: $("#ClienteR_Nombre").val(), email: $("#ClienteR_Email").val(), clave: $("#ClienteR_Clave").val(), __RequestVerificationToken: g },
            success: function (data) {
                if (data.data == 0) {
                    location.href = location.href;
                } else if (data.data == -1) {
                    $(".sms-alert-login").show();
                } else if (data.data == -2) {
                    $(".sms-alert-login-email").show();
                }
            }

        });
    },

    ShowLogin: function () {
        $("#customer_login2").dialog({
            dialogClass: "alert",
            modal: true,
            resizable: false,
            closeOnEscape: true,
            position: {
                my: "left top",
                at: "left top",
                of: window
            }
        });
    },

    ShowLoginType2: function () {
        $("#customer_login3").dialog({
            dialogClass: "alert",
            modal: true,
            resizable: false,
            closeOnEscape: true,
            position: {
                my: "left top",
                at: "left top",
                of: window
            }
        });
    },

    SetStarActive: function (e) {
        $("#commentform .stars span a").removeClass("active");
        $(e).addClass("active");
        $("#rating_").val($(e).text());
    },

    SetStarActive2: function (e) {
        $("#commentform .stars span a").removeClass("icon-heart-empty");
        $(e).addClass("icon-heart");//corazon lleno al que se pincha
        $(e).prevAll().addClass("icon-heart");//corazon lleno a los anteriores
        $(e).nextAll().addClass("icon-heart-empty");//corazon vacío a los siguientes        
        $("#rating_").val($(e).attr('data-val'));//cogemos valor del atributo data-val
        //alert(("#rating_").val());
        //alert($(e).attr('data-val'));
    },

    RegisterNewsletter: function () {
        var g = $('.input-append *[name="__RequestVerificationToken"]').val();

        $.ajax({
            url: "/NewNewsletter",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_news").val(), __RequestVerificationToken: g, politica: $(".politica-mail input").attr("checked") },
            success: function (data) {

                // Inicializar estilos
                $("#newsletter-input .w-ok").css("visibility", "hidden").css("display", "none");
                $("#newsletter-input .w-ok").hide();
                $("#newsletter-input .w-politica").css("visibility", "hidden").css("display", "none");
                $("#newsletter-input .w-politica").hide();
                $("#newsletter-input .email-ko").css("visibility", "hidden").css("display", "none");
                $("#newsletter-input .email-ko").hide();
                $("#newsletter-input .email-exist").css("visibility", "hidden").css("display", "none");
                $("#newsletter-input .email-exist").hide();
                $("#newsletter-input .email-incorrecto").css("visibility", "hidden").css("display", "none");
                $("#newsletter-input .email-incorrecto").hide();

                if (data.Result == 0) {
                    $("#newsletter-input .w-ok").css("visibility", "visible").css("display", "block");
                    $("#newsletter-input .w-ok").show();
                } else if (data.Result == 1) {
                    $("#newsletter-input .w-politica").css("visibility", "visible").css("display", "block");
                    $("#newsletter-input .w-politica").show();
                } else if (data.Result == 2) {
                    $("#newsletter-input .email-ko").css("visibility", "visible").css("display", "block");
                    $("#newsletter-input .email-ko").show();
                } else if (data.Result == 3) {
                    $("#newsletter-input .email-exist").css("visibility", "visible").css("display", "block");
                    $("#newsletter-input .email-exist").show();
                } else if (data.Result == 4) {
                    $("#newsletter-input .email-incorrecto").css("visibility", "visible").css("display", "block");
                    $("#newsletter-input .email-incorrecto").show();
                }
            }

        });
    },

    RegisterPromotionCode: function () {
        var g = $('.coupon input[name="__RequestVerificationToken"]').val();
        $.ajax({
            url: "/PromotionCode",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { code: $("#cuponcode").val(), __RequestVerificationToken: g },
            success: function (data) {
                if (data.Result == 0) {
                    $(".cupon-ok").css("visibility", "visible").css("display", "block");
                    $(".cupon-ok").show();
                    location.href = location.href;
                    Eshop.GetFullCart();
                } else if (data.Result == -1 || data.Result == -2) {
                    $(".cupon-ko").css("visibility", "visible").css("display", "block");
                    $(".cupon-ko").show();
                }
            }

        });
    },

    RegisterEmailStockReminder: function () {
        var g = $('.input-append input[name="__RequestVerificationToken"]').val();
        $.ajax({
            url: "/product/SendMeEmailWhenAvailable",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email").val(), variedad_id: $('#variedad_id_selected_remember').val(), check_legal: $('#check_legal').is(':checked'), url: $('input[name="urlBase"]').val(), nombre: $('div.details h1').html(), foto: $('#photo img').attr('src'), __RequestVerificationToken: g },
            success: function (data) {
                // Inicializar estilos
                $("#stockAvailableReminder .w-ok").css("visibility", "hidden").css("display", "none");
                $("#stockAvailableReminder .w-ok").hide();
                $("#stockAvailableReminder .w-politica").css("visibility", "hidden").css("display", "none");
                $("#stockAvailableReminder .w-politica").hide();
                $("#stockAvailableReminder .email-ko").css("visibility", "hidden").css("display", "none");
                $("#stockAvailableReminder .email-ko").hide();
                $("#stockAvailableReminder .email-exist").css("visibility", "hidden").css("display", "none");
                $("#stockAvailableReminder .email-exist").hide();
                $("#stockAvailableReminder .email-incorrecto").css("visibility", "hidden").css("display", "none");
                $("#stockAvailableReminder .email-incorrecto").hide();
                $("#stockAvailableReminder .aviso-legal").css("visibility", "hidden").css("display", "none");
                $("#stockAvailableReminder .aviso-legal").hide();

                if (data.Result == -1) {
                    $("#stockAvailableReminder .w-ok").css("visibility", "visible").css("display", "block");
                    $("#stockAvailableReminder .w-ok").show();

                    setTimeout(function () { $("#modalReminder").dialog("close"); }, 3000);
                } else if (data.Result == -2) {
                    $("#stockAvailableReminder .email-exist").css("visibility", "visible").css("display", "block");
                    $("#stockAvailableReminder .email-exist").show();
                } else if (data.Result == 4) {
                    $("#stockAvailableReminder .email-incorrecto").css("visibility", "visible").css("display", "block");
                    $("#stockAvailableReminder .email-incorrecto").show();

                } else if (data.Result == 3) {
                    $("#stockAvailableReminder .aviso-legal").css("visibility", "visible").css("display", "block");
                    $("#stockAvailableReminder .aviso-legal").show();
                }
            }

        });
    },

    ChangePaymentMethod: function () {
        $("#spinnerStep3").show();
        $.ajax({
            url: "/ChangePayment",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { method: $(".method-payment input:checked").val() },
            success: function (data) {
                if (data.Result == 0) {
                    //$(".cupon-ok").css("visibility", "visible").css("display", "block");
                    //$(".cupon-ok").show();
                    location.href = location.href;
                    //$("#spinnerStep3").hide();
                    //Eshop.GetFullCart();
                } else if (data.Result == -1 || data.Result == -2) {
                    //$(".cupon-ko").css("visibility", "visible").css("display", "block");
                    //$(".cupon-ko").show();
                    //alert("asdf");
                    $("#spinnerStep3").hide();
                }
            }
        });
    },

    GoToPayment: function () {
        $("#loadpayment").show();
        $('#step3form input[name=proceed]').hide();
        $('#step3form').submit();
    },

    GetFullCart: function () {
        $("#spinnerCarrito").show();
        //$(".loading-carrito").show();
        //$(".span3 .cart-details").animate({ opacity: 0.2 }, 200);
        //$(".loader").animate({ opacity: 0.2 }, 200, function () {
        return $.ajax({
            url: "/GetCart",
            type: "post",
            asyn: true,
            success: function (data) {
                $("#postVirtual-8").html(data)
                $("#postVirtual-8").find('.numSelecc').each(function () {
                    cantidad = $(this).val();
                    ean = $(this).data("ean");
                    varId = $(this).data("varid");
                    listId = $(this).data("code");
                    //optativa = $(this).data("optativa");

                    if (cantidad == 0) { //&& optativa == 1) {
                        $("#dig_" + ean).show();
                        if (idNew == varId && idList == listId) {
                            $(this).closest('.product-item').find('a.cartdetail').attr('data-content', Resources.TXT_Socializado_minus);
                            $(this).closest('.product-item').find('a.cartdetail').attr('data-trigger', 'focus');
                            $(document).scrollTop($(this).closest('.product-item').offset().top - $(window).outerHeight() / 4);
                            $(this).closest('.product-item').find('a.cartdetail').popover('show');
                            var popObj = $(this);
                            setTimeout(function () { $(popObj).closest('.product-item').find('a.cartdetail').popover('destroy'); }, 1000);
                            idNew = "";
                        }
                        if (idVar == varId && idList == listId) {
                            $(this).closest('.product-item').find('a.cartdetail').attr('data-content', Resources.TXT_ELIMINADO_CANT_0);
                            $(this).closest('.product-item').find('a.cartdetail').attr('data-trigger', 'focus');
                            $(document).scrollTop($(this).closest('.product-item').offset().top - $(window).outerHeight() / 4);
                            $(this).closest('.product-item').find('a.cartdetail').popover('show');
                            var popObj = $(this);
                            setTimeout(function () { $(popObj).closest('.product-item').find('a.cartdetail').popover('destroy'); }, 1000);
                            idVar = "";
                        }
                    }
                    if (cantidad > 0) {
                        $("#dig_" + ean).hide();
                    }

                });
                Loading('hide');
            }
        });
        //});
    },

    GetFullCartLib: function () {
        $("#spinnerCarrito").show();
        //$(".loading-carrito").show();
        //$(".span3 .cart-details").animate({ opacity: 0.2 }, 200);
        //$(".loader").animate({ opacity: 0.2 }, 200, function () {
        return $.ajax({
            url: "/GetCartLib",
            type: "post",
            asyn: true,
            success: function (data) {
                $("#dISBNs").html(data)
                $("#dISBNs").find('.numSelecc').each(function () {
                    cantidad = $(this).val();
                    ean = $(this).data("ean");
                    optativa = $(this).data("optativa");

                    if (cantidad == 0 && optativa == 'False') {
                        $("#dig_" + ean).show();
                    }
                    if (cantidad > 0) {
                        $("#dig_" + ean).hide();
                    }

                });


            }
        });
        //});
    },

    Fixed: function () {
        //if ($(".trackglobe-woo .row-fluid").length > 0) {
        //    $(".trackglobe-woo .row-fluid > form").height($(".trackglobe-woo .row-fluid").height());
        //}

        //if (window.screen.width > 979) {
        //    $('.cart-user-info').positionSticky();
        //}
        //var wid = $("#post-8").width() - $(".cart-list").width();
        //if ($(".cart-list").length > 0 && $("#post-8").offset().top < ($("body").scrollTop() + 30) && $("#post-8").width() > 939) {
        //    $(".cart-user-info").css({
        //        top: 50,
        //        "left": ($("#post-8").offset().left + $("#post-8").width() - wid - 10),
        //        "position": 'fixed',
        //        "width": wid + "px",
        //        "background": "white",
        //        "z-index": "2"                
        //    });
        //} else {
        //    $(".cart-user-info").removeAttr("style");
        //}
        //wid = $("#post-8").width() - $(".span8.classic").width();
        //if ($(".transport-container").length > 0 && $(".span8.classic").offset().top < ($("body").scrollTop() + 30) && $("#post-8").width() > 939) {
        //    $(".cart-user-info").css({
        //        top: 50,
        //        "left": ($(".span8.classic").offset().left + $(".span8.classic").width() - 10),
        //        "position": 'fixed',
        //        "width": wid + "px",
        //        "background": "white",
        //        "z-index": "2"
        //    });
        //} else if ($(".transport-container").length > 0) { $(".cart-user-info").removeAttr("style"); }
    },

    ToggleFilters: function () {
        $("div.widget-1.widget-first.widget.yith-woo-ajax-navigation.trackglobe-woo.widget_layered_nav > *").hide();
        $("div.widget-1.widget-first.widget.yith-woo-ajax-navigation.trackglobe-woo.widget_layered_nav > h3").show();
        $($("div.widget-1.widget-first.widget.yith-woo-ajax-navigation.trackglobe-woo.widget_layered_nav")[0]).children().show()
        $($("div.widget-1.widget-first.widget.yith-woo-ajax-navigation.trackglobe-woo.widget_layered_nav")[1]).children().show()
    },

    InicialiceInfoSizes: function () {
        $(".cell-uno-piezas").on("mouseenter", ".img-info-talla", function () {
            $(".sp-sms-alert").hide();
            $(this).next().show();
        });
        $(".cell-uno-piezas").on("click", ".img-info-talla", function () {
            $(this).next().show();
        });
        $(".cart-subtotal").on("mouseenter", ".img-info-talla", function () {
            $(".sp-sms-alert").hide();
            $(this).next().show();
        });
        $(".cart-subtotal").on("click", ".img-info-talla", function () {
            $(this).next().show();
        });
        jQuery('body').on("click", "*[class!=sizes-cuadro],*[class!=sizes-cuadro] *", function () {
            $(".sp-sms-alert").hide();
        });
    },

    LoadFactAddress: function () {
        if (Eshop.bDatFact == 1) {
            if ($('#shiptobilling-checkbox').length > 0 && $('#shiptobilling-checkbox').attr('checked') == 'checked') {
                $('#factaddressCliente').show();
                $('#DireccionMismosDatos').removeAttr('disabled');
                $('#DireccionMismosDatos').attr('checked', false);
                $('#DireccionMismosDatos').removeAttr('checked');
                $('#labdirec').removeAttr('disabled');
            }
            else {
                $('#factaddressCliente').hide();
                $('#factaddress').hide();
                $('#hiddeonsamedata').hide();
                $('#DireccionMismosDatos').attr('disabled', 'disabled');
                $('#labdirec').attr('disabled', 'disabled');
                $('#DireccionMismosDatos').attr('checked', false);
            }
        }
        else {
            if ($('#shiptobilling-checkbox').length > 0 && $('#shiptobilling-checkbox').attr('checked') == 'checked') {
                $('#factaddress').show();
                $('#hiddeonsamedata').show();
                $('#DireccionMismosDatos').removeAttr('disabled');
                $('#DireccionMismosDatos').attr('checked', false);
                $('#DireccionMismosDatos').removeAttr('checked');
                $('#labdirec').removeAttr('disabled');
            }
            else {
                $('#factaddressCliente').hide();
                $('#factaddress').hide();
                $('#hiddeonsamedata').hide();
                $('#DireccionMismosDatos').attr('disabled', 'disabled');
                $('#labdirec').attr('disabled', 'disabled');
                $('#DireccionMismosDatos').attr('checked', false);
            }
        }
    },

    MismosDatosFact: function () {
        if (Eshop.bDatFact == 1) {
            if ($('#DireccionMismosDatos').length > 0 && $('#DireccionMismosDatos').attr('checked') == 'checked') {
                $('#hiddeonsamedata').hide();
                $('#factaddress').hide();
                $('#factaddressCliente').hide();
                $('#ClienteFacturacion_raz_soc_nv').val("");
                $('#ClienteFacturacion_doc_nv').val("");
                $('#ClienteFacturacion_id_i').val("0");
            }
            else {
                $('#factaddressCliente').show();
                $('#hiddeonsamedata').hide();
                $('#factaddress').hide();
            }
        }
        else {
            if ($('#DireccionMismosDatos').length > 0 && $('#DireccionMismosDatos').attr('checked') == 'checked') {
                $('#hiddeonsamedata').hide();
                $('#factaddress').hide();
            }
            else {
                $('#hiddeonsamedata').show();
                $('#factaddress').show();
            }
        }
    },

    ShowDataEnv: function (id) {
        $('#ClienteDireccion_id_i').val(id);
        for (var i = 0; i < dicDirEnvArray.length; i = i + 1) {
            if (dicDirEnvArray[i] != id) {
                $("div[data-id=" + dicDirEnvArray[i] + "]").removeClass('active');
                //$("div[data-id=" + dicDirEnvArray[i] + "]").css('background-color', '#fbfbf9');
                if (dicDirEnvArray[i] > 0) {
                    $("i[data-id=" + dicDirEnvArray[i] + "]").removeClass('icon-check').addClass('icon-check-empty');
                }
            }
        }
        //$(".shipping_address .well.cursor-link").removeClass('active');
        $("div[data-id=" + id + "]").addClass('active');
        //$("div[data-id=" + id + "]").css('background-color', '#d8ebe1');
        $("i[data-id=" + id + "]").removeClass('icon-check-empty').addClass('icon-check');

        if (id == 0) {
            $('#ClienteDireccion_nom_nv').val("");
            $('#ClienteDireccion_ape_nv').val("");
            $('#ClienteDireccion_doc_nv').val("");
            $('#ClienteDireccion_dir_nv').val("");
            $('#ClienteDireccion_cp_nv').val("");
            $('#ClienteDireccion_loc_nv').val("");
            $('#ClienteDireccion_tlf_nv').val("");
            $('#ClienteDireccion_mov_nv').val("");
            $('#ClienteDireccion_alias_nv').val("");
            $('#DirCliEnv').show();
        }
        else {
            $('#DirCliEnv').hide();
            Eshop.St1CheckTransportBox();
        }
    },

    ShowDataFac: function (id) {
        $('#ClienteFacturacion_id_i').val(id);
        for (var i = 0; i < dicDirFacArray.length; i = i + 1) {
            if (dicDirFacArray[i] != id) {
                $("div[data-fac-id=" + dicDirFacArray[i] + "]").removeClass('active');
                //$("div[data-fac-id=" + dicDirFacArray[i] + "]").css('background-color', '#fbfbf9');
                if (dicDirFacArray[i] > 0) {
                    $("i[data-fac-id=" + dicDirFacArray[i] + "]").removeClass('icon-check').addClass('icon-check-empty');
                }
            }
        }
        //$("div[data-fac-id=" + id + "]").css('background-color', '#d8ebe1');
        $("div[data-fac-id=" + id + "]").addClass('active');
        $("i[data-fac-id=" + id + "]").removeClass('icon-check-empty').addClass('icon-check');

        if (id == 0) {
            $('#ClienteFacturacion_raz_soc_nv').val("");
            $('#ClienteFacturacion_doc_nv').val("");
            $('#ClienteFacturacion_nom_nv').val("");
            $('#ClienteFacturacion_ape_nv').val("");
            $('#ClienteFacturacion_dir_nv').val("");
            $('#ClienteFacturacion_cp_nv').val("");
            $('#ClienteFacturacion_loc_nv').val("");
            $('#ClienteFacturacion_tlf_nv').val("");
            $('#ClienteFacturacion_mov_nv').val("");
            $('#ClienteFacturacion_alias_nv').val("");
            $('#factaddress').show();
            $('#hiddeonsamedata').show();
        }
        else {
            $('#hiddeonsamedata').hide();
            $('#factaddress').hide();
        }
    },

    Search: function () {
        if ($('#query').val().length > 3) {
            var form = $("#form_search");
            $(form).submit();
        }
    },

    Search2: function () {
        if ($('#query2').val().length > 3) {
            var form = $("#form_search2");
            $(form).submit();
        }
    },

    St1CheckTransportBox: function () {
        //var form = $("#FormConfirm");
        //$(form).attr("action", "/datos-pedido?red=no")
        //$(form).submit();
        //Eshop.St1CalculaTransporte();
    },

    St1CheckTransport: function () {

        Loading('show');
        var modelo = [];

        modelo.push(new Object({
            TipoEnvio: $("#TipoEnvio").val(),
            Nombre: $("#Nombre").val(),
            Apellido1: $("#Apellido1").val(),
            Apellido2: $("#Apellido2").val(),
            Escalera: $("#ClienteDireccion_escalera_nv").val(),
            Puerta: $("#ClienteDireccion_puerta_nv").val(),
            Piso: $("#ClienteDireccion_piso_nv").val(),
            Alumno: $("#NombreAlumno").val(),
            AlumnoApellido: $("#ApellidosAlumno").val(),
            AlumnoEmail: $('#CorreoAlumno').val(),
            AlumnoSecundario: $("#NombreAlumnoSecundario").val() == undefined
                ? ""
                : $("#NombreAlumnoSecundario").val(),
            AlumnoApellidoSecundario: $("#ApellidosAlumnoSecundario").val() == undefined
                ? ""
                : $("#ApellidosAlumnoSecundario").val(),
            AlumnoEmailSecundario: $('#CorreoAlumnoSecundario').val() == undefined
                ? ""
                : $('#CorreoAlumnoSecundario').val(),
            Email: $("#Cliente_email_nv").val(),
            Numero: $("#ClienteDireccion_numero_nv").val(),
            DirEnvio: $("#DirEnvioSelected").val(),

            Calle: $("#ClienteFacturacion_dir_nv").val(),
            Telefono: $("#ClienteFacturacion_tlf_nv").val(),
            Documento: $("#ClienteFacturacion_doc_nv").val(),
            Localidad: $("#ClienteFacturacion_loc_nv").val(),
            Provincia: $("#ClienteFacturacion_prov_id_s").val(),
            CodigoPostal: $("#ClienteFacturacion_cp_nv").val(),

            DirEnv_NombreCompleto: $("#ClienteDireccion_nom_nv").val() + " " + $("#ClienteDireccion_ape_nv").val(),
            DirEnv_Nombre: $("#ClienteDireccion_nom_nv").val(),
            DirEnv_Apellidos: $("#ClienteDireccion_ape_nv").val(),
            DirEnv_Calle: $("#ClienteDireccion_dir_nv").val(),
            DirEnv_CodigoPostal: $("#ClienteDireccion_cp_nv").val(),
            DirEnv_Documento: $("#ClienteDireccion_doc_nv").val(),
            DirEnv_Localidad: $("#ClienteDireccion_loc_nv").val(),
            DirEnv_Provincia: $("#ClienteDireccion_prov_id_s").val(),
            DirEnv_Telefono: $("#ClienteDireccion_tlf_nv").val(),

            DirCentro_Prov: $('#Centro_prov_terr_id_s').val(),

            AceptPolitica: $("#Cliente_acep_polit_b").val(),
            FormaPago: $("#FormaPagoSeleccionada").val(),

            DireccionC: $("#direccion-c").is(':checked'),
            DireccionA: $("#direccion-a").is(':checked'),
            DireccionB: $("#direccion-b").is(':checked'),
            EsEnvioPorLista: $('#EsEnvioSoloEnLista').val()
        }))

        if ((provAct != $("#ClienteFacturacion_prov_id_s").val() && $("#direccion-c").is(':checked'))
            || (provAct != $('#Centro_prov_terr_id_s').val() && $("#direccion-b").is(':checked'))
            || (provAct != $("#ClienteDireccion_prov_id_s").val() && $("#direccion-a").is(':checked'))) {

            if ($("#direccion-c").is(':checked')) {
                provAct = $("#ClienteFacturacion_prov_id_s").val();
            }
            else if ($("#direccion-b").is(':checked')) {
                provAct = $('#Centro_prov_terr_id_s').val();
            }
            else if ($("#direccion-a").is(':checked')) {
                provAct = $("#ClienteDireccion_prov_id_s").val();
            }
            //Funcon ajax para refrescar la pagina con el modelo y los nuevos importes de IVA
            $.ajax({
                url: "/FunctionRecalculateTaxes",
                type: "post",
                asyn: true,
                dataType: "html",
                data: { mo: JSON.stringify(modelo) },
                success: function (data) {
                    $("#envioPagop").html(data);
                    //TiposEnvio
                    if ($('#direccion-a').is(':checked')) {
                        $('#direccion-a').trigger('click');
                    }
                    else if ($('#direccion-b').is(':checked')) {
                        $('#direccion-b').trigger('click');
                    }
                    else if ($('#direccion-c').is(':checked')) {
                        $('#direccion-c').trigger('click');
                    }
                    Loading('hide');
                }
            });
        }
        else {
            Loading('hide');
        }


        if (Eshop.bDatFact == 1) {
            $('#ClienteDireccion_id_i').val("0");
            $('#ClienteFacturacion_id_i').val("0");
        }
    },

    St1CheckTransportProv: function () {

        Loading('show');
        var modelo = [];

        modelo.push(new Object({
            TipoEnvio: $("#TipoEnvio").val(),
            Nombre: $("#Nombre").val(),
            Apellido1: $("#Apellido1").val(),
            Apellido2: $("#Apellido2").val(),
            Escalera: $("#ClienteDireccion_escalera_nv").val(),
            Puerta: $("#ClienteDireccion_puerta_nv").val(),
            Piso: $("#ClienteDireccion_piso_nv").val(),
            Alumno: $("#NombreAlumno").val(),
            AlumnoApellido: $("#ApellidosAlumno").val(),
            AlumnoEmail: $('#CorreoAlumno').val(),
            AlumnoSecundario: $("#NombreAlumnoSecundario").val() == undefined
                ? ""
                : $("#NombreAlumnoSecundario").val(),
            AlumnoApellidoSecundario: $("#ApellidosAlumnoSecundario").val() == undefined
                ? ""
                : $("#ApellidosAlumnoSecundario").val(),
            AlumnoEmailSecundario: $('#CorreoAlumnoSecundario').val() == undefined
                ? ""
                : $('#CorreoAlumnoSecundario').val(),
            Email: $("#Cliente_email_nv").val(),
            Numero: $("#ClienteDireccion_numero_nv").val(),
            DirEnvio: $("#DirEnvioSelected").val(),

            Calle: $("#ClienteFacturacion_dir_nv").val(),
            Telefono: $("#ClienteFacturacion_tlf_nv").val(),
            Documento: $("#ClienteFacturacion_doc_nv").val(),
            Localidad: $("#ClienteFacturacion_loc_nv").val(),
            Provincia: $("#ClienteFacturacion_prov_id_s").val(),
            CodigoPostal: $("#ClienteFacturacion_cp_nv").val(),

            DirEnv_NombreCompleto: $("#ClienteDireccion_nom_nv").val() + " " + $("#ClienteDireccion_ape_nv").val(),
            DirEnv_Nombre: $("#ClienteDireccion_nom_nv").val(),
            DirEnv_Apellidos: $("#ClienteDireccion_ape_nv").val(),
            DirEnv_Calle: $("#ClienteDireccion_dir_nv").val(),
            DirEnv_CodigoPostal: $("#ClienteDireccion_cp_nv").val(),
            DirEnv_Documento: $("#ClienteDireccion_doc_nv").val(),
            DirEnv_Localidad: $("#ClienteDireccion_loc_nv").val(),
            DirEnv_Provincia: $("#ClienteDireccion_prov_id_s").val(),
            DirEnv_Telefono: $("#ClienteDireccion_tlf_nv").val(),

            DirCentro_Prov: $('#Centro_prov_terr_id_s').val(),

            AceptPolitica: $("#Cliente_acep_polit_b").val(),
            FormaPago: $("#FormaPagoSeleccionada").val(),

            DireccionC: $("#direccion-c").is(':checked'),
            DireccionA: $("#direccion-a").is(':checked'),
            DireccionB: $("#direccion-b").is(':checked'),
            EsEnvioPorLista: $('#EsEnvioSoloEnLista').val()

        }))

        if ((provAct != $("#ClienteFacturacion_prov_id_s").val() && $("#direccion-c").is(':checked'))
            || (provAct != $('#Centro_prov_terr_id_s').val() && $("#direccion-b").is(':checked'))
            || (provAct != $("#ClienteDireccion_prov_id_s").val() && $("#direccion-a").is(':checked'))) {

            if ($("#direccion-c").is(':checked')) {
                provAct = $("#ClienteFacturacion_prov_id_s").val();
            }
            else if ($("#direccion-b").is(':checked')) {
                provAct = $('#Centro_prov_terr_id_s').val();
            }
            else if ($("#direccion-a").is(':checked')) {
                provAct = $("#ClienteDireccion_prov_id_s").val();
            }
            //Funcon ajax para refrescar la pagina con el modelo y los nuevos importes de IVA
            $.ajax({
                url: "/FunctionRecalculateTaxes",
                type: "post",
                asyn: true,
                dataType: "html",
                data: { mo: JSON.stringify(modelo), refresh: false },
                success: function (data) {
                    $("#envioPagop").html(data);
                    //TiposEnvio
                    if ($('#direccion-a').is(':checked')) {
                        $('#direccion-a').trigger('click');
                    }
                    else if ($('#direccion-b').is(':checked')) {
                        $('#direccion-b').trigger('click');
                    }
                    else if ($('#direccion-c').is(':checked')) {
                        $('#direccion-c').trigger('click');
                    }
                    Loading('hide');
                }
            });
        }
        else {
            Loading('hide');
        }


        if (Eshop.bDatFact == 1) {
            $('#ClienteDireccion_id_i').val("0");
            $('#ClienteFacturacion_id_i').val("0");
        }
    },


    St1CheckTransportProvReparaciones: function (rma, codLista) {

        Loading('show');
        var modelo = [];

        modelo.push(new Object({
            TipoEnvio: $("#TipoEnvio").val(),
            Nombre: $("#Nombre").val(),
            Apellido1: $("#Apellido1").val(),
            Apellido2: $("#Apellido2").val(),
            Escalera: $("#ClienteDireccion_escalera_nv").val(),
            Puerta: $("#ClienteDireccion_puerta_nv").val(),
            Piso: $("#ClienteDireccion_piso_nv").val(),
            Alumno: $("#NombreAlumno").val(),
            AlumnoApellido: $("#ApellidosAlumno").val(),
            AlumnoEmail: $('#CorreoAlumno').val(),
            AlumnoSecundario: $("#NombreAlumnoSecundario").val() == undefined
                ? ""
                : $("#NombreAlumnoSecundario").val(),
            AlumnoApellidoSecundario: $("#ApellidosAlumnoSecundario").val() == undefined
                ? ""
                : $("#ApellidosAlumnoSecundario").val(),
            AlumnoEmailSecundario: $('#CorreoAlumnoSecundario').val() == undefined
                ? ""
                : $('#CorreoAlumnoSecundario').val(),
            Email: $("#Cliente_email_nv").val(),
            Numero: $("#ClienteDireccion_numero_nv").val(),
            DirEnvio: $("#DirEnvioSelected").val(),

            Calle: $("#ClienteFacturacion_dir_nv").val(),
            Telefono: $("#ClienteFacturacion_tlf_nv").val(),
            Documento: $("#ClienteFacturacion_doc_nv").val(),
            Localidad: $("#ClienteFacturacion_loc_nv").val(),
            Provincia: $("#ClienteFacturacion_prov_id_s").val(),
            CodigoPostal: $("#ClienteFacturacion_cp_nv").val(),

            DirEnv_NombreCompleto: $("#ClienteDireccion_nom_nv").val() + " " + $("#ClienteDireccion_ape_nv").val(),
            DirEnv_Nombre: $("#ClienteDireccion_nom_nv").val(),
            DirEnv_Apellidos: $("#ClienteDireccion_ape_nv").val(),
            DirEnv_Calle: $("#ClienteDireccion_dir_nv").val(),
            DirEnv_CodigoPostal: $("#ClienteDireccion_cp_nv").val(),
            DirEnv_Documento: $("#ClienteDireccion_doc_nv").val(),
            DirEnv_Localidad: $("#ClienteDireccion_loc_nv").val(),
            DirEnv_Provincia: $("#ClienteDireccion_prov_id_s").val(),
            DirEnv_Telefono: $("#ClienteDireccion_tlf_nv").val(),

            DirCentro_Prov: $('#Centro_prov_terr_id_s').val(),

            AceptPolitica: $("#Cliente_acep_polit_b").val(),
            FormaPago: $("#FormaPagoSeleccionada").val(),

            DireccionC: $("#direccion-c").is(':checked'),
            DireccionA: $("#direccion-a").is(':checked'),
            DireccionB: $("#direccion-b").is(':checked'),
            EsEnvioPorLista: $('#EsEnvioSoloEnLista').val(),

            SerialNumber: rma.SerialNumber,
            RMANumber: rma.RMANumber,
            Total: rma.Total

        }))

        if ($("#direccion-c").is(':checked')) {
            provAct = $("#ClienteFacturacion_prov_id_s").val();
        }
        else if ($("#direccion-b").is(':checked')) {
            provAct = $('#Centro_prov_terr_id_s').val();
        }
        else if ($("#direccion-a").is(':checked')) {
            provAct = $("#ClienteDireccion_prov_id_s").val();
        }
        //Funcon ajax para refrescar la pagina con el modelo y los nuevos importes de IVA
        $.ajax({
            url: "/FunctionRecalculateTaxes",
            type: "post",
            asyn: true,
            dataType: "html",
            data: { mo: JSON.stringify(modelo), refresh: false },
            success: function (data) {
                $("#envioPagop").html(data);
                //TiposEnvio
                if ($('#direccion-a').is(':checked')) {
                    $('#direccion-a').trigger('click');
                }
                else if ($('#direccion-b').is(':checked')) {
                    $('#direccion-b').trigger('click');
                }
                else if ($('#direccion-c').is(':checked')) {
                    $('#direccion-c').trigger('click');
                }

                $('.NumeroSerie-' + codLista).val(rma.SerialNumber);
                $('#NumeroRMA').val(rma.RMANumber);
            },
            always: function () {
                Loading('hide');
            }

        });

        if (Eshop.bDatFact == 1) {
            $('#ClienteDireccion_id_i').val("0");
            $('#ClienteFacturacion_id_i').val("0");
        }
    },



    //St1CalculaTransporte: function myfunction() {
    //    if (Eshop.numTransports > 1) {
    //        $("#LstTransportistas").show();
    //    }
    //    else {
    //        $("#LstTransportistas").hide();
    //    }

    //    // Dirección seleccionada para obtener los transportistas para ese PAIS y PROVINCIA
    //    var idCliEnv = "0";
    //    if (Eshop.bDatEnv == 1) {
    //        idCliEnv = $('#ClienteDireccion_id_i').val();
    //    }

    //    $(".transport-label").hide();
    //    $(".transport-container img,.gastosenviocont img").show();

    //    if ($("#ClienteDireccion_prov_id_s").val() > 0) {
    //        $.ajax({
    //            url: "/Buy/CalculaTransporte",
    //            type: "post",
    //            asyn: true,
    //            dataType: "json",
    //            data: { idCliEnv: idCliEnv, pais: $("#ClienteDireccion_pais_id_s").val(), provincia: $("#ClienteDireccion_prov_id_s").val(), transportista: $('input[name=transportista]:checked').val() },
    //            success: function (data) {
    //                if (data.Result == 0) {
    //                    $(".transport-container img, .gastosenviocont img").hide();
    //                    $(".transport-label").show();
    //                    $("#transportistasRdb").html(data.Data);
    //                    $("#gastosenvio").html(data.precioEnvio);
    //                    $("#tototal").html(data.totalCarrito);
    //                    Eshop.numTransports = data.numTransports;
    //                    if (Eshop.numTransports > 1) {
    //                        $("#LstTransportistas").show();
    //                    }
    //                    else {
    //                        $("#LstTransportistas").hide();
    //                    }
    //                } else {
    //                }
    //            },
    //            //complete: function () {
    //            // location.href = location.href;
    //            //}
    //        });
    //    }
    //    else {
    //        $(".transport-container img, .gastosenviocont img").hide();
    //    }
    //},

    Literal: {
        Delete: "",
        Si: "",
        No: ""
    },

    Modals: {
        varModal: function () {
            $('body').scrollTop(0);
            $("#land_corporativa").dialog({
                dialogClass: "alert",
                modal: true,
                resizable: false,
                closeOnEscape: true,
                maxHeight: 400,
                position: {
                    my: "left top",
                    at: "left top",
                    of: window
                }
            });
        },
        AtencionCli: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        ParaEmpresas: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        QuieresSer: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        Condiciones: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        Politica: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        Aviso: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        DevModifi: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        Condiciones: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
        Terminos: function () {
            $(".modal-dialog").dialog({
                dialogClass: "alert",
                modal: true, resizable: false, closeOnEscape: true
            });
        },
    },/*,

    SolicitudCambioPass: function () {
    $.ajax({
    url: "/es/recordar",
    type: "post",
    asyn: true,
    dataType: "json",
    data: { email: $("#email_recPass").val()},
    success: function (data) {
    if (data.Result == 0) {
    // no se ha encontrado cliente
    $(".newsletter-input .w-ok").css("visibility", "visible").css("display", "block");
    $(".newsletter-input .w-ok").show();
    } else if (data.Result == 1) {
    // se ha enviado el correo
    $(".newsletter-input .w-politica").css("visibility", "visible").css("display", "block");
    $(".newsletter-input .w-politica").show();
    } else if (data.Result == 2) {
    // no ha introducido email
    $(".newsletter-input .email-ko").css("visibility", "visible").css("display", "block");
    $(".newsletter-input .email-ko").show();
    } else if (data.Result == 3) {
    // ha ocurrido algun error
    $(".newsletter-input .email-ko").css("visibility", "visible").css("display", "block");
    $(".newsletter-input .email-ko").show();
    }
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
    $("#divInfoHorario").hide();
    }
    });

    }
    */

    Marista: {
        Init: function () {
            Eshop.Marista.Modal.Init();
            Eshop.Marista.IncrementDecrement();
            $("input[id^='rb_product_mar_']").change(function () {
                Eshop.Marista.OnSelectProduct($(this).val(), $(this).data("product"));
            });
        },
        Modal: {
            Init: function () {
                $('.sinStock').click(function () {
                    Eshop.Marista.Modal.ShowSinStock();
                });

                $('.marista-productos .sinStock').click(function () {
                    var inputRadio = $(this).find("input[id^='rb_product_mar_']").first();
                    Eshop.Marista.OnSelectProduct($(inputRadio).val(), $(inputRadio).data("product"));
                });

                $('#btnModalStockOk').click(function () {
                    Eshop.Marista.Modal.HideSinStock();
                });

                $('#btnModalProductosStockOk').click(function () {
                    Eshop.Marista.Modal.HideSinStockProductos();
                });
            },
            ShowSinStock: function () {
                //$('#modalSinStock').modal('show');
            },
            HideSinStock: function () {
                $('#modalSinStock').modal('hide');
            },
            ShowRemoveProduct: function () {
                $('#modalRemoveProduct').modal('show');
            },
            HideRemoveProduct: function () {
                $('#modalRemoveProduct').modal('hide');
            },
            ShowSinStockProductos: function () {
                $('#modalProductosSinStock').modal('show');
            },
            HideSinStockProductos: function () {
                $('#modalProductosSinStock').modal('hide');
            },
            HideData: function (modal) {
                $('#' + modal).modal('hide');
            },
        },
        IncrementDecrement: function () {
            //var cant_min = parseInt($('input[name="cant_min_b2b"]').val());
            var cant_min = 1;

            jQuery("body").on("click", ".marista.plus.cart-plus", function (event) {
                var stock = 9999;
                if ($("#stock_variedad").val() >= 0) {
                    stock = $("#stock_variedad").val();
                }
                if (jQuery(this).prev().val() < stock) {
                    jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);

                    var ou = jQuery(this);
                    Eshop.Marista.IncrementItem($(ou).data("va"), jQuery(this).prev().val(), $("#usr_" + $(ou).data("va")).val(), event, true);
                    showPrice();
                }
            });

            jQuery("body").on("click", ".marista.minus.cart-minus", function (event) {
                if (jQuery(this).next().val() > 1) {
                    if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                        jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                    }

                    var ou = jQuery(this);
                    Eshop.Marista.IncrementItem($(ou).data("va"), jQuery(this).next().val(), $("#usr_" + $(ou).data("va")).val(), event, true);
                    showPrice();
                }
            });

            jQuery("body").on("click", ".marista.add.cart-plus", function (event) {
                if (jQuery(this).prev().val() < parseInt(jQuery(this).prev().prop('max'))) {
                    jQuery(this).prev().val(parseInt(jQuery(this).prev().val()) + 1);
                }

                var ou = jQuery(this);
                //Comprobamos si esta seleccionado el Item
                var inputRadio = $("input[value='" + $(ou).data("va") + "']");
                if ($(inputRadio).prop("checked")) {
                    //Ya esta seleccionado, incrementamos
                    Eshop.Marista.IncrementItem($(ou).data("va"), jQuery(this).prev().val(), $("#usr_" + $(ou).data("va")).val(), event, true);
                }
                else {
                    //No esta seleccionado, forzamos cambio
                    $(inputRadio).prop("checked", true);
                    Eshop.Marista.OnSelectProduct($(inputRadio).val(), $(inputRadio).data("product"));
                }
            });

            jQuery("body").on("click", ".marista.remove.cart-minus", function (event) {
                if (jQuery(this).next().val() > 0) {
                    if (jQuery(this).next().val() > parseInt(jQuery(this).next().prop('min'))) {
                        jQuery(this).next().val(parseInt(jQuery(this).next().val()) - 1);
                    }
                    var ou = jQuery(this);
                    Eshop.Marista.IncrementItem($(ou).data("va"), jQuery(this).next().val(), $("#usr_" + $(ou).data("va")).val(), event, true);
                    var inputRadio = $("input[value='" + $(ou).data("va") + "']");
                    Eshop.Marista.OnRemoveProduct($(inputRadio).val(), $(inputRadio).data("product"));
                }
            });
        },
        UpdateItemPrice: function myfunction(va, usr, price, price_old) {
            $("#lbl_price_" + usr + "_" + va).html(price);
            $("#lbl_price_old_" + usr + "_" + va).html(price_old);
        },
        IncrementItem: function myfunction(va, ca, usr, e, checkCart) {
            checkCart = checkCart || false;
            var struct = [];
            var int = 0;
            var eo = e;
            usr = usr || 0;
            var inputCantidad = "#cant_" + usr + "_" + va;
            var inputPrice = "#price_" + usr + "_" + va;
            //$(".loading-carrito").show();
            //$(".span3 .cart-details").animate({ opacity: 0.2 }, 200);
            //$(".loader").animate({ opacity: 0.2 }, 200, function () {
            $("#spinnerMaristaProducts").show();
            $("#btnMaristaProducts").attr("disabled", "");
            struct.push(new Object({
                Variedad: va,
                Cant: $(inputCantidad).val(),
                Precio: $(inputPrice).val()
            }));

            $.ajax({
                url: "/Marista/ChangeItemMaristaCart",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { vm: JSON.stringify(struct) },
                success: function (data) {
                    if (data.Result == 0) {
                        Eshop.Marista.UpdateItemPrice(va, usr, data.Html_price, data.Html_price_old);
                        if (checkCart == true) {
                            $.when(Eshop.Marista.GetFullCart()).done(function () {
                                //$(".loader").animate({ opacity: 1 }, 200);
                                $("#spinnerMaristaProducts").hide();
                                $("#btnMaristaProducts").removeAttr("disabled");
                            });
                        }

                        //var promise = Eshop.Marista.GetFullCart();
                        //promise.done(function () {
                        //    $("#spinnerMaristaProducts").hide();
                        //    $("#btnMaristaProducts").removeAttr("disabled");
                        //});
                    }
                    // Hay errores
                    if (data.Result == 1) {
                        $(data.Data).each(function (i, item) {
                            //$(".loader").animate({ opacity: 1 }, 200);
                            $("#spinnerMaristaProducts").hide();
                            $("#btnMaristaProducts").removeAttr("disabled");
                            $(inputCantidad).popover({ placement: 'bottom', content: item.Value, template: '<div class="popover" data-trigger="focus" ><div class="arrow"></div><div class="popover-inner"><div class="popover-content"><p></p></div></div></div>' });
                            //Corrección del valor
                            $(inputCantidad).val($(inputCantidad).val() - 1);
                            //Mostramos popover, espera 3 segundos, destruye el elemento
                            $(inputCantidad).popover('show');
                            setTimeout(function () { $(inputCantidad).popover('destroy'); }, 1000);
                        });
                    }
                },
                complete: function () {
                    //$(".loading-carrito").hide();
                    //$("#spinnerMaristaProducts").hide();
                    //$("#btnMaristaProducts").removeAttr("disabled");
                }
            });
            //});
        },
        SetItemCantidad: function (id_var, cant) {
            var inputCantidad = "#cant_" + Eshop.Marista.GetItemUser(id_var) + "_" + id_var;
            if (cant <= parseInt($(inputCantidad).prop('max')) && parseInt($(inputCantidad).attr('stock')) > 0) {
                $(inputCantidad).val(parseInt(cant));
                return true;
            }
            else if (parseInt($(inputCantidad).attr('stock')) == 0) {
                return
            }
            else return false;
        },
        GetFullCart: function myfunction(e) {
            var struct = [];
            var int = 0;
            var eo = e;
            $("#spinnerMaristaProducts").show();
            $("#btnMaristaProducts").attr("disabled", "");
            struct = Eshop.Marista.GetItemsSelected();

            return $.ajax({
                url: "/Marista/GetFullMaristaCart",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { vm: JSON.stringify(struct) },
                success: function (data) {
                    if (data.Result == 0) {
                        $("#divMaristaCart").html(data.Html);
                    }
                    // Hay errores
                    if (data.Result == 1) {

                    }
                },
                complete: function () {
                }
            });
        },
        GetItemUser: function (itm_var) {
            return $("#usr_" + itm_var).val();
        },
        GetItemsSelected: function () {
            var struct = [];
            var itemsSelected = $("input[id^='rb_product_mar_']:checked");
            itemsSelected.each(function (index) {
                var itm_nom = $(this).data("name");
                var itm_var = $(this).val();
                var itm_usr = $("#usr_" + itm_var).val();
                var itm_cant = $("#cant_" + itm_usr + "_" + itm_var).val();
                var itm_precio = $("#price_" + itm_usr + "_" + itm_var).val();
                var itm_iva = $(this).data("iva");
                if (itm_cant > 0) {
                    struct.push(new Object({
                        Nombre: itm_nom,
                        Variedad: itm_var,
                        Alumno: itm_usr,
                        Cant: itm_cant,
                        Precio: itm_precio,
                        Iva: itm_iva,
                    }));
                }
            });
            return struct;
        },
        GetItemsNoStock: function () {
            var struct = [];
            var itemsNoStock = $("input[id^='rb_product_mar_'][data-stock='False']:checked");
            itemsNoStock.each(function (index) {
                var itm_var = $(this).val();
                struct.push(new Object({
                    Wishlist: -1,
                    Variedad: itm_var,
                }));
            });
            return struct;
        },
        OnSelectProduct: function (id_var, id_product) {
            var itemSelectedSelector = $("#rb_product_mar_" + Eshop.Marista.GetItemUser(id_var) + "_" + id_product + "_" + id_var);
            var itemsVariedadProduct = $("input[id^='rb_product_mar_" + Eshop.Marista.GetItemUser(id_var) + "_" + id_product + "_']");

            if (itemSelectedSelector.data("stock") == "False") {
                $('#btnModalStockOk').click(function (event) {
                    Eshop.Marista.Modal.HideSinStock();
                    $(itemSelectedSelector).prop("checked", true);
                    itemsVariedadProduct.each(function (index) {
                        if (itemsVariedadProduct.length - 1 == index) {
                            checkCart = true;
                        }
                        else {
                            checkCart = false;
                        }
                        var cant = 0;
                        if ($(this).attr("id") == $(itemSelectedSelector).attr("id")) {
                            cant = 1;
                        }

                        if (Eshop.Marista.SetItemCantidad($(this).val(), cant)) {
                            Eshop.Marista.IncrementItem($(this).val(), cant, Eshop.Marista.GetItemUser($(this).val()), null, checkCart);
                        }
                        else {
                            //No hay stock disponible. Deberiamos dejar cantidades originales
                        }
                    });

                    //$.when(Eshop.Marista.GetFullCart()).done(function () {
                    //    //$(".loader").animate({ opacity: 1 }, 200);
                    //    $("#spinnerMaristaProducts").hide();
                    //    $("#btnMaristaProducts").removeAttr("disabled");
                    //});
                });
            }
            else {

                itemsVariedadProduct.each(function (index) {
                    if (itemsVariedadProduct.length - 1 == index) {
                        checkCart = true;
                    }
                    else {
                        checkCart = false;
                    }
                    var cant = 0;
                    if ($(this).attr("id") == $(itemSelectedSelector).attr("id")) {
                        cant = 1;
                    }

                    if (Eshop.Marista.SetItemCantidad($(this).val(), cant)) {
                        Eshop.Marista.IncrementItem($(this).val(), cant, Eshop.Marista.GetItemUser($(this).val()), null, checkCart);
                    }
                    else {
                        //No hay stock disponible. Deberiamos dejar cantidades originales
                    }
                });

                //$.when(Eshop.Marista.GetFullCart()).done(function () {
                //    //$(".loader").animate({ opacity: 1 }, 200);
                //    $("#spinnerMaristaProducts").hide();
                //    $("#btnMaristaProducts").removeAttr("disabled");
                //});
            }
        },
        AddItemsShoppingCarr: function () {
            //$(".loader").animate({ opacity: 0.2 }, 200);
            $("#spinnerMaristaProducts").show();
            $("#btnMaristaProducts").attr("disabled", "");
            //logued = logued || false;
            var struct = [];
            struct = Eshop.Marista.GetItemsSelected();

            if (struct.length > 0) {
                return $.ajax({
                    url: "/Buy/AddItemsBuyCart",
                    type: "post",
                    asyn: true,
                    dataType: "json",
                    data: { vm: JSON.stringify(struct) },
                    success: function (data) {
                        if (data.Result == 0) {
                            //if (!logued)
                            //{
                            //    LoginPopUp.Action = "Step1";
                            //    LoginPopUp.Controller = "Buy";
                            //    LoginPopUp.mostrarModalLogin();
                            //    $(".loader").animate({ opacity: 1 }, 200);
                            //    $("#spinnerMaristaProducts").hide();
                            //    $("#btnMaristaProducts").removeAttr("disabled");
                            //} else {
                            //    Eshop.Marista.AddItemsToWishlist();
                            //    if (returnUrl != "") { window.location.href = returnUrl; }
                            //}

                        } else {
                            $(data.Data).each(function (i, item) {
                                //$("#AvisoAsync").text(item.Value);
                                //$("#AvisoAsync").show();
                                $(".loader").animate({ opacity: 1 }, 200);
                                $("#spinnerMaristaProducts").hide();
                                $("#btnMaristaProducts").removeAttr("disabled");
                            });
                        }
                    },
                    complete: function () {
                        //$(".ajax-loading").hide();
                        //$("#btnComprar").removeClass("disabled loading");
                    }
                });
            }
            else {
                //Debe seleccionar
                //$(".loader").animate({ opacity: 1 }, 200);
                $("#spinnerMaristaProducts").hide();
                $("#btnMaristaProducts").removeAttr("disabled");
            }
        },
        BuyItemsMarista: function (logued, returnUrl) {

            var struct = [];
            struct = Eshop.Marista.GetItemsNoStock();
            if (struct.length > 0) {
                Eshop.Marista.Modal.ShowSinStockProductos();
                $('#btnModalProductosStockOk').click(function () {
                    Eshop.Marista.Modal.HideSinStockProductos();
                    logued = logued || false;

                    if (!logued) {
                        LoginPopUp.Action = "Step1";
                        LoginPopUp.Controller = "Buy";
                        LoginPopUp.From = "LstProductMarista";
                        LoginPopUp.mostrarModalLogin();
                    } else {
                        Eshop.Marista.ActionBuyItemsMarista(returnUrl);
                    }
                });
            }
            else {

                logued = logued || false;

                if (!logued) {
                    LoginPopUp.Action = "Step1";
                    LoginPopUp.Controller = "Buy";
                    LoginPopUp.From = "LstProductMarista";
                    LoginPopUp.mostrarModalLogin();
                } else {
                    Eshop.Marista.ActionBuyItemsMarista(returnUrl);
                }
            }
        },
        ActionBuyItemsMarista: function (returnUrl) {
            //$(".loader").animate({ opacity: 0.2 }, 200);
            $("#spinnerMaristaProducts").show();
            $("#btnMaristaProducts").attr("disabled", "");

            //MARISTAS - Add To Cart - Add To Wishlist
            $.when(Eshop.Marista.AddItemsShoppingCarr(), Eshop.Marista.AddItemsToWishlist()).then(function () {
                //WithCart
                var num_car = Eshop.Marista.GetNumElementsShopCart();
                var num_wish = Eshop.Marista.GetNumElementsWishList();
                if (num_car > 0) returnUrl = returnUrl.split("|")[0];
                else returnUrl = returnUrl.split("|")[1];

                if (returnUrl != "") {
                    window.location.href = returnUrl;
                }
                //$.when(Eshop.Marista.GetNumElementsShopCart(), Eshop.Marista.GetNumElementsWishList()).then(function () {
                //    var num_car = $("#cart-mini-edv").attr("data-title");
                //    var num_wish = $("#wl-mini-edv").attr("data-title");
                //    if (num_car > 0) returnUrl = returnUrl.split("|")[0];
                //    else returnUrl = returnUrl.split("|")[1];

                //    if (returnUrl != "") {
                //        window.location.href = returnUrl;
                //    }
                //});
                //$("#spinnerMaristaProducts").hide();
            });
        },

        GetNumElementsShopCart: function () {
            return Eshop.Marista.GetItemsSelected().length;
            //return $.post("/buy/get-num-cart", function (data) {
            //    $("#cart-mini-edv").attr("data-title", data);
            //}).done(function () {
            //});
        },

        GetNumElementsWishList: function () {
            return Eshop.Marista.GetItemsNoStock().length;
            //return $.post("/buy/get-num-wl", function (data) {
            //    $("#wl-mini-edv").attr("data-title", data);
            //}).done(function () {

            //});
        },


        AddItemsToWishlist: function () {
            //$(".loader").animate({ opacity: 0.2 }, 200);
            $("#spinnerMaristaProducts").show();
            $("#btnMaristaProducts").attr("disabled", "");

            var struct = [];
            struct = Eshop.Marista.GetItemsNoStock();

            if (struct.length > 0) {
                $.ajax({
                    url: "/Buy/AddProductsWish",
                    type: "post",
                    asyn: true,
                    dataType: "json",
                    data: { vm: JSON.stringify(struct) },
                    success: function (data) {
                        if (data.Result == 0) {


                        } else {


                        }
                    },
                    complete: function () {

                    }
                });
            }
            else {
                //$(".loader").animate({ opacity: 1 }, 200);
                //$("#spinnerMaristaProducts").hide();
                //$("#btnMaristaProducts").removeAttr("disabled");
            }
        },
        OnRemoveProduct: function (id_var, id_product) {

            var itemSelectedSelector = $("#rb_product_mar_" + Eshop.Marista.GetItemUser(id_var) + "_" + id_product + "_" + id_var);
            var itemsVariedadProductDig = $("input[id^='rb_product_mar_" + Eshop.Marista.GetItemUser(id_var) + "_" + id_product + "_'][data-dig='True']");

            if (itemsVariedadProductDig.length > 0) {

                //Mostramos Popup
                Eshop.Marista.Modal.ShowRemoveProduct();

                jQuery("body").on("click", "#btnModalRemoveProductOk", function (event) {
                    //Marcamos Digital
                    $(itemsVariedadProductDig).first().prop("checked", true);
                    Eshop.Marista.OnSelectProduct($(itemsVariedadProductDig).first().val(), $(itemsVariedadProductDig).first().data("product"));
                    Eshop.Marista.Modal.HideRemoveProduct();
                });

                jQuery("body").on("click", "#btnModalRemoveProductCancel", function (event) {
                    Eshop.Marista.Modal.HideRemoveProduct();
                });
            }
        },

        /*
         * Para la vista de mis-alumnos
         */
        GetItemsMisAlumnosSelected: function (idAlumno) {
            var struct = [];
            var itemsSelected = $("input[id^='rb_product_off_mar_" + idAlumno + "_']:checked");
            itemsSelected.each(function (index) {
                var itm_var = $(this).val();

                if (itm_var != '-1') {
                    struct.push(new Object({
                        Nombre: $('#nombreLibro_' + idAlumno + '-' + $(this).data('product')).html(),
                        Variedad: itm_var,
                        Alumno: '',
                        Cant: $('#cant_' + idAlumno + '-' + $(this).data('product')).val(),
                        Precio: '0',
                        Iva: '0',
                    }));
                }
            });
            return struct;
        },

        SavePedidoAlumno: function myfunction(idAlumno, idCentroEtapaCurso) {
            $("#msgErrorPedidoAlumno-" + idAlumno).hide();
            $("#msgExitoPedidoAlumno-" + idAlumno).hide();
            $("#spinner-misalumnos-" + idAlumno).show();

            var struct = [];
            var int = 0;

            struct = Eshop.Marista.GetItemsMisAlumnosSelected(idAlumno);

            $.ajax({
                url: "/Marista/SavePedidoMisAlumnos",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { vm: JSON.stringify(struct), idAlumno: idAlumno, idCentroEtapaCurso: idCentroEtapaCurso },
                success: function (data) {
                    if (data.Result <= 0) {
                        // ha ocurrido un error
                        $("#msgErrorPedidoAlumno-" + idAlumno).html(data.Mensaje).show();
                        // ocultamos el boton de confirmar
                        //$("#divConfirmarAlumno-" + idAlumno).hide();
                    } else if (data.Result > 0) {
                        // el usuario se ha registrado con exito
                        $("#msgExitoPedidoAlumno-" + idAlumno).html(data.Mensaje).show();
                        // marcamos como guardo el usuario
                        $("#icGuardadoCliente-" + idAlumno).show();
                        // habilitamos la opcion de crear el pedido
                        $("#divConfirmarAlumno-" + idAlumno).show();

                        // Ha ido todo ok, falta saber si hay que permitir confirmar
                        if (data.Result == 1) {
                            // todos los usuarios estan guardados
                            $('#span-conf-pedido-ML-' + idCentroEtapaCurso).hide();
                            $('#button-conf-pedido-ML-' + idCentroEtapaCurso).show();
                        } else if (data.Result == 2) {
                            // hay algun usuario sin guardar
                            $('#span-conf-pedido-ML-' + idCentroEtapaCurso).show();
                            $('#button-conf-pedido-ML-' + idCentroEtapaCurso).hide();
                        }
                    }
                },
                complete: function () {
                    $("#spinner-misalumnos-" + idAlumno).hide();
                }
            });
        },

        ConfirmPedidoAlumno: function (idAlumno, idCentroEtapaCurso) {
            $("#msgErrorPedidoAlumno-" + idAlumno).hide();
            $("#msgExitoPedidoAlumno-" + idAlumno).hide();
            $("#spinner-misalumnos-" + idAlumno).show();

            var struct = [];
            struct = Eshop.Marista.GetItemsMisAlumnosSelected(idAlumno);

            $.ajax({
                url: "/Marista/ConfirmPedidoAlumno",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { vm: JSON.stringify(struct), idAlumno: idAlumno, idCentroEtapaCurso: idCentroEtapaCurso },
                success: function (data) {
                    if (data.Result > 0) {
                        window.location.href = data.Url;
                    } else {
                        $("#msgErrorPedidoAlumno-" + idAlumno).html(data.Mensaje).show();
                        //$("#divConfirmarAlumno-" + idAlumno).hide();
                    }
                },
                complete: function () {
                    $("#spinner-misalumnos-" + idAlumno).hide();
                }
            })
        },

        GetEdicionAlumno: function (idAlumno) {
            var struct = [];
            struct.push(new Object({
                Id: idAlumno,
                Nombre: $('#editar-alumno-nombre-' + idAlumno).val(),
                Apellidos: $('#editar-alumno-apell-' + idAlumno).val(),
                NombrePadre: $('#editar-alumno-padre-nombre-' + idAlumno).val(),
                NIFPadre: $('#editar-alumno-padre-nif-' + idAlumno).val(),
                DireccionPadre: $('#editar-alumno-padre-dir-' + idAlumno).val(),
                TelefonoPadre: $('#editar-alumno-padre-telefono-' + idAlumno).val()
            }));
            return struct;
        },

        EditAlumno: function (idAlumno, idCentroEtapaCurso) {
            $("#msgErrorEditarAlumno-" + idAlumno).hide();
            $("#msgExitoEditarAlumno-" + idAlumno).hide();

            var struct = [];
            var int = 0;

            struct = Eshop.Marista.GetEdicionAlumno(idAlumno);

            $.ajax({
                url: "/Marista/EditarAlumno",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { vm: JSON.stringify(struct), idAlumno: idAlumno, idCentroEtapaCurso: idCentroEtapaCurso },
                success: function (data) {
                    if (data.Result == -1) {
                        // ha ocurrido un error
                        $("#msgErrorEditarAlumno-" + idAlumno).html(data.Mensaje).show();
                    } else if (data.Result > 0) {
                        // el usuario se ha registrado con exito
                        $("#msgExitoEditarAlumno-" + idAlumno).html(data.Mensaje).show();
                        $("#alumno-cabecera-" + idAlumno).html(data.Alumno);
                        $("#alumno-lateral-" + idAlumno).html(data.Alumno);
                    }
                },
                complete: function () {
                }
            });

        }

    }
}

var Tglobe = {

    InicialiceDataSlider: function () {
        /// <summary>
        /// Inicializa el listener de eventos para el gadget de paginacion con listas horizontales
        /// </summary>
        /// <returns type="void" />
        $("li.pageDecrement").on("click", Tglobe.DataSlider.Decrement);
        $("li.pageIncrement").on("click", Tglobe.DataSlider.Increment);
        $(".iliV").live("click", Tglobe.DataSlider.SetCurrent);
    },


    DataSlider: {
        Decrement: function () {
            console.log("Decrement");
            $("li.pageDecrement").unbind("click");
            $("li.pageIncrement").unbind("click");
            if (!$($(this).parent().children('.iliV').first().prev()).hasClass("pageDecrement")) {
                $(this).parent().children('.iliV ').last().removeClass("iliV").addClass("iliH").hide();
                $(this).parent().children('.iliV').first().prev().removeClass("iliH").addClass("iliV").show();
                Tglobe.DataSlider._resetBind();
                //$(this).parent().children('.iliV ').last().css("","0px").animate({ width: '0px', "display": "none" }, 100, function () {
                //    $(this).removeClass("iliV").addClass("iliH").css("display", "none").css("width", "37px");
                //    $(this).parent().children('.iliV').first().prev().css("width", "0px").removeClass("iliH").addClass("iliV").animate({ width: '37px', "display": "inline" }, 200, function () {
                //        Tglobe.DataSlider._resetBind();
                //    });
                //});
            } else {
                Tglobe.DataSlider._resetBind();
            }
        },
        Increment: function () {
            console.log("Increment");
            $("li.pageDecrement").unbind("click");
            $("li.pageIncrement").unbind("click");
            if (!$($(this).parent().children('.iliV').last().next()).hasClass("pageIncrement")) {
                $(this).parent().children('.iliV ').first().removeClass("iliV").addClass("iliH").hide();
                $(this).parent().children('.iliV').last().next().removeClass("iliH").addClass("iliV").show();
                Tglobe.DataSlider._resetBind();
                //$(this).parent().children('.iliV ').first().animate({ width: '0px', "display": "none" }, 100, function () {
                //    $(this).removeClass("iliV").addClass("iliH").css("display", "none").css("width", "37px");
                //    $(this).parent().children('.iliV').last().next().css("width", "0px").removeClass("iliH").addClass("iliV").animate({ width: '37px', "display": "inline" }, 200, function () {
                //        Tglobe.DataSlider._resetBind();
                //    });
                //});
            } else {
                Tglobe.DataSlider._resetBind();
            }
        },
        SetCurrent: function () {
            $(this).parent().children(".iliV").removeClass("current");
            $(this).parent().children(".iliH").removeClass("current");
            $(this).addClass("current");
        },

        _resetBind:
            function () {
                $("li.pageDecrement").on("click", Tglobe.DataSlider.Decrement);
                $("li.pageIncrement").on("click", Tglobe.DataSlider.Increment);
            }
    }

}

function testPopUp3min() {
    var cookiprom = getCookie("endprom");
    if (Date.parse(Date()) >= Date.parse(new Date(2014, 10, 16, 23, 59, 59, 59))) {
        //primera vez
        if (cookiprom == undefined || cookiprom == "") {
            var expires = new Date(2014, 10, 24, 23, 30, 59, 59);
            document.cookie = "endprom" + "= " + expires + "; path=/";
        }
        if (Date.parse(Date()) <= Date.parse(cookiprom)) {
            var startcooki = getCookie("startuser");
            if (startcooki == undefined || startcooki == "") {
                document.cookie = "startuser" + "= ";
                document.cookie = "startuser" + "= " + Date() + "; path=/";
            }

            var diff = Date.parse(Date()) - Date.parse(startcooki);

            var mins = (((diff / 1000) / 60));

            if (mins > 3) {
                var show = getCookie("showpromo");

                //primera vez
                if (show == undefined || show == "") {
                    document.cookie = "showpromo" + "= false; path=/";
                    $(".popup3mincontainer").show();
                    $(".popup3min").css("top", (($(window).height() / 2) - ($(".popup3min").height() / 2)));
                    $(".popup3min").css("left", (($(window).width() / 2) - ($(".popup3min").width() / 2)));
                }
            }
        }
    }
}

function okpop3min() {
    $.ajax({
        url: "/Pop3Min",
        type: "post",
        asyn: true,
        data: { email: $(".popup3min input[type=text]").val() },
        success: function (data) {
            $(".popup3min input[type=text]").val("");
            if (data.result == 0) {
                var image = $(".popup3min img");
                image.fadeOut('fast', function () {
                    image.attr('src', '/Content/images/pop_up2.png');
                    $(".popup3min input[type=text]").addClass("pop3result");
                    image.fadeIn('fast', function () {
                        $(".min3ok").remove();
                        $(".popup3min input[type=text]").val(data.value);
                        ga('send', 'event', 'Promo 3 minutos', 'click', 'Promocion');
                    });
                });
                //$(".popup3min img").attr("src", "/Content/images/pop_up2.png");
            } else {
                $(".popup3min input[type=text]").val(data.value);
            }
        }
    });
}

function getCookie(c_name) {
    if (document.cookie.length > 0) {
        c_start = document.cookie.indexOf(c_name + "=");
        if (c_start != -1) {
            c_start = c_start + c_name.length + 1;
            c_end = document.cookie.indexOf(";", c_start);
            if (c_end == -1) {
                c_end = document.cookie.length;
            }
            return unescape(document.cookie.substring(c_start, c_end));
        }
    }
    return "";
}

/*
/*  JCA. 15/01/2015
0.- Conjunto de funciones que se usan en la ficha de producto para permitir la selección de valores de atributos dinámicamente.
---
1.- initialize : carga la ficha de producto con la variedad predeterminada a mostrar.
2.- select_item_var: actualiza el hash de valores de atributos seleccionados. actualiza el marcado attr de las celdas que seleccionamos.
3.- search_item_var: busca el resultado de combinar los valores de los atributos seleccionados.
4.- show_availability: actualiza el marcado en attr de los valores de atributos que producen resultados ,
5.- showPrice: muestra el precio de una variedad concreta seleccionada.
*/
function initialize(variedad) {
    var jsonDic = jQuery.parseJSON(dic_atr_val);
    $.each(jsonDic, function (idx, obj) {
        if (idx == variedad) {
            $("#var_id_selected").val(idx);
            $("#variedad_id_selected_remember").val(idx);
            var dic_item_vals = obj;
            if (dic_item_vals.$values != null) {
                $.each(dic_item_vals.$values, function (id, val) {
                    hash_vals_items[val.Key] = val.Value;
                    $("li[data-id=" + val.Key + "][data-value-id=" + val.Value + "]").attr('data-selected', true);
                    //$("td[data-id=" + val.Key + "][data-value-id=" + val.Value + "]").css('color', 'red');
                });
            }
        }
    });
}

function select_item_var(currentNode, currentIndex, newValue) {
    var valueChange = false;
    if (hash_vals_items[currentIndex] != newValue) valueChange = true;
    $("li[data-id=" + currentIndex + "][data-value-id=" + hash_vals_items[currentIndex] + "]").removeAttr('data-selected');
    //$("td[data-id=" + currentIndex + "]").css('color', 'black');
    //$(currentNode).attr('data-selected', true);
    //$(currentNode).css('color', 'red');
    hash_vals_items["" + currentIndex + ""] = newValue;
    return valueChange;
}

function check_item_var_full(selected) {
    var empty = true;
    $.each(hash_vals_items, function (idx, obj) {
        if (idx != selected) {
            if (obj == 0) { empty = false; }
        }
    });

    return empty;
}

function comprobar_selecciones_variedad() {
    var empty = true;
    $.each(hash_vals_items, function (idx, obj) {
        if (obj == 0) { empty = false; }
    });
    return empty;
}

function search_item_var(id_row, val_row) {

    $('.atr_clickable div ul li[data-id]').each(function () {
        try {
            $(this).removeAttr('title');
            //Tipped.remove($(this));
        }
        catch (ex) { };
    });


    var jsonDic = jQuery.parseJSON(dic_atr_val);
    var item_available = false;
    //


    // Buscar en el diccionario de ATRIBUTO/VALOR la variedad actual
    $.each(jsonDic, function (idx, obj) {
        var idx_variedad = idx;
        var dic_item_vals = obj;
        var cont = 0;
        if (dic_item_vals.$values != null) {
            $.each(dic_item_vals.$values, function (id, val) {
                if (hash_vals_items[val.Key] == val.Value) cont++;
            });
            // Se cumple que tiene una variedad completa seleccionada
            if (cont == Object.keys(hash_vals_items).length) {

                console.log("Encontrado: " + idx_variedad);
                item_available = true;
                $("#var_id_selected").val(idx_variedad);
                $("#variedad_id_selected_remember").val(idx_variedad);
                var permalink = $("#permalink").val();

                var jsonDic = jQuery.parseJSON(var_items);
                $.each(jsonDic, function (idx, obj) {
                    if (idx == $("#var_id_selected").val()) {

                        // Buscamos imagenes para actualizar container galeria (image y thumbs)
                        $.ajax({
                            url: "/product/getImages",
                            async: true, // antes async: true (En observación) JCA --> Necesito el html que me devuelve junto a la imagen para poder mostrar su descuento correspondiente en el siguiente paso de actualizar datos de ficha de producto.
                            dataType: "json",
                            data: { permalink: permalink, variedad: idx_variedad },
                            success: function (data) {
                                $("#photo").html(data.htmlImage);
                                $("#urlImage").val(data.urlImage);
                                $("#gallery").html(data.htmlThumbs);

                                // Actualizamos enlaces SOME
                                $("#lnkFacebook").prop('href', 'http://www.facebook.com/sharer.php?u=' + $("#urlBase").val() + $("#permalink").val() + "/" + $("#var_id_selected").val());
                                $("#lnkTwitter").prop('href', 'http://www.twitter.com/?status=' + $("#urlBase").val() + $("#permalink").val() + "/" + $("#var_id_selected").val());
                                $("#lnkPinterest").hide();
                                if ($("#urlImage").val() != "") {
                                    $("#lnkPinterest").show();
                                    $("#lnkPinterest").prop('href', 'http://pinterest.com/pin/create/button/?url=' + $("#urlBase").val() + $("#permalink").val() + "/" + $("#var_id_selected").val() + "&amp;media=" + $("#urlImage").val());
                                }

                                //  REINICIALIZAR OBJETOS PARA QUE FUNCIONE EL ZOOM Y GALERIA EN MODO ASÍNCRONO
                                // --------------------------------------------------------------
                                if (data.urlImage != "") {
                                    $("#imgBig").data('zoom-image', data.urlImage).elevateZoom({
                                        responsive: true,
                                        zoomType: "inner",
                                        containLensZoom: true,
                                        cursor: 'crosshair',
                                        gallery: 'gallery',
                                        galleryActiveClass: "active"
                                    });
                                    $("#imgBig").bind("click", function (e) {
                                        var ez = $('#imgBig').data('elevateZoom');
                                        $.fancybox(ez.getGalleryList()); return false;
                                    });
                                }
                                // --------------------------------------------------------------
                            },
                            complete: function () {

                            }
                        });

                        $.each(obj.$values, function (ind, val) {
                            // actualizamos datos en ficha de producto.
                            //if (val.Key == "nom_var_full") { $("div.details h1").html(val.Value); }
                            //if (val.Key == "ean") { $("div.sku span").html(val.Value); $("div.sku span").data('original-title', val.Value); }
                            if (val.Key == "prec") {
                                $("input[name='prec_unit']").html(val.Value);
                                showPrice();
                            }
                            if (val.Key == "prec_div") {
                                $("div.prices del span").first().html(val.Value);
                            }

                            if (val.Key == "stock") {
                                $("#stock_variedad").val(val.Value);
                                if (val.Value == 0) { $("#btnComprar").prop("disabled", true); $("#AvisoStock").show(); }
                                else { $("#btnComprar").prop("disabled", false); $("#AvisoStock").hide(); }
                            }

                            if (val.Key == "descuento" && val.Value != "") {
                                if (val.Value != "true") $("span.badge.main").addClass("badge-sale").html(val.Value);
                                if (val.Value != "2x1") $("del.base").removeAttr("hidden");
                            }

                            if (val.Key == "info_extra_descuento" && val.Value != "") {
                                $('.discount-message').removeAttr("hidden").html(val.Value);
                            }
                            else if (val.Key == "info_extra_descuento" && val.Value == "") {
                                if (typeof $('.discount-message').attr("hidden") !== typeof undefined && $('.discount-message').attr("hidden") !== false) {
                                    $('.discount-message').addAttr("hidden");
                                }
                            }

                            //  COMENTAMOS ESTA LLAMADA PORQUE LA DESCRIPCIÓN LARGA VA A NIVEL DE PRODUCTO
                            //if (val.Key == "desc_editor") {
                            //    var product_id = $("input[name='pro_id']").val();
                            //    $.ajax({
                            //        url: "/product/getLongDescription",
                            //        async: true,
                            //        dataType: "json",
                            //        data: { ProductID: product_id, fichero : val.Value },
                            //        success: function (data) {
                            //            $("#description p").html(data.html);
                            //        },
                            //        complete: function () {
                            //        }
                            //    });
                            //}

                            if (val.Key == "desc_corta_nv") { $("div.short-description p").html(val.Value); }
                        });

                        return false;
                    }
                });
                return false;
            }
        }
        else {
            idx_variedad = $("input:hidden[name='var_id_selected']").val();
            console.log("Encontrado: " + idx_variedad);
            item_available = true;
            $("#var_id_selected").val(idx_variedad);
            $("#variedad_id_selected_remember").val(idx_variedad);
            var permalink = $("#permalink").val();

            var jsonDic = jQuery.parseJSON(var_items);
            $.each(jsonDic, function (idx, obj) {
                if (idx == $("#var_id_selected").val()) {

                    // Buscamos imagenes para actualizar container galeria (image y thumbs)
                    $.ajax({
                        url: "/product/getImages",
                        async: true, // antes async: true (En observación) JCA --> Necesito el html que me devuelve junto a la imagen para poder mostrar su descuento correspondiente en el siguiente paso de actualizar datos de ficha de producto.
                        dataType: "json",
                        data: { permalink: permalink, variedad: idx_variedad },
                        success: function (data) {
                            $("#photo").html(data.htmlImage);
                            $("#urlImage").val(data.urlImage);
                            $("#gallery").html(data.htmlThumbs);

                            // Actualizamos enlaces SOME
                            $("#lnkFacebook").prop('href', 'http://www.facebook.com/sharer.php?u=' + $("#urlBase").val() + $("#permalink").val() + "/" + $("#var_id_selected").val());
                            $("#lnkTwitter").prop('href', 'http://www.twitter.com/?status=' + $("#urlBase").val() + $("#permalink").val() + "/" + $("#var_id_selected").val());
                            $("#lnkPinterest").hide();
                            if ($("#urlImage").val() != "") {
                                $("#lnkPinterest").show();
                                $("#lnkPinterest").prop('href', 'http://pinterest.com/pin/create/button/?url=' + $("#urlBase").val() + $("#permalink").val() + "/" + $("#var_id_selected").val() + "&amp;media=" + $("#urlImage").val());
                            }

                            //  REINICIALIZAR OBJETOS PARA QUE FUNCIONE EL ZOOM Y GALERIA EN MODO ASÍNCRONO
                            // --------------------------------------------------------------
                            if (data.urlImage != "") {
                                $("#imgBig").data('zoom-image', data.urlImage).elevateZoom({
                                    responsive: true,
                                    zoomType: "inner",
                                    containLensZoom: true,
                                    cursor: 'crosshair',
                                    gallery: 'gallery',
                                    galleryActiveClass: "active"
                                });
                                $("#imgBig").bind("click", function (e) {
                                    var ez = $('#imgBig').data('elevateZoom');
                                    $.fancybox(ez.getGalleryList()); return false;
                                });
                            }
                            // --------------------------------------------------------------
                        },
                        complete: function () {

                        }
                    });

                    $.each(obj.$values, function (ind, val) {
                        // actualizamos datos en ficha de producto.
                        //if (val.Key == "nom_var_full") { $("div.details h1").html(val.Value); }
                        //if (val.Key == "ean") { $("div.sku span").html(val.Value); $("div.sku span").data('original-title', val.Value); }
                        if (val.Key == "prec") {
                            $("input[name='prec_unit']").html(val.Value);
                            showPrice();
                        }
                        if (val.Key == "prec_div") {
                            $("div.prices del span").first().html(val.Value);
                        }

                        if (val.Key == "stock") {
                            $("#stock_variedad").val(val.Value);
                            if (val.Value == 0) { $("#btnComprar").prop("disabled", true); $("#AvisoStock").show(); }
                            else { $("#btnComprar").prop("disabled", false); $("#AvisoStock").hide(); }
                        }

                        if (val.Key == "descuento" && val.Value != "") {
                            if (val.Value != "true") $("span.badge.main").addClass("badge-sale").html(val.Value);
                            if (val.Value != "2x1") $("del.base").removeAttr("hidden");
                        }

                        if (val.Key == "info_extra_descuento" && val.Value != "") {
                            $('.discount-message').removeAttr("hidden").html(val.Value);
                        }
                        else if (val.Key == "info_extra_descuento" && val.Value == "") {
                            if (typeof $('.discount-message').attr("hidden") !== typeof undefined && $('.discount-message').attr("hidden") !== false) {
                                $('.discount-message').addAttr("hidden");
                            }
                        }

                        //  COMENTAMOS ESTA LLAMADA PORQUE LA DESCRIPCIÓN LARGA VA A NIVEL DE PRODUCTO
                        //if (val.Key == "desc_editor") {
                        //    var product_id = $("input[name='pro_id']").val();
                        //    $.ajax({
                        //        url: "/product/getLongDescription",
                        //        async: true,
                        //        dataType: "json",
                        //        data: { ProductID: product_id, fichero : val.Value },
                        //        success: function (data) {
                        //            $("#description p").html(data.html);
                        //        },
                        //        complete: function () {
                        //        }
                        //    });
                        //}

                        if (val.Key == "desc_corta_nv") { $("div.short-description p").html(val.Value); }
                    });

                    return false;
                }
            });
            return false;
        }
    });

    show_availability();

    //console.log("disponible: " + item_available);
    if (!item_available) {
        // usamos los primeros disponibles y los cargamos.
        $('div.controls ul li').each(function () {
            if (id_row != "") {
                if ($(this).attr('data-id') != id_row && $(this).attr('data-available') == "true") {

                    // aqui tenemos que ver si esta disponible con la que tengo seleccionada en la otra fila
                    if (comprobar_combinacion(id_row, val_row, $(this).attr('data-id'), $(this).attr('data-value-id'))) {

                        //alert($(this).data('id') + " - " + $(this).data('value-id'));
                        //$(this).trigger("click");

                        //console.log('debe seleccionar: ' + $(this).data('id') + "-" + $(this).data('value-id'))
                        $(this).trigger("click");
                        return false;
                    }
                }
            }
        });
    }

    $('.atr_clickable div ul li[data-id]').each(function () {
        if ($(this).attr('data-available') == null) {
            var id_row = $(this).attr('data-id');
            var texto = "";
            $('.atr_clickable div ul li[data-id!="' + id_row + '"]').each(function () {
                if ($(this).attr('data-selected') == "true") {
                    texto = $(this).parent().parent().parent().find('.control-label').first().html() + ": " + $(this).data('text');
                }
            });
            if (texto != "") {
                $(this).attr('title', Eshop.Literal.NoDisponible + ' ' + texto);
            }
            else {
                $(this).attr('title', Eshop.Literal.PorFavorSelecciona);
            }
            //Tipped.create($(this));
        }
    });
}

// comprobamos que la opcion seleccionada actualmente esta disponible para asociarla con otra
function comprobar_combinacion(currentId, currentValue, checkId, checkValue) {
    //console.log("marca_actual:" + currentId + "-" + currentValue);
    //console.log("marca_por_definir:" + checkId + "-" + checkValue);

    var jsonDic = jQuery.parseJSON(dic_atr_val);
    var marcar = false;
    $.each(jsonDic, function (idx, obj) {
        var idx_variedad = idx;
        var dic_item_vals = obj;
        var cont = 0;
        if (dic_item_vals.$values != null) {
            $.each(dic_item_vals.$values, function (id, val) {
                if (val.Key == currentId && val.Value == currentValue) {
                    cont++;
                }
                if (val.Key == checkId && val.Value == checkValue) {
                    cont++;
                }
                if (cont > 1) {
                    marcar = true;
                    return false;
                }
            });
        }
    });

    return marcar;

}

function show_availability() {
    // cargamos diccionario de combinaciones disponibles.
    var jsonDic = jQuery.parseJSON(dic_atr_val);
    var check_val_items = [];
    // recorremos hash val items
    $.each(hash_vals_items, function (k, v) {

        // buscamos opciones disponibles
        $.each(jsonDic, function (idx, obj) {
            var dic_item_vals = obj;
            if (dic_item_vals.$values != null) {
                for (var i = 0; i < dic_item_vals.$values.length; i++) {
                    //console.log("Comprobando: " + k + " - " + v);
                    if (dic_item_vals.$values[i].Key == k && dic_item_vals.$values[i].Value == v) {
                        check_val_items.push(dic_item_vals.$values);
                    }
                }
            }
        });
    });

    $('div.controls ul li').each(function () {
        if ($(this).attr('data-available') == "true") {
            $(this).removeAttr('data-available');
        }
    });

    $.each(check_val_items, function (idx, obj) {
        var arrayRS = obj;
        for (var i = 0; i < arrayRS.length; i++) {
            var val = arrayRS[i];
            $("li[data-id=" + val.Key + "][data-value-id=" + val.Value + "]").attr("data-available", "true");
            //console.log(val.Key + " - " + val.Value);
        }
    });

    if (Object.keys(hash_vals_items).length == 1) {
        $('div.controls ul li').each(function () {
            $(this).attr('data-available', true);
        });
    }

}

function showPrice() {
    var priceUnit = parseFloat($('input[name="prec_unit"]').text().replace(',', '.'));
    var units = parseFloat($('input[name="cantidad"]').val());
    var total = priceUnit.toFixed(2).toString().replace('.', ',');  //  PARA QUE NO ACTUALICE EL PRECIO
    //var total = (priceUnit * units).toFixed(2).toString().replace('.', ',');
    $("div.prices #price-item").html(total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, "."));
    //console.log(total);
}

function comprobar_variedad() {
    // verificamos que los valores de los atributos estén marcados
    if (!comprobar_selecciones_variedad()) {
        var mensaje = Eshop.Literal.DebesSelVariedad;


        var htmlVariedades = "<div class='cart-items'><table class='styled-table'><tbody class='loader2'>";
        var jsonDic = jQuery.parseJSON(var_items);
        //var itemIdx = 0;
        $.each(jsonDic, function (idx, obj) {
            if (!isNaN(idx)) {
                var temp = $('#template-item tbody').clone(true, true);
                $.each(obj.$values, function (ind, val) {
                    if (val.Key == "nom_var_full") { $(temp).find("td.col_product h5").html(val.Value); }
                    if (val.Key == "prec") {
                        $(temp).find("td.col_total span.total-price").html(val.Value);
                    }

                    // Control STOCK
                    if (val.Key == "stock") {
                        $(temp).find("td.col_qty div input.input-text.qty.text").prop('max', val.Value);
                        if (val.Value == 0) { $("#btnComprarModal").prop("disabled", true); $("#AvisoStockModal").hide(); }
                        else { $("#btnComprarModal").prop("disabled", false); $("#AvisoStockModal").hide(); }
                    }
                });

                $(temp).find("td.col_qty div input.btn.btn-black.remove.cart-minus").attr("value", "-");
                //$(temp).find("td.col_qty div input.input-text.qty.text").attr("value", "1").val("1");
                $(temp).find("td.col_qty div input.input-text.qty.text").attr("data-va", idx);
                $(temp).find("td.col_qty div input.input-text.qty.text").attr("name", "item_quantity[" + idx + "]");
                $(temp).find("td.col_qty div input.btn.btn-black.add.cart-plus").attr("value", "+");
                $(temp).find("#btnComprarModal").attr("onclick", "Eshop.AddItemShoppingCarrFloat(" + idx + ");");

                htmlVariedades += temp.html();
                //itemIdx++
            }
        });

        htmlVariedades += "</tbody></table></div>";

        $('<div class="dialog-custom" id="multiCart"></div>').appendTo('body')
            .html('<div><h6 class="no-margin">' + mensaje + '</h6></div><br />' + htmlVariedades)
            .dialog({
                modal: true,
                title: '',
                zIndex: 10000,
                autoOpen: true,
                width: 'auto',
                resizable: false,
            });

        return false;
    }

    return true;
}


/* Funciones para el login en Libreria */
var LoginLib = {
    From: "",
    Action: "",
    Controller: "",

    mostrarRecordarContrasenaLib: function () {
        $('#divFormLoginLib').fadeOut('slow', function () {
            $('#divFormRememberLib').fadeIn('slow');
        });
    },

    mostrarLoginLib: function () {
        $('#divFormRememberLib').fadeOut('slow', function () {
            $("#email_recPassLib").val("");
            $('#divFormLoginLib').fadeIn('slow');
        });
    },

    ocultarMsgsRecordarLib: function () {
        $("#emailRecEnvLib").hide();
        $("#emailRecKOLib").hide();
        $("#emailRecVacioLib").hide();
        $("#emailRecErrLib").hide();
    },

    SolicitarCambioPassLib: function () {
        $('#email_recPassLib').prop('disabled', true);
        $('#spinnerRecPassLib').show();
        $.ajax({
            url: "/recordar",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_recPassLib").val(), libreria: "True" },
            success: function (data) {
                if (data.Result == 0) {
                    // no se ha encontrado cliente
                    LoginPopUp.ocultarMsgsRecordarLib();
                    $("#emailRecKOLib").show();
                } else if (data.Result == 1) {
                    // se ha enviado el correo
                    LoginPopUp.ocultarMsgsRecordarLib();
                    $("#btnRememberLib").prop("disabled", true);
                    $("#emailRecEnvLib").show();
                    setTimeout(function () {
                        mostrarLoginLib();
                        $("#btnRememberLib").prop("disabled", false);
                        LoginPopUp.ocultarMsgsRecordarLib();
                    }, 5000);
                } else if (data.Result == 2) {
                    // no ha introducido email
                    LoginPopUp.ocultarMsgsRecordarLib();
                    $("#emailRecVacioLib").show();
                } else if (data.Result == 3) {
                    // ha ocurrido algun error
                    LoginPopUp.ocultarMsgsRecordarLib();
                    $("#emailRecErrLib").show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                LoginPopUp.ocultarMsgsRecordarLib();
                $("#emailRecErrLib").show();
            },
            complete: function () {
                $('#email_recPassLib').prop('disabled', false);
                $('#spinnerRecPassLib').hide();
            }
        })
    },

    LoginLib: function () {
        // deshabilitamos los textbox y los botones
        $('#email_loginLib').prop('disabled', true);
        $('#pass_loginLib').prop('disabled', true);
        $('#btn_loginLib').prop('disabled', true);
        $("#msgErrorLoginLib").hide();
        $("#spinnerLoginLib").show();

        $.ajax({
            url: "/loginLib",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_loginLib").val(), clave: $("#pass_loginLib").val(), action: LoginPopUp.Action, controller: LoginPopUp.Controller },
            success: function (data) {
                if (data.Result == -3) {
                    // ha ocurrido un error inesperado
                    LoginLib.HabilitarCamposLoginLibDeNuevo();
                } else if (data.Result == -2) {
                    // el usuario ya esta logueado
                    LoginLib.HabilitarCamposLoginLibDeNuevo();
                } else if (data.Result == -1) {
                    // las credenciales no son correctas
                    LoginLib.HabilitarCamposLoginLibDeNuevo();
                    $("#msgErrorLoginLib").html(data.Mensaje).show();
                } else if (data.Result == 1) {
                    // el usuario ha accedido con exito                    
                    window.location.href = data.Url;
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                LoginLib.HabilitarCamposLoginLibDeNuevo();
                $("#msgErrorLoginLib").text(errorThrown).show();
            },
            complete: function () {
                $("#spinnerLoginLib").hide();
            }
        })
    },

    HabilitarCamposLoginLibDeNuevo: function () {
        $('#email_loginLib').prop('disabled', false);
        $('#pass_loginLib').prop('disabled', false);
        $('#pass_loginLib').val('');
        $('#btn_loginLib').prop('disabled', false);
    },
}

/* Funciones para el login en el popUp*/
var LoginPopUp = {
    From: "",
    Action: "",
    Controller: "",

    mostrarRecordarContrasena: function () {
        //$('#divFormLoginPU').fadeOut('slow', function () {
        //    $('#divFormRememberPU').fadeIn('slow');
        //});

        $('#changePasswordModal').modal();
    },

    mostrarModalLogin: function () {
        $('#iniciaSesion').modal('show');
    },

    ocultarModalLogin: function () {
        $('#iniciaSesion').modal('hide');
        // $('.dropdown-menu').hide();
    },

    mostrarModalRegister: function () {
        $('#registrate').modal('show');
    },

    ocultarModalRegister: function () {
        $('#registrate').modal('hide');
    },

    mostrarLogin: function () {
        $('#divFormRememberPU').fadeOut('slow', function () {
            $("#email_recPassPU").val("");
            $('#divFormLoginPU').fadeIn('slow');
        });
    },

    ocultarMsgsRecordar: function () {
        $("#emailRecEnvPU").hide();
        $("#emailRecKOPU").hide();
        $("#emailRecVacioPU").hide();
        $("#emailRecErrPU").hide();
    },

    SolicitarCambioPass: function () {
        $('#email_recPassPU').prop('disabled', true);
        $('#spinnerRecPassPU').show();
        Loading('show');
        $.ajax({
            url: "/recordar",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_recPassPU").val() },
            success: function (data) {
                if (data.Result == 0) {
                    // no se ha encontrado cliente
                    LoginPopUp.ocultarMsgsRecordar();
                    $("#emailRecKOPU").show();
                } else if (data.Result == 1) {
                    // se ha enviado el correo
                    LoginPopUp.ocultarMsgsRecordar();
                    $("#btnRememberPU").prop("disabled", true);
                    $("#emailRecEnvPU").show();
                    setTimeout(function () {
                        //mostrarLogin();
                        $("#btnRememberPU").prop("disabled", false);
                        //LoginPopUp.ocultarMsgsRecordar();
                    }, 5000);
                } else if (data.Result == 2) {
                    // no ha introducido email
                    LoginPopUp.ocultarMsgsRecordar();
                    $("#emailRecVacioPU").show();
                } else if (data.Result == 3) {
                    // ha ocurrido algun error
                    LoginPopUp.ocultarMsgsRecordar();
                    $("#emailRecErrPU").show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                LoginPopUp.ocultarMsgsRecordar();
                $("#emailRecErrPU").show();
                Loading('hide');
            },
            complete: function () {
                $('#email_recPassPU').prop('disabled', false);
                $('#spinnerRecPassPU').hide();
                Loading('hide');
            }
        })
    },

    HabilitarCamposLoginPUDeNuevo: function () {
        $('#email_loginPU').prop('disabled', false);
        $('#pass_loginPU').prop('disabled', false);
        $('#pass_loginPU').val('');
        $('#btn_loginPU').prop('disabled', false);
    },

    HabilitarCamposLoginPUDeNuevoCheckOut: function () {
        $('#email_loginPU').prop('disabled', false);
        $('#pass_loginPU').prop('disabled', false);
        $('#pass_loginPU').val('');
        $('#btn_loginPU').prop('disabled', false);
    },

    Login: function () {
        // deshabilitamos los textbox y los botones
        $('#email_loginPU').prop('disabled', true);
        $('#pass_loginPU').prop('disabled', true);
        $('#btn_loginPU').prop('disabled', true);
        $("#msgErrorLoginPU").hide();
        $("#spinnerLoginPU").show();


        var showMessage = function (message) {
            Swal.fire({
                icon: 'error',
                title: 'ERROR',
                text: message
            });
        };

        $.ajax({
            url: "/loginPU",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_loginPU").val(), clave: $("#pass_loginPU").val(), action: LoginPopUp.Action, controller: LoginPopUp.Controller },
            success: function (data) {
                if (data.Result == -3) {
                    // ha ocurrido un error inesperado
                    LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                    window.dataLayer = window.dataLayer || [];
                    dataLayer.push({
                        'event': 'login_usuario',
                        'form_name': 'login',
                        'status': 'Login incorrecto'
                    });
                } else if (data.Result == -2) {
                    // el usuario ya esta logueado
                    LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                } else if (data.Result == -1) {
                    // las credenciales no son correctas
                    LoginPopUp.HabilitarCamposLoginPUDeNuevo();

                    window.dataLayer = window.dataLayer || [];
                    dataLayer.push({
                        'event': 'login_usuario',
                        'form_name': 'login',
                        'status': 'Login incorrecto'
                    });

                    showMessage(data.Mensaje);
                } else if (data.Result == 1) {

                    window.dataLayer = window.dataLayer || [];
                    dataLayer.push({
                        'event': 'login_usuario',
                        'form_name': 'login',
                        'status': 'Login correcto'
                    });

                    // el usuario ha accedido con exito
                    //if (LoginPopUp.From == "LstProductMarista") {
                    //    Eshop.Marista.ActionBuyItemsMarista(data.Url);
                    //}
                    //else if (LoginPopUp.From == "StepCourse") {
                    //    $("#FormMaristasCenterStepCourse").submit();
                    //    LoginPopUp.ocultarModalLogin();
                    //}
                    //else {
                    //    window.location.href = data.Url;
                    //}

                    if (data.EsAdmin) {
                        window.location.href = data.Url;
                    } else {
                        window.location.reload();
                    }

                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                showMessage(errorThrown);
            },
            complete: function () {
                $("#spinnerLoginPU").hide();
            }
        })
    },
    LoginCheCkoutOnEnter: function (e) {
        if (e.key === "Enter") {

            $('#email_loginPU').prop('disabled', true);
            $('#pass_loginPU').prop('disabled', true);
            $('#btn_loginPU').prop('disabled', true);
            $("#msgErrorLoginPU").hide();
            $("#spinnerLoginPU").show();


            var showMessage = function (message) {
                Swal.fire({
                    icon: 'error',
                    title: 'ERROR',
                    text: message
                });
            };

            // Cancel the default action, if needed
            e.preventDefault();

            $.ajax({
                url: "/loginPU",
                type: "post",
                asyn: true,
                dataType: "json",
                data: { email: $("#email_loginPU").val(), clave: $("#pass_loginPU").val(), action: LoginPopUp.Action, controller: LoginPopUp.Controller },
                success: function (data) {
                    if (data.Result == -3) {
                        // ha ocurrido un error inesperado
                        LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                    } else if (data.Result == -2) {
                        // el usuario ya esta logueado
                        LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                    } else if (data.Result == -1) {
                        // las credenciales no son correctas
                        LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                        showMessage(data.Mensaje);
                    } else if (data.Result == 1) {
                        // el usuario ha accedido con exito
                        //if (LoginPopUp.From == "LstProductMarista") {
                        //    Eshop.Marista.ActionBuyItemsMarista(data.Url);
                        //}
                        //else if (LoginPopUp.From == "StepCourse") {
                        //    $("#FormMaristasCenterStepCourse").submit();
                        //    LoginPopUp.ocultarModalLogin();
                        //}
                        //else {
                        //    window.location.href = data.Url;
                        //}

                        if (data.EsAdmin) {
                            window.location.href = data.Url;
                        } else {
                            window.location.reload();
                        }
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    LoginPopUp.HabilitarCamposLoginPUDeNuevo();
                    showMessage(errorThrown);
                },
                complete: function () {
                    $("#spinnerLoginPU").hide();
                }
            })
        }
    },
    LoginCheckout: function () {
        Loading('show');

        var showMessage = function (message) {
            Swal.fire({
                icon: 'error',
                title: 'ERROR',
                text: message
            });
        };

        $.ajax({
            url: "/loginPU",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_loginPU-checkout").val(), clave: $("#pass_loginPU-checkout").val(), action: LoginPopUp.Action, controller: LoginPopUp.Controller },
            success: function (data) {
                if (data.Result == -3) {
                    // ha ocurrido un error inesperado
                    Loading('hide');
                } else if (data.Result == -2) {
                    // el usuario ya esta logueado
                    Loading('hide');
                } else if (data.Result == -1) {
                    // las credenciales no son correctas
                    Loading('hide');
                    showMessage(data.Mensaje);
                } else if (data.Result == 1) {
                    // el usuario ha accedido con exito
                    if (LoginPopUp.From == "LstProductMarista") {
                        Eshop.Marista.ActionBuyItemsMarista(data.Url);
                    }
                    else if (LoginPopUp.From == "StepCourse") {
                        $("#FormMaristasCenterStepCourse").submit();
                    }
                    else {
                        if (location.href.includes('finasistente')) {
                            window.location.reload();
                        } else {
                            window.location.href = data.Url;
                        }
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                Loading('hide');
                showMessage(errorThrown);
            },
            complete: function () {
                //Loading('hide');
            }
        })
    },
    LoginMobile: function () {
        Loading('show');

        var showMessage = function (message) {
            Swal.fire({
                icon: 'error',
                title: 'ERROR',
                text: message
            });
        };

        $.ajax({
            url: "/loginPU",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_loginPU-Mobile").val(), clave: $("#pass_loginPU-Mobile").val(), action: LoginPopUp.Action, controller: LoginPopUp.Controller },
            success: function (data) {
                if (data.Result == -3) {
                    // ha ocurrido un error inesperado
                    Loading('hide');
                } else if (data.Result == -2) {
                    // el usuario ya esta logueado
                    Loading('hide');
                } else if (data.Result == -1) {
                    // las credenciales no son correctas
                    Loading('hide');
                    showMessage(data.Mensaje)
                } else if (data.Result == 1) {
                    // el usuario ha accedido con exito
                    window.location.reload();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                Loading('hide');
                showMessage(errorThrown);
            },
            complete: function () {
                Loading('hide');
            }
        })
    },

    HabilitarCamposRegisterPUDeNuevo: function () {
        $('#email_registroPU').prop('disabled', false);
        $('#pass_registroPU').prop('disabled', false);
        $('#pass_registroPU').val('');
        $('#repPass_registroPU').prop('disabled', false);
        $('#repPass_registroPU').val('');
        $('#btn_registroPU').prop('disabled', false);
    },

    Register: function () {
        $('#email_registroPU').prop('disabled', true);
        $('#pass_registroPU').prop('disabled', true);
        $('#repPass_registroPU').prop('disabled', true);
        $('#btn_registroPU').prop('disabled', true);
        $("#msgErrorRegistroPU").hide();
        $("#spinnerRegistroPU").show();

        $.ajax({
            url: "/registerPU",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_registroPU").val(), clave: $("#pass_registroPU").val(), rep_clave: $("#repPass_registroPU").val(), acepto: $("#acepto_registroPU").is(":checked"), action: LoginPopUp.Action, controller: LoginPopUp.Controller },
            success: function (data) {
                if (data.Result == -1) {
                    // ha ocurrido un error
                    LoginPopUp.HabilitarCamposRegisterPUDeNuevo();
                    $("#msgErrorRegistroPU").html(data.Mensaje).show();
                } else if (data.Result == 1) {
                    // el usuario ha accedido con exito
                    if (LoginPopUp.From == "LstProductMarista") {
                        Eshop.Marista.ActionBuyItemsMarista(data.Url);
                    }
                    else if (LoginPopUp.From == "StepCourse") {
                        $("#FormMaristasCenterStepCourse").submit();
                        LoginPopUp.ocultarModalRegister();
                    }
                    else {
                        window.location.href = data.Url;
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                LoginPopUp.HabilitarCamposRegisterPUDeNuevo();
                $("#msgErrorRegistroPU").text(errorThrown).show();
            },
            complete: function () {
                $("#spinnerRegistroPU").hide();
            }
        })
    },

    RegisterNew: function (nombre, apellido, email, clave, claveRep, aceptoPolitica, recaptcha) {

        $(".userErrorMessage").hide();
        $("#spinnerRegistroPU").show();
        // $('#btncrearCuentaUsuario').prop('disabled', 'disabled');
        $("#msgErrorRegistroPU").hide();
        Loading('show');

        $.ajax({
            url: "/registerPUNew",
            type: "post",
            asyn: true,
            dataType: "json",
            data: {
                email: email,
                clave: clave,
                rep_clave: claveRep,
                nombre: nombre,
                apellido: apellido,
                acepto: aceptoPolitica,
                action: LoginPopUp.Action,
                controller: LoginPopUp.Controller,
                recaptcha: recaptcha,
            },
            success: function (data) {
                if (data.Result == -1) {
                    // ha ocurrido un error
                    LoginPopUp.HabilitarCamposRegisterPUDeNuevo();
                    $("#msgErrorRegistroPU").html(data.Mensaje).show();
                    $('.rowErrorUser').show(500);
                } else if (data.Result == 1) {
                    // el usuario ha accedido con exito
                    if (LoginPopUp.From == "LstProductMarista") {
                        Eshop.Marista.ActionBuyItemsMarista(data.Url);
                    }
                    else if (LoginPopUp.From == "StepCourse") {
                        $("#FormMaristasCenterStepCourse").submit();
                        LoginPopUp.ocultarModalRegister();
                    }
                    else {
                        window.location.href = data.Url;
                    }
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                LoginPopUp.HabilitarCamposRegisterPUDeNuevo();
                $("#msgErrorRegistroPU").html(errorThrown).show();
                $('.rowErrorUser').show(500);
                Loading('hide');
            },
            complete: function () {
                $("#spinnerRegistroPU").hide();
                $('#btncrearCuentaUsuario').removeAttr('disabled');
                Loading('hide');
            }
        })
    },

    SetModalParameter: function () {
        var modal = getUrlParameter('modal');
        if (modal !== undefined) {
            $('#' + modal).click();
        }
    },

    SuscribirBoletin: function (estaIdent) {
        $('#email_suscribirsePU').prop('disabled', true);
        $('#spinnerSuscPU').show();
        $("#emailSuscPU").hide();
        $("#emailSuscErrPU").hide();

        var chkBoletines = [];

        $('.chk-boletin').each(function () {
            var chk = $(this).is(':checked');
            var tipoBol = $(this).attr('data-tipoBol');
            chkBoletines.push(new Object({
                IdTipoBoletin: tipoBol,
                boletinChk: chk
            }));
        });

        $.ajax({
            url: "/suscribirsePU",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_suscribirsePU").val(), chkBoletines: JSON.stringify(chkBoletines), aceptPolPriv: $("#acepto_suscribirsePU").is(":checked"), estaIdent: estaIdent },
            success: function (data) {
                if (data.Result < 0) {
                    $("#emailSuscErrPU").html(data.Mensaje).show();
                    $("#emailSuscPU").hide();
                } else {
                    $("#emailSuscErrPU").hide();
                    $("#emailSuscPU").html(data.Mensaje).show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#emailSuscErrPU").text(errorThrown).show();
            },
            complete: function () {
                $('#email_suscribirsePU').prop('disabled', false);
                $('#spinnerSuscPU').hide();
            }
        })
    },

    SuscribirBoletinMC: function () {
        $('#email_suscribirseMC').prop('disabled', true);
        $('#spinnerSuscMC').show();
        $("#emailSuscMC").hide();
        $("#emailSuscErrMC").hide();

        var chkBoletines = [];

        $('.chk-boletinMC').each(function () {
            var chk = $(this).is(':checked');
            var tipoBol = $(this).attr('data-tipoBol');
            chkBoletines.push(new Object({
                IdTipoBoletin: tipoBol,
                boletinChk: chk
            }));
        });

        $.ajax({
            url: "/suscribirsePU",
            type: "post",
            asyn: true,
            dataType: "json",
            data: { email: $("#email_suscribirseMC").val(), chkBoletines: JSON.stringify(chkBoletines), aceptPolPriv: $("#acepto_suscribirseMC").is(":checked"), estaIdent: true },
            success: function (data) {
                if (data.Result < 0) {
                    $("#emailSuscErrMC").html(data.Mensaje).show();
                    $("#emailSuscMC").hide();
                } else {
                    $("#emailSuscErrMC").hide();
                    $("#emailSuscMC").html(data.Mensaje).show();
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                $("#emailSuscErrMC").text(errorThrown).show();
            },
            complete: function () {
                $('#email_suscribirseMC').prop('disabled', false);
                $('#spinnerSuscMC').hide();
            }
        })
    }

}
$("#formLoginPU").submit(function () {
    return false;
});
$("#divFormRememberPU").submit(function () {
    return false;
});
$("#formRegisterPU").submit(function () {
    return false;
});


var Incidencias = {
    IncidenciasAddAdj: function () {
        $.ajax({
            url: "/MyAccount/GetNewAdjHtml",
            type: "post",
            asyn: true,
            cache: false,
            success: function (data) {
                //console.log(data);
                var hash = "inputFile_" + new Date().getTime();
                var $html = $(data);
                $html.find('.fileInput-input').attr('for', hash);
                $html.find('input').attr('id', hash);
                $("#divLstAdj").append($html);
            }
        });
    },

    IncidenciasAddAdjId: function (id) {
        $.ajax({
            url: "/MyAccount/GetNewAdjHtml",
            type: "post",
            asyn: true,
            cache: false,
            success: function (data) {
                $("#divLstAdj_" + id).append(data);
            }
        });
    },

    LeerRespuesta: function (idsResp) {
        var arrayResp = idsResp.split(';');
        $.ajax({
            url: "/MyAccount/LeerRespuestaIncidencia",
            data: { lstResp: arrayResp },
            type: "post",
            asyn: true,
            cache: false,
            success: function (data) { }
        })
    }
}