Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function startApp() {
- menu();
- choiceHome();
- $('#loadingBox').hide();
- $('#errorBox').hide();
- $('#infoBox').hide();
- // Bind the navigation menu links
- $("#linkMenuAppHome").click(mHome);
- $("#linkMenuLogin").click(mLogin);
- $("#linkMenuRegister").click(mRegister);
- $("#linkMenuUserHome").click(mUserHome);
- $("#linkMenuShop").click(mShop);
- $("#linkMenuCart").click(mCart);
- $("#linkMenuLogout").click(mlogout);
- // Bind user home links
- $("#linkUserHomeShop").click(mShop);
- $("#linkUserHomeCart").click(mCart);
- // Bind the form submit buttons и да не зарежда друга страница
- $("#formLogin").submit(login);
- $("#formRegister").submit(register);
- $("form").submit(function (event) {
- event.preventDefault()
- });
- // Bind the info / error boxes
- $("#infoBox, #errorBox").click(function () {
- $(this).fadeOut();
- });
- // Attach AJAX "loading" event listener
- $(document).on({
- ajaxStart: function () {
- $("#loadingBox").show()
- },
- ajaxStop: function () {
- $("#loadingBox").hide()
- }
- });
- // Attach a global AJAX error handler
- $(document).ajaxError(handleAjaxError);
- const hostURL = "https://baas.kinvey.com/";
- const _id = "kid_HkBfZLMPW";
- const appSecret = "73cebc03db9049a8b96ce189ac97292f";
- const authBasic = {
- 'Authorization': "Basic " + btoa(_id + ":" + appSecret),
- };
- function getAuthKinvey() {
- return {
- 'Authorization': "Kinvey " + sessionStorage.getItem('authtoken'),
- };
- }
- function showView(viewName) {
- // Hide all views and show the selected view only (скрива всички секции)
- $('main > section').hide();
- $('#' + viewName).show();
- }
- function menu() {
- if (sessionStorage.getItem('authtoken') === null) {
- // No logged in user
- $('#menu .anonymous').show();
- $('#menu .useronly').hide();
- $('#spanMenuLoggedInUser').text("");
- } else {
- // We have logged in user
- $('#menu .anonymous').hide();
- $('#menu .useronly').show();
- $('#spanMenuLoggedInUser').text("Welcome, " +
- sessionStorage.getItem('username') + "!");
- }
- }
- function showInfo(message) {
- $('#infoBox').text(message);
- $('#infoBox').show();
- setTimeout(function () {
- $('#infoBox').fadeOut();
- }, 3000);
- }
- function showError(errorMsg) {
- $('#errorBox').text("Error: " + errorMsg);
- $('#errorBox').show();
- }
- function handleAjaxError(event, response) {
- let errorMsg = JSON.stringify(response);
- if (response.readyState === 0)
- errorMsg = "Cannot connect due to network error.";
- if (response.responseJSON && response.responseJSON.description)
- errorMsg = response.responseJSON.description;
- showError(errorMsg);
- }
- function choiceHome() {
- if (sessionStorage.getItem('username'))
- mUserHome();
- else
- mHome();
- }
- function mHome() {
- showView('viewAppHome');
- }
- function mLogin() {
- showView('viewLogin');
- $('#formLogin').trigger('reset'); //изчиства полетата
- }
- function login() {
- let userData = {
- //username: $('#formLogin input[name=username]').val(),
- username: $('#loginUsername').val(),
- password: $('#formLogin input[name=passwd]').val()
- };
- $.ajax({
- method: "POST",
- url: hostURL + "user/" + _id + "/login",
- headers: authBasic,
- data: userData,
- success: loginSuccessful
- });
- function loginSuccessful(objUser) {
- saveAuthInSession(objUser);
- menu();
- mUserHome();
- showInfo('Login successful.');
- }
- }
- function saveAuthInSession(objUser) {
- sessionStorage.setItem('username', objUser.username);
- sessionStorage.setItem('name', objUser.name);
- sessionStorage.setItem('userId', objUser._id);
- sessionStorage.setItem('authtoken', objUser._kmd.authtoken);
- }
- function mRegister() {
- $('#formRegister').trigger('reset');
- showView('viewRegister');
- }
- function register() {
- let userData = {
- username: $('#formRegister input[name=username]').val(),
- password: $('#formRegister input[name=passwd]').val(),
- name: $('#formRegister input[name=name]').val()
- };
- $.ajax({
- method: "POST",
- url: hostURL + "user/" + _id + "/",
- headers: authBasic,
- data: userData,
- success: registerSuccessful
- });
- function registerSuccessful(objUser) {
- saveAuthInSession(objUser);
- menu();
- mUserHome();
- showInfo('User registration successful.');
- }
- }
- function mUserHome() {
- $('#viewUserHome h1').text('Welcome, ' +
- sessionStorage.getItem('username') + '!');
- showView('viewUserHome');
- }
- function mShop() {
- showView('viewShop');
- $.ajax({
- method: "GET",
- url: hostURL + "appdata/" + _id + '/products',
- headers: getAuthKinvey(),
- success: renderShop
- });
- function renderShop(arrObjs) {
- $('#viewShop .products').empty();
- let table = $("<table><thead><tr><th>Product</th><th>Description</th><th>Price</th><th>Actions</th></tr></thead></table>");
- let tbody = $("<tbody>");
- table.append(tbody);
- for (let objProd of arrObjs) {
- let purchaseButton = $("<button>Purchase</button>")
- .click(purchaseProduct.bind(null, objProd));
- let tr = $("<tr>")
- .append($("<td>").text(objProd.name))
- .append($("<td>").text(objProd.description))
- .append($("<td>").text(Number(objProd.price).toFixed(2)))
- .append($("<td>").append(purchaseButton));
- tbody.append(tr);
- }
- $('#viewShop .products').append(table);
- showInfo('Shop loaded successfully.');
- }
- }
- function purchaseProduct(objProd) {
- $.ajax({
- method: "GET",
- url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
- headers: getAuthKinvey(),
- success: updateCart
- });
- function updateCart(objUser) {
- objUser.cart = objUser.cart || {};
- if (objUser.cart.hasOwnProperty(objProd._id)) {
- objUser.cart[objProd._id].quantity = Number(objUser.cart[objProd._id].quantity) + 1;
- } else {
- objUser.cart[objProd._id] = {
- quantity: 1,
- product: {
- name: objProd.name,
- description: objProd.description,
- price: objProd.price
- }
- }
- }
- $.ajax({
- method: "PUT",
- url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
- headers: getAuthKinvey(),
- data: objUser,
- success: productPurchased
- });
- }
- function productPurchased() {
- showInfo('Product purchased.');
- mCart();
- }
- }
- function mCart() {
- showView('viewCart');
- $.ajax({
- method: "GET",
- url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
- headers: getAuthKinvey(),
- success: function (objUser) {
- let cart = objUser.cart || {};
- renderCart(cart);
- }
- });
- function renderCart(cart) {
- $('#viewCart .products').empty();
- let table = $("<table><thead><tr><th>Product</th><th>Description</th><th>Quantity</th><th>Total Price</th><th>Actions</th></tr></thead></table>");
- let tbody = $("<tbody>");
- table.append(tbody);
- for (let product in cart) {
- let discardButton = $("<button>Discard</button>")
- .click(discardProduct.bind(null, product));
- let tr = $("<tr>")
- .append($("<td>").text(cart[product].product.name))
- .append($("<td>").text(cart[product].product.description))
- .append($("<td>").text(cart[product].quantity))
- .append($("<td>").text((Number(cart[product].quantity) * Number(cart[product].product.price)).toFixed(2)))
- .append($("<td>").append(discardButton));
- tbody.append(tr);
- }
- $('#viewCart .products').append(table);
- // showInfo('Cart loaded successfully.');
- }
- }
- function discardProduct(productId) {
- $.ajax({
- method: "GET",
- url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
- headers: getAuthKinvey(),
- success: updateCart
- });
- function updateCart(objUser) {
- objUser.cart = objUser.cart || {};
- let newCart = {};
- for (let id in objUser.cart) {
- if (id != productId) {
- newCart[id] = objUser.cart[id];
- }
- }
- objUser.cart = newCart;
- $.ajax({
- method: "PUT",
- url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
- headers: getAuthKinvey(),
- data: objUser,
- success: productDiscarded
- });
- }
- b
- function productDiscarded() {
- console.log("shit");
- showInfo('Product discarded.');
- mCart();
- }
- }
- function mlogout() {
- $.ajax({
- method: "POST",
- url: hostURL + "user/" + _id + "/_logout",
- headers: getAuthKinvey()
- });
- sessionStorage.clear();
- menu();
- mHome();
- showInfo('Logout successful.');
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement