(function() { $(document).on('submit', '.cart-form', function(e) { e.preventDefault(); const data = $(this).serializeArray(); const url = $(this).data('route') || $(this).attr('action'); const method = $(this).data('method') || $(this).attr('method'); const optionsAreValid = validateAttributeOptions(data); const routeToCart = $(this).data('to-cart'); var container = $(this).find('.alert-container').length < 1 ? $('.cart-form .alert-container') : $(this).find('.alert-container').first(); $(this).parent().find('.alert-dismissible').first().remove(); function getAlert(message){ const alert =``; return alert; } if (method.toUpperCase() === 'POST' && !optionsAreValid) { const message = getAlert('Você precisa selecionar todas as opções antes de adicionar um produto ao carrinho'); container.append(message); } $.ajax({ url: url, method: method, data: data, success: function(response) { if(response.toCart){ window.location.href = routeToCart; } $(document).trigger('cart-updated'); $('.modal-content .close').click(); }, statusCode: { 400: function(err) { const message = getAlert(err.responseJSON.message); showErrorForUser(message); }, 401: function(err) { const message = getAlert(err.responseJSON.message); showErrorForUser(message); }, 404: function(err) { const message = getAlert(err.responseJSON.message); showErrorForUser(message); }, 405: function (err){ const message = getAlert('Ocorreu algum erro desconhecido.'); showErrorForUser(message); }, 500: function(err) { const message = getAlert('Ocorreu algum erro desconhecido.'); showErrorForUser(message); } } }); function showErrorForUser(message) { $(".error-modal-close-button").trigger('click'); container.append(message); $('html, body').animate({ scrollTop: container.offset().top - 100 },500); } function validateAttributeOptions(serializedArray) { for (let input of serializedArray) { if (input.name.startsWith('attributes') && !(input.value)) { return false; } } return true; } }); })();