/* Minification failed. Returning unminified contents.
(51,36-37): run-time error JS1195: Expected expression: >
(54,10-11): run-time error JS1195: Expected expression: ,
(54,28-29): run-time error JS1004: Expected ';': {
(58,5-6): run-time error JS1002: Syntax error: }
(63,22-23): run-time error JS1004: Expected ';': {
(69,40-41): run-time error JS1004: Expected ';': )
(71,31-32): run-time error JS1004: Expected ';': {
(65,33-39): run-time error JS1018: 'return' statement outside of function: return
(56,13-19): run-time error JS1018: 'return' statement outside of function: return
 */
$(document).ready(setTimeout(function () {
    $.modal.defaults = {
        clickClose: false,
        showClose: true
    };

    $(".jq-social-login").click(function (event) {
        event.preventDefault();
        $("#div-regular").show();
        $("#div-guest").hide();
        fbAsyncInit();
    });
    $("#btn-guest").click(function (event) {
        event.preventDefault();
        $("#regular-login").hide();
        $("#div-email-sent").hide();
        $("#div-email-already-registered").hide();
        $("#div-maxNumberExceeded").hide();
        $("#btn-prosegui").show();
        $("#guest-login").show();
    });
    $(".jq-btn-disabled").click(function (event) {
        event.preventDefault();
    });

    $(".jq-social-error").hide();

}, 10));
window.fbAsyncInit = function () {
    if ($("#FacebookeKeyID").val() != null) {
        FB.init({
            appId: $("#FacebookeKeyID").val(),
            cookie: true,
            xfbml: true,
            version: 'v2.7'
        });
        FB.AppEvents.logPageView();
    }
};

var googleUser = {};
var client;
var access_token;


function loginGoogle() {
    if(client == null || client == undefined)
    client = google.accounts.oauth2.initTokenClient({
        client_id: $("#GoogleKeyID").val(),
        scope: 'email',
        callback: (tokenResponse) => {
            access_token = tokenResponse.access_token;
            socialLogin(access_token, 2);
        }, function(error) {
            console.log(error);
            return;
        }
    });
    client.requestAccessToken();
}


(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) { return; }
    js = d.createElement(s); js.id = id;
    js.src = "https://connect.facebook.net/en_US/sdk.js";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));

function loginFb(isRerequest) {
    var requestType = "";
    if (isRerequest) {
        requestType = "rerequest";
    }
    FB.login(function (response) {
        // handle the response
        if (response.status === "connected") {
            var executeServerLogin = true;
            FB.api('/' + response.authResponse.userID + '/permissions',
                function (t) {
                    if (t && !t.error && t.data)
                        for (var n = 0, o; n < t.data.length; n++)
                            if (o = t.data[n], 'email' === o.permission && 'declined' === o.status) {
                                $(".jq-social-error").show();
                                executeServerLogin = false;
                            }
                    if (executeServerLogin) {
                        socialLogin(response.authResponse.accessToken, 1);
                    }
                });
        } else {

            $(".jq-social-error").show();
            return;
        }
    },
        {
            scope: 'email',
            return_scopes: true,
            auth_type: requestType
        });
}



function socialLogin(token, providerType) {
    var webMethod = '/ApiService.asmx/Forward';
    var socialType = providerType == 1 ? 'Facebook' : 'Google';
    var parameters = { AccessToken: token, Provider: socialType };
    $.modal.close();
    $.ajax({
        type: "POST",
        url: webMethod,
        data: JSON.stringify({
            path: window.AppConfig.socialLoginPath,
            body: parameters,
            includeCookies: false
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            $("#div-loader").show();
            if (res.d.Status.Success === true) {
                dataLayer.push({
                    'event': 'ga4_event',
                    'event_name': 'login',
                    'method': socialType.toLowerCase()
                });
                $("#login-form").hide();
                if (window.location.pathname === "checkout/socialregistration.aspx") {
                    window.location.replace("Checkout/Profilo.aspx?op=mieidati");
                } else {
                    window.location.reload(true);
                }
            } else {
                if (res.d.SocialProfile !== null && res.d.SocialProfile.Email && res.d.SocialProfile.Email.length > 0) {
                    window.location.replace("/checkout/socialregistration.aspx?from=social&socialType=" + socialType.toLowerCase() + "&email=" + window.btoa(res.d.SocialProfile.Email));
                }
                else if (res.d.Status.Errors.length > 0 && res.d.Status.Errors[0].UserMessage) {
                    alert(res.d.Status.Errors[0].UserMessage);
                }
                $("#div-loader").hide();
            }
        },
        error: function (e) {
            console.log(e);
        }
    });
}
function login() {
    $.modal.close();
    //validate
    $("#div-error-email").hide();
    if ($("#txt-email").val().length === 0) {
        $("#div-error-email").show();
        $("#spn-message-mail-error").text("*Email obbligatoria");
        $('#login-form').modal();
        return;
    }
    if (!isEmail($("#txt-email").val())) {
        $("#div-error-email").show();
        $("#spn-message-mail-error").text("*Email non valida");
        $('#login-form').modal();
        return;
    }
    $("#div-error-password").hide();
    if ($("#txt-password").val().length === 0) {
        $("#div-error-password").show();
        $("#spn-message-password-error").text("*Password obbligatoria");
        $('#login-form').modal();
        return;
    }

    var webMethod = '/ApiService.asmx/Forward';
    var parameters = { Username: $("#txt-email").val(), Password: window.btoa($("#txt-password").val()), AntiForgeryToken: $("#hiddenAntiForgery").val() };
    $.ajax({
        type: "POST",
        url: webMethod,
        contentType: "application/json",
        dataType: "json",
        data: JSON.stringify({
            path: window.AppConfig.loginPath,
            body: parameters,
            includeCookies: false
        }),
        success: function (res) {
            if (res.d.Status.Success === true) {
                $("#login-form").hide();
                $("#div-loader").show();
                if (window.location.pathname.toLowerCase() === "/password-reimposta.aspx") {
                    window.location.href = "/";
                } else {
                    dataLayer.push({
                        'event': 'ga4_event',
                        'event_name': 'login',
                        'method': 'email'
                    });
                    window.location.reload(true);
                }
            } else {
                    $("#div-server-error").hide();
                if (res.d.Status.Errors.length > 0 && res.d.Status.Errors[0].UserMessage) {
                    $("#div-server-error").show();
                    $("#spn-message-server-error").html(res.d.Status.Errors[0].UserMessage);
                }
                $('#login-form').modal();
            }
        },
        error: function (e) {
            alert('err');
        }
    });
}

function guestLogin() {
    $("#div-error-email-guest").hide();
    $("#div-error-rules").hide();
    if ($("#txt-email-guest").val().length === 0) {
        $("#div-error-email-guest").show();
        $("#spn-message-mail-error-guest").text("*Email obbligatoria");
        return;
    }
    if ($("#txt-email-guest").val().length > 64) {
        $("#div-error-email-guest").show();
        $("#spn-message-mail-error-guest").text("*Email non deve superare i 64 caratteri");
        return;
    }
    if (!isEmail($("#txt-email-guest").val())) {
        $("#div-error-email-guest").show();
        $("#spn-message-mail-error-guest").text("*Email non valida");
        return;
    }
    if (!$('#chkSelectRule').prop('checked')) {
        $("#div-error-rules").show();
        return;
    }
    checkGuestOrders();
}


function isEmail(email) {
    var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
    return regex.test(email);
}
function checkGuestOrders() {
    var email = $("#txt-email-guest").val();
    var webMethod = '/ApiService.asmx/Forward';
    var parameters = {Email: email};
    $.ajax({
        type: "POST",
        url: webMethod,
        data: JSON.stringify({
            path: window.AppConfig.checkGuestOrderPath,
            body: parameters,
            includeCookies: false
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.d.Result === "EmailSent") {
                //email verifica inviata
                emailSent(email);
            }
            if (res.d.Result === "AlreadyRegistered") {
                //already registered  
                alreadyRegistered(email);
                return;
            }
            if (res.d.Result === "MaxNumberExceeded") {
                //troppi ordini attivi
                maxNumberExceeded();
                return;
            }
            if (res.d.Result === "LimitDateExceeded") {
                //troppo recente l'ultimo ordine
                limitDateExceeded();
            }

        },
        error: function (e) {
            console.log(e);
        }
    });
}

function alreadyRegistered(email) {

    $("#div-email-already-registered").show();
    $("#btn-prosegui").hide();
    $("#spn-message-mail-registered").text(email);
}


function alreadyGuest(email) {

    var webMethod = '/checkout/CheckoutService.asmx/GetActiveOrdersByGuestProfileType';
    var parameters = "{'email':'" + email + "'}";
    $.ajax({
        type: "POST",
        url: webMethod,
        data: parameters,
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.d === 1) {
                //MaxNumberExceeded
                alert("troppi  ordini");
                regularLogin();
            }
            if (res.d === 2) {
                //already guest
                alert("troppo poco tempo");
            }
            if (res.d === 0) {
                //already guest
                alert("Crea guest");
            }
        },
        error: function (e) {
            console.log(e);
        }
    });
}



function regularLogin() {
    $("#guest-login").hide();
    $("#regular-login").show();
}

function goToRegistrationPage() {
    $(window.location).attr('href', '/checkout/SocialRegistration.aspx?op=guest');
}

function maxNumberExceeded() {
    $("#div-maxNumberExceeded").show();
    $("#btn-prosegui").hide();
}
function limitDateExceeded() {
    $("#div-limitDateExceeded").show();
    $("#btn-prosegui").hide();
}

function emailSent(email) {
    $("#div-email-sent").show();
    $("#btn-prosegui").hide();
    $("#spn-message-mail-sent").text(email);
}
;
$(document).ready(setTimeout(function () {

    $("#btn-continue").click(function (event) {
        event.preventDefault();
        var urlParams = new URLSearchParams(window.location.search);
        var dest = urlParams.get("dest");
        if (dest !== null) {
            window.location.replace(dest);
        }
        else {
            window.location.replace("/default.aspx");
        }
    });

}, 10));

;
function manageItems() {
    
        if (window.name != "more") {
            $('.cartitem.jqc').css('display', 'none');
            $('.cartitem.jqc').slice(0, 3).css('display', 'table');

            if ($('.cartitem.jqc').length <= 3) $('.morec').show();
            $('.lessc').hide();
        }
        else {
            $('.morec').hide();
            if ($('.cartitem.jqc').length <= 3) $('.lessc').show();
        }

        $('.morec').click(function () {
            $('.cartitem.jqc').fadeIn();
            $('.morec').hide();
            $('.lessc').show();
            window.name = "more";
        });

        $('.lessc').click(function () {
            $('.cartitem.jqc').css('display', 'none');
            $('.cartitem.jqc').slice(0, 3).css('display', 'table');
            $('.lessc').hide();
            $('.morec').show();
            $('html,body').animate({ scrollTop: 0 }, 200);
            window.name = "less";
        });

        $('.cartitem.jqp').css('display', 'none');
        $('.cartitem.jqp').slice(0, 3).css('display', 'table');
        $('.lessp').hide();
        if ($('.cartitem.jqp').length <= 3) $('.morep').hide();

        $('.morep').click(function () {
            $('.cartitem.jqp').fadeIn();
            $('.morep').hide();
            $('.lessp').show();
        });

        $('.lessp').click(function () {
            $('.cartitem.jqp').css('display', 'none');
            $('.cartitem.jqp').slice(0, 3).css('display', 'table');
            $('.lessp').hide();
            $('.morep').show();
            $('html,body').animate({ scrollTop: 0 }, 200);
        });
};


function StartLoader() {
    $("#div-loader").show();
}

function StopLoader() {
    $("#div-loader").hide();
};
$(document).ready(setTimeout(function () {
    $.modal.defaults = {
        clickClose: false,
        showClose: true
    };
    $("#div-delete-error").hide();
   
}, 10));


function deleteprofile() {
    $.modal.close();
    
    var webMethod = '/ApiService.asmx/Forward';

    $.ajax({
        type: "POST",
        url: webMethod,
        data: JSON.stringify({
            path: window.AppConfig.deleteProfilePath,
            body: null,
            includeCookies: true
        }),
        contentType: "application/json",
        dataType: "json",
        success: function (res) {
            if (res.d.Status.Success === true) {

                $("#delete-form").hide();
                $("#div-loader").show();
                window.location.href = "/";
            } else {
                $("#div-infos").hide();
                $("#btn-delete-profile").hide();

                if (res.d.Status.Errors.length > 0 && res.d.Status.Errors[0].UserMessage) {
                    $("#div-delete-error").show();
                    $("#spn-message-delete-error").show();
                    $("#spn-message-delete-error").html(res.d.Status.Errors[0].UserMessage);
                }
                $('#delete-form').modal();
            }
        },
        error: function (e) {
            alert('err');
        }
    });
}
;
