EV.Core.init({
    serviceName: 'registration_prensacom',
    realmName: 'default_realm',
    icDomain: 'https://ev.prensa.com/ic/2.0',
    recaptchaSiteKey: '6LfuTMUUAAAAABVeg9A65R2lCHlT7ZH8U8fqetZ3',
    ssoCookieDomain: 'prensa.com',
	secureMode: true,
	brand: 'prensa.com',
	disableCookies: true
});

EV.PM.init({
	pmDomain: 'https://ev.prensa.com/pm/api/v2',
	version: 2,
	stripeKey: ""
});



console.log("** one tap test 8 inicio");

EV.Em.init({
	url: "https://ev.prensa.com/acd/api/3.0",
	sidCookieDomain: "prensa.com",
	meterHD: true,
	disableCookies: false,
	enableGoogleOneTap: true,
	socialAttributeMapping: {
		"email_address": "email"
	},
	googleClientId: "1003169699927-hpql9heav9nhhv3fvppla4ii72q5tvle.apps.googleusercontent.com",
	serviceName: "registration_prensacom",
	realmName: "default_realm",
	autoLinkLoginRedirectUrl: "https://www.prensa.com/login",
	icDomain: "ev.prensa.com/ic/2.0",
	ssoCookieDomain: "prensa.com",
	autoPopulate: true,
	secureModeEnabled: true,
	googleGenericConf: {'cancel_on_tap_outside': false }
});

console.log("** one tap test fin");



EV.Social.init({
	icDomain: 'https://ev.prensa.com/ic/2.0',
	serviceName: 'registration_prensacom',
	realmName: 'default_realm',
	redirectUri: 'https://prensa.com/social-redirect',
	socialAttributeMapping: {
		"email_address": "email"
	},
	socialKeys: {
        facebook: "2547484861996513",
        google: "1003169699927-hpql9heav9nhhv3fvppla4ii72q5tvle.apps.googleusercontent.com",
        twitter: "iUJEduCdM1lew02nGZ3kUSPVa",
        linkedin: "869o4wfv2ta8a6"
	}
});

/*EV.Dab.init({
	adServiceURL: "https://adservice.google.com/adsid/integrator.js?domain=www.prensa.com"
});*/

//WEB MANAGER INITIALISATION
EV.WM.init({
    wmDomain: "https://ev.prensa.com/wm/api/v1/ev-widgets",
    //wmDomain: "https://cor.uat.evolok.net/wm/api/v1/ev-widgets",
    brand: "prensa.com",
    language: "es",
    useWmTranslations: false
});

EV.Widgets = EV.Widgets || {};

EV.Widgets.Display = {
	'opt_in_titulares_prensa': {
		 'type': 'checkbox',
		 'values': [
			{'caption': 'Recibir titulares por e-mail de La Prensa', 'value': 'true' }
		]
	},
	'opt_in_titulares_ellas': {
		 'type': 'checkbox',
		 'values': [
			{'caption': 'Recibir newsletter por e-mail de Ellas', 'value': 'true' }
		]
	},
	'opt_in_promociones': {
		 'type': 'checkbox',
		 'values': [
			{'caption': 'Recibir promociones por e-mail', 'value': 'true' }
		]
	}
};


/*
TRANSLATIONS
*/
EV.Translate.addTranslationTable("es", {

    "ev.widgets.login.title": "Iniciar sesión",
    "ev.widgets.attr.email_address.label": "E-mail",
    "ev.widgets.attr.email_address.placeholder": "E-mail",
    "ev.widgets.attr.password.label": "Clave",
    "ev.widgets.attr.password.placeholder": "Clave",
    "ev.widgets.login.rememberMe": "Recordar este equipo",
    "ev.widgets.login.buttons.submit": "Iniciar sesión",
    "ev.widgets.login.buttons.cancel": "Cancelar",
    "ev.widgets.login.forgotPassword": "Olvidé mi contraseña",
    "ev.widgets.social.buttons.login.description": "Entrar con red social conectada a mi cuenta",
    "ev.widgets.orseparator": "o con mis datos de acceso",

    "ev.widgets.registration.title": "Registro",
    "ev.widgets.registration.buttons.submit": "Crear cuenta",
    "ev.widgets.registration.buttons.cancel": "Cancelar",
    "ev.widgets.attr.clave.confirm.label": "Confirmar clave",
	"ev.widgets.attr.clave.confirm.placeholder": "Confirmar clave",
	"ev.widgets.social.buttons.register.description": "Crear nueva cuenta con mis redes sociales",

	"ev.widgets.forgotpassword.buttons.submit": "Restaurar Clave",
    "ev.widgets.forgotpassword.buttons.cancel": "Cancelar",
    
    "ev.widgets.errors.user_not_registered": "Error: Usuario no registrado",
    "ev.widgets.errors.attribute_required": "Error: Campo requerido",

    "ev.widgets.errors.password_length" : "La clave debe tener un mínimo de 6 caracteres.", 
    "ev.widgets.errors.general_attributes": "Los siguientes campos están incorrectos o vacíos.", 

    'ev.widgets.errors.identifiers_not_found': 'Cuenta no encontrada, puede registrar una cuenta nueva.',
    'ev.widgets.errors.duplicate_user_profile': 'Este email ha sido registrado previamente. Por favor usa un email diferente o ingresa tu clave para iniciar sesión.',
    'ev.widgets.errors.forgot_password_success': "Cambiado con éxito",
    //'ev.widgets.errors.user_linked_with_different_account': 'Tu cuenta {0} ya está asociada a otra cuenta.',
    'ev.widgets.errors.user_linked_with_different_account': 'Tu cuenta ya está asociada a otra cuenta.',
    'ev.widgets.errors.duplicate_identifiers_found': 'La cuenta ya está registrada. Si olvidaste tu contraseña puedes restablecerla en el enlace "Olvidé mi contraseña"',
    'ev.widgets.errors.identifiers_invalid': 'Nombre de usuario y contraseña inválidos. Restablece tu contraseña a través del enlace Olvidé mi contraseña e intenta nuevamente.',
    'ev.widgets.errors.user_already_linked_with_same_social_network': 'Tu cuenta de usuario ya está conectado a la cuenta {1} con el correo electrónico {0}. Debes desconectar {1} de tu cuenta antes de conectarla a otro usuario.',
    'ev.widgets.errors.user_profile_inactive': 'Tu cuenta aún no está activada. <a class=\'resend-activation\' ng-click=\'resendActivation()\'>Reenviar email</a>',
    'ev.widgets.errors.unlink_user_social_network': 'Tu cuenta no se puede desconectar debido a falta de información en el perfil. Por favor actualiza la cuenta <a class=\'resend-activation\' ng-click=\'onSocialUnlinkFailedAction()\'>aquí</a>.',
    'ev.widgets.errors.user_profile_identifiers_not_found': 'No tenemos una cuenta con esa dirección de correo electrónico. Intenta con una dirección diferente o crea una cuenta nueva.',
    'ev.widgets.errors.nothing_selected': 'Por favor elige una opción para continuar',
    'ev.widgets.errors.technical_difficulties': 'Lo sentimos, estamos teniendo dificultades técnicas. Vuelve a intentarlo en breve.',
    'ev.widgets.errors.change_card_failed': 'No fue posible actualizar los detalles de la tarjeta. Vuelve a intentarlo en breve.',
    'ev.widgets.errors.retrieve_card_fail': 'No fue posible recuperar las tarjetas existentes',
    'ev.widgets.errors.reset_validation_failed': 'La validación para el atributo {0}, con valor {1} falló',
    'ev.widgets.errors.reset_key_used': 'No se encontró la clave de atributo de restablecimiento {0} o ya no se está utilizando.',
    'ev.widgets.errors.attribute_validation_failed_change_password': 'Se produjo un error con la validación del atributo.',
    'ev.widgets.errors.general_attributes': 'Los siguientes campos son incorrectos o están vacíos [{0}]. Estos campos son obligatorios para uno o más servicios conectados a tu perfil.',
    'ev.widgets.errors.general_attribute': 'El siguiente campo es incorrecto o está vacío [{0}]. El campo es obligatorio para uno o más servicios conectados a tu perfil.',
    'ev.widgets.errors.product_not_found': "Producto no encontrado",
    'ev.widgets.errors.duplicated_purchase': "Esta compra no es posible porque ya existe",
    'ev.widgets.errors.not_logged_in': "Debes iniciar sesión para usar este widget",
    'ev.widgets.errors.undefined_order_id': "El pedido no ha sido creado",
    'ev.widgets.errors.create_payment_failed': "Hubo un problema con el pago. Vuelve a intentarlo.",
    'ev.widgets.errors.invalid_request': "Solicitud no válida",
    "ev.widgets.errors.field_required": "Campo requerido",
    "ev.widgets.errors.field_length6": "Longitud incorrecta (debe tener 6 caracteres)",
    "ev.widgets.errors.field_length8": "Longitud incorrecta (debe tener 8 caracteres)",
    "ev.widgets.errors.invalid_bank_details": "Por favor revisa tus datos bancarios",
    "ev.widgets.errors.password_length": "La contraseña debe tener un mínimo de 6 caracteres.",
    "ev.widgets.errors.validator_invalid": "Confirma que {0} está vacío o no coincide con {0}",
    "ev.widgets.errors.delivery_address_required": "Falta la dirección de entrega",
    "ev.widgets.errors.billing_address_required": "Falta dirección de facturación",
    "ev.widgets.errors.authentication_values_required": "Faltan algunos campos de autenticación: {0}",
    "ev.widgets.errors.personal_details_required": "Los siguientes datos personales no deben estar vacíos: {0}",
    "ev.widgets.errors.attributes_required": "Algunos de los siguientes campos están vacíos: {0}",
    "ev.widgets.errors.attribute_validation_failed": "Algunos campos no son válidos: {0}. <br> Asegúrate de insertar un correo electrónico y una contraseña válidos con al menos una letra mayúscula, un carácter especial y un número.",
    "ev.widgets.errors.not_robot": "Por favor verifica que no eres un robot",
    "ev.widgets.errors.invalid_form": "Faltan algunos datos o no son válidos, verifica nuevamente tu información",
    "ev.widgets.errors.invalid_profile": "Perfil no válido: revisa los campos en la sección de tu perfil",
    "ev.widgets.errors.invalid_delivery_country": "Ha especificado un país de entrega no válido.",
    "ev.widgets.errors.no_products_selected": "Necesitas seleccionar un producto",
    "ev.widgets.errors.incomplete_name": "El campo Nombre está incompleto",

    'ev.widgets.plan.frequency.NONE': "Una vez",
    'ev.widgets.plan.frequency.DAY1': "Diario",
    'ev.widgets.plan.frequency.WEEK1': "Semanal",
    'ev.widgets.plan.frequency.MONTH1': "Mensual",
    'ev.widgets.plan.frequency.MONTH3': "3 meses",
    'ev.widgets.plan.frequency.MONTH6': "Semestral",
    'ev.widgets.plan.frequency.MONTH12': "Anual",
    'ev.widgets.plan.frequency.MONTH18': "18 meses",
    'ev.widgets.plan.frequency.MONTH36' : "3 años",

    'ev.widgets.resetpassword.title' : 'Cambio de clave',
    'ev.widgets.attr.confirm_password.label' : 'Confirmar clave',
    'ev.widgets.attr.password.confirm.label' : 'Confirmar clave',
    'ev.widgets.attr.confirm_password.placeholder' : 'Confirmar clave',
    'ev.widgets.attr.password.confirm.placeholder': 'Confirmar clave',
    'ev.widgets.resetpassword.buttons.submit' : 'Cambiar clave',
    'ev.widgets.resetpassword.buttons.cancel' : 'Cancelar',

    'ev.widgets.forgotpassword.success' : 'Email para restablecer contraseña enviado con éxito. Puede tardar unos minutos en llegar a su bandeja de entrada. Si no lo ve, pruebe revisar su bandeja de correo no deseado.',
    'ev.widgets.resetpassword.success' : 'Contraseña cambiada con éxito',

    'ev.widgets.productSelection.paymentPlansHeader' : 'Disfruta del contenido exclusivo de La Prensa<br><small>Suscríbete por menos de 20¢ al día</small>',
    'ev.widgets.productSelection.select' : 'Elegir plan',
    'ev.widgets.paymentType.default' : 'Elegir método de pago',
    'ev.widgets.productSummary.productName' : 'Nombre',
    'ev.widgets.productSummary.productDescription' : 'Descripción',
    'ev.widgets.productSummary.productFrequency' : 'Frecuencia',
    'ev.widgets.productSummary.productPrice' : 'Precio',
    'ev.widgets.productSummary.noProductsSelected' : 'No se ha elegido un plan',
    'ev.widgets.productProfile.selectProductWarning' : 'Debes elegir un plan antes de seguir con este paso',
    'ev.widgets.errors.invalid_widget_config' : 'Configuración inválida: No se ha definido un "groupName" o "productName"',
    'ev.widgets.errors.user_attribute_update_forbidden' : 'Acción denegada: No tiene permiso para cambiar este atributo',

    'ev.widgets.userProfileUpdateSuccess' : '¡Actualizado exitosamente!',
    'ev.widgets.editprofile.buttons.submit' : 'Actualizar',
    'ev.widgets.social.linkaccounts.linkbutton' : 'Conectar',
    'ev.widgets.attr.confirm_password.confirm.label' : 'Confirmar clave',
    'ev.widgets.attr.confirm_password.confirm.placeholder' : 'Confirmar clave',
    'ev.widgets.checkout.submit' : 'Continuar con el pago',
    'ev.widgets.checkout.processingProfile' : 'Procesando perfil',
    'ev.widgets.checkout.processingOrder' : 'Procesando pedido',
    'ev.widgets.checkout.processingPayment' : 'Procesar pago',
    'ev.widgets.errors.checkout' : 'Hubo un error con el checkout, por favor intente de nuevo',
    'ev.widgets.errors.payment' : 'Hubo un error con el pago, por favor intente de nuevo',
    'ev.widgets.errors.order' : 'Hubo un error con el pedido, por favor intente de nuevo',
    'ev.widgets.changepassword.buttons.submit' : 'Cambiar clave',
    'ev.widgets.changepassword.buttons.cancel' : 'Cancelar',
    'ev.widgets.social.unlinkaccounts.cardview.unlinkButton' : 'Desconectar',
    'ev.widgets.changepassword.success' : 'Clave cambiada con éxito!',
    'ev.widgets.errors.no_social_network_linked' : 'No se ha conectado ninguna red social',
    'ev.widgets.editprofile.buttons.cancel' : 'Cancelar',
    'ev.widgets.errors.service_not_linked_to_authentication_profile' : 'Servicio no enlazado a perfil',

    'ev.widgets.twocheckout.transactionSecurity' : 'Esta transacción está asegurada con encriptación SSL',
    'ev.widgets.twocheckout.cardNumber' : 'Número de tarjeta de crédito',
    'ev.widgets.twocheckout.placeholder.cardNumber' : '4000000000000002',
    'ev.widgets.twocheckout.cardExpirationMonth' : 'Mes de expiración',
    'ev.widgets.twocheckout.placeholder.cardExpirationMonth' : '10',
    'ev.widgets.twocheckout.cardExpirationYear' : 'Año de expiración',
    'ev.widgets.twocheckout.placeholder.cardExpirationYear' : '25',
    'ev.widgets.twocheckout.securityCode' : 'Código de seguridad',
    'ev.widgets.twocheckout.placeholder.securityCode' : '123',
    'ev.widgets.twocheckout.submitPayment' : 'Procesar pago',
    'ev.widgets.twocheckout.paymentSuccessful' : 'Pago exitoso',
    'ev.widgets.twocheckout.errors.300' : 'Vendedor no autorizado para usar la API o clave publicable incorrecta',
    'ev.widgets.twocheckout.errors.400' : 'Al formulario de pago le faltan atributos',
    'ev.widgets.twocheckout.errors.401' : 'Al formulario de pago le faltan los atributos requeridos',
    'ev.widgets.twocheckout.errors.200' : 'No se puede procesar la solicitud.',
    'ev.widgets.twocheckout.errors.500' : 'Error en el pago',
    'ev.widgets.twocheckout.errors.' : 'Parámetros inválidos',

    "ev.widgets.productProfile.alreadyRegistered": "¿Ya estás registrado? Inicia sesión aquí",
    "ev.widgets.productProfile.address.billingAddressTitle" : "Dirección de facturación",
    "ev.widgets.productProfile.address.deliveryAddressTitle" : "Dirección de envío (Solo en Panamá)",
    "ev.widgets.productProfile.address.country.defaultOption" : "Elegir país",
    "ev.widgets.productProfile.address.useDeliveryAddress" : "Elegir dirección de envío",
    "ev.widgets.productProfile.address.useBillingAddress" : "Usar dirección de facturación",
    "ev.widgets.productProfile.address.newAddress" : "Agregar dirección",
    "ev.widgets.editProfile.invalid_deliveryCountry" : "País de envío inválido",

    "ev.widgets.purchases.productName" : "Plan",
    "ev.widgets.purchases.startDate" : "Inicio",
    "ev.widgets.purchases.endDate" : "Fin",
    "ev.widgets.purchases.frequency" : "Frecuencia",
    "ev.widgets.purchases.status" : "Estado",
    "ev.widgets.purchases.numberBeneficiaries" : "Beneficiarios",
    "ev.widgets.purchases.actions" : "",
    "ev.widgets.purchases.noPurchases" : 'No has realizado ninguna compra recientemente. Si realizaste una compra y no aparece aquí, por favor contáctanos al 323-6400 / suscripciones@prensa.com',
    "ev.widgets.purchases.actionsButton.label" : "Opciones",
    "ev.widgets.purchases.actionsButton.action.displayBeneficiaries" : "Ver beneficiarios",
    "ev.widgets.purchases.actionsButton.action.addBeneficiary" : "Agregar beneficiario",
    "ev.widgets.purchases.actionsButton.action.cancelPurchase" : "Cancelar suscripción",
    "ev.widgets.purchases.beneficiaries.title" : "Beneficiarios",
    "ev.widgets.purchases.beneficiaries.email" : "Email",
    "ev.widgets.purchases.beneficiaries.status" : "Estado",
    "ev.widgets.purchases.beneficiaries.action" : "Opciones",
    "ev.widgets.purchases.beneficiaries.remove" : "Remover",
    "ev.widgets.purchases.beneficiaries.cancel" : "Cancelar",
    "ev.widgets.purchases.beneficiaries.noBeneficiaries" : "Sin beneficiarios",
    "ev.widgets.purchases.confirmDialog.confirm" : "Confirmar",
    "ev.widgets.purchases.confirmDialog.cancel" : "Cancelar",
    "ev.widgets.purchases.notification.title" : "Agregar beneficiario",
    "ev.widgets.purchases.notification.email" : "Email",
    "ev.widgets.purchases.notification.emailPlaceholder" : "Email del beneficiario",
    "ev.widgets.purchases.notification.emailHelp" : "Ingresa el Email del beneficiario que desea invitar",
    "ev.widgets.purchases.notification.emailRequired" : "Debes ingresar el Email del beneficiario que deseas invitar",
    "ev.widgets.purchases.notification.emailInvalid" : "El Email ingresado no es válido",
    "ev.widgets.purchases.notification.message" : "Mensaje de invitación",
    "ev.widgets.purchases.notification.add" : "Agregar",
    "ev.widgets.purchases.notification.cancel" : "Cancelar",
    "ev.widgets.purchases.notification.success" : "Invitación enviada satisfactoriamente",
    "ev.widgets.purchases.notification.close" : "Cerrar",
    "ev.widgets.purchases.cancel.title" : "Cancelar suscripción",
    "ev.widgets.purchases.cancel.message" : "¿Estás seguro de cancelar esta suscripción?",
    "ev.widgets.purchases.cancel.confirm" : "Confirmar cancelación",
    "ev.widgets.purchases.cancel.close" : "Cerrar",
    "ev.widgets.purchases.cancel.cancelling" : "Cancelando suscripción",
    "ev.widgets.purchases.cancel.success" : "Suscripción cancelada con éxito",
    "ev.widgets.purchases.cancel.reason_for_cancellation" : "Motivo de cancelación",
    "ev.widgets.purchases.cancel.select_a_reason" : "Elije un motivo de cancelación",

    "ev.widgets.errors.idmex409" : "Ya tienes una cuenta asociada a este email. Por favor haz clic en el botón para iniciar sesión",

    "ev.widgets.paymentSelector.CARD" : "Tarjeta de Crédito",

    "ev.widgets.grant.productName" : "Producto",
    "ev.widgets.grant.actions" : "Opciones",
    "ev.widgets.grant.accept" : "Aceptar",
    "ev.widgets.grant.decline" : "Rechazar",
    
});

EV.Translate.setActiveLanguage("es", true);

angular.element(document).ready(function () {
	//REGISTER FORM
	document.querySelector("#registration-widget > #widget-body > #login-divider > div > p").innerHTML = "o con mis datos personales";

});

/*
EDIT PROFILE
*/

// (function ($) {
//     $(document).ready(function(){
//         $("#ev-edit-profile-main #widget-header span").html('Editar Perfil');
//     });
// })(jQuery);

/**********************************/

/*
INJECT SPECIAL MESSAGES 
*/
(function ($) {
    $(window).load(function() {
        //$("#login-divider").after('<div class="login-help">Puedes iniciar sesión con tu e-mail o número de suscriptor seguido de "@prensa.com". Ejemplo:  <b>1234567@prensa.com</b></div>');
        //$("#login-flip-back").before('<div class="login-message"><center><b>¿Necesitas ayuda?</b> <br> Contáctanos al 323-6400 / <a href="suscripciones@prensa.com" class="underline">suscripciones@prensa.com</a> </center></div>');
        $("#login-flip-back").before('<div class="login-message"><center><b>¿Necesitas ayuda?</b> <br> Contáctanos al 323-6400 / <a href="mailto:suscripciones@prensa.com" rel="nofollow" class="underline">suscripciones@prensa.com</a> </center></div>');
    });
})(jQuery);

/*
STYLE FIRST OR LAST WORD
*/

function styleLastWord(item) {
    (function ($) {
        $(item).html(function(){
            var text = $(this).text().trim().split(" ");
            var last = text.pop();
            return text.join(" ") + (text.length > 0 ? " <span class='red'>" + last + "</span>" : last);
        });
    })(jQuery);
}

function styleLastWord(item) {
    (function ($) {
        $(item).html(function(){
            var text = $(this).text().trim().split(" ");
            var first = text.shift();
            return (text.length > 0 ? "<span class='red'>"+ first + "</span> " : first) + text.join(" ");
        });
    })(jQuery);
}

styleLastWord('.product-title');

function showLogin() {

	window.location.replace("https://www.prensa.com/login/?ref=" + window.location.href);
}

/* function loginFromModal() {
	killModals();
	showLogin();
} */

function hideLogin() {
	$('.evolokModal').css('display', 'none');
}

function killModals() {
	$('body').removeClass('ev-modals').removeClass('modal-open');
	$('.modal, .modal-backdrop').remove();
}


function isMoreThanAYear(date){
	var today = new Date();
	var varDate = new Date(date); 
	let dif = today - varDate;
	let isYear = dif/(1000*60*60*24*365);

	if(isYear >= 1) {
		console.log("Greated or equal than a year");
		return true;
	} else { 
		console.log("Less than a year");
		return false;
	}
}

$('#evolokProfile').hide();

$(() => {
	mobileThings();
	gtagTrackPageView();
	$('body').append('<link rel="stylesheet" type="text/css" href="https://multimedia.corprensa.com/la-prensa/evolok/coral.css?v=1.1">');
});

function redirectToMovil() {
	console.log("redirectToMovil was called");
	var lp = new MobileDetect(window.navigator.userAgent);
	
	if (window.location.href.indexOf("prensa.com/m/") > -1 && localStorage.getItem('suscriptor') == "false" && $('meta[name="cXenseParse:pageclass"]').prop('content') == "article") {
		console.log('Redirect a Desktop');
		window.location.href = "https://prensa.com" + window.location.pathname.substring(2);
	}
	
	if (lp.mobile() != null && window.location.pathname.indexOf('/m/') < 0 && window.location.href.split("/").length >= 6 && $('meta[name="cXenseParse:pageclass"]').prop('content') == "article" && localStorage.getItem('suscriptor') == "true") {
		console.log('Redirect a Movil');
		window.location.href = "https://prensa.com" + "/m" + window.location.pathname;
	} else if (lp.mobile() == null && window.location.pathname.indexOf('/m/') > -1 && window.location.href.split("/").length >= 6 && $('meta[name="cXenseParse:pageclass"]').prop('content') == "article") {
		console.log('Redirect a Desktop');
		window.location.href = "https://prensa.com" + window.location.pathname.substring(2);
	} else {
		console.log('No Redirect');
	}
}

(function() {
	redirectToMovil();
})();

// Botones
setTimeout(() => {	
    $(() => {
		
		$('.evolokProfile').show();
        $('.nav-top-print').css('margin-top', '0px');

        $('.nav-top, .article-sharer').css('z-index', '1');
        $('div.signin_buttons').css('padding-top', '5px');
        $('div.signin_reg.signinform').css('padding-top', '20px');
        $('div#widget-body').css('padding-bottom', '5px');

        //$('#loginOverlay, #evolokClose').click(hideLogin);
        $('#evolokLogin').click(showLogin);

        $('div.signinbut.signbutton').click(() => {
            $('div.signin_login.signinform').css('display', 'block');
            $('div.signin_reg.signinform').css('display', 'none');
            $('div.signinbut.signbutton').addClass('active');
            $('div.signupbut.signbutton').removeClass('active');
        });

        $('div.signupbut.signbutton').click(() => {
            $('div.signin_login.signinform').css('display', 'none');
            $('div.signin_reg.signinform').css('display', 'block');
            $('div.signinbut.signbutton').removeClass('active');
            $('div.signupbut.signbutton').addClass('active');
        });
		
		removeAds();
    });
	
	adblockDetect();

    if (window.location.href.indexOf('/kiosco/epaper/') > -1 && window.location.href.split("/").length >= 7) {
        EV.Em.authorize('{"articleId": "' + atob(atob(window.location.href.split("/")[5])) + '", "section": "flipping", "site": "prensa.com"}', function(response) {
			fixCookie(response);
			
            if (response.result != "ALLOW_ACCESS") {
                gtagEventPopup('Flipping');
                showPaywall();
            } else {
                window.location.href = $('#iframeFlip').prop('src');
            }
        }, function() {
        });
    } else if ((window.location.href.indexOf('/impresa/') > -1 && window.location.href.split("/").length >= 7 && !moment(window.location.href.split('/')[5], "YYYY-MM-DD", true).isValid()) || ($('article').length > 0 && window.location.href.split("/").length >= 5) ) {
		var authors = "";
		
		if (Fusion.globalContent && Fusion.globalContent.credits && Fusion.globalContent.credits.by) {
			for (i = 0; i < Fusion.globalContent.credits.by.length; i++) {
				if (Fusion.globalContent.credits.by[i].type == "author") {
					authors += Fusion.globalContent.credits.by[i].name.replace(/\\/g, '\\').replace(/\//g, '\/').replace(/"/g, '\"').replace(/'/g, '\'').trim() + ",";
				} else {
					authors += Fusion.globalContent.credits.by[i]._id.replace(/\\/g, '\\').replace(/\//g, '\/').replace(/"/g, '\"').replace(/'/g, '\'').trim() + ",";
				}
			}
			
			authors = authors.substr(0, authors.length - 1);
		}
		
		var tags = "";
		
		if (Fusion.globalContent && Fusion.globalContent.taxonomy && Fusion.globalContent.taxonomy.tags) {
			for (i = 0; i < Fusion.globalContent.taxonomy.tags.length; i++) {
				tags += Fusion.globalContent.taxonomy.tags[i].description.replace(/\\/g, '\\').replace(/\//g, '\/').replace(/"/g, '\"').replace(/'/g, '\'').trim() + ",";
			}
			
			tags = tags.substr(0, tags.length - 1);

			// SE AGREGA TAG DE EXCLUSIVO SI PAYWALL ES ACTIVADO EN COMPOSER
			//console.log ("content_restrictions:" + Fusion.globalContent.content_restrictions.content_code);
			if (Fusion.globalContent.content_restrictions.content_code == 1) {
				tags = tags + ",exclusivo";
			}
		}

	console.log("name evolok:recomendation------------> "+$('meta[name*="evolok:recomendation"]').prop('content'));	
		
		var section = Fusion.globalContent && Fusion.globalContent.taxonomy && Fusion.globalContent.taxonomy.primary_section && Fusion.globalContent.taxonomy.primary_section.name || "";
		
		console.log("document.title.replace --->",document.title.replace(/"/g, '\"').replace(/'/g, '\'').replace("| La Prensa Panamá", "").trim()); 
		// console.log("Fusion.globalContent.headlines --->",Fusion.globalContent.headlines.basic);
		// console.log("Fusion.globalContent.headlines (replace) --->",Fusion.globalContent.headlines.basic.replace(/"/g, '\"').replace(/'/g, '\'').trim());
		
        EV.Em.authorize('{"content_type": "article", "article_url": "' + window.location.href + '", "thumbnail_url": "' + $('meta[name*="evolok:recomendation"]').prop('content') + '", "articleId": "' + (Fusion.globalContent && Fusion.globalContent._id || "") + '", "section": "' + section + '", "site": "prensa.com", "authors": "' + authors + '", "tags": "' + tags + '", "title": "' + (document.title.replace(/"/g, '\"').replace(/'/g, '\'').replace("| La Prensa Panamá", "").trim()) + '", "publishDate": "' + (Fusion.globalContent && Fusion.globalContent.publish_date || "") + '", "brand": "prensa.com", "lastModifiedDate": "'+Fusion.globalContent.last_updated_date+'", "isArchive": "'+ isMoreThanAYear((Fusion.globalContent.publish_date || "")) +'"}', function(response) {
			
			fixCookie(response);
            var count = 0, total = 0;

            if (response.result != "ALLOW_ACCESS") {
                gtagEventPopup(section);
				
				if (response.result == "REQUIRE_LOGIN" && response.requireEntitlement == true) {
					gtagRequireLogiWithEntitlement();
				} else if (response.result == "REQUIRE_LOGIN") {
					gtagRequireLogin();
				} else if (response.result == "REQUIRE_ENTITLEMENT") {
					gtagRequireEntitlement();
				} else {
					gtagUnknownStatus();
				}
				
                showPaywall();

				if (response.exceededMeter) {
					count = response.exceededMeter.count;
					total = response.exceededMeter.max;
				}
				
				if (response.offeredMeter) {
					count = response.offeredMeter.count;
					total = response.offeredMeter.max;
				}
            } else {
				if (response.activeMeter) {
					count = response.activeMeter.count;
					total = response.activeMeter.max;
				}
            }

            var segments = "", notifierUrl = "";
				
            for (var s = 0; s < response.segments.length; s++) {
                segments += "segments=" + response.segments[s] + "&";
            }

			var stopwallTimer = setInterval(() => {
				// REQUIRE LOGIN
				if ($('#stopwall-login').length > 0) {
					gtagStopwallLogin();
				}

				// REQUIRE LOGIN WITH ENTITLEMENT
				if ($('#stopwall').length > 0) {
					gtagStopwall();
				}
				
				// REQUIRE ENTITLEMENT
				if ($('#stopwall-entitlement').length > 0) {
					gtagStopwallEntitlement();
				}

				if ( $('#stopwall-login').length > 0 || $('#stopwall').length > 0 || $('#stopwall-entitlement').length > 0 ) {
					clearInterval(stopwallTimer);
				}
			}, 1000);

			if (count > 0) {
				notifierUrl = "https://ev.prensa.com/acd/api/3.0/widgets/templates/notifier?count=" + count + "&total=" + total + "&" + segments + "ev_sid=" + response.sessionId + "&groupName=stickybar_prensacom";
				
				$.get(notifierUrl, (notifier) => {
					if (notifier) {
						$('ev-paywall-notifier').html(notifier.content.replace(/{{count}}/g, count));

						$('.sticky-bar-toggle').unbind('click').click(() => {
							toggleStickyBar();
						});
						
						gtagSticky(count);
						
						console.log('Sticky Bar Loaded.');
					}
				});
				
				setTimeout(() => {
					if ($('body').prop('class').indexOf('ev-modals') < 0) {
						notifierUrl = "https://ev.prensa.com/acd/api/3.0/widgets/templates/notifier?count=" + count + "&total=" + total + "&" + segments + "ev_sid=" + response.sessionId + "&groupName=popup_prensacom";
						
						$.get(notifierUrl, (notifier) => {
							if (notifier) {
								$('body').addClass('ev-modals').addClass('modal-open');
								$('body').prepend('<div id="modal-container" class="ev modal show" style="z-index: 1050; display: flex;"><div class="modal-dialog modal-sm"><div class="modal-content">' + notifier.content + '</div></div></div>');
								$('#modal-container').after('<div id="modal-backdrop" class="modal-backdrop fade in" style="z-index: 1040;"></div>');
								
								gtagPopup(count);
						
								console.log('Popup Loaded.');
							}
						});
					}
				}, 1000);
				
				var buttonCount = 0;
				var addButton = setInterval(() => {
					$('.ev-widget-header.row').append('<span onclick="killModals()" class="icon close"></span>');
					buttonCount++;
					
					if (buttonCount > 2) {
						clearInterval(addButton);
						console.log('Extra Modal Buttons - Deleted.');
					}
				}, 1000);
			} else {
				if (typeof response.sessionKeys !== "undefined") {
					notifierUrl = "https://ev.prensa.com/acd/api/3.0/widgets/templates/notifier?" + segments + "ev_sid=" + response.sessionKeys.ev_sid;

					$.get(notifierUrl, (notifier) => {
						if (notifier) {
							$('ev-paywall-notifier').html(notifier.content);
						
							$('.sticky-bar-toggle').unbind('click').click(() => {
								toggleStickyBar();
							});
							
							console.log('Sticky Bar Loaded.');
						}
					});
				}

				setTimeout(() => {
					if ($('body').prop('class').indexOf('ev-modals') < 0) {
						notifierUrl = "https://ev.prensa.com/acd/api/3.0/widgets/templates/notifier?count=" + count + "&total=" + total + "&" + segments + "ev_sid=" + response.sessionId + "&groupName=popup_prensacom";
						
						$.get(notifierUrl, (notifier) => {
							if (notifier) {
								$('body').addClass('ev-modals').addClass('modal-open');
								$('body').prepend('<div id="modal-container" class="ev modal show" style="z-index: 1050; display: flex;"><div class="modal-dialog modal-sm"><div class="modal-content">' + notifier.content + '</div></div></div>');
								$('#modal-container').after('<div id="modal-backdrop" class="modal-backdrop fade in" style="z-index: 1040;"></div>');
								
								gtagPopup(count);
						
								console.log('Popup Loaded.');
							}
						});
					}
				}, 1000);
            }
        }, function() {
        });
    }
}, 5000);

// Eventos
EV.Event.on('login.success', () => {
   	window.location.reload(true);
});

EV.Event.on('social-login.success', () => {
    window.location.reload(true);
});

EV.Event.on('login.cancelled', () => {
    $('.evolokModal').css('display', 'none');
});

EV.Event.on('ev.notifier.close', () => {
    $('#loginContent').css('z-index', '1000000').css('display', 'block');
	$('.modal-content').css('display', 'none');
});

/*++++++++++++++++++++++++++++++++++++++++++++++++*/
/*                EV-EM Events                    */


EV.Em.on(EV.Em.Event.SOCIAL_LOGIN_SUCCESS, function(event) {
	
	console.log("** GA4 login inicio 9: ");

	//Prensa login page
	gtag('event', 'evolok_login', {
	'label': 'evolok_login_onetap',
	'test_label': 'evolok_login_onetap',
	'test_label_1seg': 'evolok_login_onetap'
	});
	
	gtag('event', 'test_evolok_login', {
	'test_label': 'evolok_login_onetap',
	'test_label_1seg': 'evolok_login_onetap'
	});
	
	gtag('event', 'evolok_logins', {
	'label': 'evolok_login_onetap'
	});

	console.log("** GA4 login fin 9: ");

	
    let session = event.detail;
    console.log("** EV.Em.Event.SOCIAL_LOGIN_SUCCESS", session);
    console.log("** ev em social login success reload");

    setTimeout(function() {
	// Se programaron 2 segundos de reload para que el evento evolok logins en GA4 pueda capturar los datos
	window.location.reload(true);
	}, 2500);
	
})


/**************************************************/
/**************************************************/

function showInContentMessage() {
	$( document ).ready(function() {
		htmlMessage = `<div class="article-paywall">
		<h2>Accede a investigaciones <br>y reportajes exclusivos</h2>
		<br>
		Obtén acceso ilimitado a todo el contenido de La Prensa, Ellas, Martes Financiero y Mi Diario Digital.<br>
		<br>
		<b>Suscríbete por $1 el primer mes, luego $5 mensual.</b>
		<br>
		<br>
		<a href="https://suscribete.prensa.com/" target="_blank" class="article-paywall-button ">Obtener oferta</a>
		</div><!--article-paywall-->`;

		p1 = $(".article-content p:first").text();
		p2 = $(".article-content p:eq(2)").text();
		
		$('.article-content').empty();
		$('.article-content').append("<div class='hidden-content'><p>" + p1 + "</p>" + "<p>" + p2 + "</p></div>");
		$('.hidden-content').after(htmlMessage);
	});
}


function showPaywall() {
	// if (window.location.href.indexOf("articulo_paywall") > -1) {
	if (window.location.href.indexOf("panama-termina-2019-en-el-puesto-81-del-ranking-fifa-y-sigue-de-9-en-la-concacaf") > -1) {
		showInContentMessage();
		console.log('Paywall In content loaded');
	} else {
		// $('.article-content, .flipping-book, .article-sharer').remove();
		$('.flipping-book, .article-sharer').remove();

		$('#evolokClose').unbind().click(() => {
			$('#loginContent').css('display', 'none');
			$('.modal-content').css('display', 'block');
		});
		console.log('Paywall Loaded.');
	}
}

function toggleStickyBar() {
    $('.sticky-bar-toggle').unbind('click').click(() => {
        if ($('.sticky-bar-expanded').css('display') == "none") {
            $('.sticky-bar-collapsed').css('display', 'none');
            $('.sticky-bar-expanded').css('display', 'block');
        } else {
            $('.sticky-bar-collapsed').css('display', 'block');
            $('.sticky-bar-expanded').css('display', 'none')
        }
    });

    if ($('.sticky-bar-expanded').css('display') == "none") {
        $('.sticky-bar-collapsed').css('display', 'none');
        $('.sticky-bar-expanded').css('display', 'block');
    } else {
        $('.sticky-bar-collapsed').css('display', 'block');
        $('.sticky-bar-expanded').css('display', 'none')
    }
}






function ga4_userid_register() {

    var evolok = JSON.parse(localStorage.getItem('evolok:ev_session'));

    console.log('** ga4_userid_register ready 2');

    //setTimeout(() => {

        console.log('** ga4_userid_register 3secs');
        window.dataLayer = window.dataLayer || [];

        // GA4
        if (evolok != null) {
            //gtag('config', 'G-D6E1T76QJ4', { 'user_id': evolok["guid"] });
            window.dataLayer.push({'user_id': evolok["guid"]});
            console.log('Fired GA4 - PageView5 - ' + evolok["guid"]);

        } else {
            //gtag('config', 'G-D6E1T76QJ4', { 'user_id': 'N/A' });
            window.dataLayer.push({'user_id': 'N/A'});
            console.log('Fired GA4 - PageView5 - N/A');
        }

    //}, 3000);

}



$(document).ready(function() {

ga4_userid_register();

});


function gtagTrackPageView() {

    console.log('** gtagTrackPageView');

    //var evolok = JSON.parse(localStorage.getItem('evolok:ev_session'));

    
	// GA3
	/* if (evolok != null) {
        gtag('config', 'UA-6897643-1', { 'user_id': evolok["guid"] });
        console.log('Fired - PageView - ' + evolok["guid"]);
    } else {
        gtag('config', 'UA-6897643-1', { 'user_id': 'N/A' });
        console.log('Fired - PageView - N/A');
    } */
	
}

function gtagEventPopup(section) {
    gtag('event', 'EVOLOK', { 'event_category': 'Paywall', 'event_label': 'paywall_prensacom - ' + section, 'non_interaction': true });
    console.log('Fired - paywall_prensacom - ' + section);
}

function gtagRequireLogin() {
	gtag('event', 'EVOLOK', { 'event_category': 'Login/Entitlement', 'event_label': 'paywall_prensacom_require_login', 'non_interaction': true });
	console.log('Fired - paywall_prensacom_require_login');
}

function gtagRequireEntitlement() {
	gtag('event', 'EVOLOK', { 'event_category': 'Login/Entitlement', 'event_label': 'paywall_prensacom_require_entitlement', 'non_interaction': true });
	console.log('Fired - paywall_prensacom_require_entitlement');
}

function gtagRequireLogiWithEntitlement() {
	gtag('event', 'EVOLOK', { 'event_category': 'Login/Entitlement', 'event_label': 'paywall_prensacom_require_login_entitlement', 'non_interaction': true });
	console.log('Fired - paywall_prensacom_require_login_entitlement');
}

function gtagUnknownStatus() {
	gtag('event', 'EVOLOK', { 'event_category': 'Paywall', 'event_label': 'paywall_prensacom_unknown_status', 'non_interaction': true });
	console.log('Fired - paywall_prensacom_unknown_status');
}

function gtagSticky(amount) {
	gtag('event', 'EVOLOK', { 'event_category': 'Sticky Bar', 'event_label': 'stickybar_news_' + amount, 'non_interaction': true });
    console.log('Fired - Sticky Bar Events');
}

// CUSTOM COUNT
function gtagPopup(amount) {
	gtag('event', 'EVOLOK', { 'event_category': 'Popup', 'event_label': 'popup_news_' + amount, 'non_interaction': true });
    console.log('Fired - Popup Events');
}
// REQUIRE LOGIN
function gtagStopwallLogin() {
	gtag('event', 'EVOLOK', { 'event_category': 'Popup', 'event_label': 'popup_celeste', 'non_interaction': true });
    console.log('Fired - Popup Celeste');
}
// REQUIRE LOGIN WITH ENTITLEMENT
function gtagStopwall() {
	gtag('event', 'EVOLOK', { 'event_category': 'Popup', 'event_label': 'popup_verde', 'non_interaction': true });
    console.log('Fired - Popup Verde');
}
// REQUIRE ENTITLEMENT
function gtagStopwallEntitlement() {
	gtag('event', 'EVOLOK', { 'event_category': 'Popup', 'event_label': 'popup_amarillo', 'non_interaction': true });
    console.log('Fired - Popup Amarillo');
}

function addPaywallButtons() {
	var lp = new MobileDetect(window.navigator.userAgent);
	
	$('#evolokProfile').prepend('<ul><li><a href="#" id="evolokLogin" onclick="showLogin();">Inicia Sesión</a></li><li><a href="https://suscribete.prensa.com/?utm_source=Prensacom&utm_medium=Boton+de+Suscribete&utm_campain=Base" class="red">Suscríbete desde $5</a></li></ul>');
		
	if (lp.mobile() != null) {
		/*
		if ($('.main-menu').is(":visible")) {
			$(".nav-top-right ul").css("display", "inline-block");
		} else {
			$(".nav-top-right ul").css("display", "none");
		}
		*/
	}
}

function mobileThings() {
	var lp = new MobileDetect(window.navigator.userAgent);

    if (lp.mobile() != null) {
        $('.login-privacy').css('padding-top', '110%');
    } else {
        $('.login-privacy').css('padding-top', '75%');
    }
	
	console.log('Mobile Things - Done');
}

function fixCookie(response) {
	if (response.newAnonSession == 1) {
		document.cookie = "ev_did=" + response.sessionKeys.ev_did + ";SameSite=None;Secure;Max-age=31536000;Path=/;Domain=prensa.com";
		document.cookie = "ev_sid=" + response.sessionKeys.ev_sid + ";SameSite=None;Secure;Max-age=31536000;Path=/;Domain=prensa.com";
	}
}

function adblockDetect() {
	EV.Dab.isAdblockDetected().then(function (res) {
		console.log("Adblock Detected: " + res);
	});

    EV.Dab.detectPrivateMode().then(function(res) {
        console.log("Incognito: " + res);
    });
}

function detectAdblock() {
	if (window.location.href.indexOf("prensa.com/homepage-test/") > -1) {
		if ($('#desktop-banner-top').children().length > 0 && ($('#desktop-banner-top').children().length > 0 && $('#desktop-banner-top').children().children().length > 0)) {
			$('body').prepend('<center><h1 style="color:green">NO ADBLOCK DETECTED</h1></center>');
		} else {
			$('body').prepend('<center><h1 style="color:red">ADBLOCK DETECTED</h1></center>');
		}
	}
}

function removeAds() {
	if ($('.article-tags').html() != null && $('.article-tags').html().indexOf('/patrocinado/') > -1) {
		$('#desktop_1x1_vidoomy, #mobile_1x1_vidoomy, #desktop_1x1_teads, #mobile_1x1_teads, .desktop-in-article-ad, .mobile-in-article-ad, .teads-inread, #wigoiframe, #vslider-lo-platform, .LO_VS_container, #criteo-syncframe').remove();
		$('[src*="rubiconproject.com"], [src*="adnxs.com"], [src*="openx.net"]').remove();
		$('span:contains("CLOSE AD")').parent().parent().remove();
	}
}

function encodeB64(content) {
	return btoa(JSON.stringify(content)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
}



// ADS STICKY & ITT --------------------------------------------------


// GPT ad slots
var anchorSlot;
var ittSlot;

	const evolokSession = JSON.parse(localStorage.getItem('evolok:ev_session'));
	const localSuscriber = localStorage.getItem('subscriberTemp');


	const showSticky = () => {
		
		const script = document.createElement("script");
		script.src = "https://multimedia.corprensa.com/la-prensa/ads/adsSticky.js?r="+ Math.round(Math.random() * 10000000);
		script.async = true;
		document.head.appendChild(script); 

	}

	const showItt = () => {
		
		const scriptItt = document.createElement("script");
		scriptItt.src = "https://multimedia.corprensa.com/la-prensa/ads/adsItt.js?r="+ Math.round(Math.random() * 10000000);
		scriptItt.async = true;
		document.head.appendChild(scriptItt); 
	}


	const getCookie = (cname) => {
		let name = cname + "=";
		let decodedCookie = decodeURIComponent(document.cookie);
		let ca = decodedCookie.split(';');
		for(let i = 0; i <ca.length; i++) {
		  let c = ca[i];
		  while (c.charAt(0) == ' ') {
			c = c.substring(1);
		  }
		  if (c.indexOf(name) == 0) {
			return c.substring(name.length, c.length);
		  }
		}
		return "";
	  }
	
		
		let varCookie = getCookie("ev_ss");


		if ( evolokSession != null ){ 

		if(localSuscriber != null){
			
				if(localSuscriber == "true") {
					console.log("Si es suscriptor(Ya en usa sesión iniciada)-> LocalSuscriber= "+localSuscriber);
				}
	
				else if(localSuscriber == "false"){	
					console.log("No es suscriptor(Ya en usa sesión iniciada)-> LocalSuscriber= "+localSuscriber);
				}
				
			} 
		
		} else if (varCookie != "") {
	
		try{	
			fetch("https://ev.prensa.com:443/ic/api/session/"+varCookie, {
			method: "get",
			headers: {
				Accept: "application/json",
				"Content-Type": "application/json",
				Authorization: "Evolok evolok.api.service=registration_prensacom evolok.api.sessionId="+varCookie,
			},
		})
          .then((response) => response.json())
          .then(function (data) {
            console.log(console.log("DATA COOKIE" + JSON.stringify(data.guid)));
            if (data.guid != "") {
              fetch(
                "https://ev.prensa.com:443/ic/api/userProfile/"+data.guid+"/entitlement/WEB_ACCESS",
                {
                  method: "get",
                  headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    Authorization: "Evolok evolok.api.service=registration_prensacom evolok.api.sessionId="+varCookie,
                  },
                }
              )
                .then((response) => response.json())
                .then(function (data) {
                  console.log("USUARIO LOGUEADO .-- JS COOKIE" + JSON.stringify(data));								  
				  if (JSON.stringify(data).length != null && JSON.stringify(data).length > 20) {
					  console.log("Si es suscriptor --> ");
					  localStorage.setItem('subscriberTemp', 'true');
				  }
				  else {
					  console.log("No es suscriptor -->");
					  localStorage.setItem('subscriberTemp', 'false');	
				
					}
					
					showSticky();
					showItt();
                });
				                                               
            }
          });
		}
					
			catch{
				(error => console.error(error)); 
				showSticky();
				showItt();
		}
		      
		 
	   } else {
		 console.log("inicie sesion");
			 showSticky();
			 showItt();
	   }
	
	// }



	//    TEST 
/*
INJECT SPECIAL MESSAGES 
*/
/*
(function ($) {
    $(window).load(function() {
        $("#login-flip-back").before('<div class="login-message"><center><b>¿Necesitas ayuda?</b> <br> Contáctanos al 323-6400 / <a href="suscripciones@prensa.com" class="underline">suscripciones@prensa.com</a> </center></div>');
    });
})(jQuery);
*/
	
	// if(window.location.href.indexOf("/newsfeed-test/") > -1 ) {
	// 	console.log("Estoy en /newsfeed-test/");




///------------------------------- TEST


function initiateCoral2(id, email, username) {
	var loaded = false;

    if (Fusion.layout == "lp-article"){ // Descomentar en PROD
    // if(window.location.href.indexOf("/newsfeed-test/") > -1)  { //TODO : DELETE window.location.href.indexOf("/newsfeed-test/") in PROD
	//if ($('article').length > 0) {

    console.log("********************");
    console.log("** coral id 5: ", id);
    console.log("********************");

		if (id == '' && email == '' && username == '') {
			(function() {

                console.log("** coral entro: ", username);

				var d = document, s = d.createElement('script');
				s.src = 'https://talk.prensa.com/assets/js/embed.js';
				s.async = false;
				s.defer = true;
				s.onload = function() {
					Coral.createStreamEmbed({
						id: 'coral_thread',
						storyID: $('meta[name="cXenseParse:articleid"]').prop('content'),
						autoRender: true,
						rootURL: 'https://talk.prensa.com',
						events: function(events) {                  
							events.on("createCommentFocus", function() {
								if (!loaded) {
									$("#coral_thread").prepend("<div class='ev-coral-message_main'></div>");
                                    console.log("** initiate Coral 3.4");
									if (localStorage.getItem('evolok:ev_session') == null) {
										//$(".ev-coral-message_main").prepend("<div class='ev-coral-message'>Para participar en los comentarios debes ser suscriptor e iniciar sesión. <a href='https://www.prensa.com/sociedad/nota-de-la-directora-del-diario-la-prensa/' style='color:white;font-weight:bold;text-decoration:underline' target='_blank'>Ver más detalles</a>. <div class='ev-link-login' onclick='showLogin()'>Iniciar Sesión</div></div>");
                                        $(".ev-coral-message_main").prepend("<div class='ev-coral-message'>Para participar en los comentarios debes iniciar sesión. <a href='https://www.prensa.com/sociedad/nota-de-la-directora-del-diario-la-prensa/' style='color:white;font-weight:bold;text-decoration:underline' target='_blank'>Ver más detalles</a>. <div class='ev-link-login' onclick='showLogin()'>Iniciar Sesión</div></div>");
									} /* else {
										$(".ev-coral-message_main").prepend("<div class='ev-coral-message2'>Para participar en los comentarios debes tener una suscripción activa. <a href='https://www.prensa.com/sociedad/nota-de-la-directora-del-diario-la-prensa/' style='color:white;font-weight:bold;text-decoration:underline' target='_blank'>Ver más detalles</a>. <a class='ev-link-login' href='https://suscribete.prensa.com/detalle/?productName=digital'>Suscríbete desde $5</a></div>");
									} */
									$(".ev-coral-message_main").prepend("<div class='coral_bg_black'></div>");

									loaded = true;
								}
							});
						}
					});
					
					$('.coral-spinner').remove();
				};
				(d.head || d.body).appendChild(s);
			})();
		} else {
			var header = {
				"alg": "HS256",
				"typ": "JWT"
			};

			var data = {
				"iat": Math.floor(Date.now() / 1000),
				"user": {
					"id": id,
					"email": email,
					"username": unescape(encodeURIComponent(username))
				}
			};
			
			var shaObj = new jsSHA("SHA-256", "TEXT", {
				hmacKey: { value: atob('c3Nvc2VjXzE5OTg0MzA3YzFlMTg0MGRlMGU0MmZiYjdjYjlkMTg4ZWM2NDY4NTMxZmYyZjg2NDg5MTJhZjlkYWFkNzEyYjJlYg==') , format: "TEXT" },
			});
			
			var signature = encodeB64(header) + '.' + encodeB64(data);
			shaObj.update(signature);
			var key = shaObj.getHMAC('B64').replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
			var accessToken = signature + '.' + key;
			
			(function() {
				var d = document, s = d.createElement('script');
				s.src = 'https://talk.prensa.com/assets/js/embed.js';
				s.async = false;
				s.defer = true;
				s.onload = function() {
					Coral.createStreamEmbed({
						id: 'coral_thread',
						storyID: $('meta[name="cXenseParse:articleid"]').prop('content'),
						autoRender: true,
						rootURL: 'https://talk.prensa.com',
						accessToken: accessToken
					});
					
					setTimeout(() => {
						var lp = new MobileDetect(window.navigator.userAgent);
						
                        console.log("** initiate Coral 1");

						if (lp.mobile() != null) {
							$('#coral_thread').parent().prepend('<a href="https://suscribete.prensa.com/perfil/" style="position:absolute;margin-top:150px;z-index:999999;color:rgb(225, 34, 72);font-weight:bold">Cambiar Alias</a>');
						} else {
							$('#coral_thread').parent().prepend('<a href="https://suscribete.prensa.com/perfil/" style="position:absolute;margin-top:125px;z-index:999999;color:rgb(225, 34, 72);font-weight:bold">Cambiar Alias</a>');
						}
						
						$('.coral-spinner').remove();
					}, 1000);
				};
				(d.head || d.body).appendChild(s);
			})();
		}
	}
}






    let varCookieb = getCookie("ev_ss");

    console.log("varCookie ----------> " + varCookieb);

      if (varCookieb != "") {
        fetch("https://ev.prensa.com:443/ic/api/session/"+varCookieb, {
          method: "get",
          headers: {
            Accept: "application/json",
            "Content-Type": "application/json",
            Authorization: "Evolok evolok.api.service=registration_prensacom evolok.api.sessionId="+varCookieb,
          },
        })
          .then((response) => response.json())
          .then(function (data) {
            console.log(console.log("DATA COOKIE" + JSON.stringify(data.guid)));
            if (data.guid != "") {
              fetch(
                "https://ev.prensa.com:443/ic/api/userProfile/"+data.guid+"/entitlement/WEB_ACCESS",
                {
                  method: "get",
                  headers: {
                    Accept: "application/json",
                    "Content-Type": "application/json",
                    Authorization: "Evolok evolok.api.service=registration_prensacom evolok.api.sessionId="+varCookieb,
                  },
                }
              )
                .then((response) => response.json())
                .then(function (data) {
                  console.log("USUARIO LOGUEADO --- JS" + JSON.stringify(data));
                  console.log("DATA.CODE -- JS" + JSON.stringify(data.code));

				if (data.code == "SESSION_NOT_FOUND"){
					EV.Core.UI.logout();
					console.log("SESSION_NOT_FOUND......."); // Handle any errors from the first or second fetch
					localStorage.setItem("suscriptor", "false");
					pasteButtonsSession();
					PasteCoral();
					return;
				}

				if(
                    JSON.stringify(data).length != null &&
                    JSON.stringify(data).length > 20
                  ) {


					var bannerCounter = 0;
					
					var banner = setInterval(() => {
						$('#desktop_1x1_vidoomy, #mobile_1x1_vidoomy, #desktop_1x1_teads, #mobile_1x1_teads, .desktop-in-article-ad, .mobile-in-article-ad, .teads-inread, #wigoiframe, #vslider-lo-platform, .LO_VS_container, #criteo-syncframe').remove();
						$('[src*="rubiconproject.com"], [src*="adnxs.com"], [src*="openx.net"], [src*="vid.pubmatic.com"], [src*="player.aniview.com"]').remove();
						$('span:contains("CLOSE AD")').parent().parent().remove();
						$('#article-message-2, .trv-player-container').remove();
						$('#aniBox').remove();
						$('#4f4d9546-b0c1-4f83-a4ba-1489df5edb23').remove(); // div video Player actual

						$('[src*="static.videoo.tv"]', '[src*="videoo.tv"]').remove();
						$('.videootv').remove();
						
						if (bannerCounter > 480) {
							clearInterval(banner);
							console.log('1x1 Removed.');
						} else {
							bannerCounter++;
						}
					}, 250);

                    localStorage.setItem("suscriptor", "true");
                  } else {
                    localStorage.setItem("suscriptor", "false");
                  }
                });
			
				if( data.code != "SESSION_NOT_FOUND" ){
					fetch(
						"https://ev.prensa.com/ic/2.0/userProfile/"+data.guid+"?serviceName=my_account_suscribete",
						{
						method: "get",
						headers: {
							Accept: "application/json",
							"Content-Type": "application/json",
							Authorization: "Evolok evolok.api.service=my_account_suscribete evolok.api.sessionId="+varCookieb,
						},
						}
					)
						.then((response) => response.json())
						.then(function (data) {
						var attrs = [];
						for (var i = 0; i < data.userProfile.attributes.length; i++) {
							attrs[data.userProfile.attributes[i].name] =
							data.userProfile.attributes[i].value;
						}

						// console.log('Entra a displayName trae de localstorage evolok:ev_session: '+JSON.stringify(evolok))




                        //if (window.location.href.indexOf('/deportes/panama-sera-el-gran-ausente-en-el-preclasificatorio-olimpico') > -1) {
                        //}

                        // Sesion ya iniciada

                        var sesion_ev_iniciada1 = JSON.parse(localStorage.getItem('evolok:ev_session'));

                        console.log("** coral sesion_ev_iniciada: ", sesion_ev_iniciada1);


						//if(localStorage.getItem('suscriptor') == "true" ){
                        if (sesion_ev_iniciada1 != null) {

                                console.log("** coral sesion iniciada");

							//$(window).load(function () {
								if (attrs["user_name"] != null) {
								initiateCoral2(
									data.userProfile.guid,
									attrs["email_address"],
									attrs["user_name"]
								);
								} else {
								initiateCoral2(
									data.userProfile.guid,
									attrs["email_address"],
									attrs["email_address"]
								);
								}
							//});

						} else {
							initiateCoral2("", "", "");
						}

						

						var hours = new Date().getHours();
						var phrase = "Buenas noches";

						if (hours >= 6 && hours < 12) {
							phrase = "Buenos días";
						} else if (hours >= 12 && hours < 18) {
							phrase = "Buenas tardes";
						}

						if (attrs["first_name"] != null) {
							phrase = phrase + ', ' + '<strong>' + attrs["first_name"] + '</strong>';
						}

						var lp = new MobileDetect(window.navigator.userAgent);
						console.log("phrase----------->" + phrase);
						
						$( document ).ready(function() {
							
							var counter = 0;
							var checkevolokProfileExist = setInterval(function() {
								counter++;
								
								if ($('#evolokProfile').length) {
									console.log("#evolokProfile Exists!");

									if (lp.mobile() != null) {

										/* console.log ("** font-awesome 1a");
										if (window.location.href.indexOf('/backup-homepage') > -1) {
											if (Fusion.layout == "lp-frontpage") { */

												$('.registrate-mobile').css('display', 'none');
												$('.suscribete-mobile').css('display','none');
												$('.user-card-icon').css('display', 'block');
												$('#evolokProfile').prepend('<ul id="evolokButtons"><li>&nbsp;<a href="https://suscribete.prensa.com/perfil/" class="ev-link-profile" target="_blank" style="display:none;">Perfil</a></li></ul>');
												$('.ev-link-profile').parent().parent().prepend('<li style="width:100%"><small style="position:relative;z-index:99999">' + phrase + ' <i id="evolokLogout" class="awe-logout cruz1 fa-regular fa-circle-xmark show"></i></small></li>');
											
											console.log ("** font-awesome 2");

											//TEST MOBILE NEW DESIGN
																						
												// 
												// $('.registrate-mobile').css('displayName', 'none');
												// $('user-card-icon').css('displayName', 'block');

											/* }

										} else {
										
										$('#evolokProfile').prepend('<ul id="evolokButtons"><li>&nbsp;<a href="https://suscribete.prensa.com/perfil/" class="ev-link-profile" target="_blank">Perfil</a></li></ul>');
										$('.ev-link-profile').parent().parent().prepend('<li style="width:100%"><small style="position:relative;z-index:99999">' + phrase + ' <span id="evolokLogout" style="color:red;font-weight:bold;cursor:pointer;">[X]</span></small></li>');					
									
										} */
						
									
									} else {
												
											
										/* console.log ("** font-awesome 3a");
										if (window.location.href.indexOf('/backup-homepage') > -1) {
											if (Fusion.layout == "lp-frontpage") { */
											
											$('#evolokProfile').prepend('<small style="position:relative;z-index:99999">' + phrase + ' <i id="evolokLogout" class="awe-logout cruz1 fa-regular fa-circle-xmark show"></i></small><ul id="evolokButtons"><li>&nbsp;<a href="https://suscribete.prensa.com/perfil/" class="ev-link-profile" target="_blank">Perfil</a></li></ul>');					
											console.log ("** font-awesome 10");

											/* }

										} else {
										
										$('#evolokProfile').prepend('<small style="position:relative;z-index:99999">' + phrase + ' <span id="evolokLogout" style="color:red;font-weight:bold;cursor:pointer;">[X]</span></small><ul id="evolokButtons"><li>&nbsp;<a href="https://suscribete.prensa.com/perfil/" class="ev-link-profile" target="_blank">Perfil</a></li></ul>');					
									
										} */
										
									}
									
									if(localStorage.getItem('suscriptor') == "false" ){
										$('#evolokButtons').append('<li><a href="https://suscribete.prensa.com/?utm_source=Prensacom&utm_medium=Boton+de+Hazte+Socio&utm_campain=Base" class="red">Hazte Socio</a></li>');
									}

										//$('#evolokLogout').click(() => {
										$('body').on('click', '#evolokLogout', function () {

											if(localStorage.getItem('subscriber') != null && localStorage.getItem('registrado') != null && localStorage.getItem('anonimo') != null){
												localStorage.removeItem('subscriber');
												localStorage.removeItem('registrado');
												localStorage.removeItem('anonimo');												
											}

											if(localStorage.getItem('subscriber') != null){
												localStorage.removeItem('subscriber');
											}
											if(localStorage.getItem('subscriberTemp') != null){
												localStorage.removeItem('subscriberTemp');
											}
											EV.Core.UI.logout();
											console.log ("** logout 1");
											setTimeout(() => {
												window.location.reload();
											}, 1000);
										});


									
										clearInterval(checkevolokProfileExist);
										
								}
						
								if (counter >= 100) {
									console.log("couter"+counter)
									clearInterval(checkevolokProfileExist);
								}
							}, 200);
				
						});


						

						});
					}
			}
          }).catch( (error) => {
			console.error(error); // Handle any errors from the first or second fetch
			localStorage.setItem("suscriptor", "false");
			pasteButtonsSession();
			PasteCoral();
		  } );
		} else {	
				localStorage.setItem("suscriptor", "false");
				pasteButtonsSession();
				PasteCoral();
		  }


	// } else {
	// 	console.log("NO Estoy en /newsfeed-test/");
	// }


	function pasteButtonsSession() {

		$( document ).ready(function() {
			var lp = new MobileDetect(window.navigator.userAgent);
			var counter = 0;
			var checkevolokProfileExist = setInterval(function() {
				counter++;
		
				if ($('#evolokProfile').length) {
					console.log("#evolokProfile Exists!");
					// if (lp.mobile() != null) {
					// 	$('#evolokProfile').prepend(
					// 		'<ul><li class="ev-link-loginNew"><a href="#" id="evolokLogin" onclick="showLogin();">Inicia Sesión</a></li><li class="ev-button-suscribase"><a href="https://suscribete.prensa.com/" class="red">Suscríbete desde $5</a></li></ul>'
					// 	);
					// } else {
					// 	$('#evolokProfile').prepend(
					// 		'<ul><li class="ev-link-loginNew"><a href="#" id="evolokLogin" onclick="showLogin();">Inicia Sesión</a></li><li class="ev-button-suscribase"><a href="https://suscribete.prensa.com/" class="red">Suscríbete desde $5</a></li></ul>'
					// 	);
					// }
					$('#evolokProfile').prepend(
						'<ul><li class="ev-link-loginNew"><a data-google-interstitial="false" href="#" id="evolokLogin" onclick="showLogin();">Inicia Sesión</a></li><li class="ev-button-suscribase"><a data-google-interstitial="false" href="https://suscribete.prensa.com/" class="red">Suscríbete desde $5</a></li></ul>'
					);
						
					clearInterval(checkevolokProfileExist);
						
				}
		
				if (counter >= 200) {
					console.log("couter"+counter)
					clearInterval(checkevolokProfileExist);
				}
			}, 200);

		});
	  }

	function PasteCoral() {

		$( document ).ready(function() {

			var counter = 0;
			var checkcoral_threadExist = setInterval(function() {
				counter++;
		
				if ($('#coral_thread').length) {
					console.log("#Coral Exists!");
						

					initiateCoral2("", "", "");
					clearInterval(checkcoral_threadExist);
						
				}
		
				if (counter >= 100) {
					console.log("couter"+counter)
					clearInterval(checkcoral_threadExist);
				}
			}, 200);

		});
	  }

