console.log('Theme JS');
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 formEditor = {
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: "/loja/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) {
console.log(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 () {
if ($('#produto-form-personalizar').length > 0) {
return
}
$container = $(`
Preencha os dados corretamente
`);
$container.insertAfter('#innerProdutoInfo');
},
configForm: function () {
for (let key = 0; key < this.texts.length; key++) {
let id = this.texts[key].name.replace(/ /g, '').toLowerCase()
id = id.normalize('NFD').replace(/\p{Mn}/gu, "");
const element = id;
const elementID = id;
const mask = element.toLowerCase().indexOf('telefone') != -1 || element.toLowerCase().indexOf('celular') != -1 ? true : false;
const maxlength = element.toLowerCase().indexOf('nome') != -1 ? 20 : false;
const type = 'text';
let label = this.texts[key].name;
const 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();
formEditor.save();
});
$(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('');
}
} 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();
}
},
};
if (document.URL.indexOf('produtos-detalhes') > 0) {
if (document.URL.indexOf('/8PMPPLNJ/') > 0 || document.URL.indexOf('/4IPFPLNJ/') > 0 || document.URL.indexOf('/0MQIPLNJ/') > 0 || document.URL.indexOf('/8PRLPLNJ/') > 0) {
$('#innerProdutoInfo').after(`
Suba sua foto
Carregando...
`);
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"){
fncToast('Erro', `Não foi possível enviar seu arquivo "${file.name}". A conexão com os servidores da Amazon não está disponível.`, 'alerta');
}else if(err.code == "RequestTimeTooSkewed"){
fncToast('Erro', `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.`, 'alerta');
}else{
fncToast('Erro', `Não foi possível enviar seu arquivo "${file.name}". Houve um problema na comunicação entre os servidores.`, 'alerta');
}
}else{
$('#imgEnvioArq').attr("src", data.Location);
localStorage.setItem('#imagemeditor#', data.Location);
}
}).on('httpUploadProgress',function(evt){
});
});
}
});
}
}
$(document).ready(function(){
if (document.URL.indexOf('/produtos-detalhes/') > 0) {
if (document.URL.indexOf('/8PMPPLNJ/') > 0 || document.URL.indexOf('/4IPFPLNJ/') > 0 || document.URL.indexOf('/0MQIPLNJ/') > 0 || document.URL.indexOf('/8PRLPLNJ/') > 0) {
setTimeout(function(){
console.log('entrou??')
formEditor.init();
}, 1000);
}
}
});