Advertisement
Guest User

myMarket

a guest
Aug 20th, 2017
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function startApp() {
  2.     menu();
  3.     choiceHome();
  4.  
  5.     $('#loadingBox').hide();
  6.     $('#errorBox').hide();
  7.     $('#infoBox').hide();
  8.  
  9.     // Bind the navigation menu links
  10.     $("#linkMenuAppHome").click(mHome);
  11.     $("#linkMenuLogin").click(mLogin);
  12.     $("#linkMenuRegister").click(mRegister);
  13.  
  14.     $("#linkMenuUserHome").click(mUserHome);
  15.     $("#linkMenuShop").click(mShop);
  16.     $("#linkMenuCart").click(mCart);
  17.     $("#linkMenuLogout").click(mlogout);
  18.  
  19.     // Bind user home links
  20.     $("#linkUserHomeShop").click(mShop);
  21.     $("#linkUserHomeCart").click(mCart);
  22.  
  23.     // Bind the form submit buttons и да не зарежда друга страница
  24.     $("#formLogin").submit(login);
  25.     $("#formRegister").submit(register);
  26.     $("form").submit(function (event) {
  27.         event.preventDefault()
  28.     });
  29.  
  30.     // Bind the info / error boxes
  31.     $("#infoBox, #errorBox").click(function () {
  32.         $(this).fadeOut();
  33.     });
  34.  
  35.     // Attach AJAX "loading" event listener
  36.     $(document).on({
  37.         ajaxStart: function () {
  38.             $("#loadingBox").show()
  39.         },
  40.         ajaxStop: function () {
  41.             $("#loadingBox").hide()
  42.         }
  43.     });
  44.  
  45.     // Attach a global AJAX error handler
  46.     $(document).ajaxError(handleAjaxError);
  47.  
  48.     const hostURL = "https://baas.kinvey.com/";
  49.     const _id = "kid_HkBfZLMPW";
  50.     const appSecret = "73cebc03db9049a8b96ce189ac97292f";
  51.     const authBasic = {
  52.         'Authorization': "Basic " + btoa(_id + ":" + appSecret),
  53.     };
  54.  
  55.     function getAuthKinvey() {
  56.         return {
  57.             'Authorization': "Kinvey " + sessionStorage.getItem('authtoken'),
  58.         };
  59.     }
  60.  
  61.     function showView(viewName) {
  62.         // Hide all views and show the selected view only (скрива всички секции)
  63.         $('main > section').hide();
  64.         $('#' + viewName).show();
  65.     }
  66.  
  67.     function menu() {
  68.         if (sessionStorage.getItem('authtoken') === null) {
  69.             // No logged in user
  70.             $('#menu .anonymous').show();
  71.             $('#menu .useronly').hide();
  72.             $('#spanMenuLoggedInUser').text("");
  73.         } else {
  74.             // We have logged in user
  75.             $('#menu .anonymous').hide();
  76.             $('#menu .useronly').show();
  77.             $('#spanMenuLoggedInUser').text("Welcome, " +
  78.                 sessionStorage.getItem('username') + "!");
  79.         }
  80.     }
  81.  
  82.     function showInfo(message) {
  83.         $('#infoBox').text(message);
  84.         $('#infoBox').show();
  85.         setTimeout(function () {
  86.             $('#infoBox').fadeOut();
  87.         }, 3000);
  88.     }
  89.  
  90.     function showError(errorMsg) {
  91.         $('#errorBox').text("Error: " + errorMsg);
  92.         $('#errorBox').show();
  93.     }
  94.  
  95.     function handleAjaxError(event, response) {
  96.         let errorMsg = JSON.stringify(response);
  97.         if (response.readyState === 0)
  98.             errorMsg = "Cannot connect due to network error.";
  99.         if (response.responseJSON && response.responseJSON.description)
  100.             errorMsg = response.responseJSON.description;
  101.         showError(errorMsg);
  102.     }
  103.  
  104.     function choiceHome() {
  105.         if (sessionStorage.getItem('username'))
  106.             mUserHome();
  107.         else
  108.             mHome();
  109.     }
  110.  
  111.     function mHome() {
  112.         showView('viewAppHome');
  113.     }
  114.  
  115.     function mLogin() {
  116.         showView('viewLogin');
  117.         $('#formLogin').trigger('reset');            //изчиства полетата
  118.     }
  119.  
  120.     function login() {
  121.         let userData = {
  122.             //username: $('#formLogin input[name=username]').val(),
  123.             username: $('#loginUsername').val(),
  124.             password: $('#formLogin input[name=passwd]').val()
  125.         };
  126.         $.ajax({
  127.             method: "POST",
  128.             url: hostURL + "user/" + _id + "/login",
  129.             headers: authBasic,
  130.             data: userData,
  131.             success: loginSuccessful
  132.         });
  133.  
  134.         function loginSuccessful(objUser) {
  135.             saveAuthInSession(objUser);
  136.             menu();
  137.             mUserHome();
  138.             showInfo('Login successful.');
  139.         }
  140.     }
  141.  
  142.     function saveAuthInSession(objUser) {
  143.         sessionStorage.setItem('username', objUser.username);
  144.         sessionStorage.setItem('name', objUser.name);
  145.         sessionStorage.setItem('userId', objUser._id);
  146.         sessionStorage.setItem('authtoken', objUser._kmd.authtoken);
  147.     }
  148.  
  149.     function mRegister() {
  150.         $('#formRegister').trigger('reset');
  151.         showView('viewRegister');
  152.     }
  153.  
  154.     function register() {
  155.         let userData = {
  156.             username: $('#formRegister input[name=username]').val(),
  157.             password: $('#formRegister input[name=passwd]').val(),
  158.             name: $('#formRegister input[name=name]').val()
  159.         };
  160.         $.ajax({
  161.             method: "POST",
  162.             url: hostURL + "user/" + _id + "/",
  163.             headers: authBasic,
  164.             data: userData,
  165.             success: registerSuccessful
  166.         });
  167.  
  168.         function registerSuccessful(objUser) {
  169.             saveAuthInSession(objUser);
  170.             menu();
  171.             mUserHome();
  172.             showInfo('User registration successful.');
  173.         }
  174.     }
  175.  
  176.     function mUserHome() {
  177.         $('#viewUserHome h1').text('Welcome, ' +
  178.             sessionStorage.getItem('username') + '!');
  179.         showView('viewUserHome');
  180.     }
  181.  
  182.     function mShop() {
  183.         showView('viewShop');
  184.  
  185.         $.ajax({
  186.             method: "GET",
  187.             url: hostURL + "appdata/" + _id + '/products',
  188.             headers: getAuthKinvey(),
  189.             success: renderShop
  190.         });
  191.  
  192.         function renderShop(arrObjs) {
  193.             $('#viewShop .products').empty();
  194.             let table = $("<table><thead><tr><th>Product</th><th>Description</th><th>Price</th><th>Actions</th></tr></thead></table>");
  195.             let tbody = $("<tbody>");
  196.             table.append(tbody);
  197.             for (let objProd of arrObjs) {
  198.                 let purchaseButton = $("<button>Purchase</button>")
  199.                     .click(purchaseProduct.bind(null, objProd));
  200.                 let tr = $("<tr>")
  201.                     .append($("<td>").text(objProd.name))
  202.                     .append($("<td>").text(objProd.description))
  203.                     .append($("<td>").text(Number(objProd.price).toFixed(2)))
  204.                     .append($("<td>").append(purchaseButton));
  205.                 tbody.append(tr);
  206.             }
  207.             $('#viewShop .products').append(table);
  208.             showInfo('Shop loaded successfully.');
  209.         }
  210.     }
  211.  
  212.     function purchaseProduct(objProd) {
  213.         $.ajax({
  214.             method: "GET",
  215.             url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
  216.             headers: getAuthKinvey(),
  217.             success: updateCart
  218.         });
  219.  
  220.         function updateCart(objUser) {
  221.             objUser.cart = objUser.cart || {};
  222.  
  223.             if (objUser.cart.hasOwnProperty(objProd._id)) {
  224.                 objUser.cart[objProd._id].quantity = Number(objUser.cart[objProd._id].quantity) + 1;
  225.             } else {
  226.                 objUser.cart[objProd._id] = {
  227.                     quantity: 1,
  228.                     product: {
  229.                         name: objProd.name,
  230.                         description: objProd.description,
  231.                         price: objProd.price
  232.                     }
  233.                 }
  234.             }
  235.  
  236.             $.ajax({
  237.                 method: "PUT",
  238.                 url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
  239.                 headers: getAuthKinvey(),
  240.                 data: objUser,
  241.                 success: productPurchased
  242.             });
  243.         }
  244.  
  245.         function productPurchased() {
  246.             showInfo('Product purchased.');
  247.             mCart();
  248.         }
  249.     }
  250.  
  251.     function mCart() {
  252.         showView('viewCart');
  253.  
  254.         $.ajax({
  255.             method: "GET",
  256.             url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
  257.             headers: getAuthKinvey(),
  258.             success: function (objUser) {
  259.                 let cart = objUser.cart || {};
  260.                 renderCart(cart);
  261.             }
  262.         });
  263.  
  264.         function renderCart(cart) {
  265.             $('#viewCart .products').empty();
  266.             let table = $("<table><thead><tr><th>Product</th><th>Description</th><th>Quantity</th><th>Total Price</th><th>Actions</th></tr></thead></table>");
  267.             let tbody = $("<tbody>");
  268.             table.append(tbody);
  269.             for (let product in cart) {
  270.  
  271.                 let discardButton = $("<button>Discard</button>")
  272.                     .click(discardProduct.bind(null, product));
  273.                 let tr = $("<tr>")
  274.                     .append($("<td>").text(cart[product].product.name))
  275.                     .append($("<td>").text(cart[product].product.description))
  276.                     .append($("<td>").text(cart[product].quantity))
  277.                     .append($("<td>").text((Number(cart[product].quantity) * Number(cart[product].product.price)).toFixed(2)))
  278.                     .append($("<td>").append(discardButton));
  279.                 tbody.append(tr);
  280.             }
  281.             $('#viewCart .products').append(table);
  282.             // showInfo('Cart loaded successfully.');
  283.         }
  284.     }
  285.  
  286.     function discardProduct(productId) {
  287.         $.ajax({
  288.             method: "GET",
  289.             url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
  290.             headers: getAuthKinvey(),
  291.             success: updateCart
  292.         });
  293.  
  294.         function updateCart(objUser) {
  295.             objUser.cart = objUser.cart || {};
  296.             let newCart = {};
  297.             for (let id in objUser.cart) {
  298.                 if (id != productId) {
  299.                     newCart[id] = objUser.cart[id];
  300.                 }
  301.             }
  302.             objUser.cart = newCart;
  303.  
  304.             $.ajax({
  305.                 method: "PUT",
  306.                 url: hostURL + "user/" + _id + '/' + sessionStorage.getItem('userId'),
  307.                 headers: getAuthKinvey(),
  308.                 data: objUser,
  309.                 success: productDiscarded
  310.             });
  311.         }
  312.  
  313.         b
  314.  
  315.         function productDiscarded() {
  316.             console.log("shit");
  317.             showInfo('Product discarded.');
  318.             mCart();
  319.         }
  320.     }
  321.  
  322.     function mlogout() {
  323.         $.ajax({
  324.             method: "POST",
  325.             url: hostURL + "user/" + _id + "/_logout",
  326.             headers: getAuthKinvey()
  327.         });
  328.         sessionStorage.clear();
  329.         menu();
  330.         mHome();
  331.         showInfo('Logout successful.');
  332.     }
  333. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement