console.log('Theme JS');
if ($('#breadcrumb').find('a:contains("Crachá")').length > 0) {
$('#innerProdutoInfo').after(`
`);
if (localStorage.getItem('#imagemeditor#')){
$('#imgEnvioArq').attr("src", localStorage.getItem('#imagemeditor#'));
}
$('#btnFotoEditor').click(function (event) {
$('#input_foto_editor').click();
});
$('#input_foto_editor').unbind("change");
$('#input_foto_editor').change(function (event) {
event.stopPropagation();
event.preventDefault();
var file = this.files[0];
txtArquivoExt = String(file.name).split('.').pop().split('?').shift();
txtNovoNome = file.name.split('?').shift().split('.').shift().replace(/([^a-z0-9]+)/gi, '-').replace(' ', '-') + '_' + fcnRandomString(20) + ' ' + '.' + txtArquivoExt;
txtNovoNome = txtNovoNome.replace(/\s/g, '');
//Verifica se é imagem png ou jpg
if(file.type != 'image/png' && file.type != 'image/jpg' && file.type != 'image/jpeg' ) {
alert("Formato de imagem inválido.");
}else{
$('.js-spinner').removeClass('d-none');
$.getScript('//sdk.amazonaws.com/js/aws-sdk-2.7.20.min.js', function(){
var UPLOAD_PATH = 'galeria/loja/quintoandar/';
var IdentityPoolId = 'us-east-1:a4162646-7687-43d2-982c-2277264ef656';
var bucket = 'editor-printone';
var region = 'us-east-1';
AWS.config.update({
region: region,
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
}),
correctClockSkew:true
});
var s3 = new AWS.S3({
apiVersion: '2006-03-01',
region: region,
params: {Bucket: bucket},
httpOptions: {timeout: 60 * 1000 * 60}
});
AWS.events.on('retry', function(response) {
if (response.error.name === 'RequestTimeTooSkewed') {
var serverTime = new Date(response.httpResponse.headers.date); // parse header into Date
AWS.config.systemClockOffset = serverTime.getTime() - new Date().getTime();
response.error.retryable = true; // make sure we retry this request
}
});
var key = UPLOAD_PATH+txtNovoNome;
var params = {
Key: key,
ContentType: file.type,
Body: file
};
managerUpload = s3.upload(params,function(err,data){
$('.js-spinner').addClass('d-none');
if(err){
if(err.code == "NetworkingError"){
$.colorbox({ html: 'Não foi possÃvel enviar seu arquivo (' + file.name + '). A conexão com os servidores da Amazon não está disponÃvel.
', fixed: true, opacity: 0.3, width: 400, height: 150 });
}else if(err.code == "RequestTimeTooSkewed"){
$.colorbox({ html: 'Não foi possÃvel enviar seu arquivo (' + file.name + '). A conexão com os servidores foi recusada em virtude da diferença de horário. Verifique se o seu computador está com a data e hora atualizada.
', fixed: true, opacity: 0.3, width: 450, height: 200 });
}else{
console.log("Erro no Upload: " + err.code + " - " + err.message);
$.colorbox({ html: 'Não foi possÃvel enviar seu arquivo (' + file.name + '). Houve um problema na comunicação entre os servidores.
', fixed: true, opacity: 0.3, width: 400, height: 150 });
}
}else{
$('#imgEnvioArq').attr("src", data.Location);
localStorage.setItem('#imagemeditor#', data.Location);
}
}).on('httpUploadProgress',function(evt){
});
});
}
});
}var SPMaskBehaviorFlyer = function (val) {
return val.replace(/\D/g, '').length === 11 ? '(00) 00000-0000' : '(00) 0000-00009';
};
var spOptionsFlyer = {
onKeyPress: function (val, e, field, options) {
field.mask(SPMaskBehaviorFlyer.apply({}, arguments), options);
}
};
var formQuinto = {
id_produto: 0,
id_produto_chave: 0,
texts: [],
images: [],
inputs: [],
models: [],
key:0,
project:0,
id_model:0,
tipo_editor: 0,
appendForm: '#produto-form-personalizar .js-form-body',
buttonHandler: '#produtos-detalhes #botPersonalizar',
init: function () {
self = this;
this.id_produto = objProdutoDetalhes.idProduto;
this.id_produto_chave = objProdutoDetalhes.idProdutoChave;
$.ajax({
url: "/lojapp1/jsons/produtosDetalhesPersonalizacao.js",
type: "POST",
dataType:'json',
data : {
idP : this.id_produto,
salario : this.id_produto_chave
},
beforeSend: function () {
},
success: function (objJSON) {
if( typeof (objJSON.numTipoProduto) != "undefined") {
self.tipo_editor = objJSON.numTipoProduto;
}
if( typeof (objJSON.objPersonalizacaoInfo.txtModelo) != "undefined") {
self.id_model = objJSON.objPersonalizacaoInfo.txtModelo;
}
if( typeof (objJSON.objPersonalizacaoInfo.txtChave) != "undefined") {
self.key = objJSON.objPersonalizacaoInfo.txtChave;
}
self.initEditor();
},
error: function (objXHR, txtStatus, txtErro) {
console.error('erro', objXHR);
},
complete: function (xhr) {
}
});
},
initEditor: function () {
self = this;
if (this.id_model == 0){
console.error('Modelo não encontrado.');
return;
}
if (this.key == 0){
console.error('Chave do editor não informada.');
return;
}
$.ajax({
url: "https://editor.print-one.com.br/api/modelo/"+this.id_model+"/layers/?key="+this.key,
type: "GET",
dataType:'json',
beforeSend: function () {
},
success: function (objJSON) {
self.texts = objJSON.layers.texts
self.images = objJSON.layers.images
if (typeof self.texts != 'undefined') {
self.configForm();
self.createContainer();
self.createForm();
}else{
console.error('Não existe layer de texto para este modelo.');
}
},
error: function (objXHR, txtStatus, txtErro) {
console.error('erro', objXHR);
},
complete: function (xhr) {
}
});
},
createContainer: function () {
$container = $(``);
$container.insertAfter('#innerProdutoInfo');
},
configForm: function () {
for (let key = 0; key < this.texts.length; key++) {
let element = this.texts[key].name;
let elementID = this.texts[key].name.replace(' ', '').toLowerCase();
elementID = elementID.replace('ç', 'c');
let mask = element.toLowerCase().indexOf('telefone') != -1 || element.toLowerCase().indexOf('celular') != -1 ? true : false;
let maxlength = element.toLowerCase().indexOf('nome') != -1 ? 20 : false;
let type = 'text';
let label = this.capitalize(element.replace(/\#/g,''));
console.log('label', label)
console.log('label.toLowerCase().indexOf', label.toLowerCase().indexOf('end'))
label = label.toLowerCase().indexOf('end') != -1 ? 'Endereço' : label;
let value = '';
if (this.findArray(elementID)){
this.inputs.push({
name:elementID,
label: label,
match:"#"+elementID+"#",
value:value,
required: true,
id: elementID,
type: type,
mask: mask,
maxlength, maxlength
});
}
}
},
createForm: function () {
if (!this.inputs.length) {
console.error('Nenhum input definido');
} else {
for (var i in this.inputs) {
$(this.appendForm).append(this.getInput(this.inputs[i]));
}
$button = $('
');
$button.css({
'position': 'absolute',
'top': 0,
'left': 0,
'right': 0,
'bottom': 0,
'z-index': 1,
'cursor': 'pointer',
'width': $(this.buttonHandler).width() + 34
}).click(function (event) {
event.preventDefault();
formQuinto.save();
});
console.log('$(this.buttonHandler).', $(this.buttonHandler).width())
$(this.buttonHandler).css({
'position': 'relative'
}).parent().css({
'position': 'relative'
}).append($button)
}
},
capitalize: function (string) {
string = string[0].toUpperCase() + string.slice(1);
//tem número na string? Ex: Telefone1, Telefone2...
hasNumber = string.match(/[0-9]/);
if(hasNumber){
//Separa para ficar Telefone 1, Telefone 2, Telefone 3
string = string.replace(hasNumber[0], ' ' + hasNumber[0]);
}
return string;
},
findArray: function (string) {
//Verifica se já existe um campo com o nome igual, se tiver não deixa criar o input
if (this.inputs.filter(p => p.name == string).length > 0){
return false;
}else{
return true;
}
},
getInput: function (input) {
$field = $('
');
var $input;
if (input.type == 'select') {
$input = $(' ');
for (var i in input.value) {
$input.append('' + input.value[i] + ' ');
}
} else {
$input = $(' ');
}
$input.attr({
'name': input.name,
'id': input.id
}).data({
'match': input.match,
'required': input.required,
})
if (!!localStorage.getItem(input.match)) {
$input.val(localStorage.getItem(input.match));
}
if (input.maxlength) {
$input.attr({
'maxlength': input.maxlength,
}).data({
'maxlength': input.maxlength
})
}
var $label = $(' ');
$label.attr({
'for': input.id
}).text(input.label);
var $span;
if (input.maxlength) {
$span = $('' + ($input.val().length) + '/' + input.maxlength + ' ');
$input.on('input', function () {
max = $(this).data('maxlength');
current = $(this).val().length;
$(this).next('span').text(current + '/' + max);
})
}
if(input.mask !== false){
$input.mask(SPMaskBehaviorFlyer, spOptionsFlyer);
}
$field.append($label);
$field.append($input);
$field.append($span);
return $field;
},
save:function(){
self = this;
var validate = true;
if ($('#produto-form-personalizar-model').length > 0){
if (self.model_selecionado == false) {
alert('Informe o tipo de modelo antes de continuar.');
validate = false;
}else{
localStorage.setItem('#idmodelo#', self.id_model);
}
localStorage.setItem('#preview#', 1);
for (var i in self.images){
if (self.images[i].bit_block_upload == 0){
localStorage.setItem('#preview#', 0);
break;
}
}
}
for (var i in self.inputs){
if(self.inputs[i].required && $('#'+self.inputs[i].id).val() == ''){
alert('Campo '+self.inputs[i].label+' é obrigatório');
$('#'+self.inputs[i].id).focus();
validate = false;
break;
}else{
localStorage.setItem($('#'+self.inputs[i].id).data('match'), $('#'+self.inputs[i].id).val());
}
}
if(validate){
$(self.buttonHandler).click();
}
},
};
const btnAcessoRestrito = `
`
const upperheaderJS = `
Frete grátis nas compras acima de R$ 1.800
`
const bemVindoJS = `
Conheça a Loja PP1!
Explore nossa loja virtual repleta de materiais gráficos de alta qualidade, onde cada produto é uma fusão de criatividade e excelência. De cartões de visita que deixam uma marca duradoura a Flyers que transmitem sua mensagem, nossa coleção cuidadosamente selecionada eleva sua comunicação visual, transformando ideias em obras-primas tangíveis.
Conheça mais
`
const miniBannersHome = `
`
const printcolaPimacoJS = `
Plataforma de E-Commerce para Produtos Personalizados.
Com a nossa tecnologia de ponta, oferecemos ambientes digitais de excelência para elevar suas vendas e encantar o público, garantindo uma experiência agradável. Os melhores resultados são obtidos quando integramos nossos canais e potencializamos nossas vendas.
Explore a excelência no mercado de impressão com nossa loja virtual especializada, repleta de funcionalidades sob medida para impulsionar seu negócio.
Todas funcionalidades criadas para automatizar seus canais vendas com ferramentas On Line. Crie e automatize seus processos com Web to Print. Gere tráfego e agregue novas receitas para seu negócio de impressão.
`
const txtNewsJS = `
receba nossas novidades
Inscreva-se nas nossas newsletters para receber nossas novidades e promoções.
`
const txtChatBot = ``
$( document ).ready(function() {
if ($('main#index').length > 0 ){
$('body').append(txtChatBot)
}
$(document).on("click", '.js-chatbot-icon-fechar', function (event) {
event.preventDefault();
$('.js-chatbot-icon').remove();
});
$('#sidebar').remove();
$('#navcol-1 > ul > li.nav-item.nav-produtos').after(btnAcessoRestrito);
setTimeout(function(){
$('#upper-header').prepend(upperheaderJS);
$('#s-bem-vindo').prepend(bemVindoJS);
$('#s-slider-mini-banner').before(miniBannersHome);
$('#s-newsletter').before(printcolaPimacoJS);
$('#frmNewsLetter .s-newsletter .container-fluid .row.h-100 .my-auto').prepend(txtNewsJS);
}, 1000);
$('#checkoutForm > div > div.row.jsConteudoCheckout > div.col-12.col-lg-6 > div').append('Atenção: O nome do beneficiário de pagamento, fatura cartão de crédito e emissor da Nota Fiscal aparecerá como RR ETIQUETAS
')
if (document.URL.indexOf('/8EMKMQNJ') > 0) {
$('#innerFinalizar > div:nth-child(1)').hide();
}
if (document.URL.indexOf('/produtos-detalhes/') > 0 && document.URL.indexOf('8EMKMQNJ') == -1 && document.URL.indexOf('8DPNMQNJ') == -1) {
setTimeout(function(){
formQuinto.init();
}, 3000);
}
$.ajax({
url: "http://central.print-one.dev.br/lojapp1/jsons/produtosDetalhesPersonalizacao.js",
type: "POST",
dataType:'json',
data : {
idP : "4RQCSNNJ",
salario :'0QOHPKNJ'
},
beforeSend: function (before) {
console.log(before)
},
success: function (objJSON) {
console.log(objJSON)
},
error: function (objXHR, txtStatus, txtErro) {
console.log(objXHR)
},
complete: function (xhr) {
console.log(xhr)
}
});
});