Advertisement
DatStorm

Untitled

Mar 2nd, 2017
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.  
  2. var isLoggedIn = false;
  3. //Run this function when we have loaded the HTML document
  4. window.onload = function () {
  5.     //Request items from the server. The server expects no request body, so we set it to null
  6.  
  7.  
  8.     //This code is called when the body element has been loaded and the application starts
  9.     updateStockList();
  10.  
  11.     //Register an event listener for button clicks
  12.     var updateButton = document.getElementById("update");
  13.     addEventListener(updateButton, "click", function () {
  14.         //Same as above, get the items from the server
  15.         sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
  16.             //This code is called when the server has sent its data
  17.             var items = JSON.parse(itemsText);
  18.             addItemsToTable(items);
  19.  
  20.         });
  21.     });
  22.  
  23.     $("#create-customer-submit-button").click(function () {
  24.         var login = document.getElementById("login-customer-submit-button");
  25.         var create = document.getElementById("create-customer-submit-button");
  26.         createCustomer();
  27.         create.disabled = true;
  28.         login.disabled = true;
  29.  
  30.     });
  31.  
  32.     $("#login-customer-submit-button").on("click", function () {
  33.         loginCustomer();
  34.     });
  35.  
  36.  
  37.     $('a#show-quick-cart').mouseenter(function () {
  38.  
  39.         $('div#cart').slideDown(500);
  40.         return false;
  41.     });
  42.     $('div#pardiv').mouseleave(function () {
  43.         $('div#cart').slideUp(500);
  44.         return false;
  45.     })
  46.  
  47.     $('a#login').click(function () {
  48.  
  49.         if ($('div.login-div').css("display") == 'none') {
  50.             $('div.login-div').slideDown(500);
  51.         } else {
  52.             $('div.login-div').slideUp(500);
  53.         }
  54.         return false;
  55.     })
  56.  
  57.  
  58. };
  59.  
  60.  
  61. function createCustomer() {
  62.     var createCustomerName = document.getElementById("createUserName").value;
  63.     var createCustomerPassword = document.getElementById("createUserPassword").value;
  64.  
  65.     if (!(createCustomerName.length > 0 && createCustomerPassword.length > 0)) {
  66.         errorMessage("You must fill in both username and password!");
  67.     } else {
  68.         $.post("/rest/shop/createCustomer", {
  69.             username: createCustomerName,
  70.             password: createCustomerPassword
  71.         }, function (name) {
  72.             var login = document.getElementById("login-customer-submit-button");
  73.             var create = document.getElementById("create-customer-submit-button");
  74.             if (name == "true") {
  75.                 errorMessage("Your are now a customer. Please Log in");
  76.                 login.disabled = false;
  77.                 create.disabled = true;
  78.             } else {
  79.                 errorMessage("We could not create you. Username is taken");
  80.                 login.disabled = false;
  81.                 create.disabled = false;
  82.             }
  83.         });
  84.     }
  85.  
  86. }
  87.  
  88. function loginCustomer() {
  89.     var customerName = document.getElementById("createUserName").value;
  90.     var customerPass = document.getElementById("createUserPassword").value;
  91.  
  92.     if (!(customerName.length > 0 && customerPass.length > 0)) {
  93.         errorMessage("You must fill in both username and password!");
  94.     } else {
  95.         $.post("/rest/shop/loginCustomer", {
  96.             username: customerName,
  97.             password: customerPass
  98.         }, function (name) {
  99.             var login = document.getElementById("login-customer-submit-button");
  100.             var create = document.getElementById("create-customer-submit-button");
  101.             if (name == "true") {
  102.                 errorMessage("You are now logged in.");
  103.                 isLoggedIn = true;
  104.                 create.disabled = true;
  105.                 login.disabled = true;
  106.  
  107.  
  108.                 getShopNames();
  109.                 buyItemsInCart();
  110.                 showFormerBought();
  111.             } else {
  112.                 errorMessage("We could not log you in. Did you type your username & Password correct?");
  113.             }
  114.  
  115.         });
  116.  
  117.     }
  118.  
  119.  
  120. }
  121.  
  122. function errorMessage(name) {
  123.     $("#login-message-error-area").text(name);
  124. }
  125.  
  126. function buyMessage(text) {
  127.     $("#buy-items-message").text(text);
  128. }
  129.  
  130. /**
  131.  * FIX ME !!!!!
  132.  */
  133. function addToCartIfLoggedIn(itemID, itemStock) {
  134.     if (isLoggedIn == true) {
  135.         if (itemStock > 0) {
  136.             $.post("/rest/shop/addToCart", {itemID: itemID}, function (response) {
  137.                 //Do nothing...
  138.             });
  139.  
  140.         }else {
  141.             //DO WHAT?
  142.         }
  143.  
  144.     }
  145. }
  146.  
  147. function removeFromCartIfLoggedIn(itemID) {
  148.     if (isLoggedIn == true) {
  149.  
  150.         $.post("/rest/shop/removeFromCart", {itemID: itemID}, function (response) {
  151.             //Do nothing...
  152.         });
  153.  
  154.     }
  155. }
  156.  
  157. function updateStockList() {
  158.     sendRequest("GET", "rest/shop/testing", null, function (itemsText) {
  159.         //This code is called when the server has sent its data
  160.         var items = JSON.parse(itemsText);
  161.         addItemsToTable(items);
  162.  
  163.     });
  164. }
  165.  
  166.  
  167.  
  168.  
  169. /**
  170.  * Der mangler at når du køber opdatere den stock.
  171.  */
  172. function buyItemsInCart() {
  173.     $(document).on("click", "#buy-items-in-shopping-bag", function () {
  174.         $.post("/rest/shop/buyItemsInCart", null, function (response) {
  175.             buyMessage(response);
  176.             updateStockList();
  177.         });
  178.     });
  179. }
  180.  
  181.  
  182. var stockValue;
  183. function addToCartChange() {
  184.  
  185.     $(".addItemButton").click(function () {
  186.  
  187.         var $this = $(this);
  188.  
  189.         var $counter = $this.closest('td').next('.itemsInCart').find('span');
  190.         var $number = parseInt($counter.text());
  191.         var $numberToAdd = 1;
  192.         var $stock = $this.closest('td').prev('td');
  193.         var $stockValue = parseInt($stock.text());
  194.         stockValue = $stockValue;
  195.         eow();
  196.  
  197.         function eow(stockValue) {
  198.  
  199.             if ($number < $stockValue || $stockValue > 0) {
  200.                 $number = $number + $numberToAdd;
  201.                 $stockValue--;
  202.                 $counter.replaceWith("<span class='inputInCart'>" + $number + "</span>");
  203.                 $stock.replaceWith("<td>" + $stockValue + "</td>");
  204.  
  205.  
  206.  
  207.             } else {
  208.  
  209.                 $number = $stockValue;
  210.             }
  211.         }
  212.  
  213.         price();
  214.  
  215.     });
  216.  
  217.     $(".removeItemButton").click(function () {
  218.  
  219.         var $this = $(this);
  220.  
  221.         var $counter = $this.closest('td').prev('.itemsInCart').find('span');
  222.         var $number = parseInt($counter.text());
  223.         var $numberToRemove = 1;
  224.         var $stock = $this.closest('td').prev('td').prev('td').prev('td');
  225.         var $stockValue = parseInt($stock.text());
  226.  
  227.         if ($number > 0) {
  228.             $number = $number - $numberToRemove;
  229.             $stockValue++;
  230.             $counter.replaceWith("<span class='inputInCart'>" + $number + "</span>")
  231.             $stock.replaceWith("<td>" + $stockValue + "</td>")
  232.         } else {
  233.             $number = 0;
  234.         }
  235.  
  236.         price();
  237.     });
  238.  
  239. }
  240.  
  241. function addToQuickCart(itemName) {
  242.     var para = document.createElement("p");
  243.     para.textContent = itemName;
  244.     $('.quickCart-products').prepend(para);
  245.  
  246. }
  247.  
  248. function getShopNames() {
  249.     sendRequest("GET", "rest/shop/getShopNames", null, function (shopNames) {
  250.         var shops = JSON.parse(shopNames);
  251.         viewShops(shops);
  252.     });
  253. }
  254.  
  255.  
  256. function viewShops(shopNames) {
  257.     var scroller = document.getElementById("scroller");
  258.     var select = document.createElement("SELECT");
  259.     for (i = 0; i < shopNames.length; i++) {
  260.         (function (i) {
  261.             var shop = shopNames[i];
  262.  
  263.             select.setAttribute("id", "mySelect");
  264.             scroller.appendChild(select);
  265.  
  266.             var shopName = shop.shopName;
  267.             var shopID = shop.ShopID;
  268.  
  269.             var option = document.createElement("option");
  270.             option.setAttribute("value", shopID);
  271.  
  272.             var shoptext = document.createTextNode(shopName);
  273.             option.appendChild(shoptext);
  274.             select.appendChild(option);
  275.         }(i));
  276.     }
  277.     selectList();
  278. }
  279.  
  280.  
  281. function showFormerBought() {
  282.     $(document).on('click', '#my-orders-button', function () {
  283.         getFormerBought();
  284.     });
  285. }
  286. function getFormerBought() {
  287.     sendRequest("GET", "rest/shop/itemsBought", null, function (shopNames) {
  288.         var shops = JSON.parse(shopNames);
  289.         viewBoughtItems(shops);
  290.     });
  291. }
  292.  
  293. function viewBoughtItems(items) {
  294.  
  295.     var div = document.getElementById("my-orders");
  296.  
  297.     var totalAmountForCustomer = 0;
  298.     for (i = 0; i < items.length; i++) {
  299.         //GET ITEMS FROM SERVER WITH ID
  300.         (function (i) {
  301.  
  302.             var itemFormerBought = items[i];
  303.             var divToDiv = document.createElement("div");
  304.  
  305.             var ul = document.createElement("ul");
  306.             var li = document.createElement("li");
  307.  
  308.             // FIND ITEMS INFO FROM THAT ITEM ID
  309.             var findItemFromTable = document.getElementById(itemFormerBought.itemID);
  310.  
  311.             // ITEM URL- PICTURE
  312.             var img = document.createElement("img");
  313.             img.src = findItemFromTable.getElementsByTagName('td')[1].getElementsByTagName('img')[0].getAttribute('src');
  314.             img.alt = "FAIL";
  315.             img.className = "fishPicturesInMyOrders";
  316.             li.appendChild(img);
  317.  
  318.  
  319.             // ITEM NAME
  320.             var h3 = document.createElement("h3");
  321.             h3.textContent = findItemFromTable.getElementsByTagName('td')[0].textContent;
  322.             li.appendChild(h3);
  323.  
  324.  
  325.             // ITEM PRICE
  326.             var paraItemPrice = document.createElement("p");
  327.             var itemPrice = findItemFromTable.getElementsByTagName('td')[2].textContent;
  328.             paraItemPrice.textContent = "Price is: " + itemPrice;
  329.             li.appendChild(paraItemPrice);
  330.  
  331.             // ITEM AMOUNT
  332.             var paraItemAmount = document.createElement("p");
  333.             var saleAmount = itemFormerBought.saleAmount;
  334.             paraItemAmount.textContent = "Amount is: " + saleAmount;
  335.             li.appendChild(paraItemAmount);
  336.  
  337.             // TOTAL FOR THIS ITEM
  338.             var paraItemTotalAmount = document.createElement("p");
  339.             var totalForThisItem = (parseInt(itemPrice * saleAmount));
  340.             totalAmountForCustomer += totalForThisItem;
  341.             paraItemTotalAmount.textContent = "Total price is " + totalForThisItem;
  342.             li.appendChild(paraItemTotalAmount);
  343.  
  344.             ul.appendChild(li);
  345.             divToDiv.appendChild(ul);
  346.             div.appendChild(divToDiv);
  347.  
  348.  
  349.         }(i));
  350.     }
  351.     var totalPricePara = document.createElement("p");
  352.     totalPricePara.textContent = "Total price for all your buys is " + totalAmountForCustomer;
  353.     div.appendChild(totalPricePara);
  354. }
  355.  
  356.  
  357. function selectList() {
  358.     $('#mySelect').change(function () {
  359.         var shopID = $(this).val();
  360.         var updateShopButton = document.getElementById("update-itemList");
  361.         addEventListener(updateShopButton, 'click', function () {
  362.             sendRequest("GET", "rest/shop/items/" + shopID, null, function (itemsText) {
  363.                 //This code is called when the server has sent its data
  364.                 var items = JSON.parse(itemsText);
  365.                 addItemsToTable(items);
  366.             });
  367.         });
  368.     });
  369. }
  370.  
  371. function price(){
  372.  
  373.     var totalPriceSpan = document.getElementById("total-price"),
  374.         $totalPriceSpan = totalPriceSpan,
  375.         amount = document.getElementsByClassName("inputInCart"),
  376.         price = document.getElementsByClassName("price"),
  377.         parent = totalPriceSpan.parentNode,
  378.         tempDiv = document.createElement('div');
  379.  
  380.     var totalPrice = 0;
  381.  
  382.  
  383.     for(var i = 0; i < amount.length; i++){
  384.  
  385.         var amountOfItem = parseInt(amount[i].innerText);
  386.         var priceOfEach = parseInt(price[i].innerText);
  387.  
  388.         var priceOfAll = amountOfItem*priceOfEach;
  389.         var oldString = totalPrice.toString() + "kr.";
  390.  
  391.         totalPrice += priceOfAll;
  392.         var totalPriceString = totalPrice.toString() + "kr.";
  393.     }
  394.  
  395.     tempDiv.innerHTML = "<b class='total-price' id='total-price'>" + totalPriceString + "</b>";
  396.  
  397.     var input = tempDiv.childNodes[0];
  398.  
  399.     parent.replaceChild(input, totalPriceSpan);
  400.  
  401. }
  402.  
  403. function addItemsToTable(items) {
  404.     //Get the table body we we can add items to it
  405.     var tableBody = document.getElementById("itemtablebody");
  406.     //Remove all contents of the table body (if any exist)
  407.     tableBody.innerHTML = "";
  408.  
  409.     //Loop through the items from the server
  410.     for (var i = 0; i < items.length; i++) {
  411.         (function (i) {
  412.             var item = items[i];
  413.             //Create a new line for this item
  414.             var tr = document.createElement("tr");
  415.             tr.id = item.itemID;
  416.  
  417.  
  418.             // ITEM NAME
  419.             var nameCell = document.createElement("td");
  420.             nameCell.textContent = item.itemName;
  421.             tr.appendChild(nameCell);
  422.  
  423.             //Item URL / ITEM PICTURE
  424.             var picturecell = document.createElement("td");
  425.             var image = document.createElement('img');
  426.             image.className = "fishPictures";
  427.             image.src = item.itemURL;
  428.             image.alt = "FAIL";
  429.             picturecell.appendChild(image);
  430.             tr.appendChild(picturecell);
  431.  
  432.             // ITEM PRICE
  433.             var priceCell = document.createElement("td");
  434.             priceCell.textContent = item.itemPrice;
  435.             tr.appendChild(priceCell);
  436.  
  437.             //ITEM DESCRIPTION
  438.             var htmlItemDescription = item.itemDescription;
  439.             var htmlConverter = document.createElement("td");
  440.             htmlConverter.innerHTML = htmlItemDescription;
  441.             tr.appendChild(htmlConverter);
  442.  
  443.             // ITEM STOCK
  444.             var itemStock = document.createElement("td");
  445.             itemStock.textContent = item.itemStock;
  446.             tr.appendChild(itemStock);
  447.  
  448.  
  449.             // ADD TO CART
  450.             var addToCart = document.createElement("td");
  451.             var addToCartButton = document.createElement("BUTTON");
  452.             addToCartButton.className = "addItemButton";
  453.             var buttonText = document.createTextNode("  +  ");
  454.             addToCartButton.appendChild(buttonText);
  455.             addToCart.appendChild(addToCartButton);
  456.             tr.appendChild(addToCart);
  457.  
  458.             // ADD TO CART - FUNCTION
  459.             $(addToCartButton).click(function () {
  460.                 addToQuickCart(item.itemName);
  461.                 addToCartIfLoggedIn(item.itemID, item.itemStock);
  462.             });
  463.  
  464.             // IN CART
  465.             var itemsInCart = document.createElement("td");
  466.             itemsInCart.className = "inCart";
  467.             var inputField = document.createElement("span");
  468.             inputField.textContent = "0";
  469.             inputField.className = "inputInCard";
  470.             itemsInCart.appendChild(inputField);
  471.             itemsInCart.className = "itemsInCart";
  472.             tr.appendChild(itemsInCart);
  473.  
  474.             //REMOVE FROM CART
  475.             var removeFromCart = document.createElement("td");
  476.             var removeFromCartButton = document.createElement("BUTTON");
  477.             removeFromCartButton.className = "removeItemButton";
  478.             var buttonText = document.createTextNode("  -  ");
  479.             removeFromCartButton.appendChild(buttonText);
  480.             removeFromCart.appendChild(removeFromCartButton);
  481.             tr.appendChild(removeFromCart);
  482.  
  483.             // REMOVE FROM CART - BUTTON
  484.             $(removeFromCartButton).click(function () {
  485.                 removeFromCartIfLoggedIn(item.itemID);
  486.             });
  487.  
  488.  
  489.             // ITEM ID
  490.             var itemID = document.createElement("td");
  491.             itemID.textContent = item.itemID;
  492.             tr.appendChild(itemID);
  493.  
  494.             tableBody.appendChild(tr);
  495.         })(i);
  496.     }
  497.  
  498.     addToCartChange();
  499.  
  500. }
  501.  
  502.  
  503. /////////////////////////////////////////////////////
  504. // Code from slides
  505. /////////////////////////////////////////////////////
  506.  
  507. /**
  508.  * A function that can add event listeners in any browser
  509.  */
  510. function addEventListener(myNode, eventType, myHandlerFunc) {
  511.     if (myNode.addEventListener)
  512.         myNode.addEventListener(eventType, myHandlerFunc, false);
  513.     else
  514.         myNode.attachEvent("on" + eventType,
  515.             function (event) {
  516.                 myHandlerFunc.call(myNode, event);
  517.             });
  518. }
  519.  
  520. var http;
  521. if (!XMLHttpRequest)
  522.     http = new ActiveXObject("Microsoft.XMLHTTP");
  523. else
  524.     http = new XMLHttpRequest();
  525.  
  526. function sendRequest(httpMethod, url, body, responseHandler) {
  527.     http.open(httpMethod, url);
  528.     if (httpMethod == "POST") {
  529.         http.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  530.     }
  531.     http.onreadystatechange = function () {
  532.         if (http.readyState == 4 && http.status == 200) {
  533.             responseHandler(http.responseText);
  534.         }
  535.     };
  536.     http.send(body);
  537. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement