var orderId;
var hashId;
var bytesDocument;
var languageCalendar = document.documentElement.lang.toUpperCase();
var arrayPkPass = [];
var tryPass;
var statusPaymentValid;
var validParams;
var methodPaymentType;
var preOrderPaymentActive;
var cart;
var resultFreddomPay;
var statusPendingCheck = false;

const initCF11Ready = () => {
    const infoPaymentResultInfoParse = localStorage.getItem("paymentResultInfo");
    const dataPaymentResultInfo = JSON.parse(infoPaymentResultInfoParse);
    preOrderPaymentActive = $.cookie("paymentOrderActive");
    $(".infoCompraGeneral").hide()

    if ($.cookie("portal") == undefined) {
        callAjaxAuthorToken();
    }
    if ($.cookie("CallCenterUser") != undefined && $.cookie("CallCenterUser") != "") {
        var elementsToHideParent = $("div.cf10_notifications_funnel").parent();
        elementsToHideParent.children('div').each(function () {
            if ($(this).hasClass("cf10_notifications_funnel")) {

            } else {
                $(this).addClass("d-none")
            }
        });
        $(".downloadTicket").hide()
        $(".cf11_tickets").hide()
        $(".cc07_information").hide()

        $(".cc32_distributivecard").hide()
        $(".cc13_linkslist ").hide()
        if ($.cookie("idPreorderB2C") != undefined) {
            var successB2C = $("#sucessB2C").val();
            $(".message-container-success").html(successB2C + " <br> Order ID: " + $.cookie("idPreorderB2C"))
            deleteCookies();
            removeCookie('idCart');
        }
        $(".cc15_apps_download").html("")
        removeCookie('CallCenterUser');

    }
    if ($.cookie("b2cClient") != undefined) {
        $(".cf07_stepper").addClass("d-none");
    }

    if (window.location.search === "" && preOrderPaymentActive != undefined)
        thankYouErrrors("Error Query Params", "Dont have query Params");


    // Download tickets
    if ($("input.downloadTicket").val() == 'true') {
        let params = {};
        decodeURI(unescape(window.location.search))
            .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
                params[key] = value;
            }
            );
        $.each(params, function (index, element) {
            if (orderId == undefined && index === "orderId")
                orderId = element;
            if (hashId == undefined && index === "orderHash")
                hashId = element;

        });
        $("#dataSuccesTitle").addClass("d-none");
        $("#successB2B").addClass("d-none");
        $("#downloadTicketMessage").removeClass("d-none")
        getTickets(orderId, hashId)

    }
    else {
        var isMollie = $.cookie("paymentPlataform") === "mollie";
		if (!isMollie) {
            // is preOrder
            if (preOrderPaymentActive != undefined && preOrderPaymentActive === 'false') {
                // link out of date
                $(".downloadTicket").addClass("d-none");
                $("#dataSuccesTitle").addClass("d-none");
                $("#successB2B").addClass("d-none");

                $("#linkOutOfDate").removeClass("d-none");

                fadeOutSpinner();

            } else {

                // Get paymentType 
                methodPaymentType = $.cookie("methodPaymentType");
                validParams = false;
                //    setInterval(fadeInSpinner, 2000)

                tryPass = 0;
                if ($.cookie("SendToClient") != undefined && $.cookie("SendToClient") == 'CLIENTSENT') {
                    fadeOutSpinner();
                } else {
                    //mews paylater
                    if(localStorage.getItem("paymentResultInfo")!=null){
                        let typeOfPay = dataPaymentResultInfo.typeOfPay;
                        //confirm tib reserv
                        if(typeOfPay == "payLater"){
                            confirmTibReservation();
                        }
                    }
                    var errpr = validateEntryValues()

                    if (errpr) {

                        //try to get the order status
                        var resultData = getOrderStatus();
                        checkOrderStatus(resultData.responseJSON)
                        funtionEnableDownloand();
                        if ($.cookie("isGiftTicket") != undefined) {
                            $("#giftTicketTicket").removeClass("d-none");
                        }

                    }
                }
            }
        }
    }
    $(".cf02_cart").hide();
    $(".cf07_stepper").addClass("stepper-full-width");
    $(".cf05_controlbuttons .continue").addClass("margin-right-unset");

    if ($('.cc32_distributivecard').length > 0) {
        $('.cc32_distributivecard .card-list .block-text > .ca01_button.button.border-solid').removeClass('border-solid');
        $('.cc32_distributivecard .card-list .enlace_modal > .ca01_button.button.border-solid').removeClass('border-solid');
    }
}

const initCF11Load = () => {
    if ($(window).width() >= 1024) {
        $('.errorText').css('padding-left', parseInt($('.icon-checkmark-circle').css('margin-right')) + parseInt($('.errorText').css('padding-left')) + $('.icon-checkmark-circle').outerWidth())
        $('.dataError .button').css('padding-left', $('.errorText').css('padding-left'))
    }
}

$(window).resize(function () {
    $(".cf02_cart").hide();
});

$(".cf05_controlbuttons .continue").on("click", function () {
    deleteCookies();
});



async function checkOrderStatus(resultData) {
    statusPaymentValid = resultData.status

    if ((resultData.status === 'BARCODE_PENDING' || resultData.status == 'PAYMENT_PENDING') && localStorage.getItem("paymentResultInfo") == null) {
        statusPaymentValid = resultData.status
        $.cookie("statusOrder", resultData.status, { path: window.location.pathname, secure: true });

        for (tryPass = 0; (statusPaymentValid == 'PAYMENT_PENDING' || statusPaymentValid == 'BARCODE_PENDING') && tryPass < 10; tryPass++) {


            var ayuda = await sleep(3000)
            var promiseOrderStatus = getOrderStatus();
            resultData = promiseOrderStatus.responseJSON;

            statusPaymentValid = resultData.status;

        }
        if (statusPaymentValid !== 'VALID') {
            showErrorContainer('errorTicket');
        }

    } else if (resultData.status === 'FAILED') {
        //need to check  what will be done if it fails
        showErrorContainer('errorTicket');

    }

    if (resultData.status === 'BARCODE_PENDING') {
        //need to check  what will be done if it fails
        showErrorContainer('BARCODE_PENDING');
        funnelPurchaseAnalitycs(resultData)
    } else if (statusPaymentValid === 'PAYMENT_PENDING') {
        showErrorContainer('PAYMENT_PENDING');
        funnelPurchaseAnalitycs(resultData)
    } else if (statusPaymentValid === 'VALID') {
        if (preOrderPaymentActive != undefined && preOrderPaymentActive === 'true') {
            // link out of date
            $(".downloadTicket").addClass("d-none");
            $("#dataSuccesTitle").addClass("d-none");
            fadeOutSpinner();
        } else {
            if (namePark == "MUL") {
                $(".infoCompraGeneral").show()
                $(".downloadTicket").addClass("d-none");
                $("#dataSuccesTitle").addClass("d-none");    
            $("#successB2B").addClass("d-none");
                $("#oderIdBono").text(orderId)
                fadeOutSpinner();
            } else {

                $("#successB2B").addClass("d-none");
            returnTickets(resultData)
            }
            if ($.cookie("abandonedSaved") != undefined) {
                unsubscribeCart($.cookie("abandonedSaved"))
            }
        }

    }
}
async function sleep(msec) {
    return new Promise(resolve => setTimeout(resolve, msec));
}

function returnTickets(resultData) {
    // Get wallet in mobile 

    if ($(window).width() <= 768 && !(isAppleDevice() && detectBrowser() === "Chrome"))
        getOrderInfo();

    getTickets(resultData.orderId, hashId);
    if ($.cookie("isGiftTicket") != undefined) {
        getTicketsGift(resultData);
    }

}

function funtionEnableDownloand() {
    $(document).on('click', '#downloandButton', function (event) {
        const tagElement = event.target;
        generateTickets(tagElement);
    });
    $(document).on('click', '#downloandButton2', function (event) {
        const tagElement = event.target;
        generateTickets2(tagElement);
    });
    $(document).on('click', '#downloandButtonGift', function (event) {
        const tagElement = event.target;
        generateGiftTickets(tagElement);
    });

}


$(document).on('click', '#tryit', function () {

    retryPayment();
    /*    var initialFunnel = localStorage.getItem(`initialStepFunnel-${$("#parkmnemonic").val()}-${$.cookie("idFunnel")}`);
        deleteCookies()
        window.location.replace(initialFunnel)
    
        */
});

const generateDataLayerToTickets = (type, tagElement) => {
    const label = type;
    const slidername = tagElement.closest(".gradient-bg").querySelector(".visitor").innerText;

    return {
        "event": "eventga",
        "category": "Interaction",
        "action": "Funnel",
        "label": label,
        "slidername": slidername
    }
}

/**
 * Function that will generate the   ticket based on the response
 */
function generateTickets(tagElement) {
    //bytesDocument = "JVBERi0xLjUNCiW1tbW1DQ";
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(bytesDocument);
    link.download = "tickets.pdf";
    link.click()

    // Add event download Tickets
    dataLayer.push(generateDataLayerToTickets("downloadTickets", tagElement));
}

/**
 * Function that will generate the   ticket based on the response
 */
function generateTickets2(tagElement) {
    //bytesDocument = "JVBERi0xLjUNCiW1tbW1DQ";
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(bytesDocument);
   /* link.download = "tickets.pdf";*/
    link.click()

    // Add event download Tickets
    dataLayer.push(generateDataLayerToTickets("downloadTickets", tagElement));
}

/**
 * Get gift tickets
 */

function generateGiftTickets(tagElement) {
    //bytesDocument = "JVBERi0xLjUNCiW1tbW1DQ";
    let link = document.createElement("a");
    link.href = window.URL.createObjectURL(bytesDocumentGift);
    link.download = "GiftTickets.pdf";
    link.click()

    // Add event download Tickets
    dataLayer.push(generateDataLayerToTickets("downloadTickets", tagElement));
}

/**
 * Get gift tickets
 */




function base64ToArrayBuffer(base64) {
    var binaryString = window.atob(base64);
    var binaryLen = binaryString.length;
    var bytes = new Uint8Array(binaryLen);
    for (var i = 0; i < binaryLen; i++) {
        var ascii = binaryString.charCodeAt(i);
        bytes[i] = ascii;
    }
    return bytes;
}


function validateEntryValues() {
    var urlActual = window.location.href;

    var searchParams = new URLSearchParams(new URL(urlActual).search);
    var isAdditionalDetailsValue;
    if (searchParams.has('isAdditionalDetails')) {
        isAdditionalDetailsValue = searchParams.get('isAdditionalDetails');
    }


    if (methodPaymentType != undefined && methodPaymentType != null && methodPaymentType.includes("COMPUTOP")) {
        if (methodPaymentType != undefined && methodPaymentType != null && methodPaymentType.includes("COMPUTOP_CRM")) {
            validateUrlParametersComputopCRM();
        }else{
            validateUrlParametersComputop();
        }

    } else if (methodPaymentType != undefined && methodPaymentType != null && methodPaymentType.includes("NETS_EASY")) {
        validateUrlParametersNetsEasy()
    }
    else if (methodPaymentType != undefined && methodPaymentType != null && methodPaymentType.includes("GESTPAY")) {
        validateUrlParametersGestPay()
    }else if (methodPaymentType != undefined && methodPaymentType != null && methodPaymentType.includes("FREEDOMPAY")) {
        resultData = validateUrlParametersFreedompay();
    } else if (isAdditionalDetailsValue != null) {
        if(isAdditionalDetailsValue == "true"){
            //if is TIB timeout 4secs in order to vector have time to confirm the payment, else we receive FAILED
            if (localStorage.getItem("paymentResultInfo") != null) {
				setTimeout(function() {
			        validateUrlParameters();
			    }, 4000);
			        
			}else{
	            validParams = true;
			}
        }else{
            validParams = false;
            $("#successB2B").addClass("d-none");
        }
    } else {
        validateUrlParameters()
    }
    //show error TIB and rest of parks
    if (localStorage.getItem("paymentResultInfo") != null) {
        setTimeout(function() {
            if (!validParams || $.cookie("portal") == undefined
            || $.cookie("orderId") == undefined || $.cookie("orderHash") == undefined) {
            if(statusPendingCheck == false){
                if(typeOfPay != "payLater"){
	                showErrorMsg('errorPay');
	                showErrorContainer("errorPay");
	                if($(".container.boxes.failedPayment").length > 0){
                        $(".container.boxes").addClass("d-none");
                        $(".container.boxes.failedPayment").removeClass("d-none");
                    }
				}
            }
            return false;
        }
        }, 5000);
    }else{
        if (!validParams || $.cookie("portal") == undefined
            || $.cookie("orderId") == undefined || $.cookie("orderHash") == undefined) {
            if(statusPendingCheck == false){
                showErrorMsg('errorPay');
                showErrorContainer("errorPay");
                if($(".container.boxes.failedPayment").length > 0){
                    $(".container.boxes").addClass("d-none");
                    $(".container.boxes.failedPayment").removeClass("d-none");
                }
            }
            return false;
        }
    }    
    return true;
}

$(document).on('click', '.walletTarget .button01 ', function (event) {

    const tagElement = event.target;
    // Get data pkpass
    var dataPkPass = arrayPkPass[parseInt($(this).attr('data-id'))];

    // Download
    let link = document.createElement("a");
    link.onclick = window.open(window.URL.createObjectURL(dataPkPass), '_system')
    link.download = "tickets" + $(this).attr('data-id') + ".pkpass";
    link.click()

    // Add event download Tickets
    dataLayer.push(generateDataLayerToTickets("addToWallet", tagElement));
});
function addWalletButton(title, id) {
    $(".individualTickets").append(`	
                <div class="visitor-block downloadTicket">
			<div class="row col-12 gradient-bg">
				<div class="col-2 text-right funnel-tickets-icon d-flex justify-content-center">
					<span class="icon-ticket align-self-center"></span>
				</div>
				<div class="visitor col-5">
					<p class="title h2ddsk">${title}</p>
					
				</div>
				<div class="walletTarget ticket-amount row col-5 d-flex justify-content-center">
					<div class="button-download button border-solid align-self-center">
						<div class="button01" data-id="${id}">
							<a class="cmp-button" target="_system" >
								<span class="cmp-button__text">${$("input#addWallet").val()}</span> <input type="hidden">
							</a>
						</div>
					</div>
				</div>
			</div>
		</div>`);

    /*<h3>${title}</h3>
            <div class="button-download button border-solid align-self-center">
                <div class="button01" data-id="${id}">
                    <a class="cmp-button"  >
                        <span class="cmp-button__text" >Download!</span>  
                    </a>
                </div>
            </div>*/
}

function showErrorContainer(statusError) {
    if (preOrderPaymentActive != undefined && preOrderPaymentActive === 'true') {
        $("#dataErrorB2B").removeClass("d-none");
        $(".downloadTicket").addClass("d-none");
        $("#dataSuccesTitle").addClass("d-none");
        $("#successB2B").addClass("d-none");

    } else {

        // Hide Succes
        $(".individualTickets").addClass("d-none");
        $(".downloadTicket").addClass("d-none");
        $(".message-container-success").addClass("d-none");
        $(".message-container-success").addClass("d-none");
        $(".cc15_apps_download").hide();
        $(".cf08_syncapp_button").hide();
        $(".cc18_columns").hide();

        if (statusError == 'BARCODE_PENDING' || statusError == 'errorTicket') {
            $(".barcode-pending").removeClass("d-none");
            $(".close-message").addClass("d-none");
            $(".cf05_controlbuttons").show();
        } else if (statusError == 'errorWallet') {
            $(".barcode-pending").removeClass("d-none");
            $(".close-message").addClass("d-none");
            $(".downloadTicket").removeClass("d-none");
            if($.cookie("isGiftTicket") == undefined){
                $("#giftTicketTicket").addClass("d-none");
            }
            if(currencyCode != null && currencyCode == "USD"){
                $(".errorMsg").hide();
            }
        } else if (statusError == 'pendingPaymentBank') {
            $(".barcode-pending").removeClass("d-none");
            $(".close-message").addClass("d-none");
            $("#successB2B").addClass("d-none");
            $("#successB2BPending").removeClass("d-none");
            $(".individualTickets").addClass("d-none");
            $(".downloadTicket").addClass("d-none");
            $(".cc15_apps_download").hide();
            $(".cf08_syncapp_button").hide();
            $(".cc18_columns").hide();
            $("#dataSuccesTitle").hide();
        } else if (statusError == 'PAYMENT_PENDING') {
            $(".payment-pending").removeClass("d-none");
            $(".payment-pending #orderId").text(orderId);
        } else {
            $("#dataSuccesTitle").addClass("d-none");

            // Show container error
            $("#dataError").removeClass("d-none");

            // Hide control buttons
            $(".cf05_controlbuttons").addClass("d-none")
        }
    }
    fadeOutSpinner();
}
function funnelPageView() {
    funnelResults.push('', '', '', 'typPage');
    return funnelResults;
}

function thankYouErrrors(title, label) {
    $('meta').each(function () {
        if ($(this).attr('property') == 'og:title') {
            slidername = $(this).attr('content')
        }
    })
    dataLayer.push({
        "category": "TYPTrace", // En la categoría necesito algo común , para que todo caiga dentro de ese bloque.
        "action": title, // categoría superior, lo que queráis para que os sirva para organizarlo ( OK, KO, OK con fallo en ticket … lo que queráis )
        "label": label, // Lo que queráis
        "event": "eventga", // necesario para que se recoja,
        "urlmodule": urlCC20,
        "slidername": slidername, // El title de la página
        "Gate": namePark, // El código del parque WAR o WBE
    });

}

function setCookieAnalitycs(value) {
    const expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));

    document.cookie = 'transactionID=' + value + ';expires=' + expires.toUTCString();
}

function funnelPurchaseAnalitycs(data) {
    //Analytics
    //Landing  
    referrerCC20 = document.referrer;
    var days = [
        'Sunday',
        'Monday',
        'Tuesday',
        'Wednesday',
        'Thursday',
        'Friday',
        'Saturday'
    ];

    var weekday = dateCC20.getDay();
    let infoTotal = localStorage.getItem('infoTotal');
    let products = JSON.parse(localStorage.getItem("funnelProducts"));
    let postalCode = localStorage.getItem('postalCode');
    let discountAmount = localStorage.getItem('discountAmount');
    let couponName = localStorage.getItem('couponName');
    let transactionID = data.orderId.toString();
    let reservationIds = (JSON.parse(localStorage.getItem("paymentResultInfo") || "null")?.reservationsIds) || null;
    let category = sessionStorage.getItem('funnelVariant');
    $('meta').each(function () {
        if ($(this).attr('property') == 'og:title') {
            slidername = $(this).attr('content')
        }
    })
    let realTransaction = true;
    if(infoTotal == null){
        realTransaction = false;  
    }
    // Sacando de la variable sesión los plazos del pago a plazos
    var splitsPayments = localStorage.getItem('split_payment');
    if(splitsPayments === null || splitsPayments === undefined|| splitsPayments === '') {
        splitsPayments = 'no';
    }else {
        splitsPayments = 'yes'+splitsPayments;
    }
    var priceInitial = "undefined";
    if(sessionStorage.getItem("priceInitialAnalitics")){
        priceInitial = sessionStorage.getItem("priceInitialAnalitics");
    }
    var selectedDayAnalitics = "undefined";
    if(sessionStorage.getItem("selectedDayAnalitics")){
        selectedDayAnalitics = sessionStorage.getItem("selectedDayAnalitics");
    }
    var priceTotal = "undefinded";
    if(sessionStorage.getItem("priceInitialAnalitics")){
        priceTotal = localStorage.getItem("infoTotal");
    }
    if (($.cookie("transactionID") == null && realTransaction) || ($.cookie("transactionID") != transactionID && realTransaction)) {
        setCookieAnalitycs(transactionID);
        var datalayerCategory = "";
        if($.cookie("idFunnel") == "season-passes" || $.cookie("idFunnel") == "saisonpass" || $.cookie("idFunnel") == "saesonkort" || $.cookie("idFunnel") == "abonnement" || $.cookie("idFunnel") == "annual-passes" || $.cookie("idFunnel") == "annual-pass" || $.cookie("idFunnel") == "renewal-pass" || $.cookie("idFunnel") == "renewals" || $.cookie("idFunnel") == "renewal-funnel"){
            datalayerCategory = "Season pass";
            products.forEach((obj) => {
                if (typeof obj === 'object') {
                  obj.category = datalayerCategory;
                }
            });
        }

        //Datos que vienen de Payments para poner en analitica
       // var shipping = sessionStorage.getItem('shippingON');
        var shippingAmount = sessionStorage.getItem('shippingAmount');

        var voucher = sessionStorage.getItem('voucherON');
        var voucherAmount = sessionStorage.getItem('voucherAmount');
        if(voucherAmount == null || voucherAmount == 'No'){
            voucherAmount = 0;
        }
        if(isNaN(shippingAmount)){
            shippingAmount = 0;
        }

        if(namePark == "TIB"){
            $.each(products, function(index, product) {
            if(product.variant == "FunnelVoucher"){
              // Actualizar la propiedad "category" de cada producto a "Voucher"
              product.category = "Voucher";
            }
          });
        }
        
        dataLayer.push({
            'event': 'analyticspageview',
            'content': {
                'category': category,
                'contenthierachy': 'undefined',
                'country': countryCC20,
                'date': outputCC20,
                'asset': namePark,
                'host': hostCC20,
                'language': countryCC20,
                'mode': modeCC20,
                'pagetype': 'funnel-page', //Product detail, Product list, Funnel, Search Result, Distributive Events..etc
                'pagename': nameCC20,
                'referrer': referrerCC20,
                'Gate': namePark,
                'time': time,
                'url': urlCC20,
                'virtualurl': 'undefined',
                'weekday': days[weekday],
            },
            'user': {
                'gaclient': clientID,
                'useragent': browser,
                'subcribednewsletter': 'undefined',
                'initialdateuser': $.cookie('selectedDayInitial'),
                'initialdateweb': selectedDayAnalitics,
                'logged': 'no logado',
                'gender': 'undefined',
                'age': 'undefined',
                'lastlogindate': 'undefined',
                'sociallogin': 'undefined',
                'lastpurchase': 'undefined',
                'idcrm': 'undefined',
                'fidelitycard': 'undefined',
                'postalcode': 'undefined',
                'emailhash': 'undefined',
                'initialPrice': priceInitial,
                'finalPrice': priceTotal
            },
            'campaign': {
                'campaign': 'undefined',
                'trafficsource': 'undefined', //Hay que guardar todos estos parámetros en cookies
                'medium': 'undefinded',
                'term': 'undefinded',
                'content': 'undefinded'//https://pre-aem.parquedeatracciones.es/experiencias/atracciones/abismo?utm_source=newletter&utm_medium=email&utm_campaign=reapertura27032021&utm_term=reaperturavips&utm_content=vuelveaparquedeatracciones
            },
            'ecommerce': {
                'cmEstRevenue': localStorage.getItem("revenueAnalytics") != null ? localStorage.getItem("revenueAnalytics") : infoTotal,
                'cmDaysToVisit': $.cookie("days") != undefined ? $.cookie("days") : 1,// number ( days to the selected visit date )*
                'cmSavingAmount': discountAmount,
                'cdPostalCode': postalCode,
                'cdVisitorAge': $.cookie('birthDate'),
                'cdFirstVisit': '',
                'cdSelectedDate': $.cookie("visitDate"),
                'cd_paymentMethod': $.cookie('methodPaymentName'),
                'currencyCode': currencyCode,
                'cdGift': $.cookie("isGiftTicket") != undefined && $.cookie("idFunnel") == 'voucher-funnel' || $.cookie("idFunnel") == 'gift-annual-pass' ? $.cookie("isGiftTicket") : 'No',
                'purchase': {
                    'actionField': {
                        'id': reservationIds != null ? reservationIds : data.orderId,
                        'revenue': localStorage.getItem("revenueAnalytics") != null ? localStorage.getItem("revenueAnalytics") : (parseFloat(infoTotal) - voucherAmount) + Number(shippingAmount),
                        'shipping': shippingAmount,
                        'tax': localStorage.getItem("taxAnalytics") != null ? localStorage.getItem("taxAnalytics") : 0,
                        'action': 'purchase',
                        'coupon': couponName,
                        'voucher': voucher,
                        'voucherAmount':voucherAmount,
                        'split_payment' : splitsPayments,
                    },
                    'products': products
                }
            },
        });
    }
    
    localStorage.removeItem("funnelProducts");
    localStorage.removeItem('infoTotal');
    localStorage.removeItem('postalCode');
    localStorage.removeItem('discountAmount');
    localStorage.removeItem('couponName');
    localStorage.removeItem('funnelVariant');
    localStorage.removeItem('revenueAnalytics');
    localStorage.removeItem('taxAnalytics');
    sessionStorage.removeItem("funnelProducts");
    sessionStorage.removeItem('infoTotal');
    sessionStorage.removeItem('postalCode');
    sessionStorage.removeItem('discountAmount');
    sessionStorage.removeItem('couponName');
    sessionStorage.removeItem('funnelVariant');
    

    
}

function isAppleDevice() {
    const toMatch = [
        /iPhone/i,
        /iPad/i,
        /iPod/i
    ];

    return toMatch.some((toMatchItem) => {
        return navigator.userAgent.match(toMatchItem);
    });
}
function detectBrowser() {
    if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
        return 'Opera';
    } else if (navigator.userAgent.indexOf("Chrome") != -1 || navigator.userAgent.indexOf("CriOS") != -1) {
        return 'Chrome';
    } else if (navigator.userAgent.indexOf("Safari") != -1) {
        return 'Safari';
    } else if (navigator.userAgent.indexOf("Firefox") != -1) {
        return 'Firefox';
    } else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) {
        return 'IE';//crap
    } else {
        return 'Unknown';
    }
}


function getOrderStatus() {

    orderId = $.cookie("orderId");
    hashId = $.cookie("orderHash");
    return jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/order/" + orderId + "/" + hashId,
        type: 'GET',
        async: false,
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (resultData) {


        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {

            thankYouErrrors("Error Get Order status", `orderId: ${orderId}, orderhash: ${hashId}, status: ${XMLHttpRequest.status}`);
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });

}

function retryPayment() {
    var orderId = $.cookie("orderId");
    var hashId = $.cookie("orderHash");
    return jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/payment/tryagain/" + $.cookie("orderId") + "/" + $.cookie("orderHash"),
        type: 'POST',
        async: false,
        data: JSON.stringify({
            "returnUrl": window.location.origin + window.location.pathname,
            "cancelUrl": window.location.origin,
            "checkoutReviewReturnUrl": window.location.origin + window.location.pathname
        }),
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {
            payProcces(data)
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            if (XMLHttpRequest.status >= 500) {
                showErrorMsg("general")
                thankYouErrrors("Error Get retryPayment", `orderId: ${orderId}, orderhash: ${hashId}, status: ${XMLHttpRequest.status}`);


            }
            else if (XMLHttpRequest.responseJSON) {
                showErrorMsg(XMLHttpRequest.responseJSON.code);
                thankYouErrrors("Error Get retryPayment", `orderId: ${orderId}, orderhash: ${hashId}, status: ${XMLHttpRequest.responseJSON.code}`);

            }
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });

}


function getTickets(orderId, orderHash) {

    var req = new XMLHttpRequest();
    req.open("GET", $.cookie("urlAccessToken") + "/order/order/" + orderId + "/" + orderHash + "/ticket", true);
    req.responseType = "blob";
    req.setRequestHeader('Authorization', 'Bearer ' + $.cookie("portal"))
    req.setRequestHeader('X-Flow-ID', $.cookie("orderFlowId"))
    req.onload = function (event) {
        if (event.target.status != 200) {
            thankYouErrrors("Error Get ticket", `orderId: ${orderId}, orderhash: ${orderHash}, status: ${event.target.status}`);

            showErrorMsg("errorTicket");
            showErrorContainer("errorTicket")
        } else {
            bytesDocument = req.response;

            //If checked 
            if ($("input.downloadTicket").val() == 'true') {
                let link = document.createElement("a");
                link.href = window.URL.createObjectURL(bytesDocument);
                link.download = "tickets.pdf";
                link.click()
            }

            //generateTickets();
            fadeOutSpinner();
            let data = { orderId: orderId }
            funnelPurchaseAnalitycs(data)
        }
    };


    req.send();

}

/**
 * Get gift tickets
 */
function getTicketsGift(data) {

    var req = new XMLHttpRequest();
    req.open("GET", $.cookie("urlAccessToken") + "/order/order/" + data.orderId + "/" + hashId + "/ticket/gift/", true);
    req.responseType = "blob";
    req.setRequestHeader('Authorization', 'Bearer ' + $.cookie("portal"))
    req.setRequestHeader('X-Flow-ID', $.cookie("orderFlowId"))
    req.setRequestHeader('Access-Control-Allow-Origin', "*")
    req.onload = function (event) {
        if (event.target.status != 200) {
            thankYouErrrors("Error Get ticket", `orderId: ${data.orderId}, orderhash: ${hashId}, status: ${event.target.status}`);

            showErrorMsg("errorTicket");
            showErrorContainer("errorTicket")
        } else {
            bytesDocumentGift = req.response;
            //generateTickets();
            fadeOutSpinner();
            funnelPurchaseAnalitycs(data)
        }
    };


    req.send();

}
/**
 * Get gift tickets
 */



function validateUrlParameters() {
    let params = {};
    let payloadInfo = { "paymentParams": [] };

    orderId = $.cookie("orderId");
    hashId = $.cookie("orderHash");

    decodeURI(unescape(window.location.search))
        .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
            params[key] = value;
        }
        );
    $.each(params, function (index, element) {
        if (orderId == undefined && index === "orderId")
            orderId = element;
        if (hashId == undefined && index === "orderHash")
            hashId = element;
        let paymentparams = { "name": index, "value": element };
        payloadInfo.paymentParams.push(paymentparams);
    });
    if (orderId != null && hashId != null) {
        jQuery.ajax({
            url: $.cookie("urlAccessToken") + "/order/payment/return/" + orderId + "/" + hashId,
            type: 'POST',
            async: false,
            data: JSON.stringify(payloadInfo),
            headers: {
                "Content-Type": "application/json",
                "X-Flow-ID": $.cookie("orderFlowId"),
                "Authorization": "Bearer " + $.cookie("portal")
            },
            success: function (data) {
                var date = new Date();
                console.log("STATUS: " + data.result);
                date.setSeconds(date.getSeconds() + 3600)
                $.cookie("methodPaymentName", data.paymentMethodName, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
                $.cookie("methodPaymentType", data.paymentType, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
    
                if (data.result == 'VALID') {
    
                    $.cookie("orderId", data.orderId, { expires: date, path: removeLastDirectoryPart(window.location.pathname) });
                    $.cookie("orderHash", data.orderHash, { expires: date, path: removeLastDirectoryPart(window.location.pathname) });

                    if(localStorage.getItem("paymentResultInfo")!=null){
						//confirm tib reserv
                        confirmTibReservation();
					}
    
                    validParams = true;
                } else if(data.result == 'PAYMENT_PENDING' || data.result == 'BARCODE_PENDING' || data.result == 'PENDING'){
                    showErrorContainer('pendingPaymentBank');
                    funnelPurchaseAnalitycs(data);
                    statusPendingCheck = true;
                    validParams = false;
                } else {
                    thankYouErrrors("Error validate Params", `orderId: ${orderId}, orderhash: ${hashId}, status: 200`);
    
                    showErrorContainer('errorPay')
                    $("#successB2B").addClass("d-none")
                    $(".cc28_attention_information").addClass("d-none")
                    validParams = false;
                }
    
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                /*  if (XMLHttpRequest.responseJSON) {
                      showErrorMsg(XMLHttpRequest.responseJSON.code);
                  }*/
                if (XMLHttpRequest.status == 404) {
    
                    validParams = true;
                } else if(typeof data !== 'undefined' && (data.result == 'PAYMENT_PENDING' || data.result == 'PENDING')){
                    showErrorContainer('pendingPaymentBank');
                    funnelPurchaseAnalitycs(data);
                    statusPendingCheck = true;
                    validParams = false;
                } else {
                    thankYouErrrors("Error validate Params", `orderId: ${orderId}, orderhash: ${hashId}, status: ${XMLHttpRequest.status}`);
    
                    showErrorMsg('errorTicket')
                    showErrorContainer('errorTicket');
                    $("#successB2B").addClass("d-none")
                    $(".cc28_attention_information").addClass("d-none")
                }
                console.log("Status: {}", textStatus);
                console.log("Error: {}", errorThrown);
            }
        });
    } else {
        // Aqui se deberian pueden personalizar los mensajes de cookies expiradas en compra 

        thankYouErrrors("Error validate Params", `orderId: ${orderId}, orderhash: ${hashId}`);
        showErrorMsg('errorTicket')
        showErrorContainer('errorTicket');
        $("#successB2B").addClass("d-none")
        $(".cc28_attention_information").addClass("d-none")
    }



    return true;
}

function validateUrlParametersComputop() {
    let params = {};
    let payloadInfo = { "paymentParams": [] };
    window.location.search
        .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
            params[key] = value;
        }
        );
    $.each(params, function (index, element) {
        let paymentparams = { "name": index, "value": element };
        payloadInfo.paymentParams.push(paymentparams);
    });
    jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/payment/return/computop",
        type: 'POST',
        async: false,
        data: JSON.stringify(payloadInfo),
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {
            var date = new Date();
            date.setSeconds(date.getSeconds() + 3600)
            $.cookie("methodPaymentName", data.paymentMethodName, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
            $.cookie("methodPaymentType", data.paymentType, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

            if (data.result == 'VALID') {
                $.cookie("orderId", data.orderId, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
                $.cookie("orderHash", data.orderHash, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

                validParams = true;
            } else if(data.result == 'PAYMENT_PENDING' || data.result == 'BARCODE_PENDING' || data.result == 'PENDING'){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Computop", ``);

                showErrorContainer('errorPay')
                $("#successB2B").addClass("d-none")
                $(".cc28_attention_information").addClass("d-none")
                validParams = false;
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /*  if (XMLHttpRequest.responseJSON) {
                  showErrorMsg(XMLHttpRequest.responseJSON.code);
              }*/
            if (XMLHttpRequest.status == 404) {

                validParams = true;
            } else if(typeof data !== 'undefined' && (data.result == 'PAYMENT_PENDING' || data.result == 'PENDING')){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Computop", `status: ${XMLHttpRequest.status}`);

                showErrorMsg('errorTicket')
                showErrorContainer('errorTicket');
            }
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });

    return true;
}


function validateUrlParametersComputopCRM(){
    let params = {};
    let payloadInfo = { "paymentParams": [] };
    window.location.search
        .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
            params[key] = value;
        }
        );
    $.each(params, function (index, element) {
        let paymentparams = { "name": index, "value": element };
        payloadInfo.paymentParams.push(paymentparams);
    });
    jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/payment/return/computopCRM",
        type: 'POST',
        async: false,
        data: JSON.stringify(payloadInfo),
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {
            var date = new Date();
            date.setSeconds(date.getSeconds() + 3600)
            $.cookie("methodPaymentName", data.paymentMethodName, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
            $.cookie("methodPaymentType", data.paymentType, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

            if (data.result == 'VALID') {
                $.cookie("orderId", data.orderId, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
                $.cookie("orderHash", data.orderHash, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

                validParams = true;
            } else if(data.result == 'PAYMENT_PENDING' || data.result == 'BARCODE_PENDING' || data.result == 'PENDING'){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Computop", ``);

                showErrorContainer('errorPay')
                $("#successB2B").addClass("d-none")
                $(".cc28_attention_information").addClass("d-none")
                validParams = false;
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /*  if (XMLHttpRequest.responseJSON) {
                  showErrorMsg(XMLHttpRequest.responseJSON.code);
              }*/
            if (XMLHttpRequest.status == 404) {

                validParams = true;
            } else if(typeof data !== 'undefined' && (data.result == 'PAYMENT_PENDING' || data.result == 'PENDING')){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Computop", `status: ${XMLHttpRequest.status}`);

                showErrorMsg('errorTicket')
                showErrorContainer('errorTicket');
            }
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });

    return true;    
}


function validateUrlParametersNetsEasy() {
    let params = {};
    window.location.search
        .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
            params[key] = value;
        }
        );

    jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/payment/returnNetsEasy/" + params.paymentid,
        type: 'POST',
        async: false,
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {
            var date = new Date();
            date.setSeconds(date.getSeconds() + 3600)
            $.cookie("methodPaymentName", data.paymentMethodName, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
            $.cookie("methodPaymentType", data.paymentType, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

            if (data.result == 'VALID') {
                $.cookie("orderId", data.orderId, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
                $.cookie("orderHash", data.orderHash, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

                validParams = true;
            } else if(data.result == 'PAYMENT_PENDING' || data.result == 'PENDING'){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Computop", ``);

                showErrorContainer('errorPay')
                $("#successB2B").addClass("d-none")
                $(".cc28_attention_information").addClass("d-none")
                validParams = false;
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /*  if (XMLHttpRequest.responseJSON) {
                  showErrorMsg(XMLHttpRequest.responseJSON.code);
              }*/
            if (XMLHttpRequest.status == 404) {

                validParams = true;
            } else if(typeof data !== 'undefined' && (data.result == 'PAYMENT_PENDING' || data.result == 'PENDING')){
                showErrorContainer('pendingPaymentBank');
                validParams = true;
            } else {
                thankYouErrrors("Error validate Params Computop", `status: ${XMLHttpRequest.status}`);

                showErrorMsg('errorTicket')
                showErrorContainer('errorTicket');
            }
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });

    return true;
}
function validateUrlParametersGestPay() {
    let params = {};
    let payloadInfo = { "paymentParams": [] };
    window.location.search
        .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
            params[key] = value;
        }
        );
    $.each(params, function (index, element) {

        let paymentparams = { "name": index, "value": element };
        payloadInfo.paymentParams.push(paymentparams);
    });
    jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/payment/return/gestpay",
        type: 'POST',
        async: false,
        data: JSON.stringify(payloadInfo),
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {
            var date = new Date();
            date.setSeconds(date.getSeconds() + 3600)
            $.cookie("methodPaymentName", data.paymentMethodName, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
            $.cookie("methodPaymentType", data.paymentType, { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

            if (data.result == 'VALID') {
                $.cookie("orderId", data.orderId, { expires: date, path: removeLastDirectoryPart(window.location.pathname) });
                $.cookie("orderHash", data.orderHash, { expires: date, path: removeLastDirectoryPart(window.location.pathname) });

                validParams = true;
            } else if(data.result == 'PAYMENT_PENDING' || data.result == 'PENDING'){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Gestpay", `status: ${XMLHttpRequest.status}`);

                showErrorContainer('errorPay')
                $("#successB2B").addClass("d-none")
                $(".cc28_attention_information").addClass("d-none")
                validParams = false;
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /*  if (XMLHttpRequest.responseJSON) {
                  showErrorMsg(XMLHttpRequest.responseJSON.code);
              }*/
            if (XMLHttpRequest.status == 404) {

                validParams = true;
            } else if(typeof data !== 'undefined' && (data.result == 'PAYMENT_PENDING' || data.result == 'PENDING')){
                showErrorContainer('pendingPaymentBank');
                validParams = true;
            } else {
                thankYouErrrors("Error validate Params Computop", `status: ${XMLHttpRequest.status}`);

                showErrorMsg('errorTicket')
                showErrorContainer('errorTicket');
            }
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });

    return true;
}
function getPkPass(title, barcode, serialNumber, id) {

    orderId = $.cookie("orderId");
    hashId = $.cookie("orderHash");

    var req = new XMLHttpRequest();
    req.open("GET", $.cookie("urlAccessToken") + "/order/order/" + orderId + "/" + hashId + "/pkpass/" + barcode + "/" + serialNumber, true);
    req.responseType = "blob";
    req.setRequestHeader('Authorization', 'Bearer ' + $.cookie("portal"))
    req.setRequestHeader('X-Flow-ID', $.cookie("orderFlowId"))
    req.onload = function (event) {
        if (event.target.status != 200) {
            showErrorMsg("errorWallet");
            showErrorContainer("errorWallet");
            thankYouErrrors("Error Get PkPass", `orderId: ${orderId}, orderhash: ${hashId}, status: ${event.target.status}`);

        } else if(typeof data !== 'undefined' && (data.result == 'PAYMENT_PENDING' || data.result == 'PENDING')){
            showErrorContainer('pendingPaymentBank');
            funnelPurchaseAnalitycs(data);
            statusPendingCheck = true;
            validParams = false;
        }  else {

            arrayPkPass.push(req.response);
            addWalletButton(title, id);
        }
    };
    req.send();

}

function getOrderInfo() {

    orderId = $.cookie("orderId");
    hashId = $.cookie("orderHash");
    jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/order/" + orderId + "/" + hashId + "/info",
        type: 'GET',
        async: false,
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {

            data.barcodes.forEach((barcode, index) => {
                var title = barcode.translations.find(element => element.language == languageCalendar)
                if (title != undefined) {
                    if ($(".syncButtonContainer").length > 0) getPkPass(title.name, barcode.barcode, barcode.serialNumber, index);
                }

            });

            // Check sync button
            if ($(".syncButtonContainer").length > 0) showButtonSync(data)

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            thankYouErrrors("Error Get Order Info", `orderId: ${orderId}, orderhash: ${hashId}, status: ${XMLHttpRequest.status}`);

            $('.syncButtonContainer').hide()
            showErrorMsg("errorWallet")

            showErrorContainer("errorWallet");
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });


}

function validateUrlParametersFreedompay() {
    let params = {};
    let payloadInfo = { "paymentParams": [] };
    let dataParams;
    window.location.search
        .replace(/[?&]+([^=&]+)=([^&]*)/gi, function (str, key, value) {
            params[key] = value;
        }
        );
    $.each(params, function (index, element) {

        let paymentparams = { "name": index, "value": element };
        payloadInfo.paymentParams.push(paymentparams);
    });

    jQuery.ajax({
        url: $.cookie("urlAccessToken") + "/order/payment/return/freedompay/",
        type: 'POST',
        async: false,
        data: JSON.stringify(payloadInfo),
        headers: {
            "Content-Type": "application/json",
            "X-Flow-ID": $.cookie("orderFlowId"),
            "Authorization": "Bearer " + $.cookie("portal")
        },
        success: function (data) {
            resultFreddomPay = data;
            dataParams = data;
            var date = new Date();
            hashId = data.orderHash;
            date.setSeconds(date.getSeconds() + 3600)
            $.cookie("methodPaymentName", "FREEDOMPAY", { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });
            $.cookie("methodPaymentType", "FREEDOMPAY", { expires: date, path: removeLastDirectoryPart(window.location.pathname), secure: true });

            if (data.result == 'VALID') {
                $.cookie("orderId", data.orderId, { expires: date, path: removeLastDirectoryPart(window.location.pathname) });
                $.cookie("orderHash", data.orderHash, { expires: date, path: removeLastDirectoryPart(window.location.pathname) });

                validParams = true;
            } else if(data.result == 'PAYMENT_PENDING' || data.result == 'PENDING'){
                showErrorContainer('pendingPaymentBank');
                funnelPurchaseAnalitycs(data);
                statusPendingCheck = true;
                validParams = false;
            } else {
                thankYouErrrors("Error validate Params Freedompay", `status: ${XMLHttpRequest.status}`);

                showErrorContainer('errorPay')
                $("#successB2B").addClass("d-none")
                $(".cc28_attention_information").addClass("d-none")
                validParams = false;
            }

        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            /*  if (XMLHttpRequest.responseJSON) {
                  showErrorMsg(XMLHttpRequest.responseJSON.code);
              }*/
            if (XMLHttpRequest.status == 404) {

                validParams = true;
            }
            else {
                thankYouErrrors("Error validate Params Freedompay", `status: ${XMLHttpRequest.status}`);

                showErrorMsg('errorTicket')
                showErrorContainer('errorTicket');
                if(XMLHttpRequest.status == 500){
                    $("#successB2B").addClass("d-none");
                }
            }
            console.log("Status: {}", textStatus);
            console.log("Error: {}", errorThrown);
        }
    });
    return dataParams;
}

function confirmTibReservation(){
    var url_base = $('input.current-page-solr').attr('data-page-path');
    let reservationIds;
    const infoPaymentResultInfoParse = localStorage.getItem("paymentResultInfo");
    const dataPaymentResultInfo = JSON.parse(infoPaymentResultInfoParse);
    reservationIds = dataPaymentResultInfo.reservationsIds;
    let reservationIdsJoined = reservationIds.join("&");
    let data = { "orderIds": reservationIdsJoined};

    $.ajax({
        url: url_base + ".tibMewsConfirm.json",
        type: 'POST',
        dataType: "json",
        //traditional: true,
        data: data,
        success: function (data) {
            
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            console.log("Error: {}", errorThrown);
        }
    });
}
