var URL_BASE, URL_ABSOLUTE;
if (location.hostname === 'pre-vive.upc.edu.pe') {
URL_BASE = 'https://pre-vive.upc.edu.pe/api/';
URL_ABSOLUTE = 'https://pre-vive.upc.edu.pe/'
} else if (location.hostname === 'viveupc-pre.azurewebsites.net') {
URL_BASE = 'https://viveupc-pre.azurewebsites.net/api/';
URL_ABSOLUTE = 'https://viveupc-pre.azurewebsites.net/'
} else if (location.hostname === 'stg-vive.upc.edu.pe') {
URL_BASE = 'https://stg-vive.upc.edu.pe/api/';
URL_ABSOLUTE = 'https://stg-vive.upc.edu.pe/'
} else if (location.hostname === 'vive-upc.lucuma.co') {
URL_BASE = 'https://vive-upc.lucuma.co/api/';
URL_ABSOLUTE = 'https://viveupc.pe/'
} else if (location.hostname === 'localhost') {
URL_BASE = 'http://localhost/';
URL_ABSOLUTE = 'http://localhost/'
} else {
URL_BASE = 'https://viveupc.pe/api/';
URL_ABSOLUTE = 'https://viveupc.pe/'
}
var eventCarrer, currentCareer, currentCampus, currentEventCarrer;
var getEventCareer = function () {
// initPanel();
// $('[data-target="tab-first"]').text(window.configFields.labelFirstTab || "1. Selecciona")
// $('[data-target="tab-second"]').text(window.configFields.labelSecondTab || "2. Regístrate")
// $('#tab-first-description').text(window.configFields.labelFirstTabDescription || "Escoge la información solicitada.")
// $('#tab-second-description').text(window.configFields.labelSecondTabDescription || "Completa la información solicitada.")
$.ajax({
type: "GET",
url: URL_BASE + 'events/' + eventId + '/careers',
success: function (data) {
eventCarrer = data;
let ordered = data.sort(function(a,b){
if(a.name < b.name) {return -1};
if(a.name > b.name) {return 1};
return 0;
})
$('#careers').html('');
$('#careers').append('');
$.each(ordered, function (i, item) {
$('#careers').append('');
});
$('#careers').change(function () {
onCarreerChange($(this).val());
});
$('#careers').trigger('change');
}
});
}
function getCookie(name) {
var re = new RegExp(name + "=([^;]+)");
var value = re.exec(document.cookie);
return (value != null) ? unescape(value[1]) : null;
}
function getClientID() {
try {
var cookie = getCookie("_ga").split(".");
return cookie[2] + "." + cookie[3];
} catch (e) {
console.log("No Universal Analytics cookie found");
return undefined
}
}
var onCarreerChange = function (value) {
$('#campus').html('').parents('.select-wrapper').hide();
$('#event_career').html('').parents('.select-wrapper').hide();
$('#btn-next').attr('disabled', true);
currentCareer = eventCarrer.findIndex(o => o.career === parseInt(value));
if (currentCareer === -1) return;
currentCareer = eventCarrer[currentCareer];
if (currentCareer.items.length == 0) {
$('#campus').attr('required', false);
$('#event_career').attr('required', false);
formObj.career_id = false;
formObj.event_career_id = false;
$('#btn-next').attr('disabled', false);
return;
}
$('#campus').attr('required', true);
formObj.career_id = true;
formObj.campus_id = true;
$('#campus').append('');
currentCareer.items.map(item => {
$('#campus').append('');
})
$('#campus').change(function () {
onCampusChange($(this).val());
});
$('#campus').parents('.select-wrapper').show();
$('#campus').trigger('change');
}
var onCampusChange = function (value) {
$('#event_career').html('').parents('.select-wrapper').hide();
$('#btn-next').attr('disabled', true);
currentCampus = currentCareer.items.findIndex(o => o.campus === parseInt(value));
if (currentCampus === -1) return;
currentCampus = currentCareer.items[currentCampus];
if (currentCampus.items.length == 0) {
formObj.event_career_id = false;
$('#event_career').attr('required', false);
$('#btn-next').attr('disabled', false);
return;
};
formObj.event_career_id = true;
$('#event_career').attr('required', true);
$('#event_career').append('');
$.each(currentCampus.items, function (i, item) {
$('#event_career').append('');
});
$('#event_career').parents('.select-wrapper').show();
$('#event_career').change(function () {
onEventCareerChange($(this).val());
})
$('#event_career').parents('.select-wrapper').show();
$('#event_career').trigger('change');
}
var onEventCareerChange = function (value) {
if (!value) return;
$('#btn-next').attr('disabled', false);
}
var onGradeYearChange = function (value) {
var $field = $('[name="last_school_year"]')
$field.attr('required', false).hide();
$field.parents('.select-wrapper').hide();
if (value != 7) return;
$field.attr('required', true).show();
$field.parents('.select-wrapper').show();
}
var initPanel = function () {
var $this = $('#register-form-container');
tab_active = $this.find('.panel-tab-list > .panel-tab.active');
if (!tab_active) {
tab_active = $this.find('.panel-tab-list > .panel-tab')[0].addClass('active');
}
$this.find('.panel-column').hide();
$this.find('.panel-column#' + tab_active.data('target')).addClass('active').show();
$('[data-target="tab-first"]').click(function (e) {
e.preventDefault();
$panel = $(this).parents('.panel-wrap');
$panel.find('.panel-tab-list > .active').removeClass('active');
$panel.find('.panel-column.active').hide().removeClass('active');
$panel.find('.panel-tab[data-target="tab-first"]').addClass('active');
$panel.find('#tab-first').show().addClass('active');
})
$('#btn-next').on('click', function (e) {
e.preventDefault();
$panel = $(this).parents('.panel-wrap');
$panel.find('.panel-tab-list > .active').removeClass('active');
$panel.find('.panel-column.active').hide().removeClass('active');
$panel.find('.panel-tab[data-target="tab-second"]').addClass('active');
$panel.find('#tab-second').show().addClass('active');
$('#grade-year').trigger('change');
});
}
function getCareerUrl() {
var str = window.location.pathname
var res = str.split("/")
for (var i = 0; i < res.length; i++) {
if (res[i] === '' || res[i].indexOf('html') >= 0) {
res.splice(i, 1)
}
}
return res[res.length - 1]
}
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
function executeValidations() {
var messagesObj = {
province_id: {
required: 'Debe escoger una ciudad',
}
}
var rulesObj = {}
var messagesForm = {}
var messagesFormBO = {}
var extraRulesForm = {
first_name: {
lettersonly: true,
},
paternal_last_name: {
lettersonly: true,
},
maternal_last_name: {
lettersonly: true,
},
phone_mobile: {
cellphone: true,
},
idn: {
idn: true,
}
}
if (typeof (window.configFields) === 'undefined' || window.configFields.language != 'EN') {
messagesForm = {
grade_year: "El grado es requerido",
last_school_year: "El año de egreso es requerido",
first_name: {
required: 'El nombre es requerido',
maxlength: "La cantidad máxima de caracteres es 100",
lettersonly: "Ingresar solo texto"
},
paternal_last_name: {
required: 'El apellido es requerido',
maxlength: "La cantidad máxima de caracteres es 100",
lettersonly: "Ingresar solo texto"
},
maternal_last_name: {
required: 'El apellido es requerido',
maxlength: "La cantidad máxima de caracteres es 100",
lettersonly: "Ingresar solo texto"
},
idn: {
required: 'El dni es requerido',
maxlength: "Debe tener 8 caracteres",
minlength: "Debe tener 8 caracteres",
idn: "Ingresar el DNI correctamente"
},
phone_mobile: {
required: 'El número de celular es requerido',
maxlength: "La cantidad máxima de caracteres es 9",
minlength: "La cantidad mínima de caracteres es 9",
cellphone: "Ingresar correctamente el número de celular"
},
email: {
required: 'El correo es requerido',
email: 'Debe tener el formato de email',
maxlength: 'Debe tener como máximo 100 caracteres'
},
city_id: {
required: 'Debe escoger una ciudad',
},
university_id: {
required: 'Debe escoger una universidad',
},
career_id: {
required: 'Debe escoger una carrera',
},
event_career_id: {
required: 'Debe de escoger una fecha',
},
wednesday_id: {
required: 'Debe escoger un día',
},
campus_id: {
required: 'Debe escoger un campus',
},
gender: {
required: 'Debes escoger el género',
},
event_shift_id: {
required: 'El campo es requerido'
}
}
messagesFormBO = {
phone_mobile_bo: {
required: 'El número de celular es requerido',
maxlength: "La cantidad máxima de caracteres es 8",
minlength: "La cantidad mínima de caracteres es 8",
cellphone: "Ingresar correctamente el número de celular"
},
idn_bo: {
required: 'El CI es requerido',
maxlength: "Debe tener 7 caracteres",
minlength: "Debe tener 7 caracteres",
idn: "Ingresar el CI correctamente"
}
}
}
if (typeof (window.configFields) != 'undefined' && window.configFields.language === 'EN') {
$('[name="first_name"]').attr('placeholder', 'Name')
$('[name="paternal_last_name"]').attr('placeholder', 'Last Name')
$('[name="maternal_last_name"]').attr('placeholder', 'Second Last Name')
$('[name="email"]').attr('placeholder', 'Email')
$('[name="phone_mobile"], [name="phone_mobile_bo"]').attr('placeholder', 'Cellphone')
$('[name="gender"] option:eq(0)').html('Choose your gender')
$('[name="gender"] option:eq(1)').html('Male')
$('[name="gender"] option:eq(2)').html('Female')
$('[name="grade_year"] option:eq(0)').html('Choose your degree')
$('[name="grade_year"] option:last()').html('I finished school')
$('[name="last_school_year"] option:eq(0)').html('Graduation year')
document.getElementById('buttonEventos').innerHTML = "SEND"
document.getElementById('sectionDescription').innerHTML = "Register here and find out more"
// document.getElementById('sectionPrivacy').innerHTML = 'By clicking Send, I confirm that I have read and accepted the Privacy Policies.'
}
for (var key in formObj) {
if (key && formObj[key]) {
messagesObj[key] = messagesForm[key]
if (extraRulesForm[key])
rulesObj[key] = extraRulesForm[key]
} else {
if (key === 'city_id') key = 'province_id'
var input = $('#widget-form [name=' + key + ']')
var inputId = input.attr('id')
if (formObj.event_career_id) {
if (key !== 'campus_id' && key !== 'event_career_id') {
// $('#widget-form [name=' + key + ']').attr('required', false).parent('div').remove()
if ($('#' + inputId).is('select')) {
input.attr('required', false).parent('div').parent('div').remove()
} else {
input.attr('required', false).parent('div').remove()
}
}
} else {
if ($('#' + inputId).is('select')) {
input.parent('div').parent('div').remove()
} else {
input.parent('div').remove()
}
}
}
}
for (var key in messagesFormBO) {
messagesObj[key] = messagesFormBO[key]
}
if (typeof (window.configFields) != 'undefined' && window.configFields.showOnlyFieldsCountry) {
$('#widget-form [name="idn"]').parent('div').remove()
$('#widget-form [name="phone_mobile"]').parent('div').remove()
$('#widget-form [name="idn_bo"]').parent('div').show()
$('#widget-form [name="phone_mobile_bo"]').parent('div').show()
}
jQuery.validator.addMethod("lettersonly", function (value, element) {
return this.optional(element) || /^[a-záäéëíóöúüñ ]+$/i.test(value);
});
jQuery.validator.addMethod("telephone", function (value, element) {
return this.optional(element) || /^([0]{1}\d{8})$/i.test(value);
});
jQuery.validator.addMethod("cellphone", function (value, element) {
return this.optional(element) || /^([9]{1}\d{8})$/i.test(value);
});
jQuery.validator.addMethod("idn", function (value, element) {
return this.optional(element) || /^([0-9]{1}\d{7})$/i.test(value);
});
$('#register-form-container #register-form').validate({
rules: rulesObj,
messages: messagesObj
});
$('[name="idn"]').keypress(function () {
$('#repeated-dni-error').hide();
});
$('.lettersonly').on('input', function () {
this.value = this.value.replace(/\d+|^\s+$/g, '').replace(/\s+/g, ' ')
});
$('.numbersonly').on('input', function () {
this.value = this.value.replace(/[^0-9]/g, '');
});
function erroresManagger() {
var textError = $('label.error').text()
var textLists = Array.prototype.slice.apply(document.querySelectorAll('label.error')),
listNames = Array.prototype.slice.apply(document.querySelectorAll('input.error')),
selectNames = Array.prototype.slice.apply(document.querySelectorAll('select.error')),
// selectNames = $("selected.error").getAttribute('id'),
listErr;
listErr = textLists.map(textList => textList.getAttribute('id'))
listErrName = listNames.map(listName => listName.getAttribute('placeholder'))
selectNa = selectNames.map(selectName => selectName.getAttribute('id'))
dataLayer.push({
'event': 'erroresFormulario',
'tipoFormulario': 'Formulario Preinscripción',
'campoFormulario': listErrName + ',' + selectNa,
'tipoError': listErr
});
dataLayer.push({
'event': 'intencionRegistro',
'tipoFormulario': 'Formulario Preinscripción'
});
}
function registerVali(data) {
var carrera = $("#careers option:selected").text(),
grado = $("#grade-year option:selected").text(),
leadId = data.uuid;
console.log(grado);
dataLayer.push({
'event': 'intencionRegistro',
'tipoFormulario': 'Formulario Preinscripción'
});
dataLayer.push({
'event': 'registroExitoso',
'tipoFormulario': 'Formulario Preinscripción',
'leadId': leadId,
'clientId': getClientID(),
'carrera': getCareerUrl(),
'nivel': 'Pregrado',
'ciclo': '',
'grado': grado
});
}
$('#register-form-container #register-form, #register-form-container').submit(function (e) {
e.preventDefault();
if (!$(this).valid()) {
console.log('Has errors')
return erroresManagger()
}
document.querySelector('#loader').classList.add('active');
$("#buttonEventos").attr("disabled", true);
document.body.style.cursor = 'wait';
var data = $(this).serialize();
if (window.configFields && window.configFields.careerId)
data = data + ('&career_id=' + window.configFields.careerId);
if (typeof (country_id) != 'undefined')
data = data + '&country_id=' + country_id
var utm_source = getParameterByName('utm_source');
var utm_medium = getParameterByName('utm_medium');
var utm_campaign = getParameterByName('utm_campaign');
var g360_client_id = getClientID();
var digitalChannel = getDigitalChannel();
if (utm_source)
data = data + ('&utm_source=' + utm_source);
if (utm_medium)
data = data + ('&utm_medium=' + utm_medium);
if (utm_campaign)
data = data + ('&utm_campaign=' + utm_campaign);
if (g360_client_id)
data = data + ('&g360_client_id=' + g360_client_id)
if (digitalChannel)
data = data + ('&digital_channel=' + digitalChannel)
type_institution = $('#universities').find(":selected").data('type');
data = data + ('&type_institution=' + type_institution);
$.ajax({
type: "POST",
url: URL_BASE + 'events/' + eventId + "/participants",
data: data,
error: function (xhr, status, error) {
let message = xhr.responseText;
if(message.includes('idn_already_registered')) {
$('#repeated-dni-error').show();
}
document.querySelector('#loader').classList.remove('active');
$("#buttonEventos").attr("disabled", false);
document.body.style.cursor = 'initial';
},
success: function (data) {
document.querySelector('#loader').classList.remove('active');
$("#register-form-container-vive-upc #register-form #btn-send").attr("disabled", false);
document.body.style.cursor = 'initial';
var str = window.location.pathname;
registerVali(data);
if (str.indexOf('musiccon') > 0)
window.location = "registro/?uuid=" + data.uuid;
else if (window.goToAction)
window.goToAction();
else if (str.indexOf('talleres-vivenciales') > 0)
window.location = "https://encuestasupc.typeform.com/to/dFRCZJ?uuid=" + data.uuid;
else if (str.substr(-4, 4) != 'html' && str.charAt(str.length - 1) != '/')
window.location = str + "/gracias.html";
else
window.location = "gracias.html";
}
});
});
$('input:radio').change(function () {
if (this.value === 'yes') {
$('#buttonEventos').attr('disabled', false)
} else {
$('#buttonEventos').attr('disabled', true)
}
});
}
var getconfigFields = function () {
var configFields = window.configFields;
if (configFields && configFields.showOnlyCampusRelatedTo && configFields.showOnlyCampusRelatedTo.length > 0) {
$('[name="campus_id"]').find('option').each(function () {
var cont = 0;
for (var i = 0; i <= configFields.showOnlyCampusRelatedTo.length; i++) {
var careerWord = configFields.showOnlyCampusRelatedTo[i];
if (careerWord) {
if ($(this).text().toLowerCase().indexOf(careerWord.toLowerCase()) && $(this).text() !== 'Escoge tu campus')
cont++;
else
break;
if (cont === configFields.showOnlyCampusRelatedTo.length)
$(this).remove();
}
}
});
}
if (configFields && configFields.showOnlyCareersRelatedTo && configFields.showOnlyCareersRelatedTo.length > 0) {
$('[name="career_id"]').find('option').each(function () {
var cont = 0;
for (var i = 0; i <= (configFields.showOnlyCareersRelatedTo.length - 1); i++) {
var careerWord = configFields.showOnlyCareersRelatedTo[i];
if ($(this).text().indexOf(careerWord) && $(this).text() !== 'Escoge tu carrera')
cont++;
else
break;
if (cont === configFields.showOnlyCareersRelatedTo.length)
$(this).remove();
}
});
}
}
var getconfigGradeFields = function () {
var configFields = window.configFields;
if (configFields && configFields.showOnlyGradesRelatedTo && configFields.showOnlyGradesRelatedTo.length > 0) {
$('[name="grade_year"]').find('option').each(function () {
var cont = 0;
for (var i = 0; i <= configFields.showOnlyGradesRelatedTo.length; i++) {
var gradeWord = configFields.showOnlyGradesRelatedTo[i];
if ($(this).text().indexOf(gradeWord) && $(this).text() !== 'Escoge tu grado')
cont++;
else
break;
if (cont === configFields.showOnlyGradesRelatedTo.length)
$(this).remove();
}
});
} else {
if (typeof (configFields) === 'undefined' || (typeof (configFields) != 'undefined' && configFields.language != 'EN'))
$('[name="grade_year"] option:eq(4)').remove()
}
$('#grade-year').change(function () {
onGradeYearChange($(this).val());
});
$('#grade-year').trigger('change');
}
var getData = function (URL_API, selector, title) {
var headers = {};
if (window.language)
headers['Accept-Language'] = window.language;
$.ajax({
type: "GET",
url: URL_BASE + URL_API,
headers: headers,
success: function (data) {
$(selector).html('');
if (typeof (window.configFields) != 'undefined' && window.configFields.language === 'EN') {
$(selector).append('');
console.log('select')
} else {
$(selector).append('');
}
let ordered = data.sort(function(a,b){
if(a.name < b.name) {return -1};
if(a.name > b.name) {return 1};
return 0;
})
$.each(ordered, function (i, item) {
$(selector).append('');
});
},
complete: function () {
if (window.configFields)
getconfigFields();
}
});
}
function validateNewField(key, callback) {
if (formObj.hasOwnProperty(key) && formObj[key] === true)
callback();
else
$('#widget-form [name=' + key + ']').parent('div').remove();
}
function getCareers() {
var URL_API = 'commons/careers/';
if (window.campusId)
URL_API = (URL_API + '?campus_id=' + window.campusId);
if (window.facultyId)
URL_API = (URL_API + '?faculty_id=' + window.facultyId);
getData(URL_API, '#careers', 'carrera');
}
function getShifts() {
var URL_API = 'events/' + eventId + '/shifts';
var label = window.configFields.labelCampusLabelInShift || 'taller y campus';
getData(URL_API, '#shifts', label);
}
function getCampus() {
getData('commons/campus/simple', '#sedes', 'campus');
}
function getDigitalChannel() {
var configFields = window.configFields;
if (configFields !== undefined && configFields.digitalChannel !== undefined) {
return configFields.digitalChannel
}
return undefined
}
function getCities() {
getData('commons/provinces/?country_id=1', '#cities', 'ciudad');
}
function getUniversities() {
getData('commons/universities', '#universities', 'universidad de procedencia');
}
function getInstitutions(eventId) {
getData('commons/institutions/' + eventId, '#universities', 'institución de procedencia');
}
jQuery(document).ready(function () {
if (formObj.event_career_id) {
var form_url = URL_ABSOLUTE + 'register-talleres.html';
} else {
var form_url = URL_ABSOLUTE + 'register.html';
}
$.get(form_url, function (data) {
$('#widget-form').append(data);
formObj.idn = true
if (formObj.event_career_id)
getEventCareer();
if (formObj.career_id)
getCareers();
if (formObj.city_id)
getCities();
if (formObj.campus_id)
getCampus();
if (formObj.event_shift_id)
getShifts();
if (formObj.grade_year)
getconfigGradeFields();
// Make the following every time you add a new field on the form
// If the field exists and you want to make something then add a callback
validateNewField('university_id', function () {
// getUniversities();
getInstitutions(eventId);
});
validateNewField('wednesday_id', function () {
});
// End new fields
if (window.formObjRequired) {
var formObjRequired = window.formObjRequired;
for (var key in formObjRequired) {
if (key && formObjRequired[key])
$('[name=' + key + ']').attr('required', true);
}
} else {
for (var key in formObj) {
if (key && formObj[key]) {
$('[name=' + key + ']').attr('required', true);
}
}
}
executeValidations();
});
});